Frequent access to mod32 operation defined on the Number.prototype is slowing things down significanty.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import org.apidesign.bck2brwsr.core.JavaScriptBody;
23 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
24 import org.apidesign.vm4brwsr.ByteCodeParser.AnnotationParser;
25 import org.apidesign.vm4brwsr.ByteCodeParser.BootMethodData;
26 import org.apidesign.vm4brwsr.ByteCodeParser.CPX2;
27 import org.apidesign.vm4brwsr.ByteCodeParser.ClassData;
28 import org.apidesign.vm4brwsr.ByteCodeParser.FieldData;
29 import org.apidesign.vm4brwsr.ByteCodeParser.MethodData;
30 import org.apidesign.vm4brwsr.ByteCodeParser.StackMapIterator;
31 import org.apidesign.vm4brwsr.ByteCodeParser.TrapData;
32 import org.apidesign.vm4brwsr.ByteCodeParser.TrapDataIterator;
34 /** Translator of the code inside class files to JavaScript.
36 * @author Jaroslav Tulach <jtulach@netbeans.org>
38 abstract class ByteCodeToJavaScript implements Appendable {
40 private final Appendable out;
41 private final StringArray classRefs = new StringArray();
42 private boolean outChanged;
43 private boolean callbacks;
45 protected ByteCodeToJavaScript(Appendable out) {
50 public final Appendable append(CharSequence csq) throws IOException {
57 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
58 out.append(csq, start, end);
64 public final Appendable append(char c) throws IOException {
70 /* Collects additional required resources.
72 * @param internalClassName classes that were referenced and should be loaded in order the
73 * generated JavaScript code works properly. The names are in internal
74 * JVM form so String is <code>java/lang/String</code>.
76 protected abstract boolean requireReference(String internalClassName);
79 * @param resourcePath name of resources to read
81 protected abstract void requireScript(String resourcePath) throws IOException;
83 protected abstract void requireResource(String resourcePath) throws IOException;
85 /** Allows subclasses to redefine what field a function representing a
86 * class gets assigned. By default it returns the suggested name followed
87 * by <code>" = "</code>;
89 * @param className suggested name of the class
91 /* protected */ String assignClass(String className) {
92 return className + " = ";
94 /* protected */ String accessClass(String classOperation) {
95 return classOperation;
98 final String accessClassFalse(String classOperation) {
99 if (mangleClassName(jc.getClassName()).equals(classOperation)) {
102 classRefs.addIfMissing(classOperation);
103 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
106 protected String accessField(String object, String mangledName,
107 String[] fieldInfoName) throws IOException {
108 return object + "." + mangledName;
111 protected String accessStaticMethod(
114 String[] fieldInfoName) throws IOException {
115 return object + "." + mangledName;
118 protected String accessVirtualMethod(
121 String[] fieldInfoName,
123 ) throws IOException {
124 return object + "." + mangledName + '(';
127 protected void declaredClass(ClassData classData, String mangledName)
131 protected void declaredField(FieldData fieldData,
133 String mangledName) throws IOException {
136 protected void declaredMethod(MethodData methodData,
138 String mangledName) throws IOException {
141 /** Prints out a debug message.
143 * @param msg the message
144 * @return true if the message has been printed
145 * @throws IOException
147 boolean debug(String msg) throws IOException {
153 * Converts a given class file to a JavaScript version.
155 * @param classFile input stream with code of the .class file
156 * @return the initialization code for this class, if any. Otherwise <code>null</code>
158 * @throws IOException if something goes wrong during read or write or translating
161 public String compile(InputStream classFile) throws IOException {
162 return compile(new ClassData(classFile));
165 protected String compile(ClassData classData) throws IOException {
167 final String cn = this.jc.getClassName();
169 return compileImpl(cn);
170 } catch (IOException ex) {
171 throw new IOException("Cannot compile " + cn + ":", ex);
175 private String compileImpl(final String cn) throws IOException {
176 this.callbacks = cn.endsWith("/$JsCallbacks$");
177 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
178 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
179 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
182 byte[] arrData = jc.findAnnotationData(true);
184 String[] arr = findAnnotation(arrData, jc,
185 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
186 "resource", "processByteCode"
189 if (!arr[0].isEmpty()) {
190 requireScript(arr[0]);
192 if ("0".equals(arr[1])) {
197 final String jsResource;
199 String[] arr = findAnnotation(arrData, jc,
200 "net.java.html.js.JavaScriptResource",
204 if (arr[0].startsWith("/")) {
207 int last = cn.lastIndexOf('/');
208 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
214 String[] proto = findAnnotation(arrData, jc,
215 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
216 "container", "prototype"
218 StringArray toInitilize = new StringArray();
219 final String className = className(jc);
220 append("\n\n").append(assignClass(className));
221 append("function ").append(className).append("() {");
223 append("\n var CLS = ").append(className).append(';');
224 append("\n if (!CLS.$class) {");
226 String sc = jc.getSuperClassName(); // with _
227 append("\n var pp = ").
228 append(accessClass(mangleClassName(sc))).append("(true);");
229 append("\n var p = CLS.prototype = pp;");
230 append("\n var c = p;");
231 append("\n var sprcls = pp.constructor.$class;");
233 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
234 if (proto[0] == null) {
237 append("\n var c = ").append(proto[0]).append(";");
238 append("\n var sprcls = null;");
240 for (FieldData v : jc.getFields()) {
242 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
243 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
247 append("\n CLS.fld_").append(v.getName()).append(initField(v));
248 append("\n m = c._").append(v.getName()).append(" = function (v) {")
249 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
250 .append(" = v; return CLS.fld_").
251 append(v.getName()).append("; };");
253 append("\n m = c._").append(v.getName()).append(" = function (v) {")
254 .append(" if (arguments.length == 1) this.fld_").
255 append(className).append('_').append(v.getName())
256 .append(" = v; return this.fld_").
257 append(className).append('_').append(v.getName())
261 declaredField(v, "c", "_" + v.getName());
263 for (MethodData m : jc.getMethods()) {
264 byte[] onlyArr = m.findAnnotationData(true);
265 if (javaScriptOnly(onlyArr)) continue;
271 mn = generateStaticMethod(destObject, m, toInitilize);
273 if (m.isConstructor()) {
275 mn = generateInstanceMethod(destObject, m);
278 mn = generateInstanceMethod(destObject, m);
281 declaredMethod(m, destObject, mn);
282 byte[] runAnno = m.findAnnotationData(false);
283 if (runAnno != null) {
284 append("\n m.anno = {");
285 generateAnno(jc, runAnno);
288 append("\n m.access = " + m.getAccess()).append(";");
289 append("\n m.cls = CLS;");
291 append("\n c.constructor = CLS;");
292 append("\n function ").append(className).append("fillInstOf(x) {");
293 String instOfName = "$instOf_" + className;
294 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
295 if (jc.isInterface()) {
296 for (MethodData m : jc.getMethods()) {
297 if ((m.getAccess() & ACC_ABSTRACT) == 0
298 && (m.getAccess() & ACC_STATIC) == 0
299 && (m.getAccess() & ACC_PRIVATE) == 0) {
300 final String mn = findMethodName(m, new StringBuilder());
301 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
305 for (String superInterface : jc.getSuperInterfaces()) {
306 String intrfc = mangleClassName(superInterface);
307 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
308 requireReference(superInterface);
311 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
312 append("\n ").append(className).append("fillInstOf(c);");
313 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
314 append("\n CLS.$class = 'temp';");
315 append("\n CLS.$class = ");
316 append(accessClass("java_lang_Class(true);"));
317 append("\n CLS.$class.jvmName = '").append(cn).append("';");
318 append("\n CLS.$class.superclass = sprcls;");
319 append("\n CLS.$class.interfaces = function() { return [");
321 boolean first = true;
322 for (String intrfc : jc.getSuperInterfaces()) {
326 requireReference(intrfc);
327 String mangledIface = mangleClassName(intrfc);
329 append(accessClass(mangledIface)).append("(false).constructor.$class");
334 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
335 append("\n CLS.$class.cnstr = CLS;");
336 byte[] classAnno = jc.findAnnotationData(false);
337 if (classAnno != null) {
338 append("\n CLS.$class.anno = {");
339 generateAnno(jc, classAnno);
342 for (String init : toInitilize.toArray()) {
343 append("\n ").append(init).append("();");
345 for (String ref : classRefs.toArray()) {
346 append("\n var refs_").append(ref).append(";");
350 if (jsResource != null) {
351 requireResource(jsResource);
355 append("\n if (arguments.length === 0) {");
356 append("\n if (!(this instanceof CLS)) {");
357 append("\n return new CLS();");
359 for (FieldData v : jc.getFields()) {
360 byte[] onlyArr = v.findAnnotationData(true);
361 if (javaScriptOnly(onlyArr)) continue;
363 append("\n this.fld_").
364 append(className).append('_').
365 append(v.getName()).append(initField(v));
368 append("\n return this;");
370 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
373 declaredClass(jc, className);
375 // StringBuilder sb = new StringBuilder();
376 // for (String init : toInitilize.toArray()) {
377 // sb.append("\n").append(init).append("();");
382 private boolean javaScriptOnly(byte[] anno) throws IOException {
383 String[] only = findAnnotation(anno, jc,
384 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
388 if (only[0] != null && only[1] != null) {
389 append("\n p.").append(only[0]).append(" = ")
390 .append(only[1]).append(";");
392 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
393 append("\n p['").append(only[0]).append("'] = p.")
394 .append(only[0]).append(";");
400 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
401 String jsb = javaScriptBody(destObject, m, true);
405 final String mn = findMethodName(m, new StringBuilder());
406 boolean defineProp = generateMethod(destObject, mn, m);
407 if (mn.equals("class__V")) {
409 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
411 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
417 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
418 String jsb = javaScriptBody(destObject, m, false);
422 final String mn = findMethodName(m, new StringBuilder());
423 generateMethod(destObject, mn, m);
427 private boolean generateMethod(String destObject, String name, MethodData m)
429 final StackMapIterator stackMapIterator = m.createStackMapIterator();
430 TrapDataIterator trap = m.getTrapDataIterator();
431 final LocalsMapper lmapper =
432 new LocalsMapper(stackMapIterator.getArguments());
435 "java/lang/Object".equals(jc.getClassName()) ||
436 "java/lang/reflect/Array".equals(jc.getClassName());
439 append("Object.defineProperty(").append(destObject).
440 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
442 append("m = ").append(destObject).append(".").append(name).append(" = function(");
444 lmapper.outputArguments(this, m.isStatic());
445 append(") {").append("\n");
447 final byte[] byteCodes = m.getCode();
448 if (byteCodes == null) {
449 if (debug(" throw 'no code found for ")) {
451 .append(jc.getClassName()).append('.')
452 .append(m.getName()).append("';\n");
462 final StackMapper smapper = new StackMapper();
465 append(" var ").append(" lcA0 = this;\n");
469 TrapData[] previousTrap = null;
470 boolean wide = false;
472 if (stackMapIterator.isEmpty()) {
478 append("\n var gt = 0;\n");
482 int topMostLabel = 0;
483 for (int i = 0; i < byteCodes.length; i++) {
486 stackMapIterator.advanceTo(i);
487 boolean changeInCatch = trap.advanceTo(i);
488 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
489 if (previousTrap != null) {
490 generateCatch(previousTrap, i, topMostLabel);
494 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
499 if (openBraces > 64) {
500 for (int c = 0; c < 64; c++) {
507 lastStackFrame = stackMapIterator.getFrameIndex();
508 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
509 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
510 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
512 changeInCatch = true;
514 debug(" /* " + i + " */ ");
516 if (changeInCatch && trap.useTry()) {
518 previousTrap = trap.current();
520 final int c = readUByte(byteCodes, i);
523 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
526 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
529 smapper.assign(this, VarType.LONG, lmapper.getL(0));
532 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
535 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
538 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
541 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
544 smapper.assign(this, VarType.LONG, lmapper.getL(1));
547 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
550 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
553 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
556 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
559 smapper.assign(this, VarType.LONG, lmapper.getL(2));
562 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
565 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
568 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
571 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
574 smapper.assign(this, VarType.LONG, lmapper.getL(3));
577 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
580 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
584 final int indx = wide ? readUShort(byteCodes, i++)
585 : readUByte(byteCodes, i);
587 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
592 final int indx = wide ? readUShort(byteCodes, i++)
593 : readUByte(byteCodes, i);
595 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
600 final int indx = wide ? readUShort(byteCodes, i++)
601 : readUByte(byteCodes, i);
603 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
608 final int indx = wide ? readUShort(byteCodes, i++)
609 : readUByte(byteCodes, i);
611 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
616 final int indx = wide ? readUShort(byteCodes, i++)
617 : readUByte(byteCodes, i);
619 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
624 final int indx = wide ? readUShort(byteCodes, i++)
625 : readUByte(byteCodes, i);
627 emit(smapper, this, "var @1 = @2;",
628 lmapper.setI(indx), smapper.popI());
633 final int indx = wide ? readUShort(byteCodes, i++)
634 : readUByte(byteCodes, i);
636 emit(smapper, this, "var @1 = @2;",
637 lmapper.setL(indx), smapper.popL());
642 final int indx = wide ? readUShort(byteCodes, i++)
643 : readUByte(byteCodes, i);
645 emit(smapper, this, "var @1 = @2;",
646 lmapper.setF(indx), smapper.popF());
651 final int indx = wide ? readUShort(byteCodes, i++)
652 : readUByte(byteCodes, i);
654 emit(smapper, this, "var @1 = @2;",
655 lmapper.setD(indx), smapper.popD());
660 final int indx = wide ? readUShort(byteCodes, i++)
661 : readUByte(byteCodes, i);
663 emit(smapper, this, "var @1 = @2;",
664 lmapper.setA(indx), smapper.popA());
668 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
671 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
674 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
677 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
680 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
683 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
686 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
689 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
692 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
695 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
698 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
701 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
704 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
707 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
710 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
713 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
716 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
719 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
722 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
725 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
728 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
731 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
734 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
737 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
740 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
743 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
746 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
749 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
752 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
755 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
758 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
761 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
764 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
765 smapper.getI(1), smapper.popI());
768 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
769 smapper.getL(1), smapper.popL());
772 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
775 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
779 // direct check yields few percents
780 // in case of firefox 5.8s/4.6.s
781 smapper.replace(this, VarType.INTEGER, "((@1) % (@2))",
782 smapper.getI(1), smapper.popI());
783 // with myNum being local variable in the generated script
784 // it compiles and computes 5000 primes in 6s
785 // smapper.replace(this, VarType.INTEGER, "myNum.mod32(@1, @2)",
786 // smapper.getI(1), smapper.popI());
789 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
790 smapper.getL(1), smapper.popL());
793 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
796 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
799 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
802 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
805 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
808 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
811 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
814 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
817 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
820 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
823 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
826 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
829 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
832 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
835 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
838 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
841 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
844 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
848 final int varIndx = wide ? readUShort(byteCodes, i++)
849 : readUByte(byteCodes, i);
851 final int incrBy = wide ? readShort(byteCodes, i++)
855 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
857 emit(smapper, this, "@1 += @2;",
858 lmapper.getI(varIndx),
859 Integer.toString(incrBy));
864 emit(smapper, this, "return;");
867 emit(smapper, this, "return @1;", smapper.popI());
870 emit(smapper, this, "return @1;", smapper.popL());
873 emit(smapper, this, "return @1;", smapper.popF());
876 emit(smapper, this, "return @1;", smapper.popD());
879 emit(smapper, this, "return @1;", smapper.popA());
882 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
885 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
888 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
891 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
895 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
898 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
901 smapper.replace(this, VarType.DOUBLE, "@1",
905 smapper.replace(this, VarType.FLOAT, "@1",
909 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
913 smapper.replace(this, VarType.LONG, "(@1).toLong()",
917 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
921 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
924 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
928 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
930 case opc_aconst_null:
931 smapper.assign(this, VarType.REFERENCE, "null");
934 smapper.assign(this, VarType.INTEGER, "-1");
937 smapper.assign(this, VarType.INTEGER, "0");
940 smapper.assign(this, VarType.DOUBLE, "0");
943 smapper.assign(this, VarType.LONG, "0");
946 smapper.assign(this, VarType.FLOAT, "0");
949 smapper.assign(this, VarType.INTEGER, "1");
952 smapper.assign(this, VarType.LONG, "1");
955 smapper.assign(this, VarType.FLOAT, "1");
958 smapper.assign(this, VarType.DOUBLE, "1");
961 smapper.assign(this, VarType.INTEGER, "2");
964 smapper.assign(this, VarType.FLOAT, "2");
967 smapper.assign(this, VarType.INTEGER, "3");
970 smapper.assign(this, VarType.INTEGER, "4");
973 smapper.assign(this, VarType.INTEGER, "5");
976 int indx = readUByte(byteCodes, ++i);
977 String v = encodeConstant(indx);
978 int type = VarType.fromConstantType(jc.getTag(indx));
979 smapper.assign(this, type, v);
984 int indx = readUShortArg(byteCodes, i);
986 String v = encodeConstant(indx);
987 int type = VarType.fromConstantType(jc.getTag(indx));
988 if (type == VarType.LONG) {
989 final Long lv = new Long(v);
990 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
991 final int hi = (int)(lv.longValue() >> 32);
993 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
995 smapper.assign(this, VarType.LONG,
996 "0x" + Integer.toHexString(hi) + ".next32(0x" +
997 Integer.toHexString(low) + ")"
1001 smapper.assign(this, type, v);
1006 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
1010 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1011 smapper.popF(), smapper.popF(), smapper.pushI());
1015 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1016 smapper.popD(), smapper.popD(), smapper.pushI());
1019 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1020 "===", topMostLabel);
1023 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1024 "!==", topMostLabel);
1027 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1028 "==", topMostLabel);
1031 int indx = i + readShortArg(byteCodes, i);
1032 emitIf(smapper, this, "if ((@1) == 0) ",
1033 smapper.popI(), i, indx, topMostLabel);
1038 int indx = i + readShortArg(byteCodes, i);
1039 emitIf(smapper, this, "if ((@1) != 0) ",
1040 smapper.popI(), i, indx, topMostLabel);
1045 int indx = i + readShortArg(byteCodes, i);
1046 emitIf(smapper, this, "if ((@1) < 0) ",
1047 smapper.popI(), i, indx, topMostLabel);
1052 int indx = i + readShortArg(byteCodes, i);
1053 emitIf(smapper, this, "if ((@1) <= 0) ",
1054 smapper.popI(), i, indx, topMostLabel);
1059 int indx = i + readShortArg(byteCodes, i);
1060 emitIf(smapper, this, "if ((@1) > 0) ",
1061 smapper.popI(), i, indx, topMostLabel);
1066 int indx = i + readShortArg(byteCodes, i);
1067 emitIf(smapper, this, "if ((@1) >= 0) ",
1068 smapper.popI(), i, indx, topMostLabel);
1072 case opc_ifnonnull: {
1073 int indx = i + readShortArg(byteCodes, i);
1074 emitIf(smapper, this, "if ((@1) !== null) ",
1075 smapper.popA(), i, indx, topMostLabel);
1080 int indx = i + readShortArg(byteCodes, i);
1081 emitIf(smapper, this, "if ((@1) === null) ",
1082 smapper.popA(), i, indx, topMostLabel);
1087 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1088 "!=", topMostLabel);
1091 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1095 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1096 "<=", topMostLabel);
1099 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1103 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1104 ">=", topMostLabel);
1107 smapper.flush(this);
1108 int indx = i + readShortArg(byteCodes, i);
1109 goTo(this, i, indx, topMostLabel);
1113 case opc_lookupswitch: {
1114 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1117 case opc_tableswitch: {
1118 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1121 case opc_invokeinterface: {
1122 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1125 case opc_invokevirtual:
1126 i = invokeVirtualMethod(byteCodes, i, smapper);
1128 case opc_invokespecial:
1129 i = invokeStaticMethod(byteCodes, i, smapper, false);
1131 case opc_invokestatic:
1132 i = invokeStaticMethod(byteCodes, i, smapper, true);
1134 case opc_invokedynamic: {
1135 int indx = readUShortArg(byteCodes, i);
1136 println("invoke dynamic: " + indx);
1137 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1138 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1139 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1140 println(" type: " + methodHandle.cpx1);
1141 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1142 String mcn = mangleClassName(mi[0]);
1143 char[] returnType = {'V'};
1144 StringBuilder cnt = new StringBuilder();
1145 String mn = findMethodName(mi, cnt, returnType);
1146 StringBuilder sb = new StringBuilder();
1147 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1148 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1149 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1150 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1151 sb.append(" mn : ").append(mn).append("\n");
1152 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1153 throw new IOException(sb.toString());
1155 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1156 String type = jc.StringValue(nameAndType.cpx2);
1157 String object = accessClass(mcn) + "(false)";
1158 if (mn.startsWith("cons_")) {
1159 object += ".constructor";
1161 append("var metHan = ");
1162 append(accessStaticMethod(object, mn, mi));
1164 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1166 append(", '").append(mi[1]).append("', ");
1167 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1168 append(methodType).append("'").append(type).append("', null)");
1169 // if (numArguments > 0) {
1171 // for (int j = 1; j < numArguments; ++j) {
1177 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1183 int indx = readUShortArg(byteCodes, i);
1184 String ci = jc.getClassName(indx);
1185 emit(smapper, this, "var @1 = new @2;",
1186 smapper.pushA(), accessClass(mangleClassName(ci)));
1192 int atype = readUByte(byteCodes, ++i);
1193 generateNewArray(atype, smapper);
1195 case opc_anewarray: {
1196 int type = readUShortArg(byteCodes, i);
1198 generateANewArray(type, smapper);
1201 case opc_multianewarray: {
1202 int type = readUShortArg(byteCodes, i);
1204 i = generateMultiANewArray(type, byteCodes, i, smapper);
1207 case opc_arraylength:
1208 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1211 emit(smapper, this, "Array.at(@3, @2, @1);",
1212 smapper.popL(), smapper.popI(), smapper.popA());
1215 emit(smapper, this, "Array.at(@3, @2, @1);",
1216 smapper.popF(), smapper.popI(), smapper.popA());
1219 emit(smapper, this, "Array.at(@3, @2, @1);",
1220 smapper.popD(), smapper.popI(), smapper.popA());
1223 emit(smapper, this, "Array.at(@3, @2, @1);",
1224 smapper.popA(), smapper.popI(), smapper.popA());
1230 emit(smapper, this, "Array.at(@3, @2, @1);",
1231 smapper.popI(), smapper.popI(), smapper.popA());
1234 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1235 smapper.popI(), smapper.getA(0));
1238 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1239 smapper.popI(), smapper.getA(0));
1242 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1243 smapper.popI(), smapper.getA(0));
1246 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1247 smapper.popI(), smapper.getA(0));
1253 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1254 smapper.popI(), smapper.getA(0));
1262 final Variable v = smapper.get(0);
1263 if (smapper.isDirty()) {
1264 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1266 smapper.assign(this, v.getType(), v);
1271 final Variable vi1 = smapper.get(0);
1273 if (vi1.isCategory2()) {
1274 emit(smapper, this, "var @1 = @2;",
1275 smapper.pushT(vi1.getType()), vi1);
1277 final Variable vi2 = smapper.get(1);
1278 emit(smapper, this, "var @1 = @2, @3 = @4;",
1279 smapper.pushT(vi2.getType()), vi2,
1280 smapper.pushT(vi1.getType()), vi1);
1285 final Variable vi1 = smapper.pop(this);
1286 final Variable vi2 = smapper.pop(this);
1287 final Variable vo3 = smapper.pushT(vi1.getType());
1288 final Variable vo2 = smapper.pushT(vi2.getType());
1289 final Variable vo1 = smapper.pushT(vi1.getType());
1291 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1292 vo1, vi1, vo2, vi2, vo3, vo1);
1296 final Variable vi1 = smapper.pop(this);
1297 final Variable vi2 = smapper.pop(this);
1299 if (vi1.isCategory2()) {
1300 final Variable vo3 = smapper.pushT(vi1.getType());
1301 final Variable vo2 = smapper.pushT(vi2.getType());
1302 final Variable vo1 = smapper.pushT(vi1.getType());
1304 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1305 vo1, vi1, vo2, vi2, vo3, vo1);
1307 final Variable vi3 = smapper.pop(this);
1308 final Variable vo5 = smapper.pushT(vi2.getType());
1309 final Variable vo4 = smapper.pushT(vi1.getType());
1310 final Variable vo3 = smapper.pushT(vi3.getType());
1311 final Variable vo2 = smapper.pushT(vi2.getType());
1312 final Variable vo1 = smapper.pushT(vi1.getType());
1314 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1315 vo1, vi1, vo2, vi2, vo3, vi3);
1316 emit(smapper, this, " @1 = @2, @3 = @4;",
1317 vo4, vo1, vo5, vo2);
1322 final Variable vi1 = smapper.pop(this);
1323 final Variable vi2 = smapper.pop(this);
1325 if (vi2.isCategory2()) {
1326 final Variable vo3 = smapper.pushT(vi1.getType());
1327 final Variable vo2 = smapper.pushT(vi2.getType());
1328 final Variable vo1 = smapper.pushT(vi1.getType());
1330 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1331 vo1, vi1, vo2, vi2, vo3, vo1);
1333 final Variable vi3 = smapper.pop(this);
1334 final Variable vo4 = smapper.pushT(vi1.getType());
1335 final Variable vo3 = smapper.pushT(vi3.getType());
1336 final Variable vo2 = smapper.pushT(vi2.getType());
1337 final Variable vo1 = smapper.pushT(vi1.getType());
1339 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1340 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1345 final Variable vi1 = smapper.pop(this);
1346 final Variable vi2 = smapper.pop(this);
1348 if (vi1.isCategory2()) {
1349 if (vi2.isCategory2()) {
1350 final Variable vo3 = smapper.pushT(vi1.getType());
1351 final Variable vo2 = smapper.pushT(vi2.getType());
1352 final Variable vo1 = smapper.pushT(vi1.getType());
1354 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1355 vo1, vi1, vo2, vi2, vo3, vo1);
1357 final Variable vi3 = smapper.pop(this);
1358 final Variable vo4 = smapper.pushT(vi1.getType());
1359 final Variable vo3 = smapper.pushT(vi3.getType());
1360 final Variable vo2 = smapper.pushT(vi2.getType());
1361 final Variable vo1 = smapper.pushT(vi1.getType());
1363 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1364 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1367 final Variable vi3 = smapper.pop(this);
1369 if (vi3.isCategory2()) {
1370 final Variable vo5 = smapper.pushT(vi2.getType());
1371 final Variable vo4 = smapper.pushT(vi1.getType());
1372 final Variable vo3 = smapper.pushT(vi3.getType());
1373 final Variable vo2 = smapper.pushT(vi2.getType());
1374 final Variable vo1 = smapper.pushT(vi1.getType());
1376 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1377 vo1, vi1, vo2, vi2, vo3, vi3);
1378 emit(smapper, this, " @1 = @2, @3 = @4;",
1379 vo4, vo1, vo5, vo2);
1381 final Variable vi4 = smapper.pop(this);
1382 final Variable vo6 = smapper.pushT(vi2.getType());
1383 final Variable vo5 = smapper.pushT(vi1.getType());
1384 final Variable vo4 = smapper.pushT(vi4.getType());
1385 final Variable vo3 = smapper.pushT(vi3.getType());
1386 final Variable vo2 = smapper.pushT(vi2.getType());
1387 final Variable vo1 = smapper.pushT(vi1.getType());
1389 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1390 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1391 emit(smapper, this, " @1 = @2, @3 = @4;",
1392 vo5, vo1, vo6, vo2);
1398 final Variable vi1 = smapper.get(0);
1399 final Variable vi2 = smapper.get(1);
1401 if (vi1.getType() == vi2.getType()) {
1402 final Variable tmp = smapper.pushT(vi1.getType());
1404 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1409 smapper.pushT(vi1.getType());
1410 smapper.pushT(vi2.getType());
1415 smapper.assign(this, VarType.INTEGER,
1416 "(" + Integer.toString(byteCodes[++i]) + ")");
1419 smapper.assign(this, VarType.INTEGER,
1420 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1424 case opc_getfield: {
1425 int indx = readUShortArg(byteCodes, i);
1426 String[] fi = jc.getFieldInfoName(indx);
1427 final int type = VarType.fromFieldType(fi[2].charAt(0));
1428 final String mangleClass = mangleClassName(fi[0]);
1429 final String mangleClassAccess = accessClassFalse(mangleClass);
1430 smapper.replace(this, type, "@2.call(@1)",
1432 accessField(mangleClassAccess,
1436 addReference(fi[0]);
1439 case opc_putfield: {
1440 int indx = readUShortArg(byteCodes, i);
1441 String[] fi = jc.getFieldInfoName(indx);
1442 final int type = VarType.fromFieldType(fi[2].charAt(0));
1443 final String mangleClass = mangleClassName(fi[0]);
1444 final String mangleClassAccess = accessClassFalse(mangleClass);
1445 emit(smapper, this, "@3.call(@2, @1);",
1448 accessField(mangleClassAccess,
1451 addReference(fi[0]);
1454 case opc_getstatic: {
1455 int indx = readUShortArg(byteCodes, i);
1456 String[] fi = jc.getFieldInfoName(indx);
1457 final int type = VarType.fromFieldType(fi[2].charAt(0));
1458 String ac = accessClassFalse(mangleClassName(fi[0]));
1459 String af = accessField(ac, "_" + fi[1], fi);
1460 smapper.assign(this, type, af + "()");
1462 addReference(fi[0]);
1465 case opc_putstatic: {
1466 int indx = readUShortArg(byteCodes, i);
1467 String[] fi = jc.getFieldInfoName(indx);
1468 final int type = VarType.fromFieldType(fi[2].charAt(0));
1469 emit(smapper, this, "@1._@2(@3);",
1470 accessClassFalse(mangleClassName(fi[0])), fi[1],
1471 smapper.popT(type));
1473 addReference(fi[0]);
1476 case opc_checkcast: {
1477 int indx = readUShortArg(byteCodes, i);
1478 generateCheckcast(indx, smapper);
1482 case opc_instanceof: {
1483 int indx = readUShortArg(byteCodes, i);
1484 generateInstanceOf(indx, smapper);
1489 final CharSequence v = smapper.popA();
1492 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1493 smapper.pushA(), v);
1497 case opc_monitorenter: {
1498 debug("/* monitor enter */");
1503 case opc_monitorexit: {
1504 debug("/* monitor exit */");
1515 emit(smapper, this, "throw 'unknown bytecode @1';",
1516 Integer.toString(c));
1520 generateByteCodeComment(prev, i, byteCodes);
1526 if (previousTrap != null) {
1527 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1532 while (openBraces-- > 0) {
1543 private int generateIf(StackMapper mapper, byte[] byteCodes,
1544 int i, final CharSequence v2, final CharSequence v1,
1545 final String test, int topMostLabel
1546 ) throws IOException {
1548 int indx = i + readShortArg(byteCodes, i);
1549 append("if ((").append(v1)
1550 .append(") ").append(test).append(" (")
1551 .append(v2).append(")) ");
1552 goTo(this, i, indx, topMostLabel);
1556 private int readInt4(byte[] byteCodes, int offset) {
1557 final int d = byteCodes[offset + 0] << 24;
1558 final int c = byteCodes[offset + 1] << 16;
1559 final int b = byteCodes[offset + 2] << 8;
1560 final int a = byteCodes[offset + 3];
1561 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1563 private static int readUByte(byte[] byteCodes, int offset) {
1564 return byteCodes[offset] & 0xff;
1567 private static int readUShort(byte[] byteCodes, int offset) {
1568 return ((byteCodes[offset] & 0xff) << 8)
1569 | (byteCodes[offset + 1] & 0xff);
1571 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1572 return readUShort(byteCodes, offsetInstruction + 1);
1575 private static int readShort(byte[] byteCodes, int offset) {
1576 int signed = byteCodes[offset];
1577 byte b0 = (byte)signed;
1578 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1580 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1581 return readShort(byteCodes, offsetInstruction + 1);
1584 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1586 Boolean count = null;
1587 boolean array = false;
1589 int firstPos = sig.length();
1590 while (i < descriptor.length()) {
1591 char ch = descriptor.charAt(i++);
1612 if (ch == 'J' || ch == 'D') {
1618 sig.insert(firstPos, ch);
1620 returnType[0] = '[';
1621 sig.insert(firstPos, "_3");
1630 returnType[0] = 'V';
1631 sig.insert(firstPos, 'V');
1634 int next = descriptor.indexOf(';', i);
1635 String realSig = mangleSig(descriptor, i - 1, next + 1);
1640 sig.append(realSig);
1643 sig.insert(firstPos, realSig);
1645 sig.insert(firstPos, "_3");
1647 returnType[0] = 'L';
1656 throw new IllegalStateException("Invalid char: " + ch);
1661 static String mangleSig(String sig) {
1662 return mangleSig(sig, 0, sig.length());
1665 private static String mangleMethodName(String name) {
1666 StringBuilder sb = new StringBuilder(name.length() * 2);
1667 int last = name.length();
1668 for (int i = 0; i < last; i++) {
1669 final char ch = name.charAt(i);
1671 case '_': sb.append("_1"); break;
1672 default: sb.append(ch); break;
1675 return sb.toString();
1677 private static String mangleSig(String txt, int first, int last) {
1678 StringBuilder sb = new StringBuilder((last - first) * 2);
1679 for (int i = first; i < last; i++) {
1680 final char ch = txt.charAt(i);
1682 case '/': sb.append('_'); break;
1683 case '_': sb.append("_1"); break;
1684 case ';': sb.append("_2"); break;
1685 case '[': sb.append("_3"); break;
1687 if (Character.isJavaIdentifierPart(ch)) {
1691 String hex = Integer.toHexString(ch).toLowerCase();
1692 for (int m = hex.length(); m < 4; m++) {
1700 return sb.toString();
1703 private static String mangleClassName(String name) {
1704 return mangleSig(name);
1707 private static String findMethodName(MethodData m, StringBuilder cnt) {
1708 StringBuilder name = new StringBuilder();
1709 if ("<init>".equals(m.getName())) { // NOI18N
1710 name.append("cons"); // NOI18N
1711 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1712 name.append("class"); // NOI18N
1714 name.append(mangleMethodName(m.getName()));
1717 countArgs(m.getInternalSig(), new char[1], name, cnt);
1718 return name.toString();
1721 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1722 StringBuilder name = new StringBuilder();
1723 String descr = mi[2];//mi.getDescriptor();
1725 if ("<init>".equals(nm)) { // NOI18N
1726 name.append("cons"); // NOI18N
1728 name.append(mangleMethodName(nm));
1730 countArgs(descr, returnType, name, cnt);
1731 return name.toString();
1734 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1735 throws IOException {
1736 int methodIndex = readUShortArg(byteCodes, i);
1737 String[] mi = jc.getFieldInfoName(methodIndex);
1738 char[] returnType = { 'V' };
1739 StringBuilder cnt = new StringBuilder();
1740 String mn = findMethodName(mi, cnt, returnType);
1742 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1743 final CharSequence[] vars = new CharSequence[numArguments];
1745 for (int j = numArguments - 1; j >= 0; --j) {
1746 vars[j] = mapper.popValue();
1750 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1751 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1753 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1754 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1756 if (vars[1] instanceof String) {
1757 String field = vars[1].toString();
1758 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1759 vars[1] = "c._" + field.substring(1, field.length() - 1);
1764 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1765 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1767 if (vars[1] instanceof String) {
1768 String field = vars[2].toString();
1769 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1770 vars[2] = "c._" + field.substring(1, field.length() - 1);
1775 if (returnType[0] != 'V') {
1778 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1782 final String in = mi[0];
1785 in.equals("org/apidesign/html/boot/spi/Fn") ||
1786 in.equals("org/netbeans/html/boot/spi/Fn")
1788 mcn = "java_lang_Class";
1790 mcn = mangleClassName(in);
1792 String object = accessClassFalse(mcn);
1793 if (mn.startsWith("cons_")) {
1794 object += ".constructor";
1796 append(accessStaticMethod(object, mn, mi));
1802 if (numArguments > 0) {
1804 for (int j = 1; j < numArguments; ++j) {
1814 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1815 throws IOException {
1816 int methodIndex = readUShortArg(byteCodes, i);
1817 String[] mi = jc.getFieldInfoName(methodIndex);
1818 char[] returnType = { 'V' };
1819 StringBuilder cnt = new StringBuilder();
1820 String mn = findMethodName(mi, cnt, returnType);
1822 final int numArguments = cnt.length() + 1;
1823 final CharSequence[] vars = new CharSequence[numArguments];
1825 for (int j = numArguments - 1; j >= 0; --j) {
1826 vars[j] = mapper.popValue();
1829 if (returnType[0] != 'V') {
1832 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1836 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1838 for (int j = 1; j < numArguments; ++j) {
1848 private void addReference(String cn) throws IOException {
1849 if (requireReference(cn)) {
1850 debug(" /* needs " + cn + " */");
1854 private void outType(String d, StringBuilder out) {
1856 while (d.charAt(0) == '[') {
1860 if (d.charAt(0) == 'L') {
1861 assert d.charAt(d.length() - 1) == ';';
1862 out.append(mangleClassName(d).substring(0, d.length() - 1));
1868 private String encodeConstant(int entryIndex) throws IOException {
1869 String[] classRef = { null };
1870 String s = jc.stringValue(entryIndex, classRef);
1871 if (classRef[0] != null) {
1872 if (classRef[0].startsWith("[")) {
1873 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1875 addReference(classRef[0]);
1876 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1882 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1883 byte[] arr = m.findAnnotationData(true);
1887 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1888 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1889 class P extends AnnotationParser {
1895 String[] args = new String[30];
1901 protected void visitAttr(String type, String attr, String at, String value) {
1902 if (type.equals(jvmType)) {
1903 if ("body".equals(attr)) {
1905 } else if ("args".equals(attr)) {
1906 args[cnt++] = value;
1908 throw new IllegalArgumentException(attr);
1911 if (type.equals(htmlType)) {
1913 if ("body".equals(attr)) {
1915 } else if ("args".equals(attr)) {
1916 args[cnt++] = value;
1917 } else if ("javacall".equals(attr)) {
1918 javacall = "1".equals(value);
1919 } else if ("wait4js".equals(attr)) {
1920 // ignore, we always invoke synchronously
1922 throw new IllegalArgumentException(attr);
1929 if (p.body == null) {
1932 StringBuilder cnt = new StringBuilder();
1933 final String mn = findMethodName(m, cnt);
1934 append("m = ").append(destObject).append(".").append(mn);
1935 append(" = function(");
1938 StringBuilder toValue = new StringBuilder();
1939 for (int i = 0; i < cnt.length(); i++) {
1941 space = outputArg(this, p.args, index);
1942 if (p.html4j && space.length() > 0) {
1943 toValue.append("\n ").append(p.args[index]).append(" = ")
1944 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1945 append(p.args[index]).append(");");
1949 append(") {").append("\n");
1950 append(toValue.toString());
1952 int lastSlash = jc.getClassName().lastIndexOf('/');
1953 final String pkg = jc.getClassName().substring(0, lastSlash);
1954 append(mangleCallbacks(pkg, p.body));
1955 requireReference(pkg + "/$JsCallbacks$");
1963 private static CharSequence mangleCallbacks(String pkgName, String body) {
1964 StringBuilder sb = new StringBuilder();
1967 int next = body.indexOf(".@", pos);
1969 sb.append(body.substring(pos));
1970 body = sb.toString();
1975 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1980 String refId = body.substring(ident, next);
1982 sb.append(body.substring(pos, ident));
1984 int sigBeg = body.indexOf('(', next);
1985 int sigEnd = body.indexOf(')', sigBeg);
1986 int colon4 = body.indexOf("::", next);
1987 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1988 throw new IllegalStateException("Malformed body " + body);
1990 String fqn = body.substring(next + 2, colon4);
1991 String method = body.substring(colon4 + 2, sigBeg);
1992 String params = body.substring(sigBeg, sigEnd + 1);
1994 int paramBeg = body.indexOf('(', sigEnd + 1);
1996 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
1997 sb.append(mangleJsCallbacks(fqn, method, params, false));
1998 sb.append("(").append(refId);
1999 if (body.charAt(paramBeg + 1) != ')') {
2007 int next = body.indexOf("@", pos);
2012 sb.append(body.substring(pos));
2016 sb = new StringBuilder();
2019 sb.append(body.substring(pos, next));
2021 int sigBeg = body.indexOf('(', next);
2022 int sigEnd = body.indexOf(')', sigBeg);
2023 int colon4 = body.indexOf("::", next);
2024 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2025 throw new IllegalStateException("Malformed body " + body);
2027 String fqn = body.substring(next + 1, colon4);
2028 String method = body.substring(colon4 + 2, sigBeg);
2029 String params = body.substring(sigBeg, sigEnd + 1);
2031 int paramBeg = body.indexOf('(', sigEnd + 1);
2033 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2034 sb.append(mangleJsCallbacks(fqn, method, params, true));
2040 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2041 if (params.startsWith("(")) {
2042 params = params.substring(1);
2044 if (params.endsWith(")")) {
2045 params = params.substring(0, params.length() - 1);
2047 StringBuilder sb = new StringBuilder();
2048 final String fqnu = fqn.replace('.', '_');
2049 final String rfqn = mangleClassName(fqnu);
2050 final String rm = mangleMethodName(method);
2053 StringBuilder pb = new StringBuilder();
2054 int len = params.length();
2056 while (indx < len) {
2057 char ch = params.charAt(indx);
2058 if (ch == '[' || ch == 'L') {
2059 int column = params.indexOf(';', indx) + 1;
2060 if (column > indx) {
2061 String real = params.substring(indx, column);
2062 if ("Ljava/lang/String;".equals(real)) {
2063 pb.append("Ljava/lang/String;");
2068 pb.append("Ljava/lang/Object;");
2075 srp = mangleSig(pb.toString());
2077 final String rp = mangleSig(params);
2078 final String mrp = mangleMethodName(rp);
2079 sb.append(rfqn).append("$").append(rm).
2080 append('$').append(mrp).append("__Ljava_lang_Object_2");
2082 sb.append('L').append(fqnu).append("_2");
2085 return sb.toString();
2088 private static String className(ClassData jc) {
2089 //return jc.getName().getInternalName().replace('/', '_');
2090 return mangleClassName(jc.getClassName());
2093 private static String[] findAnnotation(
2094 byte[] arr, ClassData cd, final String className,
2095 final String... attrNames
2096 ) throws IOException {
2100 final String[] values = new String[attrNames.length];
2101 final boolean[] found = { false };
2102 final String jvmType = "L" + className.replace('.', '/') + ";";
2103 AnnotationParser ap = new AnnotationParser(false, true) {
2105 protected void visitAttr(String type, String attr, String at, String value) {
2106 if (type.equals(jvmType)) {
2108 for (int i = 0; i < attrNames.length; i++) {
2109 if (attrNames[i].equals(attr)) {
2118 return found[0] ? values : null;
2121 private CharSequence initField(FieldData v) {
2122 final String is = v.getInternalSig();
2123 if (is.length() == 1) {
2124 switch (is.charAt(0)) {
2130 case 'I': return " = 0;";
2132 case 'D': return " = 0.0;";
2134 throw new IllegalStateException(is);
2140 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2141 AnnotationParser ap = new AnnotationParser(true, false) {
2142 int[] cnt = new int[32];
2146 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2147 final String slashType = attrType.substring(1, attrType.length() - 1);
2148 requireReference(slashType);
2150 if (cnt[depth]++ > 0) {
2154 append('"').append(attrType).append("\" : ");
2161 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2167 protected void visitValueStart(String attrName, char type) throws IOException {
2168 if (cnt[depth]++ > 0) {
2172 if (attrName != null) {
2173 append('"').append(attrName).append("\" : ");
2181 protected void visitValueEnd(String attrName, char type) throws IOException {
2189 protected void visitAttr(String type, String attr, String attrType, String value)
2190 throws IOException {
2191 if (attr == null && value == null) {
2198 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2199 throws IOException {
2200 final String slashType = attrType.substring(1, attrType.length() - 1);
2201 requireReference(slashType);
2203 final String cn = mangleClassName(slashType);
2204 append(accessClassFalse(cn))
2205 .append("['valueOf__L").
2207 append("_2Ljava_lang_String_2']('").
2215 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2216 final String name = args[indx];
2220 if (name.contains(",")) {
2221 throw new IOException("Wrong parameter with ',': " + name);
2227 final void emitNoFlush(
2229 final String format, final CharSequence... params
2230 ) throws IOException {
2231 emitImpl(this, format, params);
2233 static final void emit(
2235 final Appendable out,
2236 final String format, final CharSequence... params
2237 ) throws IOException {
2239 emitImpl(out, format, params);
2241 static void emitImpl(final Appendable out,
2242 final String format,
2243 final CharSequence... params) throws IOException {
2244 final int length = format.length();
2247 int paramOffset = format.indexOf('@');
2248 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2249 final char paramChar = format.charAt(paramOffset + 1);
2250 if ((paramChar >= '1') && (paramChar <= '9')) {
2251 final int paramIndex = paramChar - '0' - 1;
2253 out.append(format, processed, paramOffset);
2254 out.append(params[paramIndex]);
2257 processed = paramOffset + 1;
2260 paramOffset = format.indexOf('@', paramOffset + 1);
2263 out.append(format, processed, length);
2266 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2267 append("} catch (e) {\n");
2269 for (TrapData e : traps) {
2273 if (e.catch_cpx != 0) { //not finally
2274 final String classInternalName = jc.getClassName(e.catch_cpx);
2275 addReference(classInternalName);
2276 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2277 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2278 append("var stA0 = e;");
2279 goTo(this, current, e.handler_pc, topMostLabel);
2282 finallyPC = e.handler_pc;
2285 if (finallyPC == -1) {
2288 append("var stA0 = e;");
2289 goTo(this, current, finallyPC, topMostLabel);
2294 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2297 out.append("{ gt = 0; continue X_" + to + "; }");
2299 out.append("{ gt = " + to + "; continue X_0; }");
2302 out.append("{ gt = " + to + "; break IF; }");
2306 private static void emitIf(
2308 Appendable out, String pattern,
2310 int current, int to, int canBack
2311 ) throws IOException {
2313 emitImpl(out, pattern, param);
2314 goTo(out, current, to, canBack);
2317 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2320 case 4: jvmType = "[Z"; break;
2321 case 5: jvmType = "[C"; break;
2322 case 6: jvmType = "[F"; break;
2323 case 7: jvmType = "[D"; break;
2324 case 8: jvmType = "[B"; break;
2325 case 9: jvmType = "[S"; break;
2326 case 10: jvmType = "[I"; break;
2327 case 11: jvmType = "[J"; break;
2328 default: throw new IllegalStateException("Array type: " + atype);
2331 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2332 smapper.popI(), smapper.pushA(), jvmType);
2335 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2336 String typeName = jc.getClassName(type);
2337 String ref = "null";
2338 if (typeName.startsWith("[")) {
2339 typeName = "'[" + typeName + "'";
2341 ref = "vm." + mangleClassName(typeName);
2342 typeName = "'[L" + typeName + ";'";
2345 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2346 smapper.popI(), smapper.pushA(), typeName, ref);
2349 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2350 String typeName = jc.getClassName(type);
2351 int dim = readUByte(byteCodes, ++i);
2352 StringBuilder dims = new StringBuilder();
2354 for (int d = 0; d < dim; d++) {
2356 dims.insert(1, ",");
2358 dims.insert(1, smapper.popI());
2362 if (typeName.charAt(dim) == 'L') {
2363 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2366 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2367 dims.toString(), smapper.pushA(), typeName, fn
2372 private int generateTableSwitch(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 low = readInt4(byteCodes, table);
2378 int high = readInt4(byteCodes, table);
2380 final CharSequence swVar = smapper.popValue();
2381 smapper.flush(this);
2382 append("switch (").append(swVar).append(") {\n");
2383 while (low <= high) {
2384 int offset = i + readInt4(byteCodes, table);
2386 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2389 append(" default: ");
2390 goTo(this, i, dflt, topMostLabel);
2396 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2397 int table = i / 4 * 4 + 4;
2398 int dflt = i + readInt4(byteCodes, table);
2400 int n = readInt4(byteCodes, table);
2402 final CharSequence swVar = smapper.popValue();
2403 smapper.flush(this);
2404 append("switch (").append(swVar).append(") {\n");
2406 int cnstnt = readInt4(byteCodes, table);
2408 int offset = i + readInt4(byteCodes, table);
2410 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2412 append(" default: ");
2413 goTo(this, i, dflt, topMostLabel);
2419 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2420 String type = jc.getClassName(indx);
2421 if (!type.startsWith("[")) {
2423 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2424 smapper.popA(), smapper.pushI(),
2425 mangleClassName(type));
2428 while (type.charAt(cnt) == '[') {
2431 if (type.charAt(cnt) == 'L') {
2432 String component = type.substring(cnt + 1, type.length() - 1);
2433 requireReference(component);
2434 type = "vm." + mangleClassName(component);
2436 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2437 smapper.popA(), smapper.pushI(),
2442 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2443 smapper.popA(), smapper.pushI(), type
2449 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2450 String type = jc.getClassName(indx);
2451 if (!type.startsWith("[")) {
2452 emitNoFlush(smapper,
2453 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2454 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2457 while (type.charAt(cnt) == '[') {
2460 if (type.charAt(cnt) == 'L') {
2461 String component = type.substring(cnt + 1, type.length() - 1);
2462 requireReference(component);
2463 type = "vm." + mangleClassName(component);
2464 emitNoFlush(smapper,
2465 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2466 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2469 emitNoFlush(smapper,
2470 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2471 smapper.getT(0, VarType.REFERENCE, false), type
2477 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2478 for (int j = prev; j <= i; j++) {
2480 final int cc = readUByte(byteCodes, j);
2481 append(Integer.toString(cc));
2485 @JavaScriptBody(args = "msg", body = "")
2486 private static void println(String msg) {
2487 System.err.println(msg);