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 org.apidesign.vm4brwsr.Bck2Brwsr.Flow;
24 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
25 import org.apidesign.vm4brwsr.ByteCodeParser.AnnotationParser;
26 import org.apidesign.vm4brwsr.ByteCodeParser.BootMethodData;
27 import org.apidesign.vm4brwsr.ByteCodeParser.CPX2;
28 import org.apidesign.vm4brwsr.ByteCodeParser.ClassData;
29 import org.apidesign.vm4brwsr.ByteCodeParser.FieldData;
30 import org.apidesign.vm4brwsr.ByteCodeParser.MethodData;
31 import org.apidesign.vm4brwsr.ByteCodeParser.StackMapIterator;
32 import org.apidesign.vm4brwsr.ByteCodeParser.TrapData;
33 import org.apidesign.vm4brwsr.ByteCodeParser.TrapDataIterator;
35 /** Translator of the code inside class files to JavaScript.
37 * @author Jaroslav Tulach <jtulach@netbeans.org>
39 abstract class ByteCodeToJavaScript implements Appendable {
41 private final Appendable out;
42 private final StringArray classRefs = new StringArray();
43 private boolean outChanged;
44 private boolean callbacks;
46 protected ByteCodeToJavaScript(Appendable out) {
51 public final Appendable append(CharSequence csq) throws IOException {
58 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
59 out.append(csq, start, end);
65 public final Appendable append(char c) throws IOException {
71 /* Collects additional required resources.
73 * @param internalClassName classes that were referenced and should be loaded in order the
74 * generated JavaScript code works properly. The names are in internal
75 * JVM form so String is <code>java/lang/String</code>.
77 protected abstract boolean requireReference(String internalClassName);
80 * @param resourcePath name of resources to read
82 protected abstract void requireScript(String resourcePath) throws IOException;
84 protected abstract void requireResource(String resourcePath) throws IOException;
86 /** Allows subclasses to redefine what field a function representing a
87 * class gets assigned. By default it returns the suggested name followed
88 * by <code>" = "</code>;
90 * @param className suggested name of the class
92 /* protected */ String assignClass(String className) {
93 return className + " = ";
95 /* protected */ String accessClass(String classOperation) {
96 return classOperation;
99 final String accessClassFalse(String classOperation) {
100 if (jc.getClassName().replace('/', '_').equals(classOperation)) {
103 classRefs.addIfMissing(classOperation);
104 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
107 protected String accessField(String object, String mangledName,
108 String[] fieldInfoName) throws IOException {
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 = superInterface.replace('/', '_');
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 = ");
443 append("m = ").append(destObject).append(".").append(name).append(" = ");
445 Flow flow = checkFlow(m);
447 // OK, assume generate
456 lmapper.outputArguments(this, m.isStatic());
457 append(") {").append("\n");
459 final byte[] byteCodes = m.getCode();
460 if (byteCodes == null) {
461 if (debug(" throw 'no code found for ")) {
463 .append(jc.getClassName()).append('.')
464 .append(m.getName()).append("';\n");
474 final StackMapper smapper = new StackMapper();
477 append(" var ").append(" lcA0 = this;\n");
481 TrapData[] previousTrap = null;
482 boolean wide = false;
484 if (stackMapIterator.isEmpty()) {
491 append("\n var gt = 0;\n");
498 int topMostLabel = 0;
499 for (int i = 0; i < byteCodes.length; i++) {
502 stackMapIterator.advanceTo(i);
503 boolean changeInCatch = trap.advanceTo(i);
504 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
505 if (previousTrap != null) {
506 generateCatch(previousTrap, flow, i, topMostLabel);
510 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
512 if (flow == null && i != 0) {
515 if (openBraces > 64) {
516 for (int c = 0; c < 64; c++) {
523 lastStackFrame = stackMapIterator.getFrameIndex();
524 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
525 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
526 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
528 changeInCatch = true;
530 debug(" /* " + i + " */ ");
532 if (changeInCatch && trap.useTry()) {
534 previousTrap = trap.current();
536 final int c = readUByte(byteCodes, i);
539 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
542 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
545 smapper.assign(this, VarType.LONG, lmapper.getL(0));
548 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
551 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
554 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
557 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
560 smapper.assign(this, VarType.LONG, lmapper.getL(1));
563 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
566 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
569 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
572 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
575 smapper.assign(this, VarType.LONG, lmapper.getL(2));
578 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
581 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
584 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
587 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
590 smapper.assign(this, VarType.LONG, lmapper.getL(3));
593 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
596 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
600 final int indx = wide ? readUShort(byteCodes, i++)
601 : readUByte(byteCodes, i);
603 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
608 final int indx = wide ? readUShort(byteCodes, i++)
609 : readUByte(byteCodes, i);
611 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
616 final int indx = wide ? readUShort(byteCodes, i++)
617 : readUByte(byteCodes, i);
619 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
624 final int indx = wide ? readUShort(byteCodes, i++)
625 : readUByte(byteCodes, i);
627 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
632 final int indx = wide ? readUShort(byteCodes, i++)
633 : readUByte(byteCodes, i);
635 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
640 final int indx = wide ? readUShort(byteCodes, i++)
641 : readUByte(byteCodes, i);
643 emit(smapper, this, "var @1 = @2;",
644 lmapper.setI(indx), smapper.popI());
649 final int indx = wide ? readUShort(byteCodes, i++)
650 : readUByte(byteCodes, i);
652 emit(smapper, this, "var @1 = @2;",
653 lmapper.setL(indx), smapper.popL());
658 final int indx = wide ? readUShort(byteCodes, i++)
659 : readUByte(byteCodes, i);
661 emit(smapper, this, "var @1 = @2;",
662 lmapper.setF(indx), smapper.popF());
667 final int indx = wide ? readUShort(byteCodes, i++)
668 : readUByte(byteCodes, i);
670 emit(smapper, this, "var @1 = @2;",
671 lmapper.setD(indx), smapper.popD());
676 final int indx = wide ? readUShort(byteCodes, i++)
677 : readUByte(byteCodes, i);
679 emit(smapper, this, "var @1 = @2;",
680 lmapper.setA(indx), smapper.popA());
684 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
687 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
690 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
693 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
696 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
699 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
702 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
705 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
708 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
711 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
714 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
717 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
720 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
723 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
726 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
729 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
732 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
735 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
738 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
741 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
744 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
747 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
750 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
753 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
756 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
759 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
762 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
765 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
768 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
771 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
774 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
777 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
780 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
781 smapper.getI(1), smapper.popI());
784 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
785 smapper.getL(1), smapper.popL());
788 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
791 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
794 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
795 smapper.getI(1), smapper.popI());
798 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
799 smapper.getL(1), smapper.popL());
802 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
805 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
808 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
811 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
814 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
817 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
820 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
823 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
826 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
829 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
832 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
835 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
838 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
841 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
844 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
847 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
850 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
853 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
857 final int varIndx = wide ? readUShort(byteCodes, i++)
858 : readUByte(byteCodes, i);
860 final int incrBy = wide ? readShort(byteCodes, i++)
864 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
866 emit(smapper, this, "@1 += @2;",
867 lmapper.getI(varIndx),
868 Integer.toString(incrBy));
873 emit(smapper, this, "return;");
876 emit(smapper, this, "return @1;", smapper.popI());
879 emit(smapper, this, "return @1;", smapper.popL());
882 emit(smapper, this, "return @1;", smapper.popF());
885 emit(smapper, this, "return @1;", smapper.popD());
888 emit(smapper, this, "return @1;", smapper.popA());
891 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
894 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
897 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
900 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
904 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
907 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
910 smapper.replace(this, VarType.DOUBLE, "@1",
914 smapper.replace(this, VarType.FLOAT, "@1",
918 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
922 smapper.replace(this, VarType.LONG, "(@1).toLong()",
926 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
930 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
933 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
937 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
939 case opc_aconst_null:
940 smapper.assign(this, VarType.REFERENCE, "null");
943 smapper.assign(this, VarType.INTEGER, "-1");
946 smapper.assign(this, VarType.INTEGER, "0");
949 smapper.assign(this, VarType.DOUBLE, "0");
952 smapper.assign(this, VarType.LONG, "0");
955 smapper.assign(this, VarType.FLOAT, "0");
958 smapper.assign(this, VarType.INTEGER, "1");
961 smapper.assign(this, VarType.LONG, "1");
964 smapper.assign(this, VarType.FLOAT, "1");
967 smapper.assign(this, VarType.DOUBLE, "1");
970 smapper.assign(this, VarType.INTEGER, "2");
973 smapper.assign(this, VarType.FLOAT, "2");
976 smapper.assign(this, VarType.INTEGER, "3");
979 smapper.assign(this, VarType.INTEGER, "4");
982 smapper.assign(this, VarType.INTEGER, "5");
985 int indx = readUByte(byteCodes, ++i);
986 String v = encodeConstant(indx);
987 int type = VarType.fromConstantType(jc.getTag(indx));
988 smapper.assign(this, type, v);
993 int indx = readUShortArg(byteCodes, i);
995 String v = encodeConstant(indx);
996 int type = VarType.fromConstantType(jc.getTag(indx));
997 if (type == VarType.LONG) {
998 final Long lv = new Long(v);
999 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
1000 final int hi = (int)(lv.longValue() >> 32);
1002 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
1004 smapper.assign(this, VarType.LONG,
1005 "0x" + Integer.toHexString(hi) + ".next32(0x" +
1006 Integer.toHexString(low) + ")"
1010 smapper.assign(this, type, v);
1015 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
1019 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1020 smapper.popF(), smapper.popF(), smapper.pushI());
1024 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1025 smapper.popD(), smapper.popD(), smapper.pushI());
1028 i = generateIf(smapper, flow, byteCodes, i, smapper.popA(), smapper.popA(),
1029 "===", topMostLabel);
1032 i = generateIf(smapper, flow, byteCodes, i, smapper.popA(), smapper.popA(),
1033 "!==", topMostLabel);
1036 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1037 "==", topMostLabel);
1040 int indx = i + readShortArg(byteCodes, i);
1041 emitIf(smapper, flow, this, "if ((@1) == 0) ",
1042 smapper.popI(), i, indx, topMostLabel);
1047 int indx = i + readShortArg(byteCodes, i);
1048 emitIf(smapper, flow, this, "if ((@1) != 0) ",
1049 smapper.popI(), i, indx, topMostLabel);
1054 int indx = i + readShortArg(byteCodes, i);
1055 emitIf(smapper, flow, this, "if ((@1) < 0) ",
1056 smapper.popI(), i, indx, topMostLabel);
1061 int indx = i + readShortArg(byteCodes, i);
1062 emitIf(smapper, flow, this, "if ((@1) <= 0) ",
1063 smapper.popI(), i, indx, topMostLabel);
1068 int indx = i + readShortArg(byteCodes, i);
1069 emitIf(smapper, flow, this, "if ((@1) > 0) ",
1070 smapper.popI(), i, indx, topMostLabel);
1075 int indx = i + readShortArg(byteCodes, i);
1076 emitIf(smapper, flow, this, "if ((@1) >= 0) ",
1077 smapper.popI(), i, indx, topMostLabel);
1081 case opc_ifnonnull: {
1082 int indx = i + readShortArg(byteCodes, i);
1083 emitIf(smapper, flow, this, "if ((@1) !== null) ",
1084 smapper.popA(), i, indx, topMostLabel);
1089 int indx = i + readShortArg(byteCodes, i);
1090 emitIf(smapper, flow, this, "if ((@1) === null) ",
1091 smapper.popA(), i, indx, topMostLabel);
1096 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1097 "!=", topMostLabel);
1100 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1104 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1105 "<=", topMostLabel);
1108 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1112 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1113 ">=", topMostLabel);
1116 smapper.flush(this);
1118 int indx = i + readShortArg(byteCodes, i);
1119 goTo(this, flow, i, indx, topMostLabel);
1124 case opc_lookupswitch: {
1125 i = generateLookupSwitch(i, byteCodes, smapper, flow, topMostLabel);
1128 case opc_tableswitch: {
1129 i = generateTableSwitch(i, byteCodes, smapper, flow, topMostLabel);
1132 case opc_invokeinterface: {
1133 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1136 case opc_invokevirtual:
1137 i = invokeVirtualMethod(byteCodes, i, smapper);
1139 case opc_invokespecial:
1140 i = invokeStaticMethod(byteCodes, i, smapper, false);
1142 case opc_invokestatic:
1143 i = invokeStaticMethod(byteCodes, i, smapper, true);
1145 case opc_invokedynamic: {
1146 int indx = readUShortArg(byteCodes, i);
1147 println("invoke dynamic: " + indx);
1148 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1149 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1150 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1151 println(" type: " + methodHandle.cpx1);
1152 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1153 String mcn = mangleClassName(mi[0]);
1154 char[] returnType = {'V'};
1155 StringBuilder cnt = new StringBuilder();
1156 String mn = findMethodName(mi, cnt, returnType);
1157 StringBuilder sb = new StringBuilder();
1158 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1159 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1160 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1161 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1162 sb.append(" mn : ").append(mn).append("\n");
1163 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1164 throw new IOException(sb.toString());
1166 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1167 String type = jc.StringValue(nameAndType.cpx2);
1168 String object = accessClass(mcn) + "(false)";
1169 if (mn.startsWith("cons_")) {
1170 object += ".constructor";
1172 append("var metHan = ");
1173 append(accessStaticMethod(object, mn, mi));
1175 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1177 append(", '").append(mi[1]).append("', ");
1178 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1179 append(methodType).append("'").append(type).append("', null)");
1180 // if (numArguments > 0) {
1182 // for (int j = 1; j < numArguments; ++j) {
1188 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1194 int indx = readUShortArg(byteCodes, i);
1195 String ci = jc.getClassName(indx);
1196 emit(smapper, this, "var @1 = new @2;",
1197 smapper.pushA(), accessClass(mangleClassName(ci)));
1203 int atype = readUByte(byteCodes, ++i);
1204 generateNewArray(atype, smapper);
1206 case opc_anewarray: {
1207 int type = readUShortArg(byteCodes, i);
1209 generateANewArray(type, smapper);
1212 case opc_multianewarray: {
1213 int type = readUShortArg(byteCodes, i);
1215 i = generateMultiANewArray(type, byteCodes, i, smapper);
1218 case opc_arraylength:
1219 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1222 emit(smapper, this, "Array.at(@3, @2, @1);",
1223 smapper.popL(), smapper.popI(), smapper.popA());
1226 emit(smapper, this, "Array.at(@3, @2, @1);",
1227 smapper.popF(), smapper.popI(), smapper.popA());
1230 emit(smapper, this, "Array.at(@3, @2, @1);",
1231 smapper.popD(), smapper.popI(), smapper.popA());
1234 emit(smapper, this, "Array.at(@3, @2, @1);",
1235 smapper.popA(), smapper.popI(), smapper.popA());
1241 emit(smapper, this, "Array.at(@3, @2, @1);",
1242 smapper.popI(), smapper.popI(), smapper.popA());
1245 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1246 smapper.popI(), smapper.getA(0));
1249 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1250 smapper.popI(), smapper.getA(0));
1253 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1254 smapper.popI(), smapper.getA(0));
1257 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1258 smapper.popI(), smapper.getA(0));
1264 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1265 smapper.popI(), smapper.getA(0));
1273 final Variable v = smapper.get(0);
1274 if (smapper.isDirty()) {
1275 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1277 smapper.assign(this, v.getType(), v);
1282 final Variable vi1 = smapper.get(0);
1284 if (vi1.isCategory2()) {
1285 emit(smapper, this, "var @1 = @2;",
1286 smapper.pushT(vi1.getType()), vi1);
1288 final Variable vi2 = smapper.get(1);
1289 emit(smapper, this, "var @1 = @2, @3 = @4;",
1290 smapper.pushT(vi2.getType()), vi2,
1291 smapper.pushT(vi1.getType()), vi1);
1296 final Variable vi1 = smapper.pop(this);
1297 final Variable vi2 = smapper.pop(this);
1298 final Variable vo3 = smapper.pushT(vi1.getType());
1299 final Variable vo2 = smapper.pushT(vi2.getType());
1300 final Variable vo1 = smapper.pushT(vi1.getType());
1302 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1303 vo1, vi1, vo2, vi2, vo3, vo1);
1307 final Variable vi1 = smapper.pop(this);
1308 final Variable vi2 = smapper.pop(this);
1310 if (vi1.isCategory2()) {
1311 final Variable vo3 = smapper.pushT(vi1.getType());
1312 final Variable vo2 = smapper.pushT(vi2.getType());
1313 final Variable vo1 = smapper.pushT(vi1.getType());
1315 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1316 vo1, vi1, vo2, vi2, vo3, vo1);
1318 final Variable vi3 = smapper.pop(this);
1319 final Variable vo5 = smapper.pushT(vi2.getType());
1320 final Variable vo4 = smapper.pushT(vi1.getType());
1321 final Variable vo3 = smapper.pushT(vi3.getType());
1322 final Variable vo2 = smapper.pushT(vi2.getType());
1323 final Variable vo1 = smapper.pushT(vi1.getType());
1325 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1326 vo1, vi1, vo2, vi2, vo3, vi3);
1327 emit(smapper, this, " @1 = @2, @3 = @4;",
1328 vo4, vo1, vo5, vo2);
1333 final Variable vi1 = smapper.pop(this);
1334 final Variable vi2 = smapper.pop(this);
1336 if (vi2.isCategory2()) {
1337 final Variable vo3 = smapper.pushT(vi1.getType());
1338 final Variable vo2 = smapper.pushT(vi2.getType());
1339 final Variable vo1 = smapper.pushT(vi1.getType());
1341 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1342 vo1, vi1, vo2, vi2, vo3, vo1);
1344 final Variable vi3 = smapper.pop(this);
1345 final Variable vo4 = smapper.pushT(vi1.getType());
1346 final Variable vo3 = smapper.pushT(vi3.getType());
1347 final Variable vo2 = smapper.pushT(vi2.getType());
1348 final Variable vo1 = smapper.pushT(vi1.getType());
1350 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1351 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1356 final Variable vi1 = smapper.pop(this);
1357 final Variable vi2 = smapper.pop(this);
1359 if (vi1.isCategory2()) {
1360 if (vi2.isCategory2()) {
1361 final Variable vo3 = smapper.pushT(vi1.getType());
1362 final Variable vo2 = smapper.pushT(vi2.getType());
1363 final Variable vo1 = smapper.pushT(vi1.getType());
1365 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1366 vo1, vi1, vo2, vi2, vo3, vo1);
1368 final Variable vi3 = smapper.pop(this);
1369 final Variable vo4 = smapper.pushT(vi1.getType());
1370 final Variable vo3 = smapper.pushT(vi3.getType());
1371 final Variable vo2 = smapper.pushT(vi2.getType());
1372 final Variable vo1 = smapper.pushT(vi1.getType());
1374 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1375 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1378 final Variable vi3 = smapper.pop(this);
1380 if (vi3.isCategory2()) {
1381 final Variable vo5 = smapper.pushT(vi2.getType());
1382 final Variable vo4 = smapper.pushT(vi1.getType());
1383 final Variable vo3 = smapper.pushT(vi3.getType());
1384 final Variable vo2 = smapper.pushT(vi2.getType());
1385 final Variable vo1 = smapper.pushT(vi1.getType());
1387 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1388 vo1, vi1, vo2, vi2, vo3, vi3);
1389 emit(smapper, this, " @1 = @2, @3 = @4;",
1390 vo4, vo1, vo5, vo2);
1392 final Variable vi4 = smapper.pop(this);
1393 final Variable vo6 = smapper.pushT(vi2.getType());
1394 final Variable vo5 = smapper.pushT(vi1.getType());
1395 final Variable vo4 = smapper.pushT(vi4.getType());
1396 final Variable vo3 = smapper.pushT(vi3.getType());
1397 final Variable vo2 = smapper.pushT(vi2.getType());
1398 final Variable vo1 = smapper.pushT(vi1.getType());
1400 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1401 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1402 emit(smapper, this, " @1 = @2, @3 = @4;",
1403 vo5, vo1, vo6, vo2);
1409 final Variable vi1 = smapper.get(0);
1410 final Variable vi2 = smapper.get(1);
1412 if (vi1.getType() == vi2.getType()) {
1413 final Variable tmp = smapper.pushT(vi1.getType());
1415 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1420 smapper.pushT(vi1.getType());
1421 smapper.pushT(vi2.getType());
1426 smapper.assign(this, VarType.INTEGER,
1427 "(" + Integer.toString(byteCodes[++i]) + ")");
1430 smapper.assign(this, VarType.INTEGER,
1431 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1435 case opc_getfield: {
1436 int indx = readUShortArg(byteCodes, i);
1437 String[] fi = jc.getFieldInfoName(indx);
1438 final int type = VarType.fromFieldType(fi[2].charAt(0));
1439 final String mangleClass = mangleClassName(fi[0]);
1440 final String mangleClassAccess = accessClassFalse(mangleClass);
1441 smapper.replace(this, type, "@2.call(@1)",
1443 accessField(mangleClassAccess,
1447 addReference(fi[0]);
1450 case opc_putfield: {
1451 int indx = readUShortArg(byteCodes, i);
1452 String[] fi = jc.getFieldInfoName(indx);
1453 final int type = VarType.fromFieldType(fi[2].charAt(0));
1454 final String mangleClass = mangleClassName(fi[0]);
1455 final String mangleClassAccess = accessClassFalse(mangleClass);
1456 emit(smapper, this, "@3.call(@2, @1);",
1459 accessField(mangleClassAccess,
1462 addReference(fi[0]);
1465 case opc_getstatic: {
1466 int indx = readUShortArg(byteCodes, i);
1467 String[] fi = jc.getFieldInfoName(indx);
1468 final int type = VarType.fromFieldType(fi[2].charAt(0));
1469 String ac = accessClassFalse(mangleClassName(fi[0]));
1470 String af = accessField(ac, "_" + fi[1], fi);
1471 smapper.assign(this, type, af + "()");
1473 addReference(fi[0]);
1476 case opc_putstatic: {
1477 int indx = readUShortArg(byteCodes, i);
1478 String[] fi = jc.getFieldInfoName(indx);
1479 final int type = VarType.fromFieldType(fi[2].charAt(0));
1480 emit(smapper, this, "@1._@2(@3);",
1481 accessClassFalse(mangleClassName(fi[0])), fi[1],
1482 smapper.popT(type));
1484 addReference(fi[0]);
1487 case opc_checkcast: {
1488 int indx = readUShortArg(byteCodes, i);
1489 generateCheckcast(indx, smapper);
1493 case opc_instanceof: {
1494 int indx = readUShortArg(byteCodes, i);
1495 generateInstanceOf(indx, smapper);
1500 final CharSequence v = smapper.popA();
1503 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1504 smapper.pushA(), v);
1508 case opc_monitorenter: {
1509 debug("/* monitor enter */");
1514 case opc_monitorexit: {
1515 debug("/* monitor exit */");
1526 emit(smapper, this, "throw 'unknown bytecode @1';",
1527 Integer.toString(c));
1531 generateByteCodeComment(prev, i, byteCodes);
1537 if (previousTrap != null) {
1538 generateCatch(previousTrap, flow, byteCodes.length, topMostLabel);
1543 while (openBraces-- > 0) {
1554 private int generateIf(StackMapper mapper, Flow flow, byte[] byteCodes, int i, final CharSequence v2, final CharSequence v1, final String test, int topMostLabel) throws IOException {
1556 int indx = i + readShortArg(byteCodes, i);
1557 append("if ((").append(v1)
1558 .append(") ").append(test).append(" (")
1559 .append(v2).append(")) ");
1560 goTo(this, flow, i, indx, topMostLabel);
1564 private int readInt4(byte[] byteCodes, int offset) {
1565 final int d = byteCodes[offset + 0] << 24;
1566 final int c = byteCodes[offset + 1] << 16;
1567 final int b = byteCodes[offset + 2] << 8;
1568 final int a = byteCodes[offset + 3];
1569 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1571 private static int readUByte(byte[] byteCodes, int offset) {
1572 return byteCodes[offset] & 0xff;
1575 private static int readUShort(byte[] byteCodes, int offset) {
1576 return ((byteCodes[offset] & 0xff) << 8)
1577 | (byteCodes[offset + 1] & 0xff);
1579 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1580 return readUShort(byteCodes, offsetInstruction + 1);
1583 private static int readShort(byte[] byteCodes, int offset) {
1584 int signed = byteCodes[offset];
1585 byte b0 = (byte)signed;
1586 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1588 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1589 return readShort(byteCodes, offsetInstruction + 1);
1592 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1594 Boolean count = null;
1595 boolean array = false;
1597 int firstPos = sig.length();
1598 while (i < descriptor.length()) {
1599 char ch = descriptor.charAt(i++);
1620 if (ch == 'J' || ch == 'D') {
1626 sig.insert(firstPos, ch);
1628 returnType[0] = '[';
1629 sig.insert(firstPos, "_3");
1638 returnType[0] = 'V';
1639 sig.insert(firstPos, 'V');
1642 int next = descriptor.indexOf(';', i);
1643 String realSig = mangleSig(descriptor, i - 1, next + 1);
1648 sig.append(realSig);
1651 sig.insert(firstPos, realSig);
1653 sig.insert(firstPos, "_3");
1655 returnType[0] = 'L';
1664 throw new IllegalStateException("Invalid char: " + ch);
1669 static String mangleSig(String sig) {
1670 return mangleSig(sig, 0, sig.length());
1673 private static String mangleMethodName(String name) {
1674 StringBuilder sb = new StringBuilder(name.length() * 2);
1675 int last = name.length();
1676 for (int i = 0; i < last; i++) {
1677 final char ch = name.charAt(i);
1679 case '_': sb.append("_1"); break;
1680 default: sb.append(ch); break;
1683 return sb.toString();
1685 private static String mangleSig(String txt, int first, int last) {
1686 StringBuilder sb = new StringBuilder((last - first) * 2);
1687 for (int i = first; i < last; i++) {
1688 final char ch = txt.charAt(i);
1690 case '/': sb.append('_'); break;
1691 case '_': sb.append("_1"); break;
1692 case ';': sb.append("_2"); break;
1693 case '[': sb.append("_3"); break;
1695 if (Character.isJavaIdentifierPart(ch)) {
1699 String hex = Integer.toHexString(ch).toLowerCase();
1700 for (int m = hex.length(); m < 4; m++) {
1708 return sb.toString();
1711 private static String mangleClassName(String name) {
1712 return mangleSig(name);
1715 private static String findMethodName(MethodData m, StringBuilder cnt) {
1716 StringBuilder name = new StringBuilder();
1717 if ("<init>".equals(m.getName())) { // NOI18N
1718 name.append("cons"); // NOI18N
1719 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1720 name.append("class"); // NOI18N
1722 name.append(mangleMethodName(m.getName()));
1725 countArgs(m.getInternalSig(), new char[1], name, cnt);
1726 return name.toString();
1729 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1730 StringBuilder name = new StringBuilder();
1731 String descr = mi[2];//mi.getDescriptor();
1733 if ("<init>".equals(nm)) { // NOI18N
1734 name.append("cons"); // NOI18N
1736 name.append(mangleMethodName(nm));
1738 countArgs(descr, returnType, name, cnt);
1739 return name.toString();
1742 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1743 throws IOException {
1744 int methodIndex = readUShortArg(byteCodes, i);
1745 String[] mi = jc.getFieldInfoName(methodIndex);
1746 char[] returnType = { 'V' };
1747 StringBuilder cnt = new StringBuilder();
1748 String mn = findMethodName(mi, cnt, returnType);
1750 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1751 final CharSequence[] vars = new CharSequence[numArguments];
1753 for (int j = numArguments - 1; j >= 0; --j) {
1754 vars[j] = mapper.popValue();
1758 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1759 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1761 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1762 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1764 if (vars[1] instanceof String) {
1765 String field = vars[1].toString();
1766 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1767 vars[1] = "c._" + field.substring(1, field.length() - 1);
1772 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1773 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1775 if (vars[1] instanceof String) {
1776 String field = vars[2].toString();
1777 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1778 vars[2] = "c._" + field.substring(1, field.length() - 1);
1783 if (returnType[0] != 'V') {
1786 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1790 final String in = mi[0];
1793 in.equals("org/apidesign/html/boot/spi/Fn") ||
1794 in.equals("org/netbeans/html/boot/spi/Fn")
1796 mcn = "java_lang_Class";
1798 mcn = mangleClassName(in);
1800 String object = accessClassFalse(mcn);
1801 if (mn.startsWith("cons_")) {
1802 object += ".constructor";
1804 append(accessStaticMethod(object, mn, mi));
1810 if (numArguments > 0) {
1812 for (int j = 1; j < numArguments; ++j) {
1822 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1823 throws IOException {
1824 int methodIndex = readUShortArg(byteCodes, i);
1825 String[] mi = jc.getFieldInfoName(methodIndex);
1826 char[] returnType = { 'V' };
1827 StringBuilder cnt = new StringBuilder();
1828 String mn = findMethodName(mi, cnt, returnType);
1830 final int numArguments = cnt.length() + 1;
1831 final CharSequence[] vars = new CharSequence[numArguments];
1833 for (int j = numArguments - 1; j >= 0; --j) {
1834 vars[j] = mapper.popValue();
1837 if (returnType[0] != 'V') {
1840 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1844 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1846 for (int j = 1; j < numArguments; ++j) {
1856 private void addReference(String cn) throws IOException {
1857 if (requireReference(cn)) {
1858 debug(" /* needs " + cn + " */");
1862 private void outType(String d, StringBuilder out) {
1864 while (d.charAt(0) == '[') {
1868 if (d.charAt(0) == 'L') {
1869 assert d.charAt(d.length() - 1) == ';';
1870 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1876 private String encodeConstant(int entryIndex) throws IOException {
1877 String[] classRef = { null };
1878 String s = jc.stringValue(entryIndex, classRef);
1879 if (classRef[0] != null) {
1880 if (classRef[0].startsWith("[")) {
1881 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1883 addReference(classRef[0]);
1884 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1890 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1891 byte[] arr = m.findAnnotationData(true);
1895 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1896 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1897 class P extends AnnotationParser {
1903 String[] args = new String[30];
1909 protected void visitAttr(String type, String attr, String at, String value) {
1910 if (type.equals(jvmType)) {
1911 if ("body".equals(attr)) {
1913 } else if ("args".equals(attr)) {
1914 args[cnt++] = value;
1916 throw new IllegalArgumentException(attr);
1919 if (type.equals(htmlType)) {
1921 if ("body".equals(attr)) {
1923 } else if ("args".equals(attr)) {
1924 args[cnt++] = value;
1925 } else if ("javacall".equals(attr)) {
1926 javacall = "1".equals(value);
1927 } else if ("wait4js".equals(attr)) {
1928 // ignore, we always invoke synchronously
1930 throw new IllegalArgumentException(attr);
1937 if (p.body == null) {
1940 StringBuilder cnt = new StringBuilder();
1941 final String mn = findMethodName(m, cnt);
1942 append("m = ").append(destObject).append(".").append(mn);
1943 append(" = function(");
1946 StringBuilder toValue = new StringBuilder();
1947 for (int i = 0; i < cnt.length(); i++) {
1949 space = outputArg(this, p.args, index);
1950 if (p.html4j && space.length() > 0) {
1951 toValue.append("\n ").append(p.args[index]).append(" = ")
1952 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1953 append(p.args[index]).append(");");
1957 append(") {").append("\n");
1958 append(toValue.toString());
1960 int lastSlash = jc.getClassName().lastIndexOf('/');
1961 final String pkg = jc.getClassName().substring(0, lastSlash);
1962 append(mangleCallbacks(pkg, p.body));
1963 requireReference(pkg + "/$JsCallbacks$");
1971 private static CharSequence mangleCallbacks(String pkgName, String body) {
1972 StringBuilder sb = new StringBuilder();
1975 int next = body.indexOf(".@", pos);
1977 sb.append(body.substring(pos));
1978 body = sb.toString();
1983 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1988 String refId = body.substring(ident, next);
1990 sb.append(body.substring(pos, ident));
1992 int sigBeg = body.indexOf('(', next);
1993 int sigEnd = body.indexOf(')', sigBeg);
1994 int colon4 = body.indexOf("::", next);
1995 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1996 throw new IllegalStateException("Malformed body " + body);
1998 String fqn = body.substring(next + 2, colon4);
1999 String method = body.substring(colon4 + 2, sigBeg);
2000 String params = body.substring(sigBeg, sigEnd + 1);
2002 int paramBeg = body.indexOf('(', sigEnd + 1);
2004 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2005 sb.append(mangleJsCallbacks(fqn, method, params, false));
2006 sb.append("(").append(refId);
2007 if (body.charAt(paramBeg + 1) != ')') {
2015 int next = body.indexOf("@", pos);
2020 sb.append(body.substring(pos));
2024 sb = new StringBuilder();
2027 sb.append(body.substring(pos, next));
2029 int sigBeg = body.indexOf('(', next);
2030 int sigEnd = body.indexOf(')', sigBeg);
2031 int colon4 = body.indexOf("::", next);
2032 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2033 throw new IllegalStateException("Malformed body " + body);
2035 String fqn = body.substring(next + 1, colon4);
2036 String method = body.substring(colon4 + 2, sigBeg);
2037 String params = body.substring(sigBeg, sigEnd + 1);
2039 int paramBeg = body.indexOf('(', sigEnd + 1);
2041 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2042 sb.append(mangleJsCallbacks(fqn, method, params, true));
2048 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2049 if (params.startsWith("(")) {
2050 params = params.substring(1);
2052 if (params.endsWith(")")) {
2053 params = params.substring(0, params.length() - 1);
2055 StringBuilder sb = new StringBuilder();
2056 final String fqnu = fqn.replace('.', '_');
2057 final String rfqn = mangleClassName(fqnu);
2058 final String rm = mangleMethodName(method);
2061 StringBuilder pb = new StringBuilder();
2062 int len = params.length();
2064 while (indx < len) {
2065 char ch = params.charAt(indx);
2066 if (ch == '[' || ch == 'L') {
2067 int column = params.indexOf(';', indx) + 1;
2068 if (column > indx) {
2069 String real = params.substring(indx, column);
2070 if ("Ljava/lang/String;".equals(real)) {
2071 pb.append("Ljava/lang/String;");
2076 pb.append("Ljava/lang/Object;");
2083 srp = mangleSig(pb.toString());
2085 final String rp = mangleSig(params);
2086 final String mrp = mangleMethodName(rp);
2087 sb.append(rfqn).append("$").append(rm).
2088 append('$').append(mrp).append("__Ljava_lang_Object_2");
2090 sb.append('L').append(fqnu).append("_2");
2093 return sb.toString();
2096 private static String className(ClassData jc) {
2097 //return jc.getName().getInternalName().replace('/', '_');
2098 return mangleClassName(jc.getClassName());
2101 private static String[] findAnnotation(
2102 byte[] arr, ClassData cd, final String className,
2103 final String... attrNames
2104 ) throws IOException {
2108 final String[] values = new String[attrNames.length];
2109 final boolean[] found = { false };
2110 final String jvmType = "L" + className.replace('.', '/') + ";";
2111 AnnotationParser ap = new AnnotationParser(false, true) {
2113 protected void visitAttr(String type, String attr, String at, String value) {
2114 if (type.equals(jvmType)) {
2116 for (int i = 0; i < attrNames.length; i++) {
2117 if (attrNames[i].equals(attr)) {
2126 return found[0] ? values : null;
2129 private CharSequence initField(FieldData v) {
2130 final String is = v.getInternalSig();
2131 if (is.length() == 1) {
2132 switch (is.charAt(0)) {
2138 case 'I': return " = 0;";
2140 case 'D': return " = 0.0;";
2142 throw new IllegalStateException(is);
2148 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2149 AnnotationParser ap = new AnnotationParser(true, false) {
2150 int[] cnt = new int[32];
2154 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2155 final String slashType = attrType.substring(1, attrType.length() - 1);
2156 requireReference(slashType);
2158 if (cnt[depth]++ > 0) {
2162 append('"').append(attrType).append("\" : ");
2169 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2175 protected void visitValueStart(String attrName, char type) throws IOException {
2176 if (cnt[depth]++ > 0) {
2180 if (attrName != null) {
2181 append('"').append(attrName).append("\" : ");
2189 protected void visitValueEnd(String attrName, char type) throws IOException {
2197 protected void visitAttr(String type, String attr, String attrType, String value)
2198 throws IOException {
2199 if (attr == null && value == null) {
2206 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2207 throws IOException {
2208 final String slashType = attrType.substring(1, attrType.length() - 1);
2209 requireReference(slashType);
2211 final String cn = mangleClassName(slashType);
2212 append(accessClassFalse(cn))
2213 .append("['valueOf__L").
2215 append("_2Ljava_lang_String_2']('").
2223 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2224 final String name = args[indx];
2228 if (name.contains(",")) {
2229 throw new IOException("Wrong parameter with ',': " + name);
2235 final void emitNoFlush(
2237 final String format, final CharSequence... params
2238 ) throws IOException {
2239 emitImpl(this, format, params);
2241 static final void emit(
2243 final Appendable out,
2244 final String format, final CharSequence... params
2245 ) throws IOException {
2247 emitImpl(out, format, params);
2249 static void emitImpl(final Appendable out,
2250 final String format,
2251 final CharSequence... params) throws IOException {
2252 final int length = format.length();
2255 int paramOffset = format.indexOf('@');
2256 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2257 final char paramChar = format.charAt(paramOffset + 1);
2258 if ((paramChar >= '1') && (paramChar <= '9')) {
2259 final int paramIndex = paramChar - '0' - 1;
2261 out.append(format, processed, paramOffset);
2262 out.append(params[paramIndex]);
2265 processed = paramOffset + 1;
2268 paramOffset = format.indexOf('@', paramOffset + 1);
2271 out.append(format, processed, length);
2274 private void generateCatch(TrapData[] traps, Flow flow, int current, int topMostLabel) throws IOException {
2275 append("} catch (e) {\n");
2277 for (TrapData e : traps) {
2281 if (e.catch_cpx != 0) { //not finally
2282 final String classInternalName = jc.getClassName(e.catch_cpx);
2283 addReference(classInternalName);
2284 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2285 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2286 append("var stA0 = e;");
2287 goTo(this, flow, current, e.handler_pc, topMostLabel);
2290 finallyPC = e.handler_pc;
2293 if (finallyPC == -1) {
2296 append("var stA0 = e;");
2297 goTo(this, flow, current, finallyPC, topMostLabel);
2302 private static void goTo(Appendable out, Flow flow, int current, int to, int canBack) throws IOException {
2305 out.append("{ gt = 0; continue X_" + to + "; }");
2307 out.append("{ gt = " + to + "; continue X_0; }");
2310 out.append("{ gt = " + to + "; break IF; }");
2314 private static void emitIf(
2315 StackMapper sm, Flow flow, Appendable out, String pattern, CharSequence param, int current, int to, int canBack
2316 ) throws IOException {
2318 emitImpl(out, pattern, param);
2319 goTo(out, flow, current, to, canBack);
2322 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2325 case 4: jvmType = "[Z"; break;
2326 case 5: jvmType = "[C"; break;
2327 case 6: jvmType = "[F"; break;
2328 case 7: jvmType = "[D"; break;
2329 case 8: jvmType = "[B"; break;
2330 case 9: jvmType = "[S"; break;
2331 case 10: jvmType = "[I"; break;
2332 case 11: jvmType = "[J"; break;
2333 default: throw new IllegalStateException("Array type: " + atype);
2336 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2337 smapper.popI(), smapper.pushA(), jvmType);
2340 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2341 String typeName = jc.getClassName(type);
2342 String ref = "null";
2343 if (typeName.startsWith("[")) {
2344 typeName = "'[" + typeName + "'";
2346 ref = "vm." + mangleClassName(typeName);
2347 typeName = "'[L" + typeName + ";'";
2350 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2351 smapper.popI(), smapper.pushA(), typeName, ref);
2354 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2355 String typeName = jc.getClassName(type);
2356 int dim = readUByte(byteCodes, ++i);
2357 StringBuilder dims = new StringBuilder();
2359 for (int d = 0; d < dim; d++) {
2361 dims.insert(1, ",");
2363 dims.insert(1, smapper.popI());
2367 if (typeName.charAt(dim) == 'L') {
2368 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2371 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2372 dims.toString(), smapper.pushA(), typeName, fn
2377 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, Flow flow, int topMostLabel) throws IOException {
2378 int table = i / 4 * 4 + 4;
2379 int dflt = i + readInt4(byteCodes, table);
2381 int low = readInt4(byteCodes, table);
2383 int high = readInt4(byteCodes, table);
2385 final CharSequence swVar = smapper.popValue();
2386 smapper.flush(this);
2387 append("switch (").append(swVar).append(") {\n");
2388 while (low <= high) {
2389 int offset = i + readInt4(byteCodes, table);
2391 append(" case " + low).append(":"); goTo(this, flow, i, offset, topMostLabel); append('\n');
2394 append(" default: ");
2395 goTo(this, flow, i, dflt, topMostLabel);
2401 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, Flow flow, int topMostLabel) throws IOException {
2402 int table = i / 4 * 4 + 4;
2403 int dflt = i + readInt4(byteCodes, table);
2405 int n = readInt4(byteCodes, table);
2407 final CharSequence swVar = smapper.popValue();
2408 smapper.flush(this);
2409 append("switch (").append(swVar).append(") {\n");
2411 int cnstnt = readInt4(byteCodes, table);
2413 int offset = i + readInt4(byteCodes, table);
2415 append(" case " + cnstnt).append(": "); goTo(this, flow, i, offset, topMostLabel); append('\n');
2417 append(" default: ");
2418 goTo(this, flow, i, dflt, topMostLabel);
2424 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2425 String type = jc.getClassName(indx);
2426 if (!type.startsWith("[")) {
2428 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2429 smapper.popA(), smapper.pushI(),
2430 type.replace('/', '_'));
2433 while (type.charAt(cnt) == '[') {
2436 if (type.charAt(cnt) == 'L') {
2437 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2439 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2440 smapper.popA(), smapper.pushI(),
2445 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2446 smapper.popA(), smapper.pushI(), type
2452 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2453 String type = jc.getClassName(indx);
2454 if (!type.startsWith("[")) {
2455 emitNoFlush(smapper,
2456 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2457 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2460 while (type.charAt(cnt) == '[') {
2463 if (type.charAt(cnt) == 'L') {
2464 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2465 emitNoFlush(smapper,
2466 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2467 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2470 emitNoFlush(smapper,
2471 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2472 smapper.getT(0, VarType.REFERENCE, false), type
2478 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2479 for (int j = prev; j <= i; j++) {
2481 final int cc = readUByte(byteCodes, j);
2482 append(Integer.toString(cc));
2486 @JavaScriptBody(args = "msg", body = "")
2487 private static void println(String msg) {
2488 System.err.println(msg);
2491 protected Flow checkFlow(MethodData byteCodes) throws IOException {