2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import org.apidesign.bck2brwsr.core.JavaScriptBody;
23 import org.apidesign.vm4brwsr.Bck2Brwsr.Flow;
24 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
26 /** Translator of the code inside class files to JavaScript.
28 * @author Jaroslav Tulach <jtulach@netbeans.org>
30 abstract class ByteCodeToJavaScript implements Appendable {
32 private final Appendable out;
33 private final StringArray classRefs = new StringArray();
34 private boolean outChanged;
35 private boolean callbacks;
37 protected ByteCodeToJavaScript(Appendable out) {
42 public final Appendable append(CharSequence csq) throws IOException {
49 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
50 out.append(csq, start, end);
56 public final Appendable append(char c) throws IOException {
62 /* Collects additional required resources.
64 * @param internalClassName classes that were referenced and should be loaded in order the
65 * generated JavaScript code works properly. The names are in internal
66 * JVM form so String is <code>java/lang/String</code>.
68 protected abstract boolean requireReference(String internalClassName);
71 * @param resourcePath name of resources to read
73 protected abstract void requireScript(String resourcePath) throws IOException;
75 protected abstract void requireResource(String resourcePath) throws IOException;
77 /** Allows subclasses to redefine what field a function representing a
78 * class gets assigned. By default it returns the suggested name followed
79 * by <code>" = "</code>;
81 * @param className suggested name of the class
83 /* protected */ String assignClass(String className) {
84 return className + " = ";
86 /* protected */ String accessClass(String classOperation) {
87 return classOperation;
90 final String accessClassFalse(String classOperation) {
91 if (jc.getClassName().replace('/', '_').equals(classOperation)) {
94 classRefs.addIfMissing(classOperation);
95 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
98 protected String accessField(String object, String mangledName,
99 String[] fieldInfoName) throws IOException {
100 return object + "." + mangledName;
103 protected String accessStaticMethod(
106 String[] fieldInfoName) throws IOException {
107 return object + "." + mangledName;
110 protected String accessVirtualMethod(
113 String[] fieldInfoName,
115 ) throws IOException {
116 return object + "." + mangledName + '(';
119 protected void declaredClass(ClassData classData, String mangledName)
123 protected void declaredField(FieldData fieldData,
125 String mangledName) throws IOException {
128 protected void declaredMethod(MethodData methodData,
130 String mangledName) throws IOException {
133 /** Prints out a debug message.
135 * @param msg the message
136 * @return true if the message has been printed
137 * @throws IOException
139 boolean debug(String msg) throws IOException {
145 * Converts a given class file to a JavaScript version.
147 * @param classFile input stream with code of the .class file
148 * @return the initialization code for this class, if any. Otherwise <code>null</code>
150 * @throws IOException if something goes wrong during read or write or translating
153 public String compile(InputStream classFile) throws IOException {
154 return compile(new ClassData(classFile));
157 protected String compile(ClassData classData) throws IOException {
159 final String cn = this.jc.getClassName();
161 return compileImpl(cn);
162 } catch (IOException ex) {
163 throw new IOException("Cannot compile " + cn + ":", ex);
167 private String compileImpl(final String cn) throws IOException {
168 this.callbacks = cn.endsWith("/$JsCallbacks$");
169 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
170 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
171 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
174 byte[] arrData = jc.findAnnotationData(true);
176 String[] arr = findAnnotation(arrData, jc,
177 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
178 "resource", "processByteCode"
181 if (!arr[0].isEmpty()) {
182 requireScript(arr[0]);
184 if ("0".equals(arr[1])) {
189 final String jsResource;
191 String[] arr = findAnnotation(arrData, jc,
192 "net.java.html.js.JavaScriptResource",
196 if (arr[0].startsWith("/")) {
199 int last = cn.lastIndexOf('/');
200 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
206 String[] proto = findAnnotation(arrData, jc,
207 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
208 "container", "prototype"
210 StringArray toInitilize = new StringArray();
211 final String className = className(jc);
212 append("\n\n").append(assignClass(className));
213 append("function ").append(className).append("() {");
215 append("\n var CLS = ").append(className).append(';');
216 append("\n if (!CLS.$class) {");
218 String sc = jc.getSuperClassName(); // with _
219 append("\n var pp = ").
220 append(accessClass(mangleClassName(sc))).append("(true);");
221 append("\n var p = CLS.prototype = pp;");
222 append("\n var c = p;");
223 append("\n var sprcls = pp.constructor.$class;");
225 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
226 if (proto[0] == null) {
229 append("\n var c = ").append(proto[0]).append(";");
230 append("\n var sprcls = null;");
232 for (FieldData v : jc.getFields()) {
234 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
235 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
239 append("\n CLS.fld_").append(v.getName()).append(initField(v));
240 append("\n m = c._").append(v.getName()).append(" = function (v) {")
241 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
242 .append(" = v; return CLS.fld_").
243 append(v.getName()).append("; };");
245 append("\n m = c._").append(v.getName()).append(" = function (v) {")
246 .append(" if (arguments.length == 1) this.fld_").
247 append(className).append('_').append(v.getName())
248 .append(" = v; return this.fld_").
249 append(className).append('_').append(v.getName())
253 declaredField(v, "c", "_" + v.getName());
255 for (MethodData m : jc.getMethods()) {
256 byte[] onlyArr = m.findAnnotationData(true);
257 if (javaScriptOnly(onlyArr)) continue;
263 mn = generateStaticMethod(destObject, m, toInitilize);
265 if (m.isConstructor()) {
267 mn = generateInstanceMethod(destObject, m);
270 mn = generateInstanceMethod(destObject, m);
273 declaredMethod(m, destObject, mn);
274 byte[] runAnno = m.findAnnotationData(false);
275 if (runAnno != null) {
276 append("\n m.anno = {");
277 generateAnno(jc, runAnno);
280 append("\n m.access = " + m.getAccess()).append(";");
281 append("\n m.cls = CLS;");
283 append("\n c.constructor = CLS;");
284 append("\n function ").append(className).append("fillInstOf(x) {");
285 String instOfName = "$instOf_" + className;
286 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
287 if (jc.isInterface()) {
288 for (MethodData m : jc.getMethods()) {
289 if ((m.getAccess() & ACC_ABSTRACT) == 0
290 && (m.getAccess() & ACC_STATIC) == 0
291 && (m.getAccess() & ACC_PRIVATE) == 0) {
292 final String mn = findMethodName(m, new StringBuilder());
293 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
297 for (String superInterface : jc.getSuperInterfaces()) {
298 String intrfc = superInterface.replace('/', '_');
299 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
300 requireReference(superInterface);
303 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
304 append("\n ").append(className).append("fillInstOf(c);");
305 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
306 append("\n CLS.$class = 'temp';");
307 append("\n CLS.$class = ");
308 append(accessClass("java_lang_Class(true);"));
309 append("\n CLS.$class.jvmName = '").append(cn).append("';");
310 append("\n CLS.$class.superclass = sprcls;");
311 append("\n CLS.$class.interfaces = function() { return [");
313 boolean first = true;
314 for (String intrfc : jc.getSuperInterfaces()) {
318 requireReference(intrfc);
319 String mangledIface = mangleClassName(intrfc);
321 append(accessClass(mangledIface)).append("(false).constructor.$class");
326 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
327 append("\n CLS.$class.cnstr = CLS;");
328 byte[] classAnno = jc.findAnnotationData(false);
329 if (classAnno != null) {
330 append("\n CLS.$class.anno = {");
331 generateAnno(jc, classAnno);
334 for (String init : toInitilize.toArray()) {
335 append("\n ").append(init).append("();");
337 for (String ref : classRefs.toArray()) {
338 append("\n var refs_").append(ref).append(";");
342 if (jsResource != null) {
343 requireResource(jsResource);
347 append("\n if (arguments.length === 0) {");
348 append("\n if (!(this instanceof CLS)) {");
349 append("\n return new CLS();");
351 for (FieldData v : jc.getFields()) {
352 byte[] onlyArr = v.findAnnotationData(true);
353 if (javaScriptOnly(onlyArr)) continue;
355 append("\n this.fld_").
356 append(className).append('_').
357 append(v.getName()).append(initField(v));
360 append("\n return this;");
362 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
365 declaredClass(jc, className);
367 // StringBuilder sb = new StringBuilder();
368 // for (String init : toInitilize.toArray()) {
369 // sb.append("\n").append(init).append("();");
374 private boolean javaScriptOnly(byte[] anno) throws IOException {
375 String[] only = findAnnotation(anno, jc,
376 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
380 if (only[0] != null && only[1] != null) {
381 append("\n p.").append(only[0]).append(" = ")
382 .append(only[1]).append(";");
384 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
385 append("\n p['").append(only[0]).append("'] = p.")
386 .append(only[0]).append(";");
392 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
393 String jsb = javaScriptBody(destObject, m, true);
397 final String mn = findMethodName(m, new StringBuilder());
398 boolean defineProp = generateMethod(destObject, mn, m);
399 if (mn.equals("class__V")) {
401 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
403 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
409 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
410 String jsb = javaScriptBody(destObject, m, false);
414 final String mn = findMethodName(m, new StringBuilder());
415 generateMethod(destObject, mn, m);
419 private boolean generateMethod(String destObject, String name, MethodData m)
421 final StackMapIterator stackMapIterator = m.createStackMapIterator();
422 TrapDataIterator trap = m.getTrapDataIterator();
423 final LocalsMapper lmapper =
424 new LocalsMapper(stackMapIterator.getArguments());
427 "java/lang/Object".equals(jc.getClassName()) ||
428 "java/lang/reflect/Array".equals(jc.getClassName());
431 append("Object.defineProperty(").append(destObject).
432 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
434 append("m = ").append(destObject).append(".").append(name).append(" = function(");
436 lmapper.outputArguments(this, m.isStatic());
437 append(") {").append("\n");
439 final byte[] byteCodes = m.getCode();
440 if (byteCodes == null) {
441 if (debug(" throw 'no code found for ")) {
443 .append(jc.getClassName()).append('.')
444 .append(m.getName()).append("';\n");
453 Flow flow = checkFlow(m);
455 final StackMapper smapper = new StackMapper();
458 append(" var ").append(" lcA0 = this;\n");
462 TrapData[] previousTrap = null;
463 boolean wide = false;
465 if (stackMapIterator.isEmpty()) {
472 append("\n var gt = 0;\n");
479 int topMostLabel = 0;
480 for (int i = 0; i < byteCodes.length; i++) {
483 stackMapIterator.advanceTo(i);
484 boolean changeInCatch = trap.advanceTo(i);
485 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
486 if (previousTrap != null) {
487 generateCatch(previousTrap, flow, i, topMostLabel);
491 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
493 if (flow == null && i != 0) {
496 if (openBraces > 64) {
497 for (int c = 0; c < 64; c++) {
504 lastStackFrame = stackMapIterator.getFrameIndex();
505 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
506 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
508 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
511 if (!flow.isFlow(i)) {
513 throw new IOException("Expecting flow suggestion at " + i);
517 changeInCatch = true;
519 debug(" /* " + i + " */ ");
521 if (changeInCatch && trap.useTry()) {
523 previousTrap = trap.current();
526 if (flow.isLoop(i)) {
527 append(" for (;;) {\n");
529 if (flow.isBreak(i)) {
532 for (int j = 0; j < flow.isEnd(i); j++) {
535 if (flow.isElse(i)) {
539 final int c = readUByte(byteCodes, i);
542 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
545 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
548 smapper.assign(this, VarType.LONG, lmapper.getL(0));
551 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
554 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
557 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
560 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
563 smapper.assign(this, VarType.LONG, lmapper.getL(1));
566 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
569 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
572 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
575 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
578 smapper.assign(this, VarType.LONG, lmapper.getL(2));
581 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
584 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
587 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
590 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
593 smapper.assign(this, VarType.LONG, lmapper.getL(3));
596 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
599 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
603 final int indx = wide ? readUShort(byteCodes, i++)
604 : readUByte(byteCodes, i);
606 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
611 final int indx = wide ? readUShort(byteCodes, i++)
612 : readUByte(byteCodes, i);
614 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
619 final int indx = wide ? readUShort(byteCodes, i++)
620 : readUByte(byteCodes, i);
622 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
627 final int indx = wide ? readUShort(byteCodes, i++)
628 : readUByte(byteCodes, i);
630 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
635 final int indx = wide ? readUShort(byteCodes, i++)
636 : readUByte(byteCodes, i);
638 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
643 final int indx = wide ? readUShort(byteCodes, i++)
644 : readUByte(byteCodes, i);
646 emit(smapper, this, "var @1 = @2;",
647 lmapper.setI(indx), smapper.popI());
652 final int indx = wide ? readUShort(byteCodes, i++)
653 : readUByte(byteCodes, i);
655 emit(smapper, this, "var @1 = @2;",
656 lmapper.setL(indx), smapper.popL());
661 final int indx = wide ? readUShort(byteCodes, i++)
662 : readUByte(byteCodes, i);
664 emit(smapper, this, "var @1 = @2;",
665 lmapper.setF(indx), smapper.popF());
670 final int indx = wide ? readUShort(byteCodes, i++)
671 : readUByte(byteCodes, i);
673 emit(smapper, this, "var @1 = @2;",
674 lmapper.setD(indx), smapper.popD());
679 final int indx = wide ? readUShort(byteCodes, i++)
680 : readUByte(byteCodes, i);
682 emit(smapper, this, "var @1 = @2;",
683 lmapper.setA(indx), smapper.popA());
687 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
690 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
693 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
696 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
699 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
702 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
705 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
708 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
711 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
714 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
717 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
720 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
723 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
726 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
729 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
732 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
735 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
738 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
741 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
744 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
747 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
750 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
753 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
756 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
759 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
762 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
765 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
768 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
771 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
774 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
777 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
780 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
783 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
784 smapper.getI(1), smapper.popI());
787 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
788 smapper.getL(1), smapper.popL());
791 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
794 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
797 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
798 smapper.getI(1), smapper.popI());
801 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
802 smapper.getL(1), smapper.popL());
805 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
808 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
811 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
814 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
817 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
820 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
823 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
826 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
829 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
832 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
835 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
838 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
841 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
844 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
847 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
850 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
853 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
856 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
860 final int varIndx = wide ? readUShort(byteCodes, i++)
861 : readUByte(byteCodes, i);
863 final int incrBy = wide ? readShort(byteCodes, i++)
867 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
869 emit(smapper, this, "@1 += @2;",
870 lmapper.getI(varIndx),
871 Integer.toString(incrBy));
876 emit(smapper, this, "return;");
879 emit(smapper, this, "return @1;", smapper.popI());
882 emit(smapper, this, "return @1;", smapper.popL());
885 emit(smapper, this, "return @1;", smapper.popF());
888 emit(smapper, this, "return @1;", smapper.popD());
891 emit(smapper, this, "return @1;", smapper.popA());
894 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
897 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
900 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
903 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
907 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
910 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
913 smapper.replace(this, VarType.DOUBLE, "@1",
917 smapper.replace(this, VarType.FLOAT, "@1",
921 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
925 smapper.replace(this, VarType.LONG, "(@1).toLong()",
929 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
933 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
936 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
940 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
942 case opc_aconst_null:
943 smapper.assign(this, VarType.REFERENCE, "null");
946 smapper.assign(this, VarType.INTEGER, "-1");
949 smapper.assign(this, VarType.INTEGER, "0");
952 smapper.assign(this, VarType.DOUBLE, "0");
955 smapper.assign(this, VarType.LONG, "0");
958 smapper.assign(this, VarType.FLOAT, "0");
961 smapper.assign(this, VarType.INTEGER, "1");
964 smapper.assign(this, VarType.LONG, "1");
967 smapper.assign(this, VarType.FLOAT, "1");
970 smapper.assign(this, VarType.DOUBLE, "1");
973 smapper.assign(this, VarType.INTEGER, "2");
976 smapper.assign(this, VarType.FLOAT, "2");
979 smapper.assign(this, VarType.INTEGER, "3");
982 smapper.assign(this, VarType.INTEGER, "4");
985 smapper.assign(this, VarType.INTEGER, "5");
988 int indx = readUByte(byteCodes, ++i);
989 String v = encodeConstant(indx);
990 int type = VarType.fromConstantType(jc.getTag(indx));
991 smapper.assign(this, type, v);
996 int indx = readUShortArg(byteCodes, i);
998 String v = encodeConstant(indx);
999 int type = VarType.fromConstantType(jc.getTag(indx));
1000 if (type == VarType.LONG) {
1001 final Long lv = new Long(v);
1002 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
1003 final int hi = (int)(lv.longValue() >> 32);
1005 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
1007 smapper.assign(this, VarType.LONG,
1008 "0x" + Integer.toHexString(hi) + ".next32(0x" +
1009 Integer.toHexString(low) + ")"
1013 smapper.assign(this, type, v);
1018 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
1022 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1023 smapper.popF(), smapper.popF(), smapper.pushI());
1027 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1028 smapper.popD(), smapper.popD(), smapper.pushI());
1031 i = generateIf(smapper, flow, byteCodes, i, smapper.popA(), smapper.popA(),
1032 "===", topMostLabel);
1035 i = generateIf(smapper, flow, byteCodes, i, smapper.popA(), smapper.popA(),
1036 "!==", topMostLabel);
1039 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1040 "==", topMostLabel);
1043 int indx = i + readShortArg(byteCodes, i);
1044 emitIf(smapper, flow, this, "if ((@1) == 0) ",
1045 smapper.popI(), i, indx, topMostLabel);
1050 int indx = i + readShortArg(byteCodes, i);
1051 emitIf(smapper, flow, this, "if ((@1) != 0) ",
1052 smapper.popI(), i, indx, topMostLabel);
1057 int indx = i + readShortArg(byteCodes, i);
1058 emitIf(smapper, flow, this, "if ((@1) < 0) ",
1059 smapper.popI(), i, indx, topMostLabel);
1064 int indx = i + readShortArg(byteCodes, i);
1065 emitIf(smapper, flow, this, "if ((@1) <= 0) ",
1066 smapper.popI(), i, indx, topMostLabel);
1071 int indx = i + readShortArg(byteCodes, i);
1072 emitIf(smapper, flow, this, "if ((@1) > 0) ",
1073 smapper.popI(), i, indx, topMostLabel);
1078 int indx = i + readShortArg(byteCodes, i);
1079 emitIf(smapper, flow, this, "if ((@1) >= 0) ",
1080 smapper.popI(), i, indx, topMostLabel);
1084 case opc_ifnonnull: {
1085 int indx = i + readShortArg(byteCodes, i);
1086 emitIf(smapper, flow, this, "if ((@1) !== null) ",
1087 smapper.popA(), i, indx, topMostLabel);
1092 int indx = i + readShortArg(byteCodes, i);
1093 emitIf(smapper, flow, this, "if ((@1) === null) ",
1094 smapper.popA(), i, indx, topMostLabel);
1099 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1100 "!=", topMostLabel);
1103 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1107 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1108 "<=", topMostLabel);
1111 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1115 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1116 ">=", topMostLabel);
1119 smapper.flush(this);
1121 int indx = i + readShortArg(byteCodes, i);
1122 goTo(this, flow, i, indx, topMostLabel);
1127 case opc_lookupswitch: {
1128 i = generateLookupSwitch(i, byteCodes, smapper, flow, topMostLabel);
1131 case opc_tableswitch: {
1132 i = generateTableSwitch(i, byteCodes, smapper, flow, topMostLabel);
1135 case opc_invokeinterface: {
1136 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1139 case opc_invokevirtual:
1140 i = invokeVirtualMethod(byteCodes, i, smapper);
1142 case opc_invokespecial:
1143 i = invokeStaticMethod(byteCodes, i, smapper, false);
1145 case opc_invokestatic:
1146 i = invokeStaticMethod(byteCodes, i, smapper, true);
1148 case opc_invokedynamic: {
1149 int indx = readUShortArg(byteCodes, i);
1150 println("invoke dynamic: " + indx);
1151 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1152 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1153 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1154 println(" type: " + methodHandle.cpx1);
1155 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1156 String mcn = mangleClassName(mi[0]);
1157 char[] returnType = {'V'};
1158 StringBuilder cnt = new StringBuilder();
1159 String mn = findMethodName(mi, cnt, returnType);
1160 StringBuilder sb = new StringBuilder();
1161 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1162 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1163 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1164 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1165 sb.append(" mn : ").append(mn).append("\n");
1166 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1167 throw new IOException(sb.toString());
1169 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1170 String type = jc.StringValue(nameAndType.cpx2);
1171 String object = accessClass(mcn) + "(false)";
1172 if (mn.startsWith("cons_")) {
1173 object += ".constructor";
1175 append("var metHan = ");
1176 append(accessStaticMethod(object, mn, mi));
1178 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1180 append(", '").append(mi[1]).append("', ");
1181 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1182 append(methodType).append("'").append(type).append("', null)");
1183 // if (numArguments > 0) {
1185 // for (int j = 1; j < numArguments; ++j) {
1191 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1197 int indx = readUShortArg(byteCodes, i);
1198 String ci = jc.getClassName(indx);
1199 emit(smapper, this, "var @1 = new @2;",
1200 smapper.pushA(), accessClass(mangleClassName(ci)));
1206 int atype = readUByte(byteCodes, ++i);
1207 generateNewArray(atype, smapper);
1209 case opc_anewarray: {
1210 int type = readUShortArg(byteCodes, i);
1212 generateANewArray(type, smapper);
1215 case opc_multianewarray: {
1216 int type = readUShortArg(byteCodes, i);
1218 i = generateMultiANewArray(type, byteCodes, i, smapper);
1221 case opc_arraylength:
1222 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1225 emit(smapper, this, "Array.at(@3, @2, @1);",
1226 smapper.popL(), smapper.popI(), smapper.popA());
1229 emit(smapper, this, "Array.at(@3, @2, @1);",
1230 smapper.popF(), smapper.popI(), smapper.popA());
1233 emit(smapper, this, "Array.at(@3, @2, @1);",
1234 smapper.popD(), smapper.popI(), smapper.popA());
1237 emit(smapper, this, "Array.at(@3, @2, @1);",
1238 smapper.popA(), smapper.popI(), smapper.popA());
1244 emit(smapper, this, "Array.at(@3, @2, @1);",
1245 smapper.popI(), smapper.popI(), smapper.popA());
1248 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1249 smapper.popI(), smapper.getA(0));
1252 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1253 smapper.popI(), smapper.getA(0));
1256 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1257 smapper.popI(), smapper.getA(0));
1260 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1261 smapper.popI(), smapper.getA(0));
1267 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1268 smapper.popI(), smapper.getA(0));
1276 final Variable v = smapper.get(0);
1277 if (smapper.isDirty()) {
1278 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1280 smapper.assign(this, v.getType(), v);
1285 final Variable vi1 = smapper.get(0);
1287 if (vi1.isCategory2()) {
1288 emit(smapper, this, "var @1 = @2;",
1289 smapper.pushT(vi1.getType()), vi1);
1291 final Variable vi2 = smapper.get(1);
1292 emit(smapper, this, "var @1 = @2, @3 = @4;",
1293 smapper.pushT(vi2.getType()), vi2,
1294 smapper.pushT(vi1.getType()), vi1);
1299 final Variable vi1 = smapper.pop(this);
1300 final Variable vi2 = smapper.pop(this);
1301 final Variable vo3 = smapper.pushT(vi1.getType());
1302 final Variable vo2 = smapper.pushT(vi2.getType());
1303 final Variable vo1 = smapper.pushT(vi1.getType());
1305 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1306 vo1, vi1, vo2, vi2, vo3, vo1);
1310 final Variable vi1 = smapper.pop(this);
1311 final Variable vi2 = smapper.pop(this);
1313 if (vi1.isCategory2()) {
1314 final Variable vo3 = smapper.pushT(vi1.getType());
1315 final Variable vo2 = smapper.pushT(vi2.getType());
1316 final Variable vo1 = smapper.pushT(vi1.getType());
1318 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1319 vo1, vi1, vo2, vi2, vo3, vo1);
1321 final Variable vi3 = smapper.pop(this);
1322 final Variable vo5 = smapper.pushT(vi2.getType());
1323 final Variable vo4 = smapper.pushT(vi1.getType());
1324 final Variable vo3 = smapper.pushT(vi3.getType());
1325 final Variable vo2 = smapper.pushT(vi2.getType());
1326 final Variable vo1 = smapper.pushT(vi1.getType());
1328 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1329 vo1, vi1, vo2, vi2, vo3, vi3);
1330 emit(smapper, this, " @1 = @2, @3 = @4;",
1331 vo4, vo1, vo5, vo2);
1336 final Variable vi1 = smapper.pop(this);
1337 final Variable vi2 = smapper.pop(this);
1339 if (vi2.isCategory2()) {
1340 final Variable vo3 = smapper.pushT(vi1.getType());
1341 final Variable vo2 = smapper.pushT(vi2.getType());
1342 final Variable vo1 = smapper.pushT(vi1.getType());
1344 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1345 vo1, vi1, vo2, vi2, vo3, vo1);
1347 final Variable vi3 = smapper.pop(this);
1348 final Variable vo4 = smapper.pushT(vi1.getType());
1349 final Variable vo3 = smapper.pushT(vi3.getType());
1350 final Variable vo2 = smapper.pushT(vi2.getType());
1351 final Variable vo1 = smapper.pushT(vi1.getType());
1353 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1354 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1359 final Variable vi1 = smapper.pop(this);
1360 final Variable vi2 = smapper.pop(this);
1362 if (vi1.isCategory2()) {
1363 if (vi2.isCategory2()) {
1364 final Variable vo3 = smapper.pushT(vi1.getType());
1365 final Variable vo2 = smapper.pushT(vi2.getType());
1366 final Variable vo1 = smapper.pushT(vi1.getType());
1368 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1369 vo1, vi1, vo2, vi2, vo3, vo1);
1371 final Variable vi3 = smapper.pop(this);
1372 final Variable vo4 = smapper.pushT(vi1.getType());
1373 final Variable vo3 = smapper.pushT(vi3.getType());
1374 final Variable vo2 = smapper.pushT(vi2.getType());
1375 final Variable vo1 = smapper.pushT(vi1.getType());
1377 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1378 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1381 final Variable vi3 = smapper.pop(this);
1383 if (vi3.isCategory2()) {
1384 final Variable vo5 = smapper.pushT(vi2.getType());
1385 final Variable vo4 = smapper.pushT(vi1.getType());
1386 final Variable vo3 = smapper.pushT(vi3.getType());
1387 final Variable vo2 = smapper.pushT(vi2.getType());
1388 final Variable vo1 = smapper.pushT(vi1.getType());
1390 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1391 vo1, vi1, vo2, vi2, vo3, vi3);
1392 emit(smapper, this, " @1 = @2, @3 = @4;",
1393 vo4, vo1, vo5, vo2);
1395 final Variable vi4 = smapper.pop(this);
1396 final Variable vo6 = smapper.pushT(vi2.getType());
1397 final Variable vo5 = smapper.pushT(vi1.getType());
1398 final Variable vo4 = smapper.pushT(vi4.getType());
1399 final Variable vo3 = smapper.pushT(vi3.getType());
1400 final Variable vo2 = smapper.pushT(vi2.getType());
1401 final Variable vo1 = smapper.pushT(vi1.getType());
1403 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1404 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1405 emit(smapper, this, " @1 = @2, @3 = @4;",
1406 vo5, vo1, vo6, vo2);
1412 final Variable vi1 = smapper.get(0);
1413 final Variable vi2 = smapper.get(1);
1415 if (vi1.getType() == vi2.getType()) {
1416 final Variable tmp = smapper.pushT(vi1.getType());
1418 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1423 smapper.pushT(vi1.getType());
1424 smapper.pushT(vi2.getType());
1429 smapper.assign(this, VarType.INTEGER,
1430 "(" + Integer.toString(byteCodes[++i]) + ")");
1433 smapper.assign(this, VarType.INTEGER,
1434 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1438 case opc_getfield: {
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 smapper.replace(this, type, "@2.call(@1)",
1446 accessField(mangleClassAccess,
1450 addReference(fi[0]);
1453 case opc_putfield: {
1454 int indx = readUShortArg(byteCodes, i);
1455 String[] fi = jc.getFieldInfoName(indx);
1456 final int type = VarType.fromFieldType(fi[2].charAt(0));
1457 final String mangleClass = mangleClassName(fi[0]);
1458 final String mangleClassAccess = accessClassFalse(mangleClass);
1459 emit(smapper, this, "@3.call(@2, @1);",
1462 accessField(mangleClassAccess,
1465 addReference(fi[0]);
1468 case opc_getstatic: {
1469 int indx = readUShortArg(byteCodes, i);
1470 String[] fi = jc.getFieldInfoName(indx);
1471 final int type = VarType.fromFieldType(fi[2].charAt(0));
1472 String ac = accessClassFalse(mangleClassName(fi[0]));
1473 String af = accessField(ac, "_" + fi[1], fi);
1474 smapper.assign(this, type, af + "()");
1476 addReference(fi[0]);
1479 case opc_putstatic: {
1480 int indx = readUShortArg(byteCodes, i);
1481 String[] fi = jc.getFieldInfoName(indx);
1482 final int type = VarType.fromFieldType(fi[2].charAt(0));
1483 emit(smapper, this, "@1._@2(@3);",
1484 accessClassFalse(mangleClassName(fi[0])), fi[1],
1485 smapper.popT(type));
1487 addReference(fi[0]);
1490 case opc_checkcast: {
1491 int indx = readUShortArg(byteCodes, i);
1492 generateCheckcast(indx, smapper);
1496 case opc_instanceof: {
1497 int indx = readUShortArg(byteCodes, i);
1498 generateInstanceOf(indx, smapper);
1503 final CharSequence v = smapper.popA();
1506 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1507 smapper.pushA(), v);
1511 case opc_monitorenter: {
1512 debug("/* monitor enter */");
1517 case opc_monitorexit: {
1518 debug("/* monitor exit */");
1529 emit(smapper, this, "throw 'unknown bytecode @1';",
1530 Integer.toString(c));
1534 generateByteCodeComment(prev, i, byteCodes);
1540 if (previousTrap != null) {
1541 generateCatch(previousTrap, flow, byteCodes.length, topMostLabel);
1546 while (openBraces-- > 0) {
1557 private int generateIf(StackMapper mapper, Flow flow, byte[] byteCodes, int i, final CharSequence v2, final CharSequence v1, final String test, int topMostLabel) throws IOException {
1559 int indx = i + readShortArg(byteCodes, i);
1560 append("if ((").append(v1)
1561 .append(") ").append(test).append(" (")
1562 .append(v2).append(")) ");
1563 goTo(this, flow, i, indx, topMostLabel);
1567 private int readInt4(byte[] byteCodes, int offset) {
1568 final int d = byteCodes[offset + 0] << 24;
1569 final int c = byteCodes[offset + 1] << 16;
1570 final int b = byteCodes[offset + 2] << 8;
1571 final int a = byteCodes[offset + 3];
1572 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1574 private static int readUByte(byte[] byteCodes, int offset) {
1575 return byteCodes[offset] & 0xff;
1578 private static int readUShort(byte[] byteCodes, int offset) {
1579 return ((byteCodes[offset] & 0xff) << 8)
1580 | (byteCodes[offset + 1] & 0xff);
1582 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1583 return readUShort(byteCodes, offsetInstruction + 1);
1586 private static int readShort(byte[] byteCodes, int offset) {
1587 int signed = byteCodes[offset];
1588 byte b0 = (byte)signed;
1589 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1591 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1592 return readShort(byteCodes, offsetInstruction + 1);
1595 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1597 Boolean count = null;
1598 boolean array = false;
1600 int firstPos = sig.length();
1601 while (i < descriptor.length()) {
1602 char ch = descriptor.charAt(i++);
1623 if (ch == 'J' || ch == 'D') {
1629 sig.insert(firstPos, ch);
1631 returnType[0] = '[';
1632 sig.insert(firstPos, "_3");
1641 returnType[0] = 'V';
1642 sig.insert(firstPos, 'V');
1645 int next = descriptor.indexOf(';', i);
1646 String realSig = mangleSig(descriptor, i - 1, next + 1);
1651 sig.append(realSig);
1654 sig.insert(firstPos, realSig);
1656 sig.insert(firstPos, "_3");
1658 returnType[0] = 'L';
1667 throw new IllegalStateException("Invalid char: " + ch);
1672 static String mangleSig(String sig) {
1673 return mangleSig(sig, 0, sig.length());
1676 private static String mangleMethodName(String name) {
1677 StringBuilder sb = new StringBuilder(name.length() * 2);
1678 int last = name.length();
1679 for (int i = 0; i < last; i++) {
1680 final char ch = name.charAt(i);
1682 case '_': sb.append("_1"); break;
1683 default: sb.append(ch); break;
1686 return sb.toString();
1688 private static String mangleSig(String txt, int first, int last) {
1689 StringBuilder sb = new StringBuilder((last - first) * 2);
1690 for (int i = first; i < last; i++) {
1691 final char ch = txt.charAt(i);
1693 case '/': sb.append('_'); break;
1694 case '_': sb.append("_1"); break;
1695 case ';': sb.append("_2"); break;
1696 case '[': sb.append("_3"); break;
1698 if (Character.isJavaIdentifierPart(ch)) {
1702 String hex = Integer.toHexString(ch).toLowerCase();
1703 for (int m = hex.length(); m < 4; m++) {
1711 return sb.toString();
1714 private static String mangleClassName(String name) {
1715 return mangleSig(name);
1718 private static String findMethodName(MethodData m, StringBuilder cnt) {
1719 StringBuilder name = new StringBuilder();
1720 if ("<init>".equals(m.getName())) { // NOI18N
1721 name.append("cons"); // NOI18N
1722 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1723 name.append("class"); // NOI18N
1725 name.append(mangleMethodName(m.getName()));
1728 countArgs(m.getInternalSig(), new char[1], name, cnt);
1729 return name.toString();
1732 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1733 StringBuilder name = new StringBuilder();
1734 String descr = mi[2];//mi.getDescriptor();
1736 if ("<init>".equals(nm)) { // NOI18N
1737 name.append("cons"); // NOI18N
1739 name.append(mangleMethodName(nm));
1741 countArgs(descr, returnType, name, cnt);
1742 return name.toString();
1745 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1746 throws IOException {
1747 int methodIndex = readUShortArg(byteCodes, i);
1748 String[] mi = jc.getFieldInfoName(methodIndex);
1749 char[] returnType = { 'V' };
1750 StringBuilder cnt = new StringBuilder();
1751 String mn = findMethodName(mi, cnt, returnType);
1753 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1754 final CharSequence[] vars = new CharSequence[numArguments];
1756 for (int j = numArguments - 1; j >= 0; --j) {
1757 vars[j] = mapper.popValue();
1761 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1762 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1764 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1765 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1767 if (vars[1] instanceof String) {
1768 String field = vars[1].toString();
1769 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1770 vars[1] = "c._" + field.substring(1, field.length() - 1);
1775 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1776 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1778 if (vars[1] instanceof String) {
1779 String field = vars[2].toString();
1780 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1781 vars[2] = "c._" + field.substring(1, field.length() - 1);
1786 if (returnType[0] != 'V') {
1789 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1793 final String in = mi[0];
1796 in.equals("org/apidesign/html/boot/spi/Fn") ||
1797 in.equals("org/netbeans/html/boot/spi/Fn")
1799 mcn = "java_lang_Class";
1801 mcn = mangleClassName(in);
1803 String object = accessClassFalse(mcn);
1804 if (mn.startsWith("cons_")) {
1805 object += ".constructor";
1807 append(accessStaticMethod(object, mn, mi));
1813 if (numArguments > 0) {
1815 for (int j = 1; j < numArguments; ++j) {
1825 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1826 throws IOException {
1827 int methodIndex = readUShortArg(byteCodes, i);
1828 String[] mi = jc.getFieldInfoName(methodIndex);
1829 char[] returnType = { 'V' };
1830 StringBuilder cnt = new StringBuilder();
1831 String mn = findMethodName(mi, cnt, returnType);
1833 final int numArguments = cnt.length() + 1;
1834 final CharSequence[] vars = new CharSequence[numArguments];
1836 for (int j = numArguments - 1; j >= 0; --j) {
1837 vars[j] = mapper.popValue();
1840 if (returnType[0] != 'V') {
1843 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1847 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1849 for (int j = 1; j < numArguments; ++j) {
1859 private void addReference(String cn) throws IOException {
1860 if (requireReference(cn)) {
1861 debug(" /* needs " + cn + " */");
1865 private void outType(String d, StringBuilder out) {
1867 while (d.charAt(0) == '[') {
1871 if (d.charAt(0) == 'L') {
1872 assert d.charAt(d.length() - 1) == ';';
1873 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1879 private String encodeConstant(int entryIndex) throws IOException {
1880 String[] classRef = { null };
1881 String s = jc.stringValue(entryIndex, classRef);
1882 if (classRef[0] != null) {
1883 if (classRef[0].startsWith("[")) {
1884 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1886 addReference(classRef[0]);
1887 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1893 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1894 byte[] arr = m.findAnnotationData(true);
1898 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1899 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1900 class P extends AnnotationParser {
1906 String[] args = new String[30];
1912 protected void visitAttr(String type, String attr, String at, String value) {
1913 if (type.equals(jvmType)) {
1914 if ("body".equals(attr)) {
1916 } else if ("args".equals(attr)) {
1917 args[cnt++] = value;
1919 throw new IllegalArgumentException(attr);
1922 if (type.equals(htmlType)) {
1924 if ("body".equals(attr)) {
1926 } else if ("args".equals(attr)) {
1927 args[cnt++] = value;
1928 } else if ("javacall".equals(attr)) {
1929 javacall = "1".equals(value);
1930 } else if ("wait4js".equals(attr)) {
1931 // ignore, we always invoke synchronously
1933 throw new IllegalArgumentException(attr);
1940 if (p.body == null) {
1943 StringBuilder cnt = new StringBuilder();
1944 final String mn = findMethodName(m, cnt);
1945 append("m = ").append(destObject).append(".").append(mn);
1946 append(" = function(");
1949 StringBuilder toValue = new StringBuilder();
1950 for (int i = 0; i < cnt.length(); i++) {
1952 space = outputArg(this, p.args, index);
1953 if (p.html4j && space.length() > 0) {
1954 toValue.append("\n ").append(p.args[index]).append(" = ")
1955 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1956 append(p.args[index]).append(");");
1960 append(") {").append("\n");
1961 append(toValue.toString());
1963 int lastSlash = jc.getClassName().lastIndexOf('/');
1964 final String pkg = jc.getClassName().substring(0, lastSlash);
1965 append(mangleCallbacks(pkg, p.body));
1966 requireReference(pkg + "/$JsCallbacks$");
1974 private static CharSequence mangleCallbacks(String pkgName, String body) {
1975 StringBuilder sb = new StringBuilder();
1978 int next = body.indexOf(".@", pos);
1980 sb.append(body.substring(pos));
1981 body = sb.toString();
1986 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1991 String refId = body.substring(ident, next);
1993 sb.append(body.substring(pos, ident));
1995 int sigBeg = body.indexOf('(', next);
1996 int sigEnd = body.indexOf(')', sigBeg);
1997 int colon4 = body.indexOf("::", next);
1998 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1999 throw new IllegalStateException("Malformed body " + body);
2001 String fqn = body.substring(next + 2, colon4);
2002 String method = body.substring(colon4 + 2, sigBeg);
2003 String params = body.substring(sigBeg, sigEnd + 1);
2005 int paramBeg = body.indexOf('(', sigEnd + 1);
2007 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2008 sb.append(mangleJsCallbacks(fqn, method, params, false));
2009 sb.append("(").append(refId);
2010 if (body.charAt(paramBeg + 1) != ')') {
2018 int next = body.indexOf("@", pos);
2023 sb.append(body.substring(pos));
2027 sb = new StringBuilder();
2030 sb.append(body.substring(pos, next));
2032 int sigBeg = body.indexOf('(', next);
2033 int sigEnd = body.indexOf(')', sigBeg);
2034 int colon4 = body.indexOf("::", next);
2035 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2036 throw new IllegalStateException("Malformed body " + body);
2038 String fqn = body.substring(next + 1, colon4);
2039 String method = body.substring(colon4 + 2, sigBeg);
2040 String params = body.substring(sigBeg, sigEnd + 1);
2042 int paramBeg = body.indexOf('(', sigEnd + 1);
2044 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2045 sb.append(mangleJsCallbacks(fqn, method, params, true));
2051 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2052 if (params.startsWith("(")) {
2053 params = params.substring(1);
2055 if (params.endsWith(")")) {
2056 params = params.substring(0, params.length() - 1);
2058 StringBuilder sb = new StringBuilder();
2059 final String fqnu = fqn.replace('.', '_');
2060 final String rfqn = mangleClassName(fqnu);
2061 final String rm = mangleMethodName(method);
2064 StringBuilder pb = new StringBuilder();
2065 int len = params.length();
2067 while (indx < len) {
2068 char ch = params.charAt(indx);
2069 if (ch == '[' || ch == 'L') {
2070 int column = params.indexOf(';', indx) + 1;
2071 if (column > indx) {
2072 String real = params.substring(indx, column);
2073 if ("Ljava/lang/String;".equals(real)) {
2074 pb.append("Ljava/lang/String;");
2079 pb.append("Ljava/lang/Object;");
2086 srp = mangleSig(pb.toString());
2088 final String rp = mangleSig(params);
2089 final String mrp = mangleMethodName(rp);
2090 sb.append(rfqn).append("$").append(rm).
2091 append('$').append(mrp).append("__Ljava_lang_Object_2");
2093 sb.append('L').append(fqnu).append("_2");
2096 return sb.toString();
2099 private static String className(ClassData jc) {
2100 //return jc.getName().getInternalName().replace('/', '_');
2101 return mangleClassName(jc.getClassName());
2104 private static String[] findAnnotation(
2105 byte[] arr, ClassData cd, final String className,
2106 final String... attrNames
2107 ) throws IOException {
2111 final String[] values = new String[attrNames.length];
2112 final boolean[] found = { false };
2113 final String jvmType = "L" + className.replace('.', '/') + ";";
2114 AnnotationParser ap = new AnnotationParser(false, true) {
2116 protected void visitAttr(String type, String attr, String at, String value) {
2117 if (type.equals(jvmType)) {
2119 for (int i = 0; i < attrNames.length; i++) {
2120 if (attrNames[i].equals(attr)) {
2129 return found[0] ? values : null;
2132 private CharSequence initField(FieldData v) {
2133 final String is = v.getInternalSig();
2134 if (is.length() == 1) {
2135 switch (is.charAt(0)) {
2141 case 'I': return " = 0;";
2143 case 'D': return " = 0.0;";
2145 throw new IllegalStateException(is);
2151 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2152 AnnotationParser ap = new AnnotationParser(true, false) {
2153 int[] cnt = new int[32];
2157 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2158 final String slashType = attrType.substring(1, attrType.length() - 1);
2159 requireReference(slashType);
2161 if (cnt[depth]++ > 0) {
2165 append('"').append(attrType).append("\" : ");
2172 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2178 protected void visitValueStart(String attrName, char type) throws IOException {
2179 if (cnt[depth]++ > 0) {
2183 if (attrName != null) {
2184 append('"').append(attrName).append("\" : ");
2192 protected void visitValueEnd(String attrName, char type) throws IOException {
2200 protected void visitAttr(String type, String attr, String attrType, String value)
2201 throws IOException {
2202 if (attr == null && value == null) {
2209 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2210 throws IOException {
2211 final String slashType = attrType.substring(1, attrType.length() - 1);
2212 requireReference(slashType);
2214 final String cn = mangleClassName(slashType);
2215 append(accessClassFalse(cn))
2216 .append("['valueOf__L").
2218 append("_2Ljava_lang_String_2']('").
2226 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2227 final String name = args[indx];
2231 if (name.contains(",")) {
2232 throw new IOException("Wrong parameter with ',': " + name);
2238 final void emitNoFlush(
2240 final String format, final CharSequence... params
2241 ) throws IOException {
2242 emitImpl(this, format, params);
2244 static final void emit(
2246 final Appendable out,
2247 final String format, final CharSequence... params
2248 ) throws IOException {
2250 emitImpl(out, format, params);
2252 static void emitImpl(final Appendable out,
2253 final String format,
2254 final CharSequence... params) throws IOException {
2255 final int length = format.length();
2258 int paramOffset = format.indexOf('@');
2259 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2260 final char paramChar = format.charAt(paramOffset + 1);
2261 if ((paramChar >= '1') && (paramChar <= '9')) {
2262 final int paramIndex = paramChar - '0' - 1;
2264 out.append(format, processed, paramOffset);
2265 out.append(params[paramIndex]);
2268 processed = paramOffset + 1;
2271 paramOffset = format.indexOf('@', paramOffset + 1);
2274 out.append(format, processed, length);
2277 private void generateCatch(TrapData[] traps, Flow flow, int current, int topMostLabel) throws IOException {
2278 append("} catch (e) {\n");
2280 for (TrapData e : traps) {
2284 if (e.catch_cpx != 0) { //not finally
2285 final String classInternalName = jc.getClassName(e.catch_cpx);
2286 addReference(classInternalName);
2287 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2288 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2289 append("var stA0 = e;");
2290 goTo(this, flow, current, e.handler_pc, topMostLabel);
2293 finallyPC = e.handler_pc;
2296 if (finallyPC == -1) {
2299 append("var stA0 = e;");
2300 goTo(this, flow, current, finallyPC, topMostLabel);
2305 private static void goTo(Appendable out, Flow flow, int current, int to, int canBack) throws IOException {
2307 if (flow.isIf(current)) {
2311 throw new IllegalStateException("Opn: ");
2315 out.append("{ gt = 0; continue X_" + to + "; }");
2317 out.append("{ gt = " + to + "; continue X_0; }");
2320 out.append("{ gt = " + to + "; break IF; }");
2324 private static void emitIf(
2325 StackMapper sm, Flow flow, Appendable out, String pattern, CharSequence param, int current, int to, int canBack
2326 ) throws IOException {
2328 emitImpl(out, pattern, param);
2329 goTo(out, flow, current, to, canBack);
2332 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2335 case 4: jvmType = "[Z"; break;
2336 case 5: jvmType = "[C"; break;
2337 case 6: jvmType = "[F"; break;
2338 case 7: jvmType = "[D"; break;
2339 case 8: jvmType = "[B"; break;
2340 case 9: jvmType = "[S"; break;
2341 case 10: jvmType = "[I"; break;
2342 case 11: jvmType = "[J"; break;
2343 default: throw new IllegalStateException("Array type: " + atype);
2346 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2347 smapper.popI(), smapper.pushA(), jvmType);
2350 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2351 String typeName = jc.getClassName(type);
2352 String ref = "null";
2353 if (typeName.startsWith("[")) {
2354 typeName = "'[" + typeName + "'";
2356 ref = "vm." + mangleClassName(typeName);
2357 typeName = "'[L" + typeName + ";'";
2360 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2361 smapper.popI(), smapper.pushA(), typeName, ref);
2364 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2365 String typeName = jc.getClassName(type);
2366 int dim = readUByte(byteCodes, ++i);
2367 StringBuilder dims = new StringBuilder();
2369 for (int d = 0; d < dim; d++) {
2371 dims.insert(1, ",");
2373 dims.insert(1, smapper.popI());
2377 if (typeName.charAt(dim) == 'L') {
2378 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2381 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2382 dims.toString(), smapper.pushA(), typeName, fn
2387 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, Flow flow, int topMostLabel) throws IOException {
2388 int table = i / 4 * 4 + 4;
2389 int dflt = i + readInt4(byteCodes, table);
2391 int low = readInt4(byteCodes, table);
2393 int high = readInt4(byteCodes, table);
2395 final CharSequence swVar = smapper.popValue();
2396 smapper.flush(this);
2397 append("switch (").append(swVar).append(") {\n");
2398 while (low <= high) {
2399 int offset = i + readInt4(byteCodes, table);
2401 append(" case " + low).append(":"); goTo(this, flow, i, offset, topMostLabel); append('\n');
2404 append(" default: ");
2405 goTo(this, flow, i, dflt, topMostLabel);
2411 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, Flow flow, int topMostLabel) throws IOException {
2412 int table = i / 4 * 4 + 4;
2413 int dflt = i + readInt4(byteCodes, table);
2415 int n = readInt4(byteCodes, table);
2417 final CharSequence swVar = smapper.popValue();
2418 smapper.flush(this);
2419 append("switch (").append(swVar).append(") {\n");
2421 int cnstnt = readInt4(byteCodes, table);
2423 int offset = i + readInt4(byteCodes, table);
2425 append(" case " + cnstnt).append(": "); goTo(this, flow, i, offset, topMostLabel); append('\n');
2427 append(" default: ");
2428 goTo(this, flow, i, dflt, topMostLabel);
2434 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2435 String type = jc.getClassName(indx);
2436 if (!type.startsWith("[")) {
2438 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2439 smapper.popA(), smapper.pushI(),
2440 type.replace('/', '_'));
2443 while (type.charAt(cnt) == '[') {
2446 if (type.charAt(cnt) == 'L') {
2447 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2449 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2450 smapper.popA(), smapper.pushI(),
2455 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2456 smapper.popA(), smapper.pushI(), type
2462 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2463 String type = jc.getClassName(indx);
2464 if (!type.startsWith("[")) {
2465 emitNoFlush(smapper,
2466 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2467 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2470 while (type.charAt(cnt) == '[') {
2473 if (type.charAt(cnt) == 'L') {
2474 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2475 emitNoFlush(smapper,
2476 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2477 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2480 emitNoFlush(smapper,
2481 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2482 smapper.getT(0, VarType.REFERENCE, false), type
2488 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2489 for (int j = prev; j <= i; j++) {
2491 final int cc = readUByte(byteCodes, j);
2492 append(Integer.toString(cc));
2496 @JavaScriptBody(args = "msg", body = "")
2497 private static void println(String msg) {
2498 System.err.println(msg);
2501 protected Flow checkFlow(MethodData byteCodes) {