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;
44 private final NumberOperations numbers = new NumberOperations();
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 (mangleClassName(jc.getClassName()).equals(classOperation)) {
103 classRefs.addIfMissing(classOperation);
104 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
107 protected FieldData findField(String[] fieldInfoName) throws IOException {
111 protected String accessField(String object, FieldData data, String[] fieldInfoName)
113 String mangledName = "_" + fieldInfoName[1];
114 return object + "." + mangledName;
117 protected String accessStaticMethod(
120 String[] fieldInfoName) throws IOException {
121 return object + "." + mangledName;
124 protected String accessVirtualMethod(
127 String[] fieldInfoName,
129 ) throws IOException {
130 return object + "." + mangledName + '(';
133 protected void declareClass(ClassData classData, String mangledName)
138 protected void declaredField(FieldData fieldData,
140 String mangledName) throws IOException {
143 protected void declaredMethod(MethodData methodData,
145 String mangledName) throws IOException {
148 /** Prints out a debug message.
150 * @param msg the message
151 * @return true if the message has been printed
152 * @throws IOException
154 boolean debug(String msg) throws IOException {
160 * Converts a given class file to a JavaScript version.
162 * @param classFile input stream with code of the .class file
163 * @return the initialization code for this class, if any. Otherwise <code>null</code>
165 * @throws IOException if something goes wrong during read or write or translating
168 public String compile(InputStream classFile) throws IOException {
169 return compile(new ClassData(classFile));
172 protected String compile(ClassData classData) throws IOException {
174 final String cn = this.jc.getClassName();
176 return compileImpl(cn);
177 } catch (IOException ex) {
178 throw new IOException("Cannot compile " + cn + ":", ex);
182 private String compileImpl(final String cn) throws IOException {
183 this.numbers.reset();
184 this.callbacks = cn.endsWith("/$JsCallbacks$");
185 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
186 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
187 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
190 byte[] arrData = jc.findAnnotationData(true);
192 String[] arr = findAnnotation(arrData, jc,
193 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
194 "resource", "processByteCode"
197 if (!arr[0].isEmpty()) {
198 requireScript(arr[0]);
200 if ("0".equals(arr[1])) {
205 final String jsResource;
207 String[] arr = findAnnotation(arrData, jc,
208 "net.java.html.js.JavaScriptResource",
212 if (arr[0].startsWith("/")) {
215 int last = cn.lastIndexOf('/');
216 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
222 String[] proto = findAnnotation(arrData, jc,
223 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
224 "container", "prototype"
226 StringArray toInitilize = new StringArray();
227 final String className = className(jc);
229 append("function ").append(className).append("() {");
231 append("\n var CLS = ").append(className).append(';');
232 append("\n if (!CLS.$class) {");
234 String sc = jc.getSuperClassName(); // with _
235 append("\n var pp = ").
236 append(accessClass(mangleClassName(sc))).append("(true);");
237 append("\n var p = CLS.prototype = pp;");
238 append("\n var c = p;");
239 append("\n var sprcls = pp.constructor.$class;");
241 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
242 if (proto[0] == null) {
245 append("\n var c = ").append(proto[0]).append(";");
246 append("\n var sprcls = null;");
248 for (FieldData v : jc.getFields()) {
250 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
251 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
255 append("\n CLS['fld_").append(v.getName()).append("']").append(initField(v));
256 append("\n m = c._").append(v.getName()).append(" = function (v) {")
257 .append(" if (arguments.length == 1) CLS['fld_").append(v.getName())
258 .append("'] = v; return CLS['fld_").
259 append(v.getName()).append("']; };");
261 append("\n m = c._").append(v.getName()).append(" = function (v) {")
262 .append(" if (arguments.length == 1) this['fld_").
263 append(className).append('_').append(v.getName())
264 .append("'] = v; return this['fld_").
265 append(className).append('_').append(v.getName())
269 declaredField(v, "c", "_" + v.getName());
271 for (MethodData m : jc.getMethods()) {
272 byte[] onlyArr = m.findAnnotationData(true);
273 if (javaScriptOnly(onlyArr)) continue;
279 mn = generateStaticMethod(destObject, m, toInitilize);
281 if (m.isConstructor()) {
283 mn = generateInstanceMethod(destObject, m);
286 mn = generateInstanceMethod(destObject, m);
289 declaredMethod(m, destObject, mn);
290 byte[] runAnno = m.findAnnotationData(false);
291 if (runAnno != null) {
292 append("\n m.anno = {");
293 AnnotationParser ap = new GenerateAnno(true, false);
294 ap.parse(runAnno, jc);
297 append("\n m.access = " + m.getAccess()).append(";");
298 append("\n m.cls = CLS;");
300 append(numbers.generate());
301 append("\n c.constructor = CLS;");
302 append("\n function ").append(className).append("fillInstOf(x) {");
303 String instOfName = "$instOf_" + className;
304 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
305 if (jc.isInterface()) {
306 for (MethodData m : jc.getMethods()) {
307 if ((m.getAccess() & ACC_ABSTRACT) == 0
308 && (m.getAccess() & ACC_STATIC) == 0
309 && (m.getAccess() & ACC_PRIVATE) == 0) {
310 final String mn = findMethodName(m, new StringBuilder());
311 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
315 for (String superInterface : jc.getSuperInterfaces()) {
316 String intrfc = mangleClassName(superInterface);
317 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
318 requireReference(superInterface);
321 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
322 append("\n ").append(className).append("fillInstOf(c);");
323 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
324 append("\n CLS.$class = 'temp';");
325 append("\n CLS.$class = ");
326 append(accessClass("java_lang_Class")).append("(true);");
327 append("\n CLS.$class.jvmName = '").append(cn).append("';");
328 append("\n CLS.$class.superclass = sprcls;");
329 append("\n CLS.$class.interfaces = function() { return [");
331 boolean first = true;
332 for (String intrfc : jc.getSuperInterfaces()) {
336 requireReference(intrfc);
337 String mangledIface = mangleClassName(intrfc);
339 append(accessClass(mangledIface)).append("(false).constructor.$class");
344 int flags = jc.getAccessFlags();
345 if (jc.hasEnclosingMethod()) {
348 append("\n CLS.$class.access = ").append(flags+";");
349 append("\n CLS.$class.cnstr = CLS;");
350 byte[] classAnno = jc.findAnnotationData(false);
351 if (classAnno != null) {
352 append("\n CLS.$class.anno = {");
353 AnnotationParser ap = new GenerateAnno(true, false);
354 ap.parse(classAnno, jc);
357 for (String init : toInitilize.toArray()) {
358 append("\n ").append(init).append("();");
360 for (String ref : classRefs.toArray()) {
361 append("\n var refs_").append(ref).append(";");
365 if (jsResource != null) {
366 requireResource(jsResource);
370 append("\n if (arguments.length === 0) {");
371 append("\n if (!(this instanceof CLS)) {");
372 append("\n return new CLS();");
374 for (FieldData v : jc.getFields()) {
375 byte[] onlyArr = v.findAnnotationData(true);
376 if (javaScriptOnly(onlyArr)) continue;
378 append("\n this['fld_").
379 append(className).append('_').
380 append(v.getName()).append("']").append(initField(v));
383 append("\n return this;");
385 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
388 append("\n").append(assignClass(className));
389 declareClass(jc, className);
392 // StringBuilder sb = new StringBuilder();
393 // for (String init : toInitilize.toArray()) {
394 // sb.append("\n").append(init).append("();");
399 private boolean javaScriptOnly(byte[] anno) throws IOException {
400 String[] only = findAnnotation(anno, jc,
401 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
405 if (only[0] != null && only[1] != null) {
406 append("\n p.").append(only[0]).append(" = ")
407 .append(only[1]).append(";");
409 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
410 append("\n p['").append(only[0]).append("'] = p.")
411 .append(only[0]).append(";");
417 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
418 String jsb = javaScriptBody(destObject, m, true);
422 final String mn = findMethodName(m, new StringBuilder());
423 boolean defineProp = generateMethod(destObject, mn, m);
424 if (mn.equals("class__V")) {
426 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
428 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
434 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
435 String jsb = javaScriptBody(destObject, m, false);
439 final String mn = findMethodName(m, new StringBuilder());
440 generateMethod(destObject, mn, m);
444 private boolean generateMethod(String destObject, String name, MethodData m)
446 final StackMapIterator stackMapIterator = m.createStackMapIterator();
447 TrapDataIterator trap = m.getTrapDataIterator();
448 final LocalsMapper lmapper =
449 new LocalsMapper(stackMapIterator.getArguments());
452 "java/lang/Object".equals(jc.getClassName()) ||
453 "java/lang/reflect/Array".equals(jc.getClassName());
456 append("Object.defineProperty(").append(destObject).
457 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
459 append("m = ").append(destObject).append(".").append(name).append(" = function(");
461 lmapper.outputArguments(this, m.isStatic());
462 append(") {").append("\n");
464 final byte[] byteCodes = m.getCode();
465 if (byteCodes == null) {
466 byte[] defaultAttr = m.getDefaultAttribute();
467 if (defaultAttr != null) {
469 AnnotationParser ap = new GenerateAnno(true, false);
470 ap.parseDefault(defaultAttr, jc);
473 if (debug(" throw 'no code found for ")) {
475 .append(jc.getClassName()).append('.')
476 .append(m.getName()).append("';\n");
487 final StackMapper smapper = new StackMapper();
490 append(" var ").append(" lcA0 = this;\n");
494 TrapData[] previousTrap = null;
495 boolean wide = false;
497 if (stackMapIterator.isEmpty()) {
503 append("\n var gt = 0;\n");
507 int topMostLabel = 0;
508 for (int i = 0; i < byteCodes.length; i++) {
511 stackMapIterator.advanceTo(i);
512 boolean changeInCatch = trap.advanceTo(i);
513 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
514 if (previousTrap != null) {
515 generateCatch(previousTrap, i, topMostLabel);
519 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
524 if (openBraces > 64) {
525 for (int c = 0; c < 64; c++) {
532 lastStackFrame = stackMapIterator.getFrameIndex();
533 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
534 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
535 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
537 changeInCatch = true;
539 debug(" /* " + i + " */ ");
541 if (changeInCatch && trap.useTry()) {
543 previousTrap = trap.current();
545 final int c = readUByte(byteCodes, i);
548 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
551 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
554 smapper.assign(this, VarType.LONG, lmapper.getL(0));
557 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
560 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
563 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
566 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
569 smapper.assign(this, VarType.LONG, lmapper.getL(1));
572 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
575 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
578 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
581 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
584 smapper.assign(this, VarType.LONG, lmapper.getL(2));
587 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
590 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
593 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
596 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
599 smapper.assign(this, VarType.LONG, lmapper.getL(3));
602 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
605 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
609 final int indx = wide ? readUShort(byteCodes, i++)
610 : readUByte(byteCodes, i);
612 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
617 final int indx = wide ? readUShort(byteCodes, i++)
618 : readUByte(byteCodes, i);
620 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
625 final int indx = wide ? readUShort(byteCodes, i++)
626 : readUByte(byteCodes, i);
628 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
633 final int indx = wide ? readUShort(byteCodes, i++)
634 : readUByte(byteCodes, i);
636 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
641 final int indx = wide ? readUShort(byteCodes, i++)
642 : readUByte(byteCodes, i);
644 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
649 final int indx = wide ? readUShort(byteCodes, i++)
650 : readUByte(byteCodes, i);
652 emit(smapper, this, "var @1 = @2;",
653 lmapper.setI(indx), smapper.popI());
658 final int indx = wide ? readUShort(byteCodes, i++)
659 : readUByte(byteCodes, i);
661 emit(smapper, this, "var @1 = @2;",
662 lmapper.setL(indx), smapper.popL());
667 final int indx = wide ? readUShort(byteCodes, i++)
668 : readUByte(byteCodes, i);
670 emit(smapper, this, "var @1 = @2;",
671 lmapper.setF(indx), smapper.popF());
676 final int indx = wide ? readUShort(byteCodes, i++)
677 : readUByte(byteCodes, i);
679 emit(smapper, this, "var @1 = @2;",
680 lmapper.setD(indx), smapper.popD());
685 final int indx = wide ? readUShort(byteCodes, i++)
686 : readUByte(byteCodes, i);
688 emit(smapper, this, "var @1 = @2;",
689 lmapper.setA(indx), smapper.popA());
693 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
696 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
699 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
702 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
705 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
708 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
711 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
714 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
717 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
720 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
723 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
726 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
729 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
732 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
735 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
738 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
741 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
744 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
747 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
750 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
753 smapper.replace(this, VarType.INTEGER, "(((@1) + (@2)) | 0)", smapper.getI(1), smapper.popI());
756 smapper.replace(this, VarType.LONG, numbers.add64(), 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) - (@2)) | 0)", smapper.getI(1), smapper.popI());
768 smapper.replace(this, VarType.LONG, numbers.sub64(), smapper.getL(1), smapper.popL());
771 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
774 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
777 smapper.replace(this, VarType.INTEGER, numbers.mul32(), smapper.getI(1), smapper.popI());
780 smapper.replace(this, VarType.LONG, numbers.mul64(), smapper.getL(1), smapper.popL());
783 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
786 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
789 smapper.replace(this, VarType.INTEGER, numbers.div32(),
790 smapper.getI(1), smapper.popI());
793 smapper.replace(this, VarType.LONG, numbers.div64(),
794 smapper.getL(1), smapper.popL());
797 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
800 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
803 smapper.replace(this, VarType.INTEGER, numbers.mod32(),
804 smapper.getI(1), smapper.popI());
807 smapper.replace(this, VarType.LONG, numbers.mod64(),
808 smapper.getL(1), smapper.popL());
811 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
814 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
817 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
820 smapper.replace(this, VarType.LONG, numbers.and64(), smapper.getL(1), smapper.popL());
823 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
826 smapper.replace(this, VarType.LONG, numbers.or64(), smapper.getL(1), smapper.popL());
829 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
832 smapper.replace(this, VarType.LONG, numbers.xor64(), smapper.getL(1), smapper.popL());
835 smapper.replace(this, VarType.INTEGER, "(-(@1) | 0)", smapper.getI(0));
838 smapper.replace(this, VarType.LONG, numbers.neg64(), smapper.getL(0));
841 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
844 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
847 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
850 smapper.replace(this, VarType.LONG, numbers.shl64(), smapper.getL(1), smapper.popI());
853 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
856 smapper.replace(this, VarType.LONG, numbers.shr64(), smapper.getL(1), smapper.popI());
859 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
862 smapper.replace(this, VarType.LONG, numbers.ushr64(), smapper.getL(1), smapper.popI());
866 final int varIndx = wide ? readUShort(byteCodes, i++)
867 : readUByte(byteCodes, i);
869 final int incrBy = wide ? readShort(byteCodes, i++)
873 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
875 emit(smapper, this, "@1 += @2;",
876 lmapper.getI(varIndx),
877 Integer.toString(incrBy));
882 emit(smapper, this, "return;");
885 emit(smapper, this, "return @1;", smapper.popI());
888 emit(smapper, this, "return @1;", smapper.popL());
891 emit(smapper, this, "return @1;", smapper.popF());
894 emit(smapper, this, "return @1;", smapper.popD());
897 emit(smapper, this, "return @1;", smapper.popA());
900 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
903 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
906 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
909 smapper.replace(this, VarType.INTEGER, "((@1) | 0)", smapper.getL(0));
913 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
916 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
919 smapper.replace(this, VarType.DOUBLE, "@1",
923 smapper.replace(this, VarType.FLOAT, "@1",
927 smapper.replace(this, VarType.INTEGER, "((@1) | 0)",
931 smapper.replace(this, VarType.LONG, "(@1).toLong()",
935 smapper.replace(this, VarType.INTEGER, "((@1)| 0)",
939 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
942 smapper.replace(this, VarType.INTEGER, "(((@1) << 24) >> 24)", smapper.getI(0));
946 smapper.replace(this, VarType.INTEGER, "(((@1) << 16) >> 16)", smapper.getI(0));
948 case opc_aconst_null:
949 smapper.assign(this, VarType.REFERENCE, "null");
952 smapper.assign(this, VarType.INTEGER, "-1");
955 smapper.assign(this, VarType.INTEGER, "0");
958 smapper.assign(this, VarType.DOUBLE, "0");
961 smapper.assign(this, VarType.LONG, "0");
964 smapper.assign(this, VarType.FLOAT, "0");
967 smapper.assign(this, VarType.INTEGER, "1");
970 smapper.assign(this, VarType.LONG, "1");
973 smapper.assign(this, VarType.FLOAT, "1");
976 smapper.assign(this, VarType.DOUBLE, "1");
979 smapper.assign(this, VarType.INTEGER, "2");
982 smapper.assign(this, VarType.FLOAT, "2");
985 smapper.assign(this, VarType.INTEGER, "3");
988 smapper.assign(this, VarType.INTEGER, "4");
991 smapper.assign(this, VarType.INTEGER, "5");
994 int indx = readUByte(byteCodes, ++i);
995 String v = encodeConstant(indx);
996 int type = VarType.fromConstantType(jc.getTag(indx));
997 smapper.assign(this, type, v);
1002 int indx = readUShortArg(byteCodes, i);
1004 String v = encodeConstant(indx);
1005 int type = VarType.fromConstantType(jc.getTag(indx));
1006 if (type == VarType.LONG) {
1007 final Long lv = new Long(v);
1008 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
1009 final int hi = (int)(lv.longValue() >> 32);
1011 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
1013 smapper.assign(this, VarType.LONG,
1014 "0x" + Integer.toHexString(hi) + ".next32(0x" +
1015 Integer.toHexString(low) + ")"
1019 smapper.assign(this, type, v);
1024 smapper.replace(this, VarType.INTEGER, numbers.compare64(), smapper.popL(), smapper.getL(0));
1028 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1029 smapper.popF(), smapper.popF(), smapper.pushI());
1033 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1034 smapper.popD(), smapper.popD(), smapper.pushI());
1037 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1038 "===", topMostLabel);
1041 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1042 "!==", topMostLabel);
1045 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1046 "==", topMostLabel);
1049 int indx = i + readShortArg(byteCodes, i);
1050 emitIf(smapper, this, "if ((@1) == 0) ",
1051 smapper.popI(), i, indx, topMostLabel);
1056 int indx = i + readShortArg(byteCodes, i);
1057 emitIf(smapper, this, "if ((@1) != 0) ",
1058 smapper.popI(), i, indx, topMostLabel);
1063 int indx = i + readShortArg(byteCodes, i);
1064 emitIf(smapper, this, "if ((@1) < 0) ",
1065 smapper.popI(), i, indx, topMostLabel);
1070 int indx = i + readShortArg(byteCodes, i);
1071 emitIf(smapper, this, "if ((@1) <= 0) ",
1072 smapper.popI(), i, indx, topMostLabel);
1077 int indx = i + readShortArg(byteCodes, i);
1078 emitIf(smapper, this, "if ((@1) > 0) ",
1079 smapper.popI(), i, indx, topMostLabel);
1084 int indx = i + readShortArg(byteCodes, i);
1085 emitIf(smapper, this, "if ((@1) >= 0) ",
1086 smapper.popI(), i, indx, topMostLabel);
1090 case opc_ifnonnull: {
1091 int indx = i + readShortArg(byteCodes, i);
1092 emitIf(smapper, this, "if ((@1) !== null) ",
1093 smapper.popA(), i, indx, topMostLabel);
1098 int indx = i + readShortArg(byteCodes, i);
1099 emitIf(smapper, this, "if ((@1) === null) ",
1100 smapper.popA(), i, indx, topMostLabel);
1105 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1106 "!=", topMostLabel);
1109 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1113 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1114 "<=", topMostLabel);
1117 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1121 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1122 ">=", topMostLabel);
1125 smapper.flush(this);
1126 int indx = i + readShortArg(byteCodes, i);
1127 goTo(this, i, indx, topMostLabel);
1131 case opc_lookupswitch: {
1132 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1135 case opc_tableswitch: {
1136 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1139 case opc_invokeinterface: {
1140 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1143 case opc_invokevirtual:
1144 i = invokeVirtualMethod(byteCodes, i, smapper);
1146 case opc_invokespecial:
1147 i = invokeStaticMethod(byteCodes, i, smapper, false);
1149 case opc_invokestatic:
1150 i = invokeStaticMethod(byteCodes, i, smapper, true);
1152 case opc_invokedynamic: {
1153 int indx = readUShortArg(byteCodes, i);
1154 println("invoke dynamic: " + indx);
1155 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1156 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1157 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1158 println(" type: " + methodHandle.cpx1);
1159 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1160 String mcn = mangleClassName(mi[0]);
1161 char[] returnType = {'V'};
1162 StringBuilder cnt = new StringBuilder();
1163 String mn = findMethodName(mi, cnt, returnType);
1164 StringBuilder sb = new StringBuilder();
1165 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1166 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1167 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1168 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1169 sb.append(" mn : ").append(mn).append("\n");
1170 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1171 throw new IOException(sb.toString());
1173 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1174 String type = jc.StringValue(nameAndType.cpx2);
1175 String object = accessClass(mcn) + "(false)";
1176 if (mn.startsWith("cons_")) {
1177 object += ".constructor";
1179 append("var metHan = ");
1180 append(accessStaticMethod(object, mn, mi));
1182 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1184 append(", '").append(mi[1]).append("', ");
1185 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1186 append(methodType).append("'").append(type).append("', null)");
1187 // if (numArguments > 0) {
1189 // for (int j = 1; j < numArguments; ++j) {
1195 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1201 int indx = readUShortArg(byteCodes, i);
1202 String ci = jc.getClassName(indx);
1203 emit(smapper, this, "var @1 = new @2;",
1204 smapper.pushA(), accessClass(mangleClassName(ci)));
1210 int atype = readUByte(byteCodes, ++i);
1211 generateNewArray(atype, smapper);
1213 case opc_anewarray: {
1214 int type = readUShortArg(byteCodes, i);
1216 generateANewArray(type, smapper);
1219 case opc_multianewarray: {
1220 int type = readUShortArg(byteCodes, i);
1222 i = generateMultiANewArray(type, byteCodes, i, smapper);
1225 case opc_arraylength:
1226 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1229 emit(smapper, this, "Array.at(@3, @2, @1);",
1230 smapper.popL(), smapper.popI(), smapper.popA());
1233 emit(smapper, this, "Array.at(@3, @2, @1);",
1234 smapper.popF(), smapper.popI(), smapper.popA());
1237 emit(smapper, this, "Array.at(@3, @2, @1);",
1238 smapper.popD(), smapper.popI(), smapper.popA());
1241 emit(smapper, this, "Array.at(@3, @2, @1);",
1242 smapper.popA(), smapper.popI(), smapper.popA());
1248 emit(smapper, this, "Array.at(@3, @2, @1);",
1249 smapper.popI(), smapper.popI(), smapper.popA());
1252 smapper.replace(this, VarType.LONG, "(@2[@1] || Array.at(@2, @1))",
1253 smapper.popI(), smapper.getA(0));
1256 smapper.replace(this, VarType.FLOAT, "(@2[@1] || Array.at(@2, @1))",
1257 smapper.popI(), smapper.getA(0));
1260 smapper.replace(this, VarType.DOUBLE, "(@2[@1] || Array.at(@2, @1))",
1261 smapper.popI(), smapper.getA(0));
1264 smapper.replace(this, VarType.REFERENCE, "(@2[@1] || Array.at(@2, @1))",
1265 smapper.popI(), smapper.getA(0));
1271 smapper.replace(this, VarType.INTEGER, "(@2[@1] || Array.at(@2, @1))",
1272 smapper.popI(), smapper.getA(0));
1280 final Variable v = smapper.get(0);
1281 if (smapper.isDirty()) {
1282 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1284 smapper.assign(this, v.getType(), v);
1289 final Variable vi1 = smapper.get(0);
1291 if (vi1.isCategory2()) {
1292 emit(smapper, this, "var @1 = @2;",
1293 smapper.pushT(vi1.getType()), vi1);
1295 final Variable vi2 = smapper.get(1);
1296 emit(smapper, this, "var @1 = @2, @3 = @4;",
1297 smapper.pushT(vi2.getType()), vi2,
1298 smapper.pushT(vi1.getType()), vi1);
1303 final Variable vi1 = smapper.pop(this);
1304 final Variable vi2 = smapper.pop(this);
1305 final Variable vo3 = smapper.pushT(vi1.getType());
1306 final Variable vo2 = smapper.pushT(vi2.getType());
1307 final Variable vo1 = smapper.pushT(vi1.getType());
1309 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1310 vo1, vi1, vo2, vi2, vo3, vo1);
1314 final Variable vi1 = smapper.pop(this);
1315 final Variable vi2 = smapper.pop(this);
1317 if (vi1.isCategory2()) {
1318 final Variable vo3 = smapper.pushT(vi1.getType());
1319 final Variable vo2 = smapper.pushT(vi2.getType());
1320 final Variable vo1 = smapper.pushT(vi1.getType());
1322 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1323 vo1, vi1, vo2, vi2, vo3, vo1);
1325 final Variable vi3 = smapper.pop(this);
1326 final Variable vo5 = smapper.pushT(vi2.getType());
1327 final Variable vo4 = smapper.pushT(vi1.getType());
1328 final Variable vo3 = smapper.pushT(vi3.getType());
1329 final Variable vo2 = smapper.pushT(vi2.getType());
1330 final Variable vo1 = smapper.pushT(vi1.getType());
1332 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1333 vo1, vi1, vo2, vi2, vo3, vi3);
1334 emit(smapper, this, " @1 = @2, @3 = @4;",
1335 vo4, vo1, vo5, vo2);
1340 final Variable vi1 = smapper.pop(this);
1341 final Variable vi2 = smapper.pop(this);
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);
1363 final Variable vi1 = smapper.pop(this);
1364 final Variable vi2 = smapper.pop(this);
1366 if (vi1.isCategory2()) {
1367 if (vi2.isCategory2()) {
1368 final Variable vo3 = smapper.pushT(vi1.getType());
1369 final Variable vo2 = smapper.pushT(vi2.getType());
1370 final Variable vo1 = smapper.pushT(vi1.getType());
1372 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1373 vo1, vi1, vo2, vi2, vo3, vo1);
1375 final Variable vi3 = smapper.pop(this);
1376 final Variable vo4 = smapper.pushT(vi1.getType());
1377 final Variable vo3 = smapper.pushT(vi3.getType());
1378 final Variable vo2 = smapper.pushT(vi2.getType());
1379 final Variable vo1 = smapper.pushT(vi1.getType());
1381 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1382 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1385 final Variable vi3 = smapper.pop(this);
1387 if (vi3.isCategory2()) {
1388 final Variable vo5 = smapper.pushT(vi2.getType());
1389 final Variable vo4 = smapper.pushT(vi1.getType());
1390 final Variable vo3 = smapper.pushT(vi3.getType());
1391 final Variable vo2 = smapper.pushT(vi2.getType());
1392 final Variable vo1 = smapper.pushT(vi1.getType());
1394 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1395 vo1, vi1, vo2, vi2, vo3, vi3);
1396 emit(smapper, this, " @1 = @2, @3 = @4;",
1397 vo4, vo1, vo5, vo2);
1399 final Variable vi4 = smapper.pop(this);
1400 final Variable vo6 = smapper.pushT(vi2.getType());
1401 final Variable vo5 = smapper.pushT(vi1.getType());
1402 final Variable vo4 = smapper.pushT(vi4.getType());
1403 final Variable vo3 = smapper.pushT(vi3.getType());
1404 final Variable vo2 = smapper.pushT(vi2.getType());
1405 final Variable vo1 = smapper.pushT(vi1.getType());
1407 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1408 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1409 emit(smapper, this, " @1 = @2, @3 = @4;",
1410 vo5, vo1, vo6, vo2);
1416 final Variable vi1 = smapper.get(0);
1417 final Variable vi2 = smapper.get(1);
1419 if (vi1.getType() == vi2.getType()) {
1420 final Variable tmp = smapper.pushT(vi1.getType());
1422 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1427 smapper.pushT(vi1.getType());
1428 smapper.pushT(vi2.getType());
1433 smapper.assign(this, VarType.INTEGER,
1434 "(" + Integer.toString(byteCodes[++i]) + ")");
1437 smapper.assign(this, VarType.INTEGER,
1438 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1442 case opc_getfield: {
1443 int indx = readUShortArg(byteCodes, i);
1444 String[] fi = jc.getFieldInfoName(indx);
1445 final int type = VarType.fromFieldType(fi[2].charAt(0));
1446 FieldData field = findField(fi);
1447 if (field == null) {
1448 final String mangleClass = mangleClassName(fi[0]);
1449 final String mangleClassAccess = accessClassFalse(mangleClass);
1450 smapper.replace(this, type, "@2.call(@1)",
1452 accessField(mangleClassAccess, null, fi)
1455 final String fieldOwner = mangleClassName(field.cls.getClassName());
1456 smapper.replace(this, type, "@1@2",
1458 accessField(fieldOwner, field, fi)
1462 addReference(fi[0]);
1465 case opc_putfield: {
1466 int indx = readUShortArg(byteCodes, i);
1467 String[] fi = jc.getFieldInfoName(indx);
1468 final int type = VarType.fromFieldType(fi[2].charAt(0));
1469 FieldData field = findField(fi);
1470 if (field == null) {
1471 final String mangleClass = mangleClassName(fi[0]);
1472 final String mangleClassAccess = accessClassFalse(mangleClass);
1473 emit(smapper, this, "@3.call(@2, @1);",
1476 accessField(mangleClassAccess, null, fi)
1479 final String fieldOwner = mangleClassName(field.cls.getClassName());
1480 emit(smapper, this, "@2@3 = @1;",
1483 accessField(fieldOwner, field, fi)
1487 addReference(fi[0]);
1490 case opc_getstatic: {
1491 int indx = readUShortArg(byteCodes, i);
1492 String[] fi = jc.getFieldInfoName(indx);
1493 final int type = VarType.fromFieldType(fi[2].charAt(0));
1494 String ac = accessClassFalse(mangleClassName(fi[0]));
1495 FieldData field = findField(fi);
1496 String af = accessField(ac, field, fi);
1497 smapper.assign(this, type, af + "()");
1499 addReference(fi[0]);
1502 case opc_putstatic: {
1503 int indx = readUShortArg(byteCodes, i);
1504 String[] fi = jc.getFieldInfoName(indx);
1505 final int type = VarType.fromFieldType(fi[2].charAt(0));
1506 emit(smapper, this, "@1._@2(@3);",
1507 accessClassFalse(mangleClassName(fi[0])), fi[1],
1508 smapper.popT(type));
1510 addReference(fi[0]);
1513 case opc_checkcast: {
1514 int indx = readUShortArg(byteCodes, i);
1515 generateCheckcast(indx, smapper);
1519 case opc_instanceof: {
1520 int indx = readUShortArg(byteCodes, i);
1521 generateInstanceOf(indx, smapper);
1526 final CharSequence v = smapper.popA();
1529 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1530 smapper.pushA(), v);
1534 case opc_monitorenter: {
1535 debug("/* monitor enter */");
1540 case opc_monitorexit: {
1541 debug("/* monitor exit */");
1552 emit(smapper, this, "throw 'unknown bytecode @1';",
1553 Integer.toString(c));
1557 generateByteCodeComment(prev, i, byteCodes);
1563 if (previousTrap != null) {
1564 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1569 while (openBraces-- > 0) {
1580 private int generateIf(StackMapper mapper, byte[] byteCodes,
1581 int i, final CharSequence v2, final CharSequence v1,
1582 final String test, int topMostLabel
1583 ) throws IOException {
1585 int indx = i + readShortArg(byteCodes, i);
1586 append("if ((").append(v1)
1587 .append(") ").append(test).append(" (")
1588 .append(v2).append(")) ");
1589 goTo(this, i, indx, topMostLabel);
1593 private int readInt4(byte[] byteCodes, int offset) {
1594 final int d = byteCodes[offset + 0] << 24;
1595 final int c = byteCodes[offset + 1] << 16;
1596 final int b = byteCodes[offset + 2] << 8;
1597 final int a = byteCodes[offset + 3];
1598 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1600 private static int readUByte(byte[] byteCodes, int offset) {
1601 return byteCodes[offset] & 0xff;
1604 private static int readUShort(byte[] byteCodes, int offset) {
1605 return ((byteCodes[offset] & 0xff) << 8)
1606 | (byteCodes[offset + 1] & 0xff);
1608 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1609 return readUShort(byteCodes, offsetInstruction + 1);
1612 private static int readShort(byte[] byteCodes, int offset) {
1613 int signed = byteCodes[offset];
1614 byte b0 = (byte)signed;
1615 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1617 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1618 return readShort(byteCodes, offsetInstruction + 1);
1621 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1623 Boolean count = null;
1624 boolean array = false;
1626 int firstPos = sig.length();
1627 while (i < descriptor.length()) {
1628 char ch = descriptor.charAt(i++);
1649 if (ch == 'J' || ch == 'D') {
1655 sig.insert(firstPos, ch);
1657 returnType[0] = '[';
1658 sig.insert(firstPos, "_3");
1667 returnType[0] = 'V';
1668 sig.insert(firstPos, 'V');
1671 int next = descriptor.indexOf(';', i);
1672 String realSig = mangleSig(descriptor, i - 1, next + 1);
1677 sig.append(realSig);
1680 sig.insert(firstPos, realSig);
1682 sig.insert(firstPos, "_3");
1684 returnType[0] = 'L';
1693 throw new IllegalStateException("Invalid char: " + ch);
1698 static String mangleSig(String sig) {
1699 return mangleSig(sig, 0, sig.length());
1702 private static String mangleMethodName(String name) {
1703 StringBuilder sb = new StringBuilder(name.length() * 2);
1704 int last = name.length();
1705 for (int i = 0; i < last; i++) {
1706 final char ch = name.charAt(i);
1708 case '_': sb.append("_1"); break;
1709 default: sb.append(ch); break;
1712 return sb.toString();
1714 private static String mangleSig(String txt, int first, int last) {
1715 StringBuilder sb = new StringBuilder((last - first) * 2);
1716 for (int i = first; i < last; i++) {
1717 final char ch = txt.charAt(i);
1719 case '/': sb.append('_'); break;
1720 case '_': sb.append("_1"); break;
1721 case ';': sb.append("_2"); break;
1722 case '[': sb.append("_3"); break;
1724 if (Character.isJavaIdentifierPart(ch)) {
1728 String hex = Integer.toHexString(ch).toLowerCase();
1729 for (int m = hex.length(); m < 4; m++) {
1737 return sb.toString();
1740 private static String mangleClassName(String name) {
1741 return mangleSig(name);
1744 private static String findMethodName(MethodData m, StringBuilder cnt) {
1745 StringBuilder name = new StringBuilder();
1746 if ("<init>".equals(m.getName())) { // NOI18N
1747 name.append("cons"); // NOI18N
1748 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1749 name.append("class"); // NOI18N
1751 name.append(mangleMethodName(m.getName()));
1754 countArgs(m.getInternalSig(), new char[1], name, cnt);
1755 return name.toString();
1758 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1759 StringBuilder name = new StringBuilder();
1760 String descr = mi[2];//mi.getDescriptor();
1762 if ("<init>".equals(nm)) { // NOI18N
1763 name.append("cons"); // NOI18N
1765 name.append(mangleMethodName(nm));
1767 countArgs(descr, returnType, name, cnt);
1768 return name.toString();
1771 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1772 throws IOException {
1773 int methodIndex = readUShortArg(byteCodes, i);
1774 String[] mi = jc.getFieldInfoName(methodIndex);
1775 char[] returnType = { 'V' };
1776 StringBuilder cnt = new StringBuilder();
1777 String mn = findMethodName(mi, cnt, returnType);
1779 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1780 final CharSequence[] vars = new CharSequence[numArguments];
1782 for (int j = numArguments - 1; j >= 0; --j) {
1783 vars[j] = mapper.popValue();
1787 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1788 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1790 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1791 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1793 if (vars[1] instanceof String) {
1794 String field = vars[1].toString();
1795 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1796 vars[1] = "c._" + field.substring(1, field.length() - 1);
1801 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1802 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1804 if (vars[1] instanceof String) {
1805 String field = vars[2].toString();
1806 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1807 vars[2] = "c._" + field.substring(1, field.length() - 1);
1812 if (returnType[0] != 'V') {
1815 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1819 final String in = mi[0];
1822 in.equals("org/apidesign/html/boot/spi/Fn") ||
1823 in.equals("org/netbeans/html/boot/spi/Fn")
1825 mcn = "java_lang_Class";
1826 } else if (in.startsWith("net/java/html/lib/") && in.endsWith("/Exports")) {
1831 mcn = mangleClassName(in);
1834 String object = accessClassFalse(mcn);
1835 if (mn.startsWith("cons_")) {
1836 object += ".constructor";
1838 append(accessStaticMethod(object, mn, mi));
1846 if (numArguments > 0) {
1848 for (int j = 1; j < numArguments; ++j) {
1857 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1858 throws IOException {
1859 int methodIndex = readUShortArg(byteCodes, i);
1860 String[] mi = jc.getFieldInfoName(methodIndex);
1861 char[] returnType = { 'V' };
1862 StringBuilder cnt = new StringBuilder();
1863 String mn = findMethodName(mi, cnt, returnType);
1865 final int numArguments = cnt.length() + 1;
1866 final CharSequence[] vars = new CharSequence[numArguments];
1868 for (int j = numArguments - 1; j >= 0; --j) {
1869 vars[j] = mapper.popValue();
1872 if (returnType[0] != 'V') {
1875 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1879 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1881 for (int j = 1; j < numArguments; ++j) {
1891 private void addReference(String cn) throws IOException {
1892 if (requireReference(cn)) {
1893 debug(" /* needs " + cn + " */");
1897 private void outType(String d, StringBuilder out) {
1899 while (d.charAt(0) == '[') {
1903 if (d.charAt(0) == 'L') {
1904 assert d.charAt(d.length() - 1) == ';';
1905 out.append(mangleClassName(d).substring(0, d.length() - 1));
1911 private String encodeConstant(int entryIndex) throws IOException {
1912 String[] classRef = { null };
1913 String s = jc.stringValue(entryIndex, classRef);
1914 if (classRef[0] != null) {
1915 if (classRef[0].startsWith("[")) {
1916 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1918 addReference(classRef[0]);
1919 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1925 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1926 byte[] arr = m.findAnnotationData(true);
1930 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1931 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1932 class P extends AnnotationParser {
1938 String[] args = new String[30];
1944 protected void visitAttr(String type, String attr, String at, String value) {
1945 if (type.equals(jvmType)) {
1946 if ("body".equals(attr)) {
1948 } else if ("args".equals(attr)) {
1949 args[cnt++] = value;
1951 throw new IllegalArgumentException(attr);
1954 if (type.equals(htmlType)) {
1956 if ("body".equals(attr)) {
1958 } else if ("args".equals(attr)) {
1959 args[cnt++] = value;
1960 } else if ("javacall".equals(attr)) {
1961 javacall = "1".equals(value);
1962 } else if ("wait4js".equals(attr)) {
1963 // ignore, we always invoke synchronously
1965 throw new IllegalArgumentException(attr);
1972 if (p.body == null) {
1975 StringBuilder cnt = new StringBuilder();
1976 final String mn = findMethodName(m, cnt);
1977 append("m = ").append(destObject).append(".").append(mn);
1978 append(" = function(");
1981 StringBuilder toValue = new StringBuilder();
1982 for (int i = 0; i < cnt.length(); i++) {
1984 space = outputArg(this, p.args, index);
1985 if (p.html4j && space.length() > 0) {
1986 toValue.append("\n ").append(p.args[index]).append(" = ")
1987 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1988 append(p.args[index]).append(");");
1992 append(") {").append("\n");
1993 append(toValue.toString());
1995 int lastSlash = jc.getClassName().lastIndexOf('/');
1996 final String pkg = jc.getClassName().substring(0, lastSlash);
1997 append(mangleCallbacks(pkg, p.body));
1998 requireReference(pkg + "/$JsCallbacks$");
2006 private CharSequence mangleCallbacks(String pkgName, String body) {
2007 StringBuilder sb = new StringBuilder();
2010 int next = body.indexOf(".@", pos);
2012 sb.append(body.substring(pos));
2013 body = sb.toString();
2018 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
2023 String refId = body.substring(ident, next);
2025 sb.append(body.substring(pos, ident));
2027 int sigBeg = body.indexOf('(', next);
2028 int sigEnd = body.indexOf(')', sigBeg);
2029 int colon4 = body.indexOf("::", next);
2030 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2031 throw new IllegalStateException("Malformed body " + body);
2033 String fqn = body.substring(next + 2, colon4);
2034 String method = body.substring(colon4 + 2, sigBeg);
2035 String params = body.substring(sigBeg, sigEnd + 1);
2037 int paramBeg = body.indexOf('(', sigEnd + 1);
2038 int paramEnd = closingParenthesis(body, paramBeg);
2040 sb.append(accessClass("java_lang_Class")).append("(false).toJS(");
2041 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2042 sb.append(mangleJsCallbacks(fqn, method, params, false));
2043 sb.append("(").append(refId);
2044 if (body.charAt(paramBeg + 1) != ')') {
2047 sb.append(body.substring(paramBeg + 1, paramEnd));
2054 int next = body.indexOf("@", pos);
2059 sb.append(body.substring(pos));
2063 sb = new StringBuilder();
2066 sb.append(body.substring(pos, next));
2068 int sigBeg = body.indexOf('(', next);
2069 int sigEnd = body.indexOf(')', sigBeg);
2070 int colon4 = body.indexOf("::", next);
2071 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2072 throw new IllegalStateException("Malformed body " + body);
2074 String fqn = body.substring(next + 1, colon4);
2075 String method = body.substring(colon4 + 2, sigBeg);
2076 String params = body.substring(sigBeg, sigEnd + 1);
2078 int paramBeg = body.indexOf('(', sigEnd + 1);
2079 int paramEnd = closingParenthesis(body, paramBeg);
2081 sb.append(accessClass("java_lang_Class")).append("(false).toJS(");
2082 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2083 sb.append(mangleJsCallbacks(fqn, method, params, true));
2085 sb.append(body.substring(paramBeg + 1, paramEnd));
2091 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2092 if (params.startsWith("(")) {
2093 params = params.substring(1);
2095 if (params.endsWith(")")) {
2096 params = params.substring(0, params.length() - 1);
2098 StringBuilder sb = new StringBuilder();
2099 final String fqnu = fqn.replace('.', '_');
2100 final String rfqn = mangleClassName(fqnu);
2101 final String rm = mangleMethodName(method);
2104 StringBuilder pb = new StringBuilder();
2105 int len = params.length();
2107 while (indx < len) {
2108 char ch = params.charAt(indx);
2109 if (ch == '[' || ch == 'L') {
2110 int column = params.indexOf(';', indx) + 1;
2111 if (column > indx) {
2112 String real = params.substring(indx, column);
2113 if ("Ljava/lang/String;".equals(real)) {
2114 pb.append("Ljava/lang/String;");
2119 pb.append("Ljava/lang/Object;");
2126 srp = mangleSig(pb.toString());
2128 final String rp = mangleSig(params);
2129 final String mrp = mangleMethodName(rp);
2130 sb.append(rfqn).append("$").append(rm).
2131 append('$').append(mrp).append("__Ljava_lang_Object_2");
2133 sb.append('L').append(fqnu).append("_2");
2136 return sb.toString();
2139 private static String className(ClassData jc) {
2140 //return jc.getName().getInternalName().replace('/', '_');
2141 return mangleClassName(jc.getClassName());
2144 private static String[] findAnnotation(
2145 byte[] arr, ClassData cd, final String className,
2146 final String... attrNames
2147 ) throws IOException {
2151 final String[] values = new String[attrNames.length];
2152 final boolean[] found = { false };
2153 final String jvmType = "L" + className.replace('.', '/') + ";";
2154 AnnotationParser ap = new AnnotationParser(false, true) {
2156 protected void visitAttr(String type, String attr, String at, String value) {
2157 if (type.equals(jvmType)) {
2159 for (int i = 0; i < attrNames.length; i++) {
2160 if (attrNames[i].equals(attr)) {
2169 return found[0] ? values : null;
2172 private CharSequence initField(FieldData v) {
2173 final String is = v.getInternalSig();
2174 if (is.length() == 1) {
2175 switch (is.charAt(0)) {
2181 case 'I': return " = 0;";
2183 case 'D': return " = 0.0;";
2185 throw new IllegalStateException(is);
2191 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2192 final String name = args[indx];
2196 if (name.contains(",")) {
2197 throw new IOException("Wrong parameter with ',': " + name);
2203 final void emitNoFlush(
2205 final String format, final CharSequence... params
2206 ) throws IOException {
2207 emitImpl(this, format, params);
2209 static final void emit(
2211 final Appendable out,
2212 final String format, final CharSequence... params
2213 ) throws IOException {
2215 emitImpl(out, format, params);
2217 static void emitImpl(final Appendable out,
2218 final String format,
2219 final CharSequence... params) throws IOException {
2220 final int length = format.length();
2223 int paramOffset = format.indexOf('@');
2224 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2225 final char paramChar = format.charAt(paramOffset + 1);
2226 if ((paramChar >= '1') && (paramChar <= '9')) {
2227 final int paramIndex = paramChar - '0' - 1;
2229 out.append(format, processed, paramOffset);
2230 out.append(params[paramIndex]);
2233 processed = paramOffset + 1;
2236 paramOffset = format.indexOf('@', paramOffset + 1);
2239 out.append(format, processed, length);
2242 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2243 append("} catch (e) {\n");
2245 for (TrapData e : traps) {
2249 if (e.catch_cpx != 0) { //not finally
2250 final String classInternalName = jc.getClassName(e.catch_cpx);
2251 addReference(classInternalName);
2252 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2253 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2254 append("var stA0 = e;");
2255 goTo(this, current, e.handler_pc, topMostLabel);
2258 finallyPC = e.handler_pc;
2261 if (finallyPC == -1) {
2264 append("var stA0 = e;");
2265 goTo(this, current, finallyPC, topMostLabel);
2270 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2273 out.append("{ gt = 0; continue X_" + to + "; }");
2275 out.append("{ gt = " + to + "; continue X_0; }");
2278 out.append("{ gt = " + to + "; break IF; }");
2282 private static void emitIf(
2284 Appendable out, String pattern,
2286 int current, int to, int canBack
2287 ) throws IOException {
2289 emitImpl(out, pattern, param);
2290 goTo(out, current, to, canBack);
2293 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2296 case 4: jvmType = "[Z"; break;
2297 case 5: jvmType = "[C"; break;
2298 case 6: jvmType = "[F"; break;
2299 case 7: jvmType = "[D"; break;
2300 case 8: jvmType = "[B"; break;
2301 case 9: jvmType = "[S"; break;
2302 case 10: jvmType = "[I"; break;
2303 case 11: jvmType = "[J"; break;
2304 default: throw new IllegalStateException("Array type: " + atype);
2307 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2308 smapper.popI(), smapper.pushA(), jvmType);
2311 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2312 String typeName = jc.getClassName(type);
2313 String ref = "null";
2314 if (typeName.startsWith("[")) {
2315 typeName = "'[" + typeName + "'";
2317 ref = "vm." + mangleClassName(typeName);
2318 typeName = "'[L" + typeName + ";'";
2321 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2322 smapper.popI(), smapper.pushA(), typeName, ref);
2325 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2326 String typeName = jc.getClassName(type);
2327 int dim = readUByte(byteCodes, ++i);
2328 StringBuilder dims = new StringBuilder();
2330 for (int d = 0; d < dim; d++) {
2332 dims.insert(1, ",");
2334 dims.insert(1, smapper.popI());
2338 if (typeName.charAt(dim) == 'L') {
2339 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2342 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2343 dims.toString(), smapper.pushA(), typeName, fn
2348 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2349 int table = i / 4 * 4 + 4;
2350 int dflt = i + readInt4(byteCodes, table);
2352 int low = readInt4(byteCodes, table);
2354 int high = readInt4(byteCodes, table);
2356 final CharSequence swVar = smapper.popValue();
2357 smapper.flush(this);
2358 append("switch (").append(swVar).append(") {\n");
2359 while (low <= high) {
2360 int offset = i + readInt4(byteCodes, table);
2362 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2365 append(" default: ");
2366 goTo(this, i, dflt, topMostLabel);
2372 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2373 int table = i / 4 * 4 + 4;
2374 int dflt = i + readInt4(byteCodes, table);
2376 int n = readInt4(byteCodes, table);
2378 final CharSequence swVar = smapper.popValue();
2379 smapper.flush(this);
2380 append("switch (").append(swVar).append(") {\n");
2382 int cnstnt = readInt4(byteCodes, table);
2384 int offset = i + readInt4(byteCodes, table);
2386 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2388 append(" default: ");
2389 goTo(this, i, dflt, topMostLabel);
2395 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2396 String type = jc.getClassName(indx);
2397 if (!type.startsWith("[")) {
2399 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2400 smapper.popA(), smapper.pushI(),
2401 mangleClassName(type));
2404 while (type.charAt(cnt) == '[') {
2407 if (type.charAt(cnt) == 'L') {
2408 String component = type.substring(cnt + 1, type.length() - 1);
2409 requireReference(component);
2410 type = "vm." + mangleClassName(component);
2412 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2413 smapper.popA(), smapper.pushI(),
2418 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2419 smapper.popA(), smapper.pushI(), type
2425 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2426 String type = jc.getClassName(indx);
2427 if (!type.startsWith("[")) {
2428 emitNoFlush(smapper,
2429 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx(@1, '@3');",
2430 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type), type.replace('/', '.'));
2433 while (type.charAt(cnt) == '[') {
2436 if (type.charAt(cnt) == 'L') {
2437 String component = type.substring(cnt + 1, type.length() - 1);
2438 requireReference(component);
2439 type = "vm." + mangleClassName(component);
2440 emitNoFlush(smapper,
2441 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx(@1, '');",
2442 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2445 emitNoFlush(smapper,
2446 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx(@1, '');",
2447 smapper.getT(0, VarType.REFERENCE, false), type
2453 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2454 for (int j = prev; j <= i; j++) {
2456 final int cc = readUByte(byteCodes, j);
2457 append(Integer.toString(cc));
2461 @JavaScriptBody(args = "msg", body = "")
2462 private static void println(String msg) {
2463 System.err.println(msg);
2466 private static int closingParenthesis(String body, int at) {
2469 switch (body.charAt(at++)) {
2470 case '(': cnt++; break;
2471 case ')': cnt--; break;
2479 private class GenerateAnno extends AnnotationParser {
2480 public GenerateAnno(boolean textual, boolean iterateArray) {
2481 super(textual, iterateArray);
2483 int[] cnt = new int[32];
2487 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2488 final String slashType = attrType.substring(1, attrType.length() - 1);
2489 requireReference(slashType);
2491 if (cnt[depth]++ > 0) {
2495 append('"').append(attrType).append("\" : ");
2502 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2508 protected void visitValueStart(String attrName, char type) throws IOException {
2509 if (cnt[depth]++ > 0) {
2513 if (attrName != null) {
2514 append('"').append(attrName).append("\" : ");
2522 protected void visitValueEnd(String attrName, char type) throws IOException {
2530 protected void visitAttr(String type, String attr, String attrType, String value)
2531 throws IOException {
2532 if (attr == null && value == null) {
2539 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2540 throws IOException {
2541 final String slashType = attrType.substring(1, attrType.length() - 1);
2542 requireReference(slashType);
2544 final String cn = mangleClassName(slashType);
2545 append(accessClassFalse(cn))
2546 .append("['valueOf__L").
2548 append("_2Ljava_lang_String_2']('").
2554 protected void visitClassAttr(String annoType, String attr, String className) throws IOException {
2555 final String slashType = className.substring(1, className.length() - 1);
2556 requireReference(slashType);
2558 final String cn = mangleClassName(slashType);
2559 append(accessClassFalse(cn)).append(".constructor.$class");