Flush mapper before pushing back a result of (virtual) method invocation. The static method call was already doing that.
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.*;
25 /** Translator of the code inside class files to JavaScript.
27 * @author Jaroslav Tulach <jtulach@netbeans.org>
29 abstract class ByteCodeToJavaScript implements Appendable {
31 private final Appendable out;
32 private boolean outChanged;
33 private boolean callbacks;
35 protected ByteCodeToJavaScript(Appendable out) {
40 public final Appendable append(CharSequence csq) throws IOException {
47 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
48 out.append(csq, start, end);
54 public final Appendable append(char c) throws IOException {
60 /* Collects additional required resources.
62 * @param internalClassName classes that were referenced and should be loaded in order the
63 * generated JavaScript code works properly. The names are in internal
64 * JVM form so String is <code>java/lang/String</code>.
66 protected abstract boolean requireReference(String internalClassName);
69 * @param resourcePath name of resources to read
71 protected abstract void requireScript(String resourcePath) throws IOException;
73 protected abstract void requireResource(String resourcePath) throws IOException;
75 /** Allows subclasses to redefine what field a function representing a
76 * class gets assigned. By default it returns the suggested name followed
77 * by <code>" = "</code>;
79 * @param className suggested name of the class
81 /* protected */ String assignClass(String className) {
82 return className + " = ";
84 /* protected */ String accessClass(String classOperation) {
85 return classOperation;
88 String accessClassFalse(String classOperation) {
89 if (jc.getClassName().replace('/', '_').equals(classOperation)) {
92 return accessClass(classOperation) + "(false)";
95 protected String accessField(String object, String mangledName,
96 String[] fieldInfoName) throws IOException {
97 return object + "." + mangledName;
100 protected String accessStaticMethod(
103 String[] fieldInfoName) throws IOException {
104 return object + "." + mangledName;
107 protected String accessVirtualMethod(
110 String[] fieldInfoName,
112 ) throws IOException {
113 return object + "." + mangledName + '(';
116 protected void declaredClass(ClassData classData, String mangledName)
120 protected void declaredField(FieldData fieldData,
122 String mangledName) throws IOException {
125 protected void declaredMethod(MethodData methodData,
127 String mangledName) throws IOException {
130 /** Prints out a debug message.
132 * @param msg the message
133 * @return true if the message has been printed
134 * @throws IOException
136 boolean debug(String msg) throws IOException {
142 * Converts a given class file to a JavaScript version.
144 * @param classFile input stream with code of the .class file
145 * @return the initialization code for this class, if any. Otherwise <code>null</code>
147 * @throws IOException if something goes wrong during read or write or translating
150 public String compile(InputStream classFile) throws IOException {
151 return compile(new ClassData(classFile));
154 protected String compile(ClassData classData) throws IOException {
156 final String cn = this.jc.getClassName();
157 this.callbacks = cn.endsWith("/$JsCallbacks$");
158 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
159 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
160 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
163 byte[] arrData = jc.findAnnotationData(true);
165 String[] arr = findAnnotation(arrData, jc,
166 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
167 "resource", "processByteCode"
170 if (!arr[0].isEmpty()) {
171 requireScript(arr[0]);
173 if ("0".equals(arr[1])) {
178 final String jsResource;
180 String[] arr = findAnnotation(arrData, jc,
181 "net.java.html.js.JavaScriptResource",
185 if (arr[0].startsWith("/")) {
188 int last = cn.lastIndexOf('/');
189 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
195 String[] proto = findAnnotation(arrData, jc,
196 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
197 "container", "prototype"
199 StringArray toInitilize = new StringArray();
200 final String className = className(jc);
201 append("\n\n").append(assignClass(className));
202 append("function ").append(className).append("() {");
204 append("\n var CLS = ").append(className).append(';');
205 append("\n if (!CLS.$class) {");
207 String sc = jc.getSuperClassName(); // with _
208 append("\n var pp = ").
209 append(accessClass(mangleClassName(sc))).append("(true);");
210 append("\n var p = CLS.prototype = pp;");
211 append("\n var c = p;");
212 append("\n var sprcls = pp.constructor.$class;");
214 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
215 if (proto[0] == null) {
218 append("\n var c = ").append(proto[0]).append(";");
219 append("\n var sprcls = null;");
221 for (FieldData v : jc.getFields()) {
223 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
224 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
228 append("\n CLS.fld_").append(v.getName()).append(initField(v));
229 append("\n m = c._").append(v.getName()).append(" = function (v) {")
230 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
231 .append(" = v; return CLS.fld_").
232 append(v.getName()).append("; };");
234 append("\n m = c._").append(v.getName()).append(" = function (v) {")
235 .append(" if (arguments.length == 1) this.fld_").
236 append(className).append('_').append(v.getName())
237 .append(" = v; return this.fld_").
238 append(className).append('_').append(v.getName())
242 declaredField(v, "c", "_" + v.getName());
244 for (MethodData m : jc.getMethods()) {
245 byte[] onlyArr = m.findAnnotationData(true);
246 if (javaScriptOnly(onlyArr)) continue;
252 mn = generateStaticMethod(destObject, m, toInitilize);
254 if (m.isConstructor()) {
256 mn = generateInstanceMethod(destObject, m);
259 mn = generateInstanceMethod(destObject, m);
262 declaredMethod(m, destObject, mn);
263 byte[] runAnno = m.findAnnotationData(false);
264 if (runAnno != null) {
265 append("\n m.anno = {");
266 generateAnno(jc, runAnno);
269 append("\n m.access = " + m.getAccess()).append(";");
270 append("\n m.cls = CLS;");
272 append("\n c.constructor = CLS;");
273 append("\n function ").append(className).append("fillInstOf(x) {");
274 String instOfName = "$instOf_" + className;
275 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
276 if (jc.isInterface()) {
277 for (MethodData m : jc.getMethods()) {
278 if ((m.getAccess() & ACC_ABSTRACT) == 0
279 && (m.getAccess() & ACC_STATIC) == 0
280 && (m.getAccess() & ACC_PRIVATE) == 0) {
281 final String mn = findMethodName(m, new StringBuilder());
283 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
284 append("\n } catch (ignore) {");
289 for (String superInterface : jc.getSuperInterfaces()) {
290 String intrfc = superInterface.replace('/', '_');
291 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
292 requireReference(superInterface);
296 append("\n Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
297 append("\n ").append(className).append("fillInstOf(c);");
298 append("\n } catch (ignore) {");
300 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
301 append("\n CLS.$class = 'temp';");
302 append("\n CLS.$class = ");
303 append(accessClass("java_lang_Class(true);"));
304 append("\n CLS.$class.jvmName = '").append(cn).append("';");
305 append("\n CLS.$class.superclass = sprcls;");
306 append("\n CLS.$class.interfaces = function() { return [");
308 boolean first = true;
309 for (String intrfc : jc.getSuperInterfaces()) {
313 requireReference(intrfc);
314 String mangledIface = mangleClassName(intrfc);
316 append(accessClass(mangledIface)).append("(false).constructor.$class");
321 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
322 append("\n CLS.$class.cnstr = CLS;");
323 byte[] classAnno = jc.findAnnotationData(false);
324 if (classAnno != null) {
325 append("\n CLS.$class.anno = {");
326 generateAnno(jc, classAnno);
329 for (String init : toInitilize.toArray()) {
330 append("\n ").append(init).append("();");
333 if (jsResource != null) {
334 requireResource(jsResource);
338 append("\n if (arguments.length === 0) {");
339 append("\n if (!(this instanceof CLS)) {");
340 append("\n return new CLS();");
342 for (FieldData v : jc.getFields()) {
343 byte[] onlyArr = v.findAnnotationData(true);
344 if (javaScriptOnly(onlyArr)) continue;
346 append("\n this.fld_").
347 append(className).append('_').
348 append(v.getName()).append(initField(v));
351 append("\n return this;");
353 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
356 declaredClass(jc, className);
358 // StringBuilder sb = new StringBuilder();
359 // for (String init : toInitilize.toArray()) {
360 // sb.append("\n").append(init).append("();");
365 private boolean javaScriptOnly(byte[] anno) throws IOException {
366 String[] only = findAnnotation(anno, jc,
367 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
371 if (only[0] != null && only[1] != null) {
372 append("\n p.").append(only[0]).append(" = ")
373 .append(only[1]).append(";");
375 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
376 append("\n p['").append(only[0]).append("'] = p.")
377 .append(only[0]).append(";");
383 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
384 String jsb = javaScriptBody(destObject, m, true);
388 final String mn = findMethodName(m, new StringBuilder());
389 boolean defineProp = generateMethod(destObject, mn, m);
390 if (mn.equals("class__V")) {
392 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
394 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
400 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
401 String jsb = javaScriptBody(destObject, m, false);
405 final String mn = findMethodName(m, new StringBuilder());
406 generateMethod(destObject, mn, m);
410 private boolean generateMethod(String destObject, String name, MethodData m)
412 final StackMapIterator stackMapIterator = m.createStackMapIterator();
413 TrapDataIterator trap = m.getTrapDataIterator();
414 final LocalsMapper lmapper =
415 new LocalsMapper(stackMapIterator.getArguments());
418 "java/lang/Object".equals(jc.getClassName()) ||
419 "java/lang/reflect/Array".equals(jc.getClassName());
422 append("Object.defineProperty(").append(destObject).
423 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
425 append("m = ").append(destObject).append(".").append(name).append(" = function(");
427 lmapper.outputArguments(this, m.isStatic());
428 append(") {").append("\n");
430 final byte[] byteCodes = m.getCode();
431 if (byteCodes == null) {
432 append(" throw 'no code found for ")
433 .append(jc.getClassName()).append('.')
434 .append(m.getName()).append("';\n");
443 final StackMapper smapper = new StackMapper();
446 append(" var ").append(" lcA0 = this;\n");
450 TrapData[] previousTrap = null;
451 boolean wide = false;
453 if (stackMapIterator.isEmpty()) {
459 append("\n var gt = 0;\n");
463 int topMostLabel = 0;
464 for (int i = 0; i < byteCodes.length; i++) {
467 stackMapIterator.advanceTo(i);
468 boolean changeInCatch = trap.advanceTo(i);
469 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
470 if (previousTrap != null) {
471 generateCatch(previousTrap, i, topMostLabel);
475 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
480 if (openBraces > 64) {
481 for (int c = 0; c < 64; c++) {
488 lastStackFrame = stackMapIterator.getFrameIndex();
489 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
490 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
491 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
493 changeInCatch = true;
495 debug(" /* " + i + " */ ");
497 if (changeInCatch && trap.useTry()) {
499 previousTrap = trap.current();
501 final int c = readUByte(byteCodes, i);
504 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
507 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
510 smapper.assign(this, VarType.LONG, lmapper.getL(0));
513 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
516 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
519 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
522 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
525 smapper.assign(this, VarType.LONG, lmapper.getL(1));
528 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
531 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
534 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
537 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
540 smapper.assign(this, VarType.LONG, lmapper.getL(2));
543 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
546 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
549 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
552 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
555 smapper.assign(this, VarType.LONG, lmapper.getL(3));
558 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
561 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
565 final int indx = wide ? readUShort(byteCodes, i++)
566 : readUByte(byteCodes, i);
568 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
573 final int indx = wide ? readUShort(byteCodes, i++)
574 : readUByte(byteCodes, i);
576 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
581 final int indx = wide ? readUShort(byteCodes, i++)
582 : readUByte(byteCodes, i);
584 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
589 final int indx = wide ? readUShort(byteCodes, i++)
590 : readUByte(byteCodes, i);
592 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
597 final int indx = wide ? readUShort(byteCodes, i++)
598 : readUByte(byteCodes, i);
600 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
605 final int indx = wide ? readUShort(byteCodes, i++)
606 : readUByte(byteCodes, i);
608 emit(smapper, this, "var @1 = @2;",
609 lmapper.setI(indx), smapper.popI());
614 final int indx = wide ? readUShort(byteCodes, i++)
615 : readUByte(byteCodes, i);
617 emit(smapper, this, "var @1 = @2;",
618 lmapper.setL(indx), smapper.popL());
623 final int indx = wide ? readUShort(byteCodes, i++)
624 : readUByte(byteCodes, i);
626 emit(smapper, this, "var @1 = @2;",
627 lmapper.setF(indx), smapper.popF());
632 final int indx = wide ? readUShort(byteCodes, i++)
633 : readUByte(byteCodes, i);
635 emit(smapper, this, "var @1 = @2;",
636 lmapper.setD(indx), smapper.popD());
641 final int indx = wide ? readUShort(byteCodes, i++)
642 : readUByte(byteCodes, i);
644 emit(smapper, this, "var @1 = @2;",
645 lmapper.setA(indx), smapper.popA());
649 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
652 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
655 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
658 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
661 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
664 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
667 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
670 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
673 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
676 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
679 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
682 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
685 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
688 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
691 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
694 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
697 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
700 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
703 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
706 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
709 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
712 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
715 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
718 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
721 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
724 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
727 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
730 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
733 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
736 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
739 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
742 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
745 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
746 smapper.getI(1), smapper.popI());
749 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
750 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).mod32(@2)",
760 smapper.getI(1), smapper.popI());
763 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
764 smapper.getL(1), smapper.popL());
767 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
770 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
773 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
776 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
779 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
782 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
785 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
788 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
791 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
794 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
797 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
800 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
803 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
806 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
809 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
812 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
815 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
818 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
822 final int varIndx = wide ? readUShort(byteCodes, i++)
823 : readUByte(byteCodes, i);
825 final int incrBy = wide ? readShort(byteCodes, i++)
829 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
831 emit(smapper, this, "@1 += @2;",
832 lmapper.getI(varIndx),
833 Integer.toString(incrBy));
838 emit(smapper, this, "return;");
841 emit(smapper, this, "return @1;", smapper.popI());
844 emit(smapper, this, "return @1;", smapper.popL());
847 emit(smapper, this, "return @1;", smapper.popF());
850 emit(smapper, this, "return @1;", smapper.popD());
853 emit(smapper, this, "return @1;", smapper.popA());
856 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
859 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
862 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
865 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
869 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
872 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
875 smapper.replace(this, VarType.DOUBLE, "@1",
879 smapper.replace(this, VarType.FLOAT, "@1",
883 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
887 smapper.replace(this, VarType.LONG, "(@1).toLong()",
891 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
895 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
898 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
902 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
904 case opc_aconst_null:
905 smapper.assign(this, VarType.REFERENCE, "null");
908 smapper.assign(this, VarType.INTEGER, "-1");
911 smapper.assign(this, VarType.INTEGER, "0");
914 smapper.assign(this, VarType.DOUBLE, "0");
917 smapper.assign(this, VarType.LONG, "0");
920 smapper.assign(this, VarType.FLOAT, "0");
923 smapper.assign(this, VarType.INTEGER, "1");
926 smapper.assign(this, VarType.LONG, "1");
929 smapper.assign(this, VarType.FLOAT, "1");
932 smapper.assign(this, VarType.DOUBLE, "1");
935 smapper.assign(this, VarType.INTEGER, "2");
938 smapper.assign(this, VarType.FLOAT, "2");
941 smapper.assign(this, VarType.INTEGER, "3");
944 smapper.assign(this, VarType.INTEGER, "4");
947 smapper.assign(this, VarType.INTEGER, "5");
950 int indx = readUByte(byteCodes, ++i);
951 String v = encodeConstant(indx);
952 int type = VarType.fromConstantType(jc.getTag(indx));
953 smapper.assign(this, type, v);
958 int indx = readUShortArg(byteCodes, i);
960 String v = encodeConstant(indx);
961 int type = VarType.fromConstantType(jc.getTag(indx));
962 if (type == VarType.LONG) {
963 final Long lv = new Long(v);
964 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
965 final int hi = (int)(lv.longValue() >> 32);
967 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
969 smapper.assign(this, VarType.LONG,
970 "0x" + Integer.toHexString(hi) + ".next32(0x" +
971 Integer.toHexString(low) + ")"
975 smapper.assign(this, type, v);
980 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
984 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
988 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
991 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
992 "===", topMostLabel);
995 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
996 "!==", topMostLabel);
999 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1000 "==", topMostLabel);
1003 int indx = i + readShortArg(byteCodes, i);
1004 emitIf(smapper, this, "if ((@1) == 0) ",
1005 smapper.popI(), i, indx, topMostLabel);
1010 int indx = i + readShortArg(byteCodes, i);
1011 emitIf(smapper, this, "if ((@1) != 0) ",
1012 smapper.popI(), i, indx, topMostLabel);
1017 int indx = i + readShortArg(byteCodes, i);
1018 emitIf(smapper, this, "if ((@1) < 0) ",
1019 smapper.popI(), i, indx, topMostLabel);
1024 int indx = i + readShortArg(byteCodes, i);
1025 emitIf(smapper, this, "if ((@1) <= 0) ",
1026 smapper.popI(), i, indx, 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);
1044 case opc_ifnonnull: {
1045 int indx = i + readShortArg(byteCodes, i);
1046 emitIf(smapper, this, "if ((@1) !== null) ",
1047 smapper.popA(), i, indx, topMostLabel);
1052 int indx = i + readShortArg(byteCodes, i);
1053 emitIf(smapper, this, "if ((@1) === null) ",
1054 smapper.popA(), i, indx, topMostLabel);
1059 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1060 "!=", topMostLabel);
1063 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1067 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1068 "<=", topMostLabel);
1071 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1075 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1076 ">=", topMostLabel);
1079 smapper.flush(this);
1080 int indx = i + readShortArg(byteCodes, i);
1081 goTo(this, i, indx, topMostLabel);
1085 case opc_lookupswitch: {
1086 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1089 case opc_tableswitch: {
1090 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1093 case opc_invokeinterface: {
1094 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1097 case opc_invokevirtual:
1098 i = invokeVirtualMethod(byteCodes, i, smapper);
1100 case opc_invokespecial:
1101 i = invokeStaticMethod(byteCodes, i, smapper, false);
1103 case opc_invokestatic:
1104 i = invokeStaticMethod(byteCodes, i, smapper, true);
1106 case opc_invokedynamic: {
1107 int indx = readUShortArg(byteCodes, i);
1108 println("invoke dynamic: " + indx);
1109 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1110 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1111 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1112 println(" type: " + methodHandle.cpx1);
1113 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1114 String mcn = mangleClassName(mi[0]);
1115 char[] returnType = {'V'};
1116 StringBuilder cnt = new StringBuilder();
1117 String mn = findMethodName(mi, cnt, returnType);
1118 StringBuilder sb = new StringBuilder();
1119 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1120 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1121 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1122 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1123 sb.append(" mn : ").append(mn).append("\n");
1124 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1125 throw new IOException(sb.toString());
1127 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1128 String type = jc.StringValue(nameAndType.cpx2);
1129 String object = accessClass(mcn) + "(false)";
1130 if (mn.startsWith("cons_")) {
1131 object += ".constructor";
1133 append("var metHan = ");
1134 append(accessStaticMethod(object, mn, mi));
1136 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1138 append(", '").append(mi[1]).append("', ");
1139 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1140 append(methodType).append("'").append(type).append("', null)");
1141 // if (numArguments > 0) {
1143 // for (int j = 1; j < numArguments; ++j) {
1149 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1155 int indx = readUShortArg(byteCodes, i);
1156 String ci = jc.getClassName(indx);
1157 emit(smapper, this, "var @1 = new @2;",
1158 smapper.pushA(), accessClass(mangleClassName(ci)));
1164 int atype = readUByte(byteCodes, ++i);
1165 generateNewArray(atype, smapper);
1167 case opc_anewarray: {
1168 int type = readUShortArg(byteCodes, i);
1170 generateANewArray(type, smapper);
1173 case opc_multianewarray: {
1174 int type = readUShortArg(byteCodes, i);
1176 i = generateMultiANewArray(type, byteCodes, i, smapper);
1179 case opc_arraylength:
1180 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1183 emit(smapper, this, "Array.at(@3, @2, @1);",
1184 smapper.popL(), smapper.popI(), smapper.popA());
1187 emit(smapper, this, "Array.at(@3, @2, @1);",
1188 smapper.popF(), smapper.popI(), smapper.popA());
1191 emit(smapper, this, "Array.at(@3, @2, @1);",
1192 smapper.popD(), smapper.popI(), smapper.popA());
1195 emit(smapper, this, "Array.at(@3, @2, @1);",
1196 smapper.popA(), smapper.popI(), smapper.popA());
1202 emit(smapper, this, "Array.at(@3, @2, @1);",
1203 smapper.popI(), smapper.popI(), smapper.popA());
1206 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1207 smapper.popI(), smapper.getA(0));
1210 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1211 smapper.popI(), smapper.getA(0));
1214 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1215 smapper.popI(), smapper.getA(0));
1218 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1219 smapper.popI(), smapper.getA(0));
1225 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1226 smapper.popI(), smapper.getA(0));
1234 final Variable v = smapper.get(0);
1235 if (smapper.isDirty()) {
1236 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1238 smapper.assign(this, v.getType(), v);
1243 final Variable vi1 = smapper.get(0);
1245 if (vi1.isCategory2()) {
1246 emit(smapper, this, "var @1 = @2;",
1247 smapper.pushT(vi1.getType()), vi1);
1249 final Variable vi2 = smapper.get(1);
1250 emit(smapper, this, "var @1 = @2, @3 = @4;",
1251 smapper.pushT(vi2.getType()), vi2,
1252 smapper.pushT(vi1.getType()), vi1);
1257 final Variable vi1 = smapper.pop(this);
1258 final Variable vi2 = smapper.pop(this);
1259 final Variable vo3 = smapper.pushT(vi1.getType());
1260 final Variable vo2 = smapper.pushT(vi2.getType());
1261 final Variable vo1 = smapper.pushT(vi1.getType());
1263 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1264 vo1, vi1, vo2, vi2, vo3, vo1);
1268 final Variable vi1 = smapper.pop(this);
1269 final Variable vi2 = smapper.pop(this);
1271 if (vi1.isCategory2()) {
1272 final Variable vo3 = smapper.pushT(vi1.getType());
1273 final Variable vo2 = smapper.pushT(vi2.getType());
1274 final Variable vo1 = smapper.pushT(vi1.getType());
1276 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1277 vo1, vi1, vo2, vi2, vo3, vo1);
1279 final Variable vi3 = smapper.pop(this);
1280 final Variable vo5 = smapper.pushT(vi2.getType());
1281 final Variable vo4 = smapper.pushT(vi1.getType());
1282 final Variable vo3 = smapper.pushT(vi3.getType());
1283 final Variable vo2 = smapper.pushT(vi2.getType());
1284 final Variable vo1 = smapper.pushT(vi1.getType());
1286 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1287 vo1, vi1, vo2, vi2, vo3, vi3);
1288 emit(smapper, this, " @1 = @2, @3 = @4;",
1289 vo4, vo1, vo5, vo2);
1294 final Variable vi1 = smapper.pop(this);
1295 final Variable vi2 = smapper.pop(this);
1297 if (vi2.isCategory2()) {
1298 final Variable vo3 = smapper.pushT(vi1.getType());
1299 final Variable vo2 = smapper.pushT(vi2.getType());
1300 final Variable vo1 = smapper.pushT(vi1.getType());
1302 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1303 vo1, vi1, vo2, vi2, vo3, vo1);
1305 final Variable vi3 = smapper.pop(this);
1306 final Variable vo4 = smapper.pushT(vi1.getType());
1307 final Variable vo3 = smapper.pushT(vi3.getType());
1308 final Variable vo2 = smapper.pushT(vi2.getType());
1309 final Variable vo1 = smapper.pushT(vi1.getType());
1311 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1312 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1317 final Variable vi1 = smapper.pop(this);
1318 final Variable vi2 = smapper.pop(this);
1320 if (vi1.isCategory2()) {
1321 if (vi2.isCategory2()) {
1322 final Variable vo3 = smapper.pushT(vi1.getType());
1323 final Variable vo2 = smapper.pushT(vi2.getType());
1324 final Variable vo1 = smapper.pushT(vi1.getType());
1326 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1327 vo1, vi1, vo2, vi2, vo3, vo1);
1329 final Variable vi3 = smapper.pop(this);
1330 final Variable vo4 = smapper.pushT(vi1.getType());
1331 final Variable vo3 = smapper.pushT(vi3.getType());
1332 final Variable vo2 = smapper.pushT(vi2.getType());
1333 final Variable vo1 = smapper.pushT(vi1.getType());
1335 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1336 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1339 final Variable vi3 = smapper.pop(this);
1341 if (vi3.isCategory2()) {
1342 final Variable vo5 = smapper.pushT(vi2.getType());
1343 final Variable vo4 = smapper.pushT(vi1.getType());
1344 final Variable vo3 = smapper.pushT(vi3.getType());
1345 final Variable vo2 = smapper.pushT(vi2.getType());
1346 final Variable vo1 = smapper.pushT(vi1.getType());
1348 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1349 vo1, vi1, vo2, vi2, vo3, vi3);
1350 emit(smapper, this, " @1 = @2, @3 = @4;",
1351 vo4, vo1, vo5, vo2);
1353 final Variable vi4 = smapper.pop(this);
1354 final Variable vo6 = smapper.pushT(vi2.getType());
1355 final Variable vo5 = smapper.pushT(vi1.getType());
1356 final Variable vo4 = smapper.pushT(vi4.getType());
1357 final Variable vo3 = smapper.pushT(vi3.getType());
1358 final Variable vo2 = smapper.pushT(vi2.getType());
1359 final Variable vo1 = smapper.pushT(vi1.getType());
1361 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1362 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1363 emit(smapper, this, " @1 = @2, @3 = @4;",
1364 vo5, vo1, vo6, vo2);
1370 final Variable vi1 = smapper.get(0);
1371 final Variable vi2 = smapper.get(1);
1373 if (vi1.getType() == vi2.getType()) {
1374 final Variable tmp = smapper.pushT(vi1.getType());
1376 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1381 smapper.pushT(vi1.getType());
1382 smapper.pushT(vi2.getType());
1387 smapper.assign(this, VarType.INTEGER,
1388 "(" + Integer.toString(byteCodes[++i]) + ")");
1391 smapper.assign(this, VarType.INTEGER,
1392 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1396 case opc_getfield: {
1397 int indx = readUShortArg(byteCodes, i);
1398 String[] fi = jc.getFieldInfoName(indx);
1399 final int type = VarType.fromFieldType(fi[2].charAt(0));
1400 final String mangleClass = mangleClassName(fi[0]);
1401 final String mangleClassAccess = accessClassFalse(mangleClass);
1402 smapper.replace(this, type, "@2.call(@1)",
1404 accessField(mangleClassAccess,
1408 addReference(fi[0]);
1411 case opc_putfield: {
1412 int indx = readUShortArg(byteCodes, i);
1413 String[] fi = jc.getFieldInfoName(indx);
1414 final int type = VarType.fromFieldType(fi[2].charAt(0));
1415 final String mangleClass = mangleClassName(fi[0]);
1416 final String mangleClassAccess = accessClassFalse(mangleClass);
1417 emit(smapper, this, "@3.call(@2, @1);",
1420 accessField(mangleClassAccess,
1423 addReference(fi[0]);
1426 case opc_getstatic: {
1427 int indx = readUShortArg(byteCodes, i);
1428 String[] fi = jc.getFieldInfoName(indx);
1429 final int type = VarType.fromFieldType(fi[2].charAt(0));
1430 String ac = accessClassFalse(mangleClassName(fi[0]));
1431 String af = accessField(ac, "_" + fi[1], fi);
1432 smapper.assign(this, type, af + "()");
1434 addReference(fi[0]);
1437 case opc_putstatic: {
1438 int indx = readUShortArg(byteCodes, i);
1439 String[] fi = jc.getFieldInfoName(indx);
1440 final int type = VarType.fromFieldType(fi[2].charAt(0));
1441 emit(smapper, this, "@1._@2(@3);",
1442 accessClassFalse(mangleClassName(fi[0])), fi[1],
1443 smapper.popT(type));
1445 addReference(fi[0]);
1448 case opc_checkcast: {
1449 int indx = readUShortArg(byteCodes, i);
1450 generateCheckcast(indx, smapper);
1454 case opc_instanceof: {
1455 int indx = readUShortArg(byteCodes, i);
1456 generateInstanceOf(indx, smapper);
1461 final CharSequence v = smapper.popA();
1464 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1465 smapper.pushA(), v);
1469 case opc_monitorenter: {
1470 debug("/* monitor enter */");
1475 case opc_monitorexit: {
1476 debug("/* monitor exit */");
1487 emit(smapper, this, "throw 'unknown bytecode @1';",
1488 Integer.toString(c));
1492 generateByteCodeComment(prev, i, byteCodes);
1498 if (previousTrap != null) {
1499 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1504 while (openBraces-- > 0) {
1515 private int generateIf(StackMapper mapper, byte[] byteCodes,
1516 int i, final CharSequence v2, final CharSequence v1,
1517 final String test, int topMostLabel
1518 ) throws IOException {
1520 int indx = i + readShortArg(byteCodes, i);
1521 append("if ((").append(v1)
1522 .append(") ").append(test).append(" (")
1523 .append(v2).append(")) ");
1524 goTo(this, i, indx, topMostLabel);
1528 private int readInt4(byte[] byteCodes, int offset) {
1529 final int d = byteCodes[offset + 0] << 24;
1530 final int c = byteCodes[offset + 1] << 16;
1531 final int b = byteCodes[offset + 2] << 8;
1532 final int a = byteCodes[offset + 3];
1533 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1535 private static int readUByte(byte[] byteCodes, int offset) {
1536 return byteCodes[offset] & 0xff;
1539 private static int readUShort(byte[] byteCodes, int offset) {
1540 return ((byteCodes[offset] & 0xff) << 8)
1541 | (byteCodes[offset + 1] & 0xff);
1543 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1544 return readUShort(byteCodes, offsetInstruction + 1);
1547 private static int readShort(byte[] byteCodes, int offset) {
1548 int signed = byteCodes[offset];
1549 byte b0 = (byte)signed;
1550 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1552 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1553 return readShort(byteCodes, offsetInstruction + 1);
1556 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1558 Boolean count = null;
1559 boolean array = false;
1561 int firstPos = sig.length();
1562 while (i < descriptor.length()) {
1563 char ch = descriptor.charAt(i++);
1584 if (ch == 'J' || ch == 'D') {
1590 sig.insert(firstPos, ch);
1592 returnType[0] = '[';
1593 sig.insert(firstPos, "_3");
1602 returnType[0] = 'V';
1603 sig.insert(firstPos, 'V');
1606 int next = descriptor.indexOf(';', i);
1607 String realSig = mangleSig(descriptor, i - 1, next + 1);
1612 sig.append(realSig);
1615 sig.insert(firstPos, realSig);
1617 sig.insert(firstPos, "_3");
1619 returnType[0] = 'L';
1628 throw new IllegalStateException("Invalid char: " + ch);
1633 static String mangleSig(String sig) {
1634 return mangleSig(sig, 0, sig.length());
1637 private static String mangleMethodName(String name) {
1638 StringBuilder sb = new StringBuilder(name.length() * 2);
1639 int last = name.length();
1640 for (int i = 0; i < last; i++) {
1641 final char ch = name.charAt(i);
1643 case '_': sb.append("_1"); break;
1644 default: sb.append(ch); break;
1647 return sb.toString();
1649 private static String mangleSig(String txt, int first, int last) {
1650 StringBuilder sb = new StringBuilder((last - first) * 2);
1651 for (int i = first; i < last; i++) {
1652 final char ch = txt.charAt(i);
1654 case '/': sb.append('_'); break;
1655 case '_': sb.append("_1"); break;
1656 case ';': sb.append("_2"); break;
1657 case '[': sb.append("_3"); break;
1659 if (Character.isJavaIdentifierPart(ch)) {
1663 String hex = Integer.toHexString(ch).toLowerCase();
1664 for (int m = hex.length(); m < 4; m++) {
1672 return sb.toString();
1675 private static String mangleClassName(String name) {
1676 return mangleSig(name);
1679 private static String findMethodName(MethodData m, StringBuilder cnt) {
1680 StringBuilder name = new StringBuilder();
1681 if ("<init>".equals(m.getName())) { // NOI18N
1682 name.append("cons"); // NOI18N
1683 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1684 name.append("class"); // NOI18N
1686 name.append(mangleMethodName(m.getName()));
1689 countArgs(m.getInternalSig(), new char[1], name, cnt);
1690 return name.toString();
1693 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1694 StringBuilder name = new StringBuilder();
1695 String descr = mi[2];//mi.getDescriptor();
1697 if ("<init>".equals(nm)) { // NOI18N
1698 name.append("cons"); // NOI18N
1700 name.append(mangleMethodName(nm));
1702 countArgs(descr, returnType, name, cnt);
1703 return name.toString();
1706 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1707 throws IOException {
1708 int methodIndex = readUShortArg(byteCodes, i);
1709 String[] mi = jc.getFieldInfoName(methodIndex);
1710 char[] returnType = { 'V' };
1711 StringBuilder cnt = new StringBuilder();
1712 String mn = findMethodName(mi, cnt, returnType);
1714 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1715 final CharSequence[] vars = new CharSequence[numArguments];
1717 for (int j = numArguments - 1; j >= 0; --j) {
1718 vars[j] = mapper.popValue();
1722 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1723 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1725 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1726 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1728 if (vars[1] instanceof String) {
1729 String field = vars[1].toString();
1730 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1731 vars[1] = "c._" + field.substring(1, field.length() - 1);
1736 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1737 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1739 if (vars[1] instanceof String) {
1740 String field = vars[2].toString();
1741 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1742 vars[2] = "c._" + field.substring(1, field.length() - 1);
1747 if (returnType[0] != 'V') {
1750 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1754 final String in = mi[0];
1757 in.equals("org/apidesign/html/boot/spi/Fn") ||
1758 in.equals("org/netbeans/html/boot/spi/Fn")
1760 mcn = "java_lang_Class";
1762 mcn = mangleClassName(in);
1764 String object = accessClassFalse(mcn);
1765 if (mn.startsWith("cons_")) {
1766 object += ".constructor";
1768 append(accessStaticMethod(object, mn, mi));
1774 if (numArguments > 0) {
1776 for (int j = 1; j < numArguments; ++j) {
1786 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1787 throws IOException {
1788 int methodIndex = readUShortArg(byteCodes, i);
1789 String[] mi = jc.getFieldInfoName(methodIndex);
1790 char[] returnType = { 'V' };
1791 StringBuilder cnt = new StringBuilder();
1792 String mn = findMethodName(mi, cnt, returnType);
1794 final int numArguments = cnt.length() + 1;
1795 final CharSequence[] vars = new CharSequence[numArguments];
1797 for (int j = numArguments - 1; j >= 0; --j) {
1798 vars[j] = mapper.popValue();
1801 if (returnType[0] != 'V') {
1804 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1808 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1810 for (int j = 1; j < numArguments; ++j) {
1820 private void addReference(String cn) throws IOException {
1821 if (requireReference(cn)) {
1822 debug(" /* needs " + cn + " */");
1826 private void outType(String d, StringBuilder out) {
1828 while (d.charAt(0) == '[') {
1832 if (d.charAt(0) == 'L') {
1833 assert d.charAt(d.length() - 1) == ';';
1834 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1840 private String encodeConstant(int entryIndex) throws IOException {
1841 String[] classRef = { null };
1842 String s = jc.stringValue(entryIndex, classRef);
1843 if (classRef[0] != null) {
1844 if (classRef[0].startsWith("[")) {
1845 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1847 addReference(classRef[0]);
1848 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1854 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1855 byte[] arr = m.findAnnotationData(true);
1859 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1860 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1861 class P extends AnnotationParser {
1867 String[] args = new String[30];
1873 protected void visitAttr(String type, String attr, String at, String value) {
1874 if (type.equals(jvmType)) {
1875 if ("body".equals(attr)) {
1877 } else if ("args".equals(attr)) {
1878 args[cnt++] = value;
1880 throw new IllegalArgumentException(attr);
1883 if (type.equals(htmlType)) {
1885 if ("body".equals(attr)) {
1887 } else if ("args".equals(attr)) {
1888 args[cnt++] = value;
1889 } else if ("javacall".equals(attr)) {
1890 javacall = "1".equals(value);
1891 } else if ("wait4js".equals(attr)) {
1892 // ignore, we always invoke synchronously
1894 throw new IllegalArgumentException(attr);
1901 if (p.body == null) {
1904 StringBuilder cnt = new StringBuilder();
1905 final String mn = findMethodName(m, cnt);
1906 append("m = ").append(destObject).append(".").append(mn);
1907 append(" = function(");
1910 StringBuilder toValue = new StringBuilder();
1911 for (int i = 0; i < cnt.length(); i++) {
1913 space = outputArg(this, p.args, index);
1914 if (p.html4j && space.length() > 0) {
1915 toValue.append("\n ").append(p.args[index]).append(" = ")
1916 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1917 append(p.args[index]).append(");");
1921 append(") {").append("\n");
1922 append(toValue.toString());
1924 int lastSlash = jc.getClassName().lastIndexOf('/');
1925 final String pkg = jc.getClassName().substring(0, lastSlash);
1926 append(mangleCallbacks(pkg, p.body));
1927 requireReference(pkg + "/$JsCallbacks$");
1935 private static CharSequence mangleCallbacks(String pkgName, String body) {
1936 StringBuilder sb = new StringBuilder();
1939 int next = body.indexOf(".@", pos);
1941 sb.append(body.substring(pos));
1942 body = sb.toString();
1947 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1952 String refId = body.substring(ident, next);
1954 sb.append(body.substring(pos, ident));
1956 int sigBeg = body.indexOf('(', next);
1957 int sigEnd = body.indexOf(')', sigBeg);
1958 int colon4 = body.indexOf("::", next);
1959 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1960 throw new IllegalStateException("Malformed body " + body);
1962 String fqn = body.substring(next + 2, colon4);
1963 String method = body.substring(colon4 + 2, sigBeg);
1964 String params = body.substring(sigBeg, sigEnd + 1);
1966 int paramBeg = body.indexOf('(', sigEnd + 1);
1968 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1969 sb.append(mangleJsCallbacks(fqn, method, params, false));
1970 sb.append("(").append(refId);
1971 if (body.charAt(paramBeg + 1) != ')') {
1979 int next = body.indexOf("@", pos);
1984 sb.append(body.substring(pos));
1988 sb = new StringBuilder();
1991 sb.append(body.substring(pos, next));
1993 int sigBeg = body.indexOf('(', next);
1994 int sigEnd = body.indexOf(')', sigBeg);
1995 int colon4 = body.indexOf("::", next);
1996 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1997 throw new IllegalStateException("Malformed body " + body);
1999 String fqn = body.substring(next + 1, colon4);
2000 String method = body.substring(colon4 + 2, sigBeg);
2001 String params = body.substring(sigBeg, sigEnd + 1);
2003 int paramBeg = body.indexOf('(', sigEnd + 1);
2005 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2006 sb.append(mangleJsCallbacks(fqn, method, params, true));
2012 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2013 if (params.startsWith("(")) {
2014 params = params.substring(1);
2016 if (params.endsWith(")")) {
2017 params = params.substring(0, params.length() - 1);
2019 StringBuilder sb = new StringBuilder();
2020 final String fqnu = fqn.replace('.', '_');
2021 final String rfqn = mangleClassName(fqnu);
2022 final String rm = mangleMethodName(method);
2025 StringBuilder pb = new StringBuilder();
2026 int len = params.length();
2028 while (indx < len) {
2029 char ch = params.charAt(indx);
2030 if (ch == '[' || ch == 'L') {
2031 int column = params.indexOf(';', indx) + 1;
2032 if (column > indx) {
2033 String real = params.substring(indx, column);
2034 if ("Ljava/lang/String;".equals(real)) {
2035 pb.append("Ljava/lang/String;");
2040 pb.append("Ljava/lang/Object;");
2047 srp = mangleSig(pb.toString());
2049 final String rp = mangleSig(params);
2050 final String mrp = mangleMethodName(rp);
2051 sb.append(rfqn).append("$").append(rm).
2052 append('$').append(mrp).append("__Ljava_lang_Object_2");
2054 sb.append('L').append(fqnu).append("_2");
2057 return sb.toString();
2060 private static String className(ClassData jc) {
2061 //return jc.getName().getInternalName().replace('/', '_');
2062 return mangleClassName(jc.getClassName());
2065 private static String[] findAnnotation(
2066 byte[] arr, ClassData cd, final String className,
2067 final String... attrNames
2068 ) throws IOException {
2072 final String[] values = new String[attrNames.length];
2073 final boolean[] found = { false };
2074 final String jvmType = "L" + className.replace('.', '/') + ";";
2075 AnnotationParser ap = new AnnotationParser(false, true) {
2077 protected void visitAttr(String type, String attr, String at, String value) {
2078 if (type.equals(jvmType)) {
2080 for (int i = 0; i < attrNames.length; i++) {
2081 if (attrNames[i].equals(attr)) {
2090 return found[0] ? values : null;
2093 private CharSequence initField(FieldData v) {
2094 final String is = v.getInternalSig();
2095 if (is.length() == 1) {
2096 switch (is.charAt(0)) {
2102 case 'I': return " = 0;";
2104 case 'D': return " = 0.0;";
2106 throw new IllegalStateException(is);
2112 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2113 AnnotationParser ap = new AnnotationParser(true, false) {
2114 int[] cnt = new int[32];
2118 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2119 final String slashType = attrType.substring(1, attrType.length() - 1);
2120 requireReference(slashType);
2122 if (cnt[depth]++ > 0) {
2126 append('"').append(attrType).append("\" : ");
2133 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2139 protected void visitValueStart(String attrName, char type) throws IOException {
2140 if (cnt[depth]++ > 0) {
2144 if (attrName != null) {
2145 append('"').append(attrName).append("\" : ");
2153 protected void visitValueEnd(String attrName, char type) throws IOException {
2161 protected void visitAttr(String type, String attr, String attrType, String value)
2162 throws IOException {
2163 if (attr == null && value == null) {
2170 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2171 throws IOException {
2172 final String slashType = attrType.substring(1, attrType.length() - 1);
2173 requireReference(slashType);
2175 final String cn = mangleClassName(slashType);
2176 append(accessClassFalse(cn))
2177 .append("['valueOf__L").
2179 append("_2Ljava_lang_String_2']('").
2187 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2188 final String name = args[indx];
2192 if (name.contains(",")) {
2193 throw new IOException("Wrong parameter with ',': " + name);
2199 final void emitNoFlush(
2201 final String format, final CharSequence... params
2202 ) throws IOException {
2203 emitImpl(this, format, params);
2205 static final void emit(
2207 final Appendable out,
2208 final String format, final CharSequence... params
2209 ) throws IOException {
2211 emitImpl(out, format, params);
2213 static void emitImpl(final Appendable out,
2214 final String format,
2215 final CharSequence... params) throws IOException {
2216 final int length = format.length();
2219 int paramOffset = format.indexOf('@');
2220 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2221 final char paramChar = format.charAt(paramOffset + 1);
2222 if ((paramChar >= '1') && (paramChar <= '9')) {
2223 final int paramIndex = paramChar - '0' - 1;
2225 out.append(format, processed, paramOffset);
2226 out.append(params[paramIndex]);
2229 processed = paramOffset + 1;
2232 paramOffset = format.indexOf('@', paramOffset + 1);
2235 out.append(format, processed, length);
2238 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2239 append("} catch (e) {\n");
2241 for (TrapData e : traps) {
2245 if (e.catch_cpx != 0) { //not finally
2246 final String classInternalName = jc.getClassName(e.catch_cpx);
2247 addReference(classInternalName);
2248 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2249 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2250 append("var stA0 = e;");
2251 goTo(this, current, e.handler_pc, topMostLabel);
2254 finallyPC = e.handler_pc;
2257 if (finallyPC == -1) {
2260 append("var stA0 = e;");
2261 goTo(this, current, finallyPC, topMostLabel);
2266 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2269 out.append("{ gt = 0; continue X_" + to + "; }");
2271 out.append("{ gt = " + to + "; continue X_0; }");
2274 out.append("{ gt = " + to + "; break IF; }");
2278 private static void emitIf(
2280 Appendable out, String pattern,
2282 int current, int to, int canBack
2283 ) throws IOException {
2285 emitImpl(out, pattern, param);
2286 goTo(out, current, to, canBack);
2289 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2292 case 4: jvmType = "[Z"; break;
2293 case 5: jvmType = "[C"; break;
2294 case 6: jvmType = "[F"; break;
2295 case 7: jvmType = "[D"; break;
2296 case 8: jvmType = "[B"; break;
2297 case 9: jvmType = "[S"; break;
2298 case 10: jvmType = "[I"; break;
2299 case 11: jvmType = "[J"; break;
2300 default: throw new IllegalStateException("Array type: " + atype);
2303 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2304 smapper.popI(), smapper.pushA(), jvmType);
2307 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2308 String typeName = jc.getClassName(type);
2309 String ref = "null";
2310 if (typeName.startsWith("[")) {
2311 typeName = "'[" + typeName + "'";
2313 ref = "vm." + mangleClassName(typeName);
2314 typeName = "'[L" + typeName + ";'";
2317 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2318 smapper.popI(), smapper.pushA(), typeName, ref);
2321 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2322 String typeName = jc.getClassName(type);
2323 int dim = readUByte(byteCodes, ++i);
2324 StringBuilder dims = new StringBuilder();
2326 for (int d = 0; d < dim; d++) {
2328 dims.insert(1, ",");
2330 dims.insert(1, smapper.popI());
2334 if (typeName.charAt(dim) == 'L') {
2335 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2338 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2339 dims.toString(), smapper.pushA(), typeName, fn
2344 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2345 int table = i / 4 * 4 + 4;
2346 int dflt = i + readInt4(byteCodes, table);
2348 int low = readInt4(byteCodes, table);
2350 int high = readInt4(byteCodes, table);
2352 final CharSequence swVar = smapper.popValue();
2353 smapper.flush(this);
2354 append("switch (").append(swVar).append(") {\n");
2355 while (low <= high) {
2356 int offset = i + readInt4(byteCodes, table);
2358 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2361 append(" default: ");
2362 goTo(this, i, dflt, topMostLabel);
2368 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2369 int table = i / 4 * 4 + 4;
2370 int dflt = i + readInt4(byteCodes, table);
2372 int n = readInt4(byteCodes, table);
2374 final CharSequence swVar = smapper.popValue();
2375 smapper.flush(this);
2376 append("switch (").append(swVar).append(") {\n");
2378 int cnstnt = readInt4(byteCodes, table);
2380 int offset = i + readInt4(byteCodes, table);
2382 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2384 append(" default: ");
2385 goTo(this, i, dflt, topMostLabel);
2391 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2392 String type = jc.getClassName(indx);
2393 if (!type.startsWith("[")) {
2395 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2396 smapper.popA(), smapper.pushI(),
2397 type.replace('/', '_'));
2400 while (type.charAt(cnt) == '[') {
2403 if (type.charAt(cnt) == 'L') {
2404 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2406 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2407 smapper.popA(), smapper.pushI(),
2412 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2413 smapper.popA(), smapper.pushI(), type
2419 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2420 String type = jc.getClassName(indx);
2421 if (!type.startsWith("[")) {
2422 emitNoFlush(smapper,
2423 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2424 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2427 while (type.charAt(cnt) == '[') {
2430 if (type.charAt(cnt) == 'L') {
2431 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2432 emitNoFlush(smapper,
2433 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2434 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2437 emitNoFlush(smapper,
2438 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2439 smapper.getT(0, VarType.REFERENCE, false), type
2445 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2446 for (int j = prev; j <= i; j++) {
2448 final int cc = readUByte(byteCodes, j);
2449 append(Integer.toString(cc));
2453 @JavaScriptBody(args = "msg", body = "")
2454 private static void println(String msg) {
2455 System.err.println(msg);