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 emit(smapper, this, "var @2 = @1.fld_@4_@3 || @5.call(@1);",
1431 smapper.popA(), smapper.pushT(type), fi[1], mangleClass,
1432 accessField(mangleClassAccess, "_" + fi[1], fi)
1435 addReference(fi[0]);
1438 case opc_putfield: {
1439 int indx = readUShortArg(byteCodes, i);
1440 String[] fi = jc.getFieldInfoName(indx);
1441 final int type = VarType.fromFieldType(fi[2].charAt(0));
1442 final String mangleClass = mangleClassName(fi[0]);
1443 final String mangleClassAccess = accessClassFalse(mangleClass);
1444 emit(smapper, this, "@3.call(@2, @1);",
1447 accessField(mangleClassAccess,
1450 addReference(fi[0]);
1453 case opc_getstatic: {
1454 int indx = readUShortArg(byteCodes, i);
1455 String[] fi = jc.getFieldInfoName(indx);
1456 final int type = VarType.fromFieldType(fi[2].charAt(0));
1457 String ac = accessClassFalse(mangleClassName(fi[0]));
1458 String af = accessField(ac, "_" + fi[1], fi);
1459 smapper.assign(this, type, af + "()");
1461 addReference(fi[0]);
1464 case opc_putstatic: {
1465 int indx = readUShortArg(byteCodes, i);
1466 String[] fi = jc.getFieldInfoName(indx);
1467 final int type = VarType.fromFieldType(fi[2].charAt(0));
1468 emit(smapper, this, "@1._@2(@3);",
1469 accessClassFalse(mangleClassName(fi[0])), fi[1],
1470 smapper.popT(type));
1472 addReference(fi[0]);
1475 case opc_checkcast: {
1476 int indx = readUShortArg(byteCodes, i);
1477 generateCheckcast(indx, smapper);
1481 case opc_instanceof: {
1482 int indx = readUShortArg(byteCodes, i);
1483 generateInstanceOf(indx, smapper);
1488 final CharSequence v = smapper.popA();
1491 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1492 smapper.pushA(), v);
1496 case opc_monitorenter: {
1497 debug("/* monitor enter */");
1502 case opc_monitorexit: {
1503 debug("/* monitor exit */");
1514 emit(smapper, this, "throw 'unknown bytecode @1';",
1515 Integer.toString(c));
1519 generateByteCodeComment(prev, i, byteCodes);
1525 if (previousTrap != null) {
1526 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1531 while (openBraces-- > 0) {
1542 private int generateIf(StackMapper mapper, byte[] byteCodes,
1543 int i, final CharSequence v2, final CharSequence v1,
1544 final String test, int topMostLabel
1545 ) throws IOException {
1547 int indx = i + readShortArg(byteCodes, i);
1548 append("if ((").append(v1)
1549 .append(") ").append(test).append(" (")
1550 .append(v2).append(")) ");
1551 goTo(this, i, indx, topMostLabel);
1555 private int readInt4(byte[] byteCodes, int offset) {
1556 final int d = byteCodes[offset + 0] << 24;
1557 final int c = byteCodes[offset + 1] << 16;
1558 final int b = byteCodes[offset + 2] << 8;
1559 final int a = byteCodes[offset + 3];
1560 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1562 private static int readUByte(byte[] byteCodes, int offset) {
1563 return byteCodes[offset] & 0xff;
1566 private static int readUShort(byte[] byteCodes, int offset) {
1567 return ((byteCodes[offset] & 0xff) << 8)
1568 | (byteCodes[offset + 1] & 0xff);
1570 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1571 return readUShort(byteCodes, offsetInstruction + 1);
1574 private static int readShort(byte[] byteCodes, int offset) {
1575 int signed = byteCodes[offset];
1576 byte b0 = (byte)signed;
1577 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1579 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1580 return readShort(byteCodes, offsetInstruction + 1);
1583 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1585 Boolean count = null;
1586 boolean array = false;
1588 int firstPos = sig.length();
1589 while (i < descriptor.length()) {
1590 char ch = descriptor.charAt(i++);
1611 if (ch == 'J' || ch == 'D') {
1617 sig.insert(firstPos, ch);
1619 returnType[0] = '[';
1620 sig.insert(firstPos, "_3");
1629 returnType[0] = 'V';
1630 sig.insert(firstPos, 'V');
1633 int next = descriptor.indexOf(';', i);
1634 String realSig = mangleSig(descriptor, i - 1, next + 1);
1639 sig.append(realSig);
1642 sig.insert(firstPos, realSig);
1644 sig.insert(firstPos, "_3");
1646 returnType[0] = 'L';
1655 throw new IllegalStateException("Invalid char: " + ch);
1660 static String mangleSig(String sig) {
1661 return mangleSig(sig, 0, sig.length());
1664 private static String mangleMethodName(String name) {
1665 StringBuilder sb = new StringBuilder(name.length() * 2);
1666 int last = name.length();
1667 for (int i = 0; i < last; i++) {
1668 final char ch = name.charAt(i);
1670 case '_': sb.append("_1"); break;
1671 default: sb.append(ch); break;
1674 return sb.toString();
1676 private static String mangleSig(String txt, int first, int last) {
1677 StringBuilder sb = new StringBuilder((last - first) * 2);
1678 for (int i = first; i < last; i++) {
1679 final char ch = txt.charAt(i);
1681 case '/': sb.append('_'); break;
1682 case '_': sb.append("_1"); break;
1683 case ';': sb.append("_2"); break;
1684 case '[': sb.append("_3"); break;
1686 if (Character.isJavaIdentifierPart(ch)) {
1690 String hex = Integer.toHexString(ch).toLowerCase();
1691 for (int m = hex.length(); m < 4; m++) {
1699 return sb.toString();
1702 private static String mangleClassName(String name) {
1703 return mangleSig(name);
1706 private static String findMethodName(MethodData m, StringBuilder cnt) {
1707 StringBuilder name = new StringBuilder();
1708 if ("<init>".equals(m.getName())) { // NOI18N
1709 name.append("cons"); // NOI18N
1710 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1711 name.append("class"); // NOI18N
1713 name.append(mangleMethodName(m.getName()));
1716 countArgs(m.getInternalSig(), new char[1], name, cnt);
1717 return name.toString();
1720 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1721 StringBuilder name = new StringBuilder();
1722 String descr = mi[2];//mi.getDescriptor();
1724 if ("<init>".equals(nm)) { // NOI18N
1725 name.append("cons"); // NOI18N
1727 name.append(mangleMethodName(nm));
1729 countArgs(descr, returnType, name, cnt);
1730 return name.toString();
1733 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1734 throws IOException {
1735 int methodIndex = readUShortArg(byteCodes, i);
1736 String[] mi = jc.getFieldInfoName(methodIndex);
1737 char[] returnType = { 'V' };
1738 StringBuilder cnt = new StringBuilder();
1739 String mn = findMethodName(mi, cnt, returnType);
1741 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1742 final CharSequence[] vars = new CharSequence[numArguments];
1744 for (int j = numArguments - 1; j >= 0; --j) {
1745 vars[j] = mapper.popValue();
1749 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1750 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1752 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1753 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1755 if (vars[1] instanceof String) {
1756 String field = vars[1].toString();
1757 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1758 vars[1] = "c._" + field.substring(1, field.length() - 1);
1763 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1764 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1766 if (vars[1] instanceof String) {
1767 String field = vars[2].toString();
1768 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1769 vars[2] = "c._" + field.substring(1, field.length() - 1);
1774 if (returnType[0] != 'V') {
1777 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1781 final String in = mi[0];
1784 in.equals("org/apidesign/html/boot/spi/Fn") ||
1785 in.equals("org/netbeans/html/boot/spi/Fn")
1787 mcn = "java_lang_Class";
1789 mcn = mangleClassName(in);
1791 String object = accessClassFalse(mcn);
1792 if (mn.startsWith("cons_")) {
1793 object += ".constructor";
1795 append(accessStaticMethod(object, mn, mi));
1801 if (numArguments > 0) {
1803 for (int j = 1; j < numArguments; ++j) {
1813 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1814 throws IOException {
1815 int methodIndex = readUShortArg(byteCodes, i);
1816 String[] mi = jc.getFieldInfoName(methodIndex);
1817 char[] returnType = { 'V' };
1818 StringBuilder cnt = new StringBuilder();
1819 String mn = findMethodName(mi, cnt, returnType);
1821 final int numArguments = cnt.length() + 1;
1822 final CharSequence[] vars = new CharSequence[numArguments];
1824 for (int j = numArguments - 1; j >= 0; --j) {
1825 vars[j] = mapper.popValue();
1828 if (returnType[0] != 'V') {
1831 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1835 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1837 for (int j = 1; j < numArguments; ++j) {
1847 private void addReference(String cn) throws IOException {
1848 if (requireReference(cn)) {
1849 debug(" /* needs " + cn + " */");
1853 private void outType(String d, StringBuilder out) {
1855 while (d.charAt(0) == '[') {
1859 if (d.charAt(0) == 'L') {
1860 assert d.charAt(d.length() - 1) == ';';
1861 out.append(mangleClassName(d).substring(0, d.length() - 1));
1867 private String encodeConstant(int entryIndex) throws IOException {
1868 String[] classRef = { null };
1869 String s = jc.stringValue(entryIndex, classRef);
1870 if (classRef[0] != null) {
1871 if (classRef[0].startsWith("[")) {
1872 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1874 addReference(classRef[0]);
1875 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1881 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1882 byte[] arr = m.findAnnotationData(true);
1886 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1887 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1888 class P extends AnnotationParser {
1894 String[] args = new String[30];
1900 protected void visitAttr(String type, String attr, String at, String value) {
1901 if (type.equals(jvmType)) {
1902 if ("body".equals(attr)) {
1904 } else if ("args".equals(attr)) {
1905 args[cnt++] = value;
1907 throw new IllegalArgumentException(attr);
1910 if (type.equals(htmlType)) {
1912 if ("body".equals(attr)) {
1914 } else if ("args".equals(attr)) {
1915 args[cnt++] = value;
1916 } else if ("javacall".equals(attr)) {
1917 javacall = "1".equals(value);
1918 } else if ("wait4js".equals(attr)) {
1919 // ignore, we always invoke synchronously
1921 throw new IllegalArgumentException(attr);
1928 if (p.body == null) {
1931 StringBuilder cnt = new StringBuilder();
1932 final String mn = findMethodName(m, cnt);
1933 append("m = ").append(destObject).append(".").append(mn);
1934 append(" = function(");
1937 StringBuilder toValue = new StringBuilder();
1938 for (int i = 0; i < cnt.length(); i++) {
1940 space = outputArg(this, p.args, index);
1941 if (p.html4j && space.length() > 0) {
1942 toValue.append("\n ").append(p.args[index]).append(" = ")
1943 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1944 append(p.args[index]).append(");");
1948 append(") {").append("\n");
1949 append(toValue.toString());
1951 int lastSlash = jc.getClassName().lastIndexOf('/');
1952 final String pkg = jc.getClassName().substring(0, lastSlash);
1953 append(mangleCallbacks(pkg, p.body));
1954 requireReference(pkg + "/$JsCallbacks$");
1962 private static CharSequence mangleCallbacks(String pkgName, String body) {
1963 StringBuilder sb = new StringBuilder();
1966 int next = body.indexOf(".@", pos);
1968 sb.append(body.substring(pos));
1969 body = sb.toString();
1974 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1979 String refId = body.substring(ident, next);
1981 sb.append(body.substring(pos, ident));
1983 int sigBeg = body.indexOf('(', next);
1984 int sigEnd = body.indexOf(')', sigBeg);
1985 int colon4 = body.indexOf("::", next);
1986 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1987 throw new IllegalStateException("Malformed body " + body);
1989 String fqn = body.substring(next + 2, colon4);
1990 String method = body.substring(colon4 + 2, sigBeg);
1991 String params = body.substring(sigBeg, sigEnd + 1);
1993 int paramBeg = body.indexOf('(', sigEnd + 1);
1995 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
1996 sb.append(mangleJsCallbacks(fqn, method, params, false));
1997 sb.append("(").append(refId);
1998 if (body.charAt(paramBeg + 1) != ')') {
2006 int next = body.indexOf("@", pos);
2011 sb.append(body.substring(pos));
2015 sb = new StringBuilder();
2018 sb.append(body.substring(pos, next));
2020 int sigBeg = body.indexOf('(', next);
2021 int sigEnd = body.indexOf(')', sigBeg);
2022 int colon4 = body.indexOf("::", next);
2023 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2024 throw new IllegalStateException("Malformed body " + body);
2026 String fqn = body.substring(next + 1, colon4);
2027 String method = body.substring(colon4 + 2, sigBeg);
2028 String params = body.substring(sigBeg, sigEnd + 1);
2030 int paramBeg = body.indexOf('(', sigEnd + 1);
2032 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2033 sb.append(mangleJsCallbacks(fqn, method, params, true));
2039 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2040 if (params.startsWith("(")) {
2041 params = params.substring(1);
2043 if (params.endsWith(")")) {
2044 params = params.substring(0, params.length() - 1);
2046 StringBuilder sb = new StringBuilder();
2047 final String fqnu = fqn.replace('.', '_');
2048 final String rfqn = mangleClassName(fqnu);
2049 final String rm = mangleMethodName(method);
2052 StringBuilder pb = new StringBuilder();
2053 int len = params.length();
2055 while (indx < len) {
2056 char ch = params.charAt(indx);
2057 if (ch == '[' || ch == 'L') {
2058 int column = params.indexOf(';', indx) + 1;
2059 if (column > indx) {
2060 String real = params.substring(indx, column);
2061 if ("Ljava/lang/String;".equals(real)) {
2062 pb.append("Ljava/lang/String;");
2067 pb.append("Ljava/lang/Object;");
2074 srp = mangleSig(pb.toString());
2076 final String rp = mangleSig(params);
2077 final String mrp = mangleMethodName(rp);
2078 sb.append(rfqn).append("$").append(rm).
2079 append('$').append(mrp).append("__Ljava_lang_Object_2");
2081 sb.append('L').append(fqnu).append("_2");
2084 return sb.toString();
2087 private static String className(ClassData jc) {
2088 //return jc.getName().getInternalName().replace('/', '_');
2089 return mangleClassName(jc.getClassName());
2092 private static String[] findAnnotation(
2093 byte[] arr, ClassData cd, final String className,
2094 final String... attrNames
2095 ) throws IOException {
2099 final String[] values = new String[attrNames.length];
2100 final boolean[] found = { false };
2101 final String jvmType = "L" + className.replace('.', '/') + ";";
2102 AnnotationParser ap = new AnnotationParser(false, true) {
2104 protected void visitAttr(String type, String attr, String at, String value) {
2105 if (type.equals(jvmType)) {
2107 for (int i = 0; i < attrNames.length; i++) {
2108 if (attrNames[i].equals(attr)) {
2117 return found[0] ? values : null;
2120 private CharSequence initField(FieldData v) {
2121 final String is = v.getInternalSig();
2122 if (is.length() == 1) {
2123 switch (is.charAt(0)) {
2129 case 'I': return " = 0;";
2131 case 'D': return " = 0.0;";
2133 throw new IllegalStateException(is);
2139 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2140 AnnotationParser ap = new AnnotationParser(true, false) {
2141 int[] cnt = new int[32];
2145 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2146 final String slashType = attrType.substring(1, attrType.length() - 1);
2147 requireReference(slashType);
2149 if (cnt[depth]++ > 0) {
2153 append('"').append(attrType).append("\" : ");
2160 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2166 protected void visitValueStart(String attrName, char type) throws IOException {
2167 if (cnt[depth]++ > 0) {
2171 if (attrName != null) {
2172 append('"').append(attrName).append("\" : ");
2180 protected void visitValueEnd(String attrName, char type) throws IOException {
2188 protected void visitAttr(String type, String attr, String attrType, String value)
2189 throws IOException {
2190 if (attr == null && value == null) {
2197 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2198 throws IOException {
2199 final String slashType = attrType.substring(1, attrType.length() - 1);
2200 requireReference(slashType);
2202 final String cn = mangleClassName(slashType);
2203 append(accessClassFalse(cn))
2204 .append("['valueOf__L").
2206 append("_2Ljava_lang_String_2']('").
2214 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2215 final String name = args[indx];
2219 if (name.contains(",")) {
2220 throw new IOException("Wrong parameter with ',': " + name);
2226 final void emitNoFlush(
2228 final String format, final CharSequence... params
2229 ) throws IOException {
2230 emitImpl(this, format, params);
2232 static final void emit(
2234 final Appendable out,
2235 final String format, final CharSequence... params
2236 ) throws IOException {
2238 emitImpl(out, format, params);
2240 static void emitImpl(final Appendable out,
2241 final String format,
2242 final CharSequence... params) throws IOException {
2243 final int length = format.length();
2246 int paramOffset = format.indexOf('@');
2247 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2248 final char paramChar = format.charAt(paramOffset + 1);
2249 if ((paramChar >= '1') && (paramChar <= '9')) {
2250 final int paramIndex = paramChar - '0' - 1;
2252 out.append(format, processed, paramOffset);
2253 out.append(params[paramIndex]);
2256 processed = paramOffset + 1;
2259 paramOffset = format.indexOf('@', paramOffset + 1);
2262 out.append(format, processed, length);
2265 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2266 append("} catch (e) {\n");
2268 for (TrapData e : traps) {
2272 if (e.catch_cpx != 0) { //not finally
2273 final String classInternalName = jc.getClassName(e.catch_cpx);
2274 addReference(classInternalName);
2275 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2276 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2277 append("var stA0 = e;");
2278 goTo(this, current, e.handler_pc, topMostLabel);
2281 finallyPC = e.handler_pc;
2284 if (finallyPC == -1) {
2287 append("var stA0 = e;");
2288 goTo(this, current, finallyPC, topMostLabel);
2293 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2296 out.append("{ gt = 0; continue X_" + to + "; }");
2298 out.append("{ gt = " + to + "; continue X_0; }");
2301 out.append("{ gt = " + to + "; break IF; }");
2305 private static void emitIf(
2307 Appendable out, String pattern,
2309 int current, int to, int canBack
2310 ) throws IOException {
2312 emitImpl(out, pattern, param);
2313 goTo(out, current, to, canBack);
2316 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2319 case 4: jvmType = "[Z"; break;
2320 case 5: jvmType = "[C"; break;
2321 case 6: jvmType = "[F"; break;
2322 case 7: jvmType = "[D"; break;
2323 case 8: jvmType = "[B"; break;
2324 case 9: jvmType = "[S"; break;
2325 case 10: jvmType = "[I"; break;
2326 case 11: jvmType = "[J"; break;
2327 default: throw new IllegalStateException("Array type: " + atype);
2330 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2331 smapper.popI(), smapper.pushA(), jvmType);
2334 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2335 String typeName = jc.getClassName(type);
2336 String ref = "null";
2337 if (typeName.startsWith("[")) {
2338 typeName = "'[" + typeName + "'";
2340 ref = "vm." + mangleClassName(typeName);
2341 typeName = "'[L" + typeName + ";'";
2344 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2345 smapper.popI(), smapper.pushA(), typeName, ref);
2348 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2349 String typeName = jc.getClassName(type);
2350 int dim = readUByte(byteCodes, ++i);
2351 StringBuilder dims = new StringBuilder();
2353 for (int d = 0; d < dim; d++) {
2355 dims.insert(1, ",");
2357 dims.insert(1, smapper.popI());
2361 if (typeName.charAt(dim) == 'L') {
2362 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2365 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2366 dims.toString(), smapper.pushA(), typeName, fn
2371 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2372 int table = i / 4 * 4 + 4;
2373 int dflt = i + readInt4(byteCodes, table);
2375 int low = readInt4(byteCodes, table);
2377 int high = readInt4(byteCodes, table);
2379 final CharSequence swVar = smapper.popValue();
2380 smapper.flush(this);
2381 append("switch (").append(swVar).append(") {\n");
2382 while (low <= high) {
2383 int offset = i + readInt4(byteCodes, table);
2385 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2388 append(" default: ");
2389 goTo(this, i, dflt, topMostLabel);
2395 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2396 int table = i / 4 * 4 + 4;
2397 int dflt = i + readInt4(byteCodes, table);
2399 int n = readInt4(byteCodes, table);
2401 final CharSequence swVar = smapper.popValue();
2402 smapper.flush(this);
2403 append("switch (").append(swVar).append(") {\n");
2405 int cnstnt = readInt4(byteCodes, table);
2407 int offset = i + readInt4(byteCodes, table);
2409 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2411 append(" default: ");
2412 goTo(this, i, dflt, topMostLabel);
2418 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2419 String type = jc.getClassName(indx);
2420 if (!type.startsWith("[")) {
2422 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2423 smapper.popA(), smapper.pushI(),
2424 mangleClassName(type));
2427 while (type.charAt(cnt) == '[') {
2430 if (type.charAt(cnt) == 'L') {
2431 String component = type.substring(cnt + 1, type.length() - 1);
2432 requireReference(component);
2433 type = "vm." + mangleClassName(component);
2435 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2436 smapper.popA(), smapper.pushI(),
2441 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2442 smapper.popA(), smapper.pushI(), type
2448 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2449 String type = jc.getClassName(indx);
2450 if (!type.startsWith("[")) {
2451 emitNoFlush(smapper,
2452 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2453 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2456 while (type.charAt(cnt) == '[') {
2459 if (type.charAt(cnt) == 'L') {
2460 String component = type.substring(cnt + 1, type.length() - 1);
2461 requireReference(component);
2462 type = "vm." + mangleClassName(component);
2463 emitNoFlush(smapper,
2464 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2465 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2468 emitNoFlush(smapper,
2469 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2470 smapper.getT(0, VarType.REFERENCE, false), type
2476 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2477 for (int j = prev; j <= i; j++) {
2479 final int cc = readUByte(byteCodes, j);
2480 append(Integer.toString(cc));
2484 @JavaScriptBody(args = "msg", body = "")
2485 private static void println(String msg) {
2486 System.err.println(msg);