Don't initialize @JavaScriptBody resources sooner than their methods are called.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 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 protected String accessField(String object, String mangledName,
89 String[] fieldInfoName) throws IOException {
90 return object + "." + mangledName;
93 protected String accessStaticMethod(
96 String[] fieldInfoName) throws IOException {
97 return object + "." + mangledName;
100 protected String accessVirtualMethod(
103 String[] fieldInfoName,
105 ) throws IOException {
106 return object + "." + mangledName + '(';
109 protected void declaredClass(ClassData classData, String mangledName)
113 protected void declaredField(FieldData fieldData,
115 String mangledName) throws IOException {
118 protected void declaredMethod(MethodData methodData,
120 String mangledName) throws IOException {
123 /** Prints out a debug message.
125 * @param msg the message
126 * @return true if the message has been printed
127 * @throws IOException
129 boolean debug(String msg) throws IOException {
135 * Converts a given class file to a JavaScript version.
137 * @param classFile input stream with code of the .class file
138 * @return the initialization code for this class, if any. Otherwise <code>null</code>
140 * @throws IOException if something goes wrong during read or write or translating
143 public String compile(InputStream classFile) throws IOException {
144 return compile(new ClassData(classFile));
147 protected String compile(ClassData classData) throws IOException {
149 this.callbacks = this.jc.getClassName().endsWith("/$JsCallbacks$");
150 if (jc.getMajor_version() < 50) {
151 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
152 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
155 byte[] arrData = jc.findAnnotationData(true);
157 String[] arr = findAnnotation(arrData, jc,
158 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
159 "resource", "processByteCode"
162 if (!arr[0].isEmpty()) {
163 requireScript(arr[0]);
165 if ("0".equals(arr[1])) {
170 final String jsResource;
172 String[] arr = findAnnotation(arrData, jc,
173 "net.java.html.js.JavaScriptResource",
177 if (arr[0].startsWith("/")) {
180 int last = jc.getClassName().lastIndexOf('/');
181 jsResource = jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0];
187 String[] proto = findAnnotation(arrData, jc,
188 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
189 "container", "prototype"
191 StringArray toInitilize = new StringArray();
192 final String className = className(jc);
193 append("\n\n").append(assignClass(className));
194 append("function ").append(className).append("() {");
196 append("\n var CLS = ").append(className).append(';');
197 append("\n if (!CLS.$class) {");
199 String sc = jc.getSuperClassName(); // with _
200 append("\n var pp = ").
201 append(accessClass(mangleClassName(sc))).append("(true);");
202 append("\n var p = CLS.prototype = pp;");
203 append("\n var c = p;");
204 append("\n var sprcls = pp.constructor.$class;");
206 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
207 if (proto[0] == null) {
210 append("\n var c = ").append(proto[0]).append(";");
211 append("\n var sprcls = null;");
213 for (FieldData v : jc.getFields()) {
215 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
216 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
220 append("\n CLS.fld_").append(v.getName()).append(initField(v));
221 append("\n m = c._").append(v.getName()).append(" = function (v) {")
222 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
223 .append(" = v; return CLS.fld_").
224 append(v.getName()).append("; };");
226 append("\n m = c._").append(v.getName()).append(" = function (v) {")
227 .append(" if (arguments.length == 1) this.fld_").
228 append(className).append('_').append(v.getName())
229 .append(" = v; return this.fld_").
230 append(className).append('_').append(v.getName())
234 declaredField(v, "c", "_" + v.getName());
236 for (MethodData m : jc.getMethods()) {
237 byte[] onlyArr = m.findAnnotationData(true);
238 if (javaScriptOnly(onlyArr)) continue;
244 mn = generateStaticMethod(destObject, m, toInitilize);
246 if (m.isConstructor()) {
248 mn = generateInstanceMethod(destObject, m);
251 mn = generateInstanceMethod(destObject, m);
254 declaredMethod(m, destObject, mn);
255 byte[] runAnno = m.findAnnotationData(false);
256 if (runAnno != null) {
257 append("\n m.anno = {");
258 generateAnno(jc, runAnno);
261 append("\n m.access = " + m.getAccess()).append(";");
262 append("\n m.cls = CLS;");
264 append("\n c.constructor = CLS;");
265 append("\n function ").append(className).append("fillInstOf(x) {");
266 String instOfName = "$instOf_" + className;
267 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
268 if (jc.isInterface()) {
269 for (MethodData m : jc.getMethods()) {
270 if ((m.getAccess() & ACC_ABSTRACT) == 0
271 && (m.getAccess() & ACC_STATIC) == 0
272 && (m.getAccess() & ACC_PRIVATE) == 0) {
273 final String mn = findMethodName(m, new StringBuilder());
275 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
276 append("\n } catch (ignore) {");
281 for (String superInterface : jc.getSuperInterfaces()) {
282 String intrfc = superInterface.replace('/', '_');
283 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
284 requireReference(superInterface);
288 append("\n Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
289 append("\n ").append(className).append("fillInstOf(c);");
290 append("\n } catch (ignore) {");
292 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
293 append("\n CLS.$class = 'temp';");
294 append("\n CLS.$class = ");
295 append(accessClass("java_lang_Class(true);"));
296 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
297 append("\n CLS.$class.superclass = sprcls;");
298 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
299 append("\n CLS.$class.cnstr = CLS;");
300 byte[] classAnno = jc.findAnnotationData(false);
301 if (classAnno != null) {
302 append("\n CLS.$class.anno = {");
303 generateAnno(jc, classAnno);
306 for (String init : toInitilize.toArray()) {
307 append("\n ").append(init).append("();");
310 if (jsResource != null) {
311 requireResource(jsResource);
315 append("\n if (arguments.length === 0) {");
316 append("\n if (!(this instanceof CLS)) {");
317 append("\n return new CLS();");
319 for (FieldData v : jc.getFields()) {
320 byte[] onlyArr = v.findAnnotationData(true);
321 if (javaScriptOnly(onlyArr)) continue;
323 append("\n this.fld_").
324 append(className).append('_').
325 append(v.getName()).append(initField(v));
328 append("\n return this;");
330 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
333 declaredClass(jc, className);
335 // StringBuilder sb = new StringBuilder();
336 // for (String init : toInitilize.toArray()) {
337 // sb.append("\n").append(init).append("();");
342 private boolean javaScriptOnly(byte[] anno) throws IOException {
343 String[] only = findAnnotation(anno, jc,
344 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
348 if (only[0] != null && only[1] != null) {
349 append("\n p.").append(only[0]).append(" = ")
350 .append(only[1]).append(";");
352 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
353 append("\n p['").append(only[0]).append("'] = p.")
354 .append(only[0]).append(";");
360 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
361 String jsb = javaScriptBody(destObject, m, true);
365 final String mn = findMethodName(m, new StringBuilder());
366 boolean defineProp = generateMethod(destObject, mn, m);
367 if (mn.equals("class__V")) {
369 toInitilize.add(accessClass(className(jc)) + "(false)['" + mn + "']");
371 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
377 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
378 String jsb = javaScriptBody(destObject, m, false);
382 final String mn = findMethodName(m, new StringBuilder());
383 generateMethod(destObject, mn, m);
387 private boolean generateMethod(String destObject, String name, MethodData m)
389 final StackMapIterator stackMapIterator = m.createStackMapIterator();
390 TrapDataIterator trap = m.getTrapDataIterator();
391 final LocalsMapper lmapper =
392 new LocalsMapper(stackMapIterator.getArguments());
395 "java/lang/Object".equals(jc.getClassName()) ||
396 "java/lang/reflect/Array".equals(jc.getClassName());
399 append("Object.defineProperty(").append(destObject).
400 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
402 append("m = ").append(destObject).append(".").append(name).append(" = function(");
404 lmapper.outputArguments(this, m.isStatic());
405 append(") {").append("\n");
407 final byte[] byteCodes = m.getCode();
408 if (byteCodes == null) {
409 append(" throw 'no code found for ")
410 .append(jc.getClassName()).append('.')
411 .append(m.getName()).append("';\n");
420 final StackMapper smapper = new StackMapper();
423 append(" var ").append(" lcA0 = this;\n");
427 TrapData[] previousTrap = null;
428 boolean wide = false;
430 if (stackMapIterator.isEmpty()) {
436 append("\n var gt = 0;\n");
440 int topMostLabel = 0;
441 for (int i = 0; i < byteCodes.length; i++) {
444 stackMapIterator.advanceTo(i);
445 boolean changeInCatch = trap.advanceTo(i);
446 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
447 if (previousTrap != null) {
448 generateCatch(previousTrap, i, topMostLabel);
452 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
457 if (openBraces > 64) {
458 for (int c = 0; c < 64; c++) {
465 lastStackFrame = stackMapIterator.getFrameIndex();
466 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
467 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
468 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
470 changeInCatch = true;
472 debug(" /* " + i + " */ ");
474 if (changeInCatch && trap.useTry()) {
476 previousTrap = trap.current();
478 final int c = readUByte(byteCodes, i);
481 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
484 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
487 smapper.assign(this, VarType.LONG, lmapper.getL(0));
490 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
493 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
496 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
499 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
502 smapper.assign(this, VarType.LONG, lmapper.getL(1));
505 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
508 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
511 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
514 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
517 smapper.assign(this, VarType.LONG, lmapper.getL(2));
520 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
523 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
526 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
529 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
532 smapper.assign(this, VarType.LONG, lmapper.getL(3));
535 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
538 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
542 final int indx = wide ? readUShort(byteCodes, i++)
543 : readUByte(byteCodes, i);
545 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
550 final int indx = wide ? readUShort(byteCodes, i++)
551 : readUByte(byteCodes, i);
553 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
558 final int indx = wide ? readUShort(byteCodes, i++)
559 : readUByte(byteCodes, i);
561 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
566 final int indx = wide ? readUShort(byteCodes, i++)
567 : readUByte(byteCodes, i);
569 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
574 final int indx = wide ? readUShort(byteCodes, i++)
575 : readUByte(byteCodes, i);
577 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
582 final int indx = wide ? readUShort(byteCodes, i++)
583 : readUByte(byteCodes, i);
585 emit(smapper, this, "var @1 = @2;",
586 lmapper.setI(indx), smapper.popI());
591 final int indx = wide ? readUShort(byteCodes, i++)
592 : readUByte(byteCodes, i);
594 emit(smapper, this, "var @1 = @2;",
595 lmapper.setL(indx), smapper.popL());
600 final int indx = wide ? readUShort(byteCodes, i++)
601 : readUByte(byteCodes, i);
603 emit(smapper, this, "var @1 = @2;",
604 lmapper.setF(indx), smapper.popF());
609 final int indx = wide ? readUShort(byteCodes, i++)
610 : readUByte(byteCodes, i);
612 emit(smapper, this, "var @1 = @2;",
613 lmapper.setD(indx), smapper.popD());
618 final int indx = wide ? readUShort(byteCodes, i++)
619 : readUByte(byteCodes, i);
621 emit(smapper, this, "var @1 = @2;",
622 lmapper.setA(indx), smapper.popA());
626 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
629 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
632 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
635 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
638 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
641 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
644 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
647 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
650 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
653 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
656 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
659 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
662 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
665 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
668 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
671 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
674 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
677 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
680 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
683 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
686 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
689 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
692 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
695 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
698 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
701 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
704 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
707 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
710 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
713 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
716 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
719 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
722 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
723 smapper.getI(1), smapper.popI());
726 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
727 smapper.getL(1), smapper.popL());
730 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
733 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
736 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
737 smapper.getI(1), smapper.popI());
740 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
741 smapper.getL(1), smapper.popL());
744 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
747 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
750 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
753 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
756 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
759 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
762 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
765 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
768 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
771 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
774 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
777 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
780 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
783 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
786 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
789 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
792 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
795 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
799 final int varIndx = wide ? readUShort(byteCodes, i++)
800 : readUByte(byteCodes, i);
802 final int incrBy = wide ? readShort(byteCodes, i++)
806 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
808 emit(smapper, this, "@1 += @2;",
809 lmapper.getI(varIndx),
810 Integer.toString(incrBy));
815 emit(smapper, this, "return;");
818 emit(smapper, this, "return @1;", smapper.popI());
821 emit(smapper, this, "return @1;", smapper.popL());
824 emit(smapper, this, "return @1;", smapper.popF());
827 emit(smapper, this, "return @1;", smapper.popD());
830 emit(smapper, this, "return @1;", smapper.popA());
833 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
836 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
839 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
842 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
846 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
849 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
852 smapper.replace(this, VarType.DOUBLE, "@1",
856 smapper.replace(this, VarType.FLOAT, "@1",
860 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
864 smapper.replace(this, VarType.LONG, "(@1).toLong()",
868 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
872 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
875 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
879 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
881 case opc_aconst_null:
882 smapper.assign(this, VarType.REFERENCE, "null");
885 smapper.assign(this, VarType.INTEGER, "-1");
888 smapper.assign(this, VarType.INTEGER, "0");
891 smapper.assign(this, VarType.DOUBLE, "0");
894 smapper.assign(this, VarType.LONG, "0");
897 smapper.assign(this, VarType.FLOAT, "0");
900 smapper.assign(this, VarType.INTEGER, "1");
903 smapper.assign(this, VarType.LONG, "1");
906 smapper.assign(this, VarType.FLOAT, "1");
909 smapper.assign(this, VarType.DOUBLE, "1");
912 smapper.assign(this, VarType.INTEGER, "2");
915 smapper.assign(this, VarType.FLOAT, "2");
918 smapper.assign(this, VarType.INTEGER, "3");
921 smapper.assign(this, VarType.INTEGER, "4");
924 smapper.assign(this, VarType.INTEGER, "5");
927 int indx = readUByte(byteCodes, ++i);
928 String v = encodeConstant(indx);
929 int type = VarType.fromConstantType(jc.getTag(indx));
930 smapper.assign(this, type, v);
935 int indx = readUShortArg(byteCodes, i);
937 String v = encodeConstant(indx);
938 int type = VarType.fromConstantType(jc.getTag(indx));
939 if (type == VarType.LONG) {
940 final Long lv = new Long(v);
941 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
942 final int hi = (int)(lv.longValue() >> 32);
944 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
946 smapper.assign(this, VarType.LONG,
947 "0x" + Integer.toHexString(hi) + ".next32(0x" +
948 Integer.toHexString(low) + ")"
952 smapper.assign(this, type, v);
957 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
961 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
965 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
968 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
969 "===", topMostLabel);
972 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
973 "!==", topMostLabel);
976 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
980 int indx = i + readShortArg(byteCodes, i);
981 emitIf(smapper, this, "if ((@1) == 0) ",
982 smapper.popI(), i, indx, topMostLabel);
987 int indx = i + readShortArg(byteCodes, i);
988 emitIf(smapper, this, "if ((@1) != 0) ",
989 smapper.popI(), i, indx, topMostLabel);
994 int indx = i + readShortArg(byteCodes, i);
995 emitIf(smapper, this, "if ((@1) < 0) ",
996 smapper.popI(), i, indx, topMostLabel);
1001 int indx = i + readShortArg(byteCodes, i);
1002 emitIf(smapper, this, "if ((@1) <= 0) ",
1003 smapper.popI(), i, indx, topMostLabel);
1008 int indx = i + readShortArg(byteCodes, i);
1009 emitIf(smapper, this, "if ((@1) > 0) ",
1010 smapper.popI(), i, indx, topMostLabel);
1015 int indx = i + readShortArg(byteCodes, i);
1016 emitIf(smapper, this, "if ((@1) >= 0) ",
1017 smapper.popI(), i, indx, topMostLabel);
1021 case opc_ifnonnull: {
1022 int indx = i + readShortArg(byteCodes, i);
1023 emitIf(smapper, this, "if ((@1) !== null) ",
1024 smapper.popA(), i, indx, topMostLabel);
1029 int indx = i + readShortArg(byteCodes, i);
1030 emitIf(smapper, this, "if ((@1) === null) ",
1031 smapper.popA(), i, indx, topMostLabel);
1036 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1037 "!=", topMostLabel);
1040 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1044 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1045 "<=", topMostLabel);
1048 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1052 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1053 ">=", topMostLabel);
1056 smapper.flush(this);
1057 int indx = i + readShortArg(byteCodes, i);
1058 goTo(this, i, indx, topMostLabel);
1062 case opc_lookupswitch: {
1063 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1066 case opc_tableswitch: {
1067 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1070 case opc_invokeinterface: {
1071 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1074 case opc_invokevirtual:
1075 i = invokeVirtualMethod(byteCodes, i, smapper);
1077 case opc_invokespecial:
1078 i = invokeStaticMethod(byteCodes, i, smapper, false);
1080 case opc_invokestatic:
1081 i = invokeStaticMethod(byteCodes, i, smapper, true);
1083 case opc_invokedynamic: {
1084 int indx = readUShortArg(byteCodes, i);
1085 println("invoke dynamic: " + indx);
1086 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1087 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1088 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1089 println(" type: " + methodHandle.cpx1);
1090 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1091 String mcn = mangleClassName(mi[0]);
1092 char[] returnType = {'V'};
1093 StringBuilder cnt = new StringBuilder();
1094 String mn = findMethodName(mi, cnt, returnType);
1095 StringBuilder sb = new StringBuilder();
1096 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1097 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1098 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1099 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1100 sb.append(" mn : ").append(mn).append("\n");
1101 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1102 throw new IOException(sb.toString());
1104 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1105 String type = jc.StringValue(nameAndType.cpx2);
1106 String object = accessClass(mcn) + "(false)";
1107 if (mn.startsWith("cons_")) {
1108 object += ".constructor";
1110 append("var metHan = ");
1111 append(accessStaticMethod(object, mn, mi));
1113 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1115 append(", '").append(mi[1]).append("', ");
1116 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1117 append(methodType).append("'").append(type).append("', null)");
1118 // if (numArguments > 0) {
1120 // for (int j = 1; j < numArguments; ++j) {
1126 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1132 int indx = readUShortArg(byteCodes, i);
1133 String ci = jc.getClassName(indx);
1134 emit(smapper, this, "var @1 = new @2;",
1135 smapper.pushA(), accessClass(mangleClassName(ci)));
1141 int atype = readUByte(byteCodes, ++i);
1142 generateNewArray(atype, smapper);
1144 case opc_anewarray: {
1145 int type = readUShortArg(byteCodes, i);
1147 generateANewArray(type, smapper);
1150 case opc_multianewarray: {
1151 int type = readUShortArg(byteCodes, i);
1153 i = generateMultiANewArray(type, byteCodes, i, smapper);
1156 case opc_arraylength:
1157 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1160 emit(smapper, this, "Array.at(@3, @2, @1);",
1161 smapper.popL(), smapper.popI(), smapper.popA());
1164 emit(smapper, this, "Array.at(@3, @2, @1);",
1165 smapper.popF(), smapper.popI(), smapper.popA());
1168 emit(smapper, this, "Array.at(@3, @2, @1);",
1169 smapper.popD(), smapper.popI(), smapper.popA());
1172 emit(smapper, this, "Array.at(@3, @2, @1);",
1173 smapper.popA(), smapper.popI(), smapper.popA());
1179 emit(smapper, this, "Array.at(@3, @2, @1);",
1180 smapper.popI(), smapper.popI(), smapper.popA());
1183 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1184 smapper.popI(), smapper.getA(0));
1187 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1188 smapper.popI(), smapper.getA(0));
1191 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1192 smapper.popI(), smapper.getA(0));
1195 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1196 smapper.popI(), smapper.getA(0));
1202 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1203 smapper.popI(), smapper.getA(0));
1211 final Variable v = smapper.get(0);
1212 if (smapper.isDirty()) {
1213 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1215 smapper.assign(this, v.getType(), v);
1220 final Variable vi1 = smapper.get(0);
1222 if (vi1.isCategory2()) {
1223 emit(smapper, this, "var @1 = @2;",
1224 smapper.pushT(vi1.getType()), vi1);
1226 final Variable vi2 = smapper.get(1);
1227 emit(smapper, this, "var @1 = @2, @3 = @4;",
1228 smapper.pushT(vi2.getType()), vi2,
1229 smapper.pushT(vi1.getType()), vi1);
1234 final Variable vi1 = smapper.pop(this);
1235 final Variable vi2 = smapper.pop(this);
1236 final Variable vo3 = smapper.pushT(vi1.getType());
1237 final Variable vo2 = smapper.pushT(vi2.getType());
1238 final Variable vo1 = smapper.pushT(vi1.getType());
1240 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1241 vo1, vi1, vo2, vi2, vo3, vo1);
1245 final Variable vi1 = smapper.pop(this);
1246 final Variable vi2 = smapper.pop(this);
1248 if (vi1.isCategory2()) {
1249 final Variable vo3 = smapper.pushT(vi1.getType());
1250 final Variable vo2 = smapper.pushT(vi2.getType());
1251 final Variable vo1 = smapper.pushT(vi1.getType());
1253 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1254 vo1, vi1, vo2, vi2, vo3, vo1);
1256 final Variable vi3 = smapper.pop(this);
1257 final Variable vo5 = smapper.pushT(vi2.getType());
1258 final Variable vo4 = smapper.pushT(vi1.getType());
1259 final Variable vo3 = smapper.pushT(vi3.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, vi3);
1265 emit(smapper, this, " @1 = @2, @3 = @4;",
1266 vo4, vo1, vo5, vo2);
1271 final Variable vi1 = smapper.pop(this);
1272 final Variable vi2 = smapper.pop(this);
1274 if (vi2.isCategory2()) {
1275 final Variable vo3 = smapper.pushT(vi1.getType());
1276 final Variable vo2 = smapper.pushT(vi2.getType());
1277 final Variable vo1 = smapper.pushT(vi1.getType());
1279 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1280 vo1, vi1, vo2, vi2, vo3, vo1);
1282 final Variable vi3 = smapper.pop(this);
1283 final Variable vo4 = smapper.pushT(vi1.getType());
1284 final Variable vo3 = smapper.pushT(vi3.getType());
1285 final Variable vo2 = smapper.pushT(vi2.getType());
1286 final Variable vo1 = smapper.pushT(vi1.getType());
1288 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1289 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1294 final Variable vi1 = smapper.pop(this);
1295 final Variable vi2 = smapper.pop(this);
1297 if (vi1.isCategory2()) {
1298 if (vi2.isCategory2()) {
1299 final Variable vo3 = smapper.pushT(vi1.getType());
1300 final Variable vo2 = smapper.pushT(vi2.getType());
1301 final Variable vo1 = smapper.pushT(vi1.getType());
1303 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1304 vo1, vi1, vo2, vi2, vo3, vo1);
1306 final Variable vi3 = smapper.pop(this);
1307 final Variable vo4 = smapper.pushT(vi1.getType());
1308 final Variable vo3 = smapper.pushT(vi3.getType());
1309 final Variable vo2 = smapper.pushT(vi2.getType());
1310 final Variable vo1 = smapper.pushT(vi1.getType());
1312 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1313 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1316 final Variable vi3 = smapper.pop(this);
1318 if (vi3.isCategory2()) {
1319 final Variable vo5 = smapper.pushT(vi2.getType());
1320 final Variable vo4 = smapper.pushT(vi1.getType());
1321 final Variable vo3 = smapper.pushT(vi3.getType());
1322 final Variable vo2 = smapper.pushT(vi2.getType());
1323 final Variable vo1 = smapper.pushT(vi1.getType());
1325 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1326 vo1, vi1, vo2, vi2, vo3, vi3);
1327 emit(smapper, this, " @1 = @2, @3 = @4;",
1328 vo4, vo1, vo5, vo2);
1330 final Variable vi4 = smapper.pop(this);
1331 final Variable vo6 = smapper.pushT(vi2.getType());
1332 final Variable vo5 = smapper.pushT(vi1.getType());
1333 final Variable vo4 = smapper.pushT(vi4.getType());
1334 final Variable vo3 = smapper.pushT(vi3.getType());
1335 final Variable vo2 = smapper.pushT(vi2.getType());
1336 final Variable vo1 = smapper.pushT(vi1.getType());
1338 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1339 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1340 emit(smapper, this, " @1 = @2, @3 = @4;",
1341 vo5, vo1, vo6, vo2);
1347 final Variable vi1 = smapper.get(0);
1348 final Variable vi2 = smapper.get(1);
1350 if (vi1.getType() == vi2.getType()) {
1351 final Variable tmp = smapper.pushT(vi1.getType());
1353 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1358 smapper.pushT(vi1.getType());
1359 smapper.pushT(vi2.getType());
1364 smapper.assign(this, VarType.INTEGER,
1365 "(" + Integer.toString(byteCodes[++i]) + ")");
1368 smapper.assign(this, VarType.INTEGER,
1369 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1373 case opc_getfield: {
1374 int indx = readUShortArg(byteCodes, i);
1375 String[] fi = jc.getFieldInfoName(indx);
1376 final int type = VarType.fromFieldType(fi[2].charAt(0));
1377 final String mangleClass = mangleClassName(fi[0]);
1378 final String mangleClassAccess = accessClass(mangleClass);
1379 smapper.replace(this, type, "@2.call(@1)",
1381 accessField(mangleClassAccess + "(false)",
1387 case opc_putfield: {
1388 int indx = readUShortArg(byteCodes, i);
1389 String[] fi = jc.getFieldInfoName(indx);
1390 final int type = VarType.fromFieldType(fi[2].charAt(0));
1391 final String mangleClass = mangleClassName(fi[0]);
1392 final String mangleClassAccess = accessClass(mangleClass);
1393 emit(smapper, this, "@3.call(@2, @1);",
1396 accessField(mangleClassAccess + "(false)",
1401 case opc_getstatic: {
1402 int indx = readUShortArg(byteCodes, i);
1403 String[] fi = jc.getFieldInfoName(indx);
1404 final int type = VarType.fromFieldType(fi[2].charAt(0));
1405 String ac = accessClass(mangleClassName(fi[0]));
1406 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1407 smapper.assign(this, type, af + "()");
1409 addReference(fi[0]);
1412 case opc_putstatic: {
1413 int indx = readUShortArg(byteCodes, i);
1414 String[] fi = jc.getFieldInfoName(indx);
1415 final int type = VarType.fromFieldType(fi[2].charAt(0));
1416 emit(smapper, this, "@1(false)._@2(@3);",
1417 accessClass(mangleClassName(fi[0])), fi[1],
1418 smapper.popT(type));
1420 addReference(fi[0]);
1423 case opc_checkcast: {
1424 int indx = readUShortArg(byteCodes, i);
1425 generateCheckcast(indx, smapper);
1429 case opc_instanceof: {
1430 int indx = readUShortArg(byteCodes, i);
1431 generateInstanceOf(indx, smapper);
1436 final CharSequence v = smapper.popA();
1439 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1440 smapper.pushA(), v);
1444 case opc_monitorenter: {
1445 debug("/* monitor enter */");
1450 case opc_monitorexit: {
1451 debug("/* monitor exit */");
1462 emit(smapper, this, "throw 'unknown bytecode @1';",
1463 Integer.toString(c));
1467 generateByteCodeComment(prev, i, byteCodes);
1473 if (previousTrap != null) {
1474 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1479 while (openBraces-- > 0) {
1490 private int generateIf(StackMapper mapper, byte[] byteCodes,
1491 int i, final CharSequence v2, final CharSequence v1,
1492 final String test, int topMostLabel
1493 ) throws IOException {
1495 int indx = i + readShortArg(byteCodes, i);
1496 append("if ((").append(v1)
1497 .append(") ").append(test).append(" (")
1498 .append(v2).append(")) ");
1499 goTo(this, i, indx, topMostLabel);
1503 private int readInt4(byte[] byteCodes, int offset) {
1504 final int d = byteCodes[offset + 0] << 24;
1505 final int c = byteCodes[offset + 1] << 16;
1506 final int b = byteCodes[offset + 2] << 8;
1507 final int a = byteCodes[offset + 3];
1508 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1510 private static int readUByte(byte[] byteCodes, int offset) {
1511 return byteCodes[offset] & 0xff;
1514 private static int readUShort(byte[] byteCodes, int offset) {
1515 return ((byteCodes[offset] & 0xff) << 8)
1516 | (byteCodes[offset + 1] & 0xff);
1518 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1519 return readUShort(byteCodes, offsetInstruction + 1);
1522 private static int readShort(byte[] byteCodes, int offset) {
1523 int signed = byteCodes[offset];
1524 byte b0 = (byte)signed;
1525 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1527 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1528 return readShort(byteCodes, offsetInstruction + 1);
1531 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1533 Boolean count = null;
1534 boolean array = false;
1536 int firstPos = sig.length();
1537 while (i < descriptor.length()) {
1538 char ch = descriptor.charAt(i++);
1559 if (ch == 'J' || ch == 'D') {
1565 sig.insert(firstPos, ch);
1567 returnType[0] = '[';
1568 sig.insert(firstPos, "_3");
1577 returnType[0] = 'V';
1578 sig.insert(firstPos, 'V');
1581 int next = descriptor.indexOf(';', i);
1582 String realSig = mangleSig(descriptor, i - 1, next + 1);
1587 sig.append(realSig);
1590 sig.insert(firstPos, realSig);
1592 sig.insert(firstPos, "_3");
1594 returnType[0] = 'L';
1603 throw new IllegalStateException("Invalid char: " + ch);
1608 static String mangleSig(String sig) {
1609 return mangleSig(sig, 0, sig.length());
1612 private static String mangleMethodName(String name) {
1613 StringBuilder sb = new StringBuilder(name.length() * 2);
1614 int last = name.length();
1615 for (int i = 0; i < last; i++) {
1616 final char ch = name.charAt(i);
1618 case '_': sb.append("_1"); break;
1619 default: sb.append(ch); break;
1622 return sb.toString();
1624 private static String mangleSig(String txt, int first, int last) {
1625 StringBuilder sb = new StringBuilder((last - first) * 2);
1626 for (int i = first; i < last; i++) {
1627 final char ch = txt.charAt(i);
1629 case '/': sb.append('_'); break;
1630 case '_': sb.append("_1"); break;
1631 case ';': sb.append("_2"); break;
1632 case '[': sb.append("_3"); break;
1634 if (Character.isJavaIdentifierPart(ch)) {
1638 String hex = Integer.toHexString(ch).toLowerCase();
1639 for (int m = hex.length(); m < 4; m++) {
1647 return sb.toString();
1650 private static String mangleClassName(String name) {
1651 return mangleSig(name);
1654 private static String findMethodName(MethodData m, StringBuilder cnt) {
1655 StringBuilder name = new StringBuilder();
1656 if ("<init>".equals(m.getName())) { // NOI18N
1657 name.append("cons"); // NOI18N
1658 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1659 name.append("class"); // NOI18N
1661 name.append(mangleMethodName(m.getName()));
1664 countArgs(m.getInternalSig(), new char[1], name, cnt);
1665 return name.toString();
1668 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1669 StringBuilder name = new StringBuilder();
1670 String descr = mi[2];//mi.getDescriptor();
1672 if ("<init>".equals(nm)) { // NOI18N
1673 name.append("cons"); // NOI18N
1675 name.append(mangleMethodName(nm));
1677 countArgs(descr, returnType, name, cnt);
1678 return name.toString();
1681 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1682 throws IOException {
1683 int methodIndex = readUShortArg(byteCodes, i);
1684 String[] mi = jc.getFieldInfoName(methodIndex);
1685 char[] returnType = { 'V' };
1686 StringBuilder cnt = new StringBuilder();
1687 String mn = findMethodName(mi, cnt, returnType);
1689 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1690 final CharSequence[] vars = new CharSequence[numArguments];
1692 for (int j = numArguments - 1; j >= 0; --j) {
1693 vars[j] = mapper.popValue();
1696 if (returnType[0] != 'V') {
1699 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1703 final String in = mi[0];
1706 in.equals("org/apidesign/html/boot/spi/Fn") ||
1707 in.equals("org/netbeans/html/boot/spi/Fn")
1709 mcn = "java_lang_Class";
1711 mcn = mangleClassName(in);
1713 String object = accessClass(mcn) + "(false)";
1714 if (mn.startsWith("cons_")) {
1715 object += ".constructor";
1717 append(accessStaticMethod(object, mn, mi));
1723 if (numArguments > 0) {
1725 for (int j = 1; j < numArguments; ++j) {
1735 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1736 throws IOException {
1737 int methodIndex = readUShortArg(byteCodes, i);
1738 String[] mi = jc.getFieldInfoName(methodIndex);
1739 char[] returnType = { 'V' };
1740 StringBuilder cnt = new StringBuilder();
1741 String mn = findMethodName(mi, cnt, returnType);
1743 final int numArguments = cnt.length() + 1;
1744 final CharSequence[] vars = new CharSequence[numArguments];
1746 for (int j = numArguments - 1; j >= 0; --j) {
1747 vars[j] = mapper.popValue();
1750 if (returnType[0] != 'V') {
1752 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1756 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1758 for (int j = 1; j < numArguments; ++j) {
1768 private void addReference(String cn) throws IOException {
1769 if (requireReference(cn)) {
1770 debug(" /* needs " + cn + " */");
1774 private void outType(String d, StringBuilder out) {
1776 while (d.charAt(0) == '[') {
1780 if (d.charAt(0) == 'L') {
1781 assert d.charAt(d.length() - 1) == ';';
1782 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1788 private String encodeConstant(int entryIndex) throws IOException {
1789 String[] classRef = { null };
1790 String s = jc.stringValue(entryIndex, classRef);
1791 if (classRef[0] != null) {
1792 if (classRef[0].startsWith("[")) {
1793 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1795 addReference(classRef[0]);
1796 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1802 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1803 byte[] arr = m.findAnnotationData(true);
1807 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1808 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1809 class P extends AnnotationParser {
1815 String[] args = new String[30];
1821 protected void visitAttr(String type, String attr, String at, String value) {
1822 if (type.equals(jvmType)) {
1823 if ("body".equals(attr)) {
1825 } else if ("args".equals(attr)) {
1826 args[cnt++] = value;
1828 throw new IllegalArgumentException(attr);
1831 if (type.equals(htmlType)) {
1833 if ("body".equals(attr)) {
1835 } else if ("args".equals(attr)) {
1836 args[cnt++] = value;
1837 } else if ("javacall".equals(attr)) {
1838 javacall = "1".equals(value);
1839 } else if ("wait4js".equals(attr)) {
1840 // ignore, we always invoke synchronously
1842 throw new IllegalArgumentException(attr);
1849 if (p.body == null) {
1852 StringBuilder cnt = new StringBuilder();
1853 final String mn = findMethodName(m, cnt);
1854 append("m = ").append(destObject).append(".").append(mn);
1855 append(" = function(");
1858 StringBuilder toValue = new StringBuilder();
1859 for (int i = 0; i < cnt.length(); i++) {
1861 space = outputArg(this, p.args, index);
1862 if (p.html4j && space.length() > 0) {
1863 toValue.append("\n ").append(p.args[index]).append(" = ")
1864 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1865 append(p.args[index]).append(");");
1869 append(") {").append("\n");
1870 append(toValue.toString());
1872 int lastSlash = jc.getClassName().lastIndexOf('/');
1873 final String pkg = jc.getClassName().substring(0, lastSlash);
1874 append(mangleCallbacks(pkg, p.body));
1875 requireReference(pkg + "/$JsCallbacks$");
1883 private static CharSequence mangleCallbacks(String pkgName, String body) {
1884 StringBuilder sb = new StringBuilder();
1887 int next = body.indexOf(".@", pos);
1889 sb.append(body.substring(pos));
1890 body = sb.toString();
1895 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1900 String refId = body.substring(ident, next);
1902 sb.append(body.substring(pos, ident));
1904 int sigBeg = body.indexOf('(', next);
1905 int sigEnd = body.indexOf(')', sigBeg);
1906 int colon4 = body.indexOf("::", next);
1907 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1908 throw new IllegalStateException("Malformed body " + body);
1910 String fqn = body.substring(next + 2, colon4);
1911 String method = body.substring(colon4 + 2, sigBeg);
1912 String params = body.substring(sigBeg, sigEnd + 1);
1914 int paramBeg = body.indexOf('(', sigEnd + 1);
1916 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1917 sb.append(mangleJsCallbacks(fqn, method, params, false));
1918 sb.append("(").append(refId);
1919 if (body.charAt(paramBeg + 1) != ')') {
1927 int next = body.indexOf("@", pos);
1932 sb.append(body.substring(pos));
1936 sb = new StringBuilder();
1939 sb.append(body.substring(pos, next));
1941 int sigBeg = body.indexOf('(', next);
1942 int sigEnd = body.indexOf(')', sigBeg);
1943 int colon4 = body.indexOf("::", next);
1944 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1945 throw new IllegalStateException("Malformed body " + body);
1947 String fqn = body.substring(next + 1, colon4);
1948 String method = body.substring(colon4 + 2, sigBeg);
1949 String params = body.substring(sigBeg, sigEnd + 1);
1951 int paramBeg = body.indexOf('(', sigEnd + 1);
1953 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1954 sb.append(mangleJsCallbacks(fqn, method, params, true));
1960 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1961 if (params.startsWith("(")) {
1962 params = params.substring(1);
1964 if (params.endsWith(")")) {
1965 params = params.substring(0, params.length() - 1);
1967 StringBuilder sb = new StringBuilder();
1968 final String fqnu = fqn.replace('.', '_');
1969 final String rfqn = mangleClassName(fqnu);
1970 final String rm = mangleMethodName(method);
1973 StringBuilder pb = new StringBuilder();
1974 int len = params.length();
1976 while (indx < len) {
1977 char ch = params.charAt(indx);
1978 if (ch == '[' || ch == 'L') {
1979 pb.append("Ljava/lang/Object;");
1980 indx = params.indexOf(';', indx) + 1;
1986 srp = mangleSig(pb.toString());
1988 final String rp = mangleSig(params);
1989 final String mrp = mangleMethodName(rp);
1990 sb.append(rfqn).append("$").append(rm).
1991 append('$').append(mrp).append("__Ljava_lang_Object_2");
1993 sb.append('L').append(fqnu).append("_2");
1996 return sb.toString();
1999 private static String className(ClassData jc) {
2000 //return jc.getName().getInternalName().replace('/', '_');
2001 return mangleClassName(jc.getClassName());
2004 private static String[] findAnnotation(
2005 byte[] arr, ClassData cd, final String className,
2006 final String... attrNames
2007 ) throws IOException {
2011 final String[] values = new String[attrNames.length];
2012 final boolean[] found = { false };
2013 final String jvmType = "L" + className.replace('.', '/') + ";";
2014 AnnotationParser ap = new AnnotationParser(false, true) {
2016 protected void visitAttr(String type, String attr, String at, String value) {
2017 if (type.equals(jvmType)) {
2019 for (int i = 0; i < attrNames.length; i++) {
2020 if (attrNames[i].equals(attr)) {
2029 return found[0] ? values : null;
2032 private CharSequence initField(FieldData v) {
2033 final String is = v.getInternalSig();
2034 if (is.length() == 1) {
2035 switch (is.charAt(0)) {
2041 case 'I': return " = 0;";
2043 case 'D': return " = 0.0;";
2045 throw new IllegalStateException(is);
2051 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2052 AnnotationParser ap = new AnnotationParser(true, false) {
2053 int[] cnt = new int[32];
2057 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2058 final String slashType = attrType.substring(1, attrType.length() - 1);
2059 requireReference(slashType);
2061 if (cnt[depth]++ > 0) {
2065 append('"').append(attrType).append("\" : ");
2072 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2078 protected void visitValueStart(String attrName, char type) throws IOException {
2079 if (cnt[depth]++ > 0) {
2083 if (attrName != null) {
2084 append('"').append(attrName).append("\" : ");
2092 protected void visitValueEnd(String attrName, char type) throws IOException {
2100 protected void visitAttr(String type, String attr, String attrType, String value)
2101 throws IOException {
2102 if (attr == null && value == null) {
2109 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2110 throws IOException {
2111 final String slashType = attrType.substring(1, attrType.length() - 1);
2112 requireReference(slashType);
2114 final String cn = mangleClassName(slashType);
2115 append(accessClass(cn))
2116 .append("(false)['valueOf__L").
2118 append("_2Ljava_lang_String_2']('").
2126 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2127 final String name = args[indx];
2131 if (name.contains(",")) {
2132 throw new IOException("Wrong parameter with ',': " + name);
2138 final void emitNoFlush(
2140 final String format, final CharSequence... params
2141 ) throws IOException {
2142 emitImpl(this, format, params);
2144 static final void emit(
2146 final Appendable out,
2147 final String format, final CharSequence... params
2148 ) throws IOException {
2150 emitImpl(out, format, params);
2152 static void emitImpl(final Appendable out,
2153 final String format,
2154 final CharSequence... params) throws IOException {
2155 final int length = format.length();
2158 int paramOffset = format.indexOf('@');
2159 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2160 final char paramChar = format.charAt(paramOffset + 1);
2161 if ((paramChar >= '1') && (paramChar <= '9')) {
2162 final int paramIndex = paramChar - '0' - 1;
2164 out.append(format, processed, paramOffset);
2165 out.append(params[paramIndex]);
2168 processed = paramOffset + 1;
2171 paramOffset = format.indexOf('@', paramOffset + 1);
2174 out.append(format, processed, length);
2177 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2178 append("} catch (e) {\n");
2180 for (TrapData e : traps) {
2184 if (e.catch_cpx != 0) { //not finally
2185 final String classInternalName = jc.getClassName(e.catch_cpx);
2186 addReference(classInternalName);
2187 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2188 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2189 append("var stA0 = e;");
2190 goTo(this, current, e.handler_pc, topMostLabel);
2193 finallyPC = e.handler_pc;
2196 if (finallyPC == -1) {
2199 append("var stA0 = e;");
2200 goTo(this, current, finallyPC, topMostLabel);
2205 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2208 out.append("{ gt = 0; continue X_" + to + "; }");
2210 out.append("{ gt = " + to + "; continue X_0; }");
2213 out.append("{ gt = " + to + "; break IF; }");
2217 private static void emitIf(
2219 Appendable out, String pattern,
2221 int current, int to, int canBack
2222 ) throws IOException {
2224 emitImpl(out, pattern, param);
2225 goTo(out, current, to, canBack);
2228 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2231 case 4: jvmType = "[Z"; break;
2232 case 5: jvmType = "[C"; break;
2233 case 6: jvmType = "[F"; break;
2234 case 7: jvmType = "[D"; break;
2235 case 8: jvmType = "[B"; break;
2236 case 9: jvmType = "[S"; break;
2237 case 10: jvmType = "[I"; break;
2238 case 11: jvmType = "[J"; break;
2239 default: throw new IllegalStateException("Array type: " + atype);
2242 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2243 smapper.popI(), smapper.pushA(), jvmType);
2246 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2247 String typeName = jc.getClassName(type);
2248 String ref = "null";
2249 if (typeName.startsWith("[")) {
2250 typeName = "'[" + typeName + "'";
2252 ref = "vm." + mangleClassName(typeName);
2253 typeName = "'[L" + typeName + ";'";
2256 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2257 smapper.popI(), smapper.pushA(), typeName, ref);
2260 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2261 String typeName = jc.getClassName(type);
2262 int dim = readUByte(byteCodes, ++i);
2263 StringBuilder dims = new StringBuilder();
2265 for (int d = 0; d < dim; d++) {
2267 dims.insert(1, ",");
2269 dims.insert(1, smapper.popI());
2273 if (typeName.charAt(dim) == 'L') {
2274 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2277 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2278 dims.toString(), smapper.pushA(), typeName, fn
2283 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2284 int table = i / 4 * 4 + 4;
2285 int dflt = i + readInt4(byteCodes, table);
2287 int low = readInt4(byteCodes, table);
2289 int high = readInt4(byteCodes, table);
2291 final CharSequence swVar = smapper.popValue();
2292 smapper.flush(this);
2293 append("switch (").append(swVar).append(") {\n");
2294 while (low <= high) {
2295 int offset = i + readInt4(byteCodes, table);
2297 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2300 append(" default: ");
2301 goTo(this, i, dflt, topMostLabel);
2307 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2308 int table = i / 4 * 4 + 4;
2309 int dflt = i + readInt4(byteCodes, table);
2311 int n = readInt4(byteCodes, table);
2313 final CharSequence swVar = smapper.popValue();
2314 smapper.flush(this);
2315 append("switch (").append(swVar).append(") {\n");
2317 int cnstnt = readInt4(byteCodes, table);
2319 int offset = i + readInt4(byteCodes, table);
2321 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2323 append(" default: ");
2324 goTo(this, i, dflt, topMostLabel);
2330 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2331 String type = jc.getClassName(indx);
2332 if (!type.startsWith("[")) {
2334 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2335 smapper.popA(), smapper.pushI(),
2336 type.replace('/', '_'));
2339 while (type.charAt(cnt) == '[') {
2342 if (type.charAt(cnt) == 'L') {
2343 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2345 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2346 smapper.popA(), smapper.pushI(),
2351 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2352 smapper.popA(), smapper.pushI(), type
2358 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2359 String type = jc.getClassName(indx);
2360 if (!type.startsWith("[")) {
2361 emitNoFlush(smapper,
2362 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2363 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2366 while (type.charAt(cnt) == '[') {
2369 if (type.charAt(cnt) == 'L') {
2370 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2371 emitNoFlush(smapper,
2372 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2373 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2376 emitNoFlush(smapper,
2377 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2378 smapper.getT(0, VarType.REFERENCE, false), type
2384 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2385 for (int j = prev; j <= i; j++) {
2387 final int cc = readUByte(byteCodes, j);
2388 append(Integer.toString(cc));
2392 @JavaScriptBody(args = "msg", body = "")
2393 private static void println(String msg) {
2394 System.err.println(msg);