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 static org.apidesign.vm4brwsr.ByteCodeParser.*;
24 /** Translator of the code inside class files to JavaScript.
26 * @author Jaroslav Tulach <jtulach@netbeans.org>
28 abstract class ByteCodeToJavaScript implements Appendable {
30 private final Appendable out;
31 private boolean outChanged;
32 final ObfuscationDelegate obfuscationDelegate;
34 protected ByteCodeToJavaScript(Appendable out) {
35 this(out, ObfuscationDelegate.NULL);
38 protected ByteCodeToJavaScript(
39 Appendable out, ObfuscationDelegate obfuscationDelegate) {
41 this.obfuscationDelegate = obfuscationDelegate;
45 public final Appendable append(CharSequence csq) throws IOException {
52 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
53 out.append(csq, start, end);
59 public final Appendable append(char c) throws IOException {
65 /* Collects additional required resources.
67 * @param internalClassName classes that were referenced and should be loaded in order the
68 * generated JavaScript code works properly. The names are in internal
69 * JVM form so String is <code>java/lang/String</code>.
71 protected abstract boolean requireReference(String internalClassName);
74 * @param resourcePath name of resources to read
76 protected abstract void requireScript(String resourcePath) throws IOException;
78 /** Allows subclasses to redefine what field a function representing a
79 * class gets assigned. By default it returns the suggested name followed
80 * by <code>" = "</code>;
82 * @param className suggested name of the class
84 /* protected */ String assignClass(String className) {
85 return className + " = ";
87 /* protected */ String accessClass(String classOperation) {
88 return classOperation;
91 abstract String getVMObject();
93 /** Prints out a debug message.
95 * @param msg the message
96 * @return true if the message has been printed
99 boolean debug(String msg) throws IOException {
105 * Converts a given class file to a JavaScript version.
107 * @param classFile input stream with code of the .class file
108 * @return the initialization code for this class, if any. Otherwise <code>null</code>
110 * @throws IOException if something goes wrong during read or write or translating
113 public String compile(InputStream classFile) throws IOException {
114 this.jc = new ClassData(classFile);
115 if (jc.getMajor_version() < 50) {
116 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
117 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
120 byte[] arrData = jc.findAnnotationData(true);
122 String[] arr = findAnnotation(arrData, jc,
123 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
124 "resource", "processByteCode"
127 if (!arr[0].isEmpty()) {
128 requireScript(arr[0]);
130 if ("0".equals(arr[1])) {
136 String[] arr = findAnnotation(arrData, jc,
137 "net.java.html.js.JavaScriptResource",
141 if (arr[0].startsWith("/")) {
142 requireScript(arr[0]);
144 int last = jc.getClassName().lastIndexOf('/');
146 jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0]
151 String[] proto = findAnnotation(arrData, jc,
152 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
153 "container", "prototype"
155 StringArray toInitilize = new StringArray();
156 final String className = className(jc);
157 append("\n\n").append(assignClass(className));
158 append("function ").append(className).append("() {");
159 append("\n var CLS = ").append(className).append(';');
160 append("\n if (!CLS.$class) {");
162 String sc = jc.getSuperClassName(); // with _
163 append("\n var pp = ").
164 append(accessClass(mangleClassName(sc))).append("(true);");
165 append("\n var p = CLS.prototype = pp;");
166 append("\n var c = p;");
167 append("\n var sprcls = pp.constructor.$class;");
169 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
170 if (proto[0] == null) {
173 append("\n var c = ").append(proto[0]).append(";");
174 append("\n var sprcls = null;");
176 for (FieldData v : jc.getFields()) {
178 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
179 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
183 append("\n CLS.fld_").append(v.getName()).append(initField(v));
184 append("\n c._").append(v.getName()).append(" = function (v) {")
185 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
186 .append(" = v; return CLS.fld_").
187 append(v.getName()).append("; };");
189 append("\n c._").append(v.getName()).append(" = function (v) {")
190 .append(" if (arguments.length == 1) this.fld_").
191 append(className).append('_').append(v.getName())
192 .append(" = v; return this.fld_").
193 append(className).append('_').append(v.getName())
197 obfuscationDelegate.exportField(this, "c", "_" + v.getName(), v);
199 for (MethodData m : jc.getMethods()) {
200 byte[] onlyArr = m.findAnnotationData(true);
201 String[] only = findAnnotation(onlyArr, jc,
202 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
206 if (only[0] != null && only[1] != null) {
207 append("\n p.").append(only[0]).append(" = ")
208 .append(only[1]).append(";");
217 mn = generateStaticMethod(destObject, m, toInitilize);
219 if (m.isConstructor()) {
221 mn = generateInstanceMethod(destObject, m);
224 mn = generateInstanceMethod(destObject, m);
227 obfuscationDelegate.exportMethod(this, destObject, mn, m);
228 byte[] runAnno = m.findAnnotationData(false);
229 if (runAnno != null) {
230 append("\n ").append(destObject).append(".").append(mn).append(".anno = {");
231 generateAnno(jc, runAnno);
234 append("\n ").append(destObject).append(".").append(mn).append(".access = " + m.getAccess()).append(";");
235 append("\n ").append(destObject).append(".").append(mn).append(".cls = CLS;");
237 append("\n c.constructor = CLS;");
238 append("\n function fillInstOf(x) {");
239 String instOfName = "$instOf_" + className;
240 append("\n x.").append(instOfName).append(" = true;");
241 for (String superInterface : jc.getSuperInterfaces()) {
242 String intrfc = superInterface.replace('/', '_');
243 append("\n vm.").append(intrfc).append("(false).fillInstOf(x);");
244 requireReference(superInterface);
247 append("\n c.fillInstOf = fillInstOf;");
248 append("\n fillInstOf(c);");
249 obfuscationDelegate.exportJSProperty(this, "c", instOfName);
250 append("\n CLS.$class = 'temp';");
251 append("\n CLS.$class = ");
252 append(accessClass("java_lang_Class(true);"));
253 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
254 append("\n CLS.$class.superclass = sprcls;");
255 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
256 append("\n CLS.$class.cnstr = CLS;");
257 byte[] classAnno = jc.findAnnotationData(false);
258 if (classAnno != null) {
259 append("\n CLS.$class.anno = {");
260 generateAnno(jc, classAnno);
263 for (String init : toInitilize.toArray()) {
264 append("\n ").append(init).append("();");
267 append("\n if (arguments.length === 0) {");
268 append("\n if (!(this instanceof CLS)) {");
269 append("\n return new CLS();");
271 for (FieldData v : jc.getFields()) {
272 byte[] onlyArr = v.findAnnotationData(true);
273 String[] only = findAnnotation(onlyArr, jc,
274 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
278 if (only[0] != null && only[1] != null) {
279 append("\n p.").append(only[0]).append(" = ")
280 .append(only[1]).append(";");
285 append("\n this.fld_").
286 append(className).append('_').
287 append(v.getName()).append(initField(v));
290 append("\n return this;");
292 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
295 obfuscationDelegate.exportClass(this, getVMObject(), className, jc);
297 // StringBuilder sb = new StringBuilder();
298 // for (String init : toInitilize.toArray()) {
299 // sb.append("\n").append(init).append("();");
303 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
304 String jsb = javaScriptBody(destObject, m, true);
308 final String mn = findMethodName(m, new StringBuilder());
309 if (mn.equals("class__V")) {
310 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
312 generateMethod(destObject, mn, m);
316 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
317 String jsb = javaScriptBody(destObject, m, false);
321 final String mn = findMethodName(m, new StringBuilder());
322 generateMethod(destObject, mn, m);
326 private void generateMethod(String destObject, String name, MethodData m)
328 final StackMapIterator stackMapIterator = m.createStackMapIterator();
329 TrapDataIterator trap = m.getTrapDataIterator();
330 final LocalsMapper lmapper =
331 new LocalsMapper(stackMapIterator.getArguments());
333 append(destObject).append(".").append(name).append(" = function(");
334 lmapper.outputArguments(this, m.isStatic());
335 append(") {").append("\n");
337 final byte[] byteCodes = m.getCode();
338 if (byteCodes == null) {
339 append(" throw 'no code found for ")
340 .append(jc.getClassName()).append('.')
341 .append(m.getName()).append("';\n");
346 final StackMapper smapper = new StackMapper();
349 append(" var ").append(" lcA0 = this;\n");
353 TrapData[] previousTrap = null;
354 boolean wide = false;
356 if (stackMapIterator.isEmpty()) {
362 append("\n var gt = 0;\n");
366 int topMostLabel = 0;
367 for (int i = 0; i < byteCodes.length; i++) {
369 stackMapIterator.advanceTo(i);
370 boolean changeInCatch = trap.advanceTo(i);
371 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
372 if (previousTrap != null) {
373 generateCatch(previousTrap, i, topMostLabel);
377 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
382 if (openBraces > 64) {
383 for (int c = 0; c < 64; c++) {
390 lastStackFrame = stackMapIterator.getFrameIndex();
391 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
392 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
393 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
395 changeInCatch = true;
397 debug(" /* " + i + " */ ");
399 if (changeInCatch && trap.useTry()) {
401 previousTrap = trap.current();
403 final int c = readUByte(byteCodes, i);
406 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
409 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
412 smapper.assign(this, VarType.LONG, lmapper.getL(0));
415 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
418 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
421 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
424 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
427 smapper.assign(this, VarType.LONG, lmapper.getL(1));
430 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
433 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
436 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
439 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
442 smapper.assign(this, VarType.LONG, lmapper.getL(2));
445 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
448 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
451 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
454 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
457 smapper.assign(this, VarType.LONG, lmapper.getL(3));
460 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
463 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
467 final int indx = wide ? readUShort(byteCodes, i++)
468 : readUByte(byteCodes, i);
470 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
475 final int indx = wide ? readUShort(byteCodes, i++)
476 : readUByte(byteCodes, i);
478 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
483 final int indx = wide ? readUShort(byteCodes, i++)
484 : readUByte(byteCodes, i);
486 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
491 final int indx = wide ? readUShort(byteCodes, i++)
492 : readUByte(byteCodes, i);
494 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
499 final int indx = wide ? readUShort(byteCodes, i++)
500 : readUByte(byteCodes, i);
502 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
507 final int indx = wide ? readUShort(byteCodes, i++)
508 : readUByte(byteCodes, i);
510 emit(smapper, this, "var @1 = @2;",
511 lmapper.setI(indx), smapper.popI());
516 final int indx = wide ? readUShort(byteCodes, i++)
517 : readUByte(byteCodes, i);
519 emit(smapper, this, "var @1 = @2;",
520 lmapper.setL(indx), smapper.popL());
525 final int indx = wide ? readUShort(byteCodes, i++)
526 : readUByte(byteCodes, i);
528 emit(smapper, this, "var @1 = @2;",
529 lmapper.setF(indx), smapper.popF());
534 final int indx = wide ? readUShort(byteCodes, i++)
535 : readUByte(byteCodes, i);
537 emit(smapper, this, "var @1 = @2;",
538 lmapper.setD(indx), smapper.popD());
543 final int indx = wide ? readUShort(byteCodes, i++)
544 : readUByte(byteCodes, i);
546 emit(smapper, this, "var @1 = @2;",
547 lmapper.setA(indx), smapper.popA());
551 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
554 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
557 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
560 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
563 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
566 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
569 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
572 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
575 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
578 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
581 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
584 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
587 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
590 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
593 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
596 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
599 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
602 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
605 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
608 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
611 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
614 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
617 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
620 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
623 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
626 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
629 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
632 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
635 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
638 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
641 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
644 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
647 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
648 smapper.getI(1), smapper.popI());
651 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
652 smapper.getL(1), smapper.popL());
655 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
658 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
661 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
662 smapper.getI(1), smapper.popI());
665 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
666 smapper.getL(1), smapper.popL());
669 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
672 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
675 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
678 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
681 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
684 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
687 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
690 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
693 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
696 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
699 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
702 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
705 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
708 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
711 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
714 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
717 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
720 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
724 final int varIndx = wide ? readUShort(byteCodes, i++)
725 : readUByte(byteCodes, i);
727 final int incrBy = wide ? readShort(byteCodes, i++)
731 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
733 emit(smapper, this, "@1 += @2;",
734 lmapper.getI(varIndx),
735 Integer.toString(incrBy));
740 emit(smapper, this, "return;");
743 emit(smapper, this, "return @1;", smapper.popI());
746 emit(smapper, this, "return @1;", smapper.popL());
749 emit(smapper, this, "return @1;", smapper.popF());
752 emit(smapper, this, "return @1;", smapper.popD());
755 emit(smapper, this, "return @1;", smapper.popA());
758 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
761 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
764 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
767 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
771 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
774 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
777 smapper.replace(this, VarType.DOUBLE, "@1",
781 smapper.replace(this, VarType.FLOAT, "@1",
785 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
789 smapper.replace(this, VarType.LONG, "(@1).toLong()",
793 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
797 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
800 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
805 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
807 case opc_aconst_null:
808 smapper.assign(this, VarType.REFERENCE, "null");
811 smapper.assign(this, VarType.INTEGER, "-1");
814 smapper.assign(this, VarType.INTEGER, "0");
817 smapper.assign(this, VarType.DOUBLE, "0");
820 smapper.assign(this, VarType.LONG, "0");
823 smapper.assign(this, VarType.FLOAT, "0");
826 smapper.assign(this, VarType.INTEGER, "1");
829 smapper.assign(this, VarType.LONG, "1");
832 smapper.assign(this, VarType.FLOAT, "1");
835 smapper.assign(this, VarType.DOUBLE, "1");
838 smapper.assign(this, VarType.INTEGER, "2");
841 smapper.assign(this, VarType.FLOAT, "2");
844 smapper.assign(this, VarType.INTEGER, "3");
847 smapper.assign(this, VarType.INTEGER, "4");
850 smapper.assign(this, VarType.INTEGER, "5");
853 int indx = readUByte(byteCodes, ++i);
854 String v = encodeConstant(indx);
855 int type = VarType.fromConstantType(jc.getTag(indx));
856 smapper.assign(this, type, v);
861 int indx = readUShortArg(byteCodes, i);
863 String v = encodeConstant(indx);
864 int type = VarType.fromConstantType(jc.getTag(indx));
865 if (type == VarType.LONG) {
866 final Long lv = new Long(v);
867 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
868 final int hi = (int)(lv.longValue() >> 32);
870 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
872 smapper.assign(this, VarType.LONG,
873 "0x" + Integer.toHexString(hi) + ".next32(0x" +
874 Integer.toHexString(low) + ")"
878 smapper.assign(this, type, v);
883 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
887 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
891 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
894 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
895 "===", topMostLabel);
898 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
899 "!==", topMostLabel);
902 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
906 int indx = i + readShortArg(byteCodes, i);
907 emitIf(smapper, this, "if ((@1) == 0) ",
908 smapper.popI(), i, indx, topMostLabel);
913 int indx = i + readShortArg(byteCodes, i);
914 emitIf(smapper, this, "if ((@1) != 0) ",
915 smapper.popI(), i, indx, topMostLabel);
920 int indx = i + readShortArg(byteCodes, i);
921 emitIf(smapper, this, "if ((@1) < 0) ",
922 smapper.popI(), i, indx, topMostLabel);
927 int indx = i + readShortArg(byteCodes, i);
928 emitIf(smapper, this, "if ((@1) <= 0) ",
929 smapper.popI(), i, indx, topMostLabel);
934 int indx = i + readShortArg(byteCodes, i);
935 emitIf(smapper, this, "if ((@1) > 0) ",
936 smapper.popI(), i, indx, topMostLabel);
941 int indx = i + readShortArg(byteCodes, i);
942 emitIf(smapper, this, "if ((@1) >= 0) ",
943 smapper.popI(), i, indx, topMostLabel);
947 case opc_ifnonnull: {
948 int indx = i + readShortArg(byteCodes, i);
949 emitIf(smapper, this, "if ((@1) !== null) ",
950 smapper.popA(), i, indx, topMostLabel);
955 int indx = i + readShortArg(byteCodes, i);
956 emitIf(smapper, this, "if ((@1) === null) ",
957 smapper.popA(), i, indx, topMostLabel);
962 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
966 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
970 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
974 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
978 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
983 int indx = i + readShortArg(byteCodes, i);
984 goTo(this, i, indx, topMostLabel);
988 case opc_lookupswitch: {
989 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
992 case opc_tableswitch: {
993 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
996 case opc_invokeinterface: {
997 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1000 case opc_invokevirtual:
1001 i = invokeVirtualMethod(byteCodes, i, smapper);
1003 case opc_invokespecial:
1004 i = invokeStaticMethod(byteCodes, i, smapper, false);
1006 case opc_invokestatic:
1007 i = invokeStaticMethod(byteCodes, i, smapper, true);
1010 int indx = readUShortArg(byteCodes, i);
1011 String ci = jc.getClassName(indx);
1012 emit(smapper, this, "var @1 = new @2;",
1013 smapper.pushA(), accessClass(mangleClassName(ci)));
1019 int atype = readUByte(byteCodes, ++i);
1020 generateNewArray(atype, smapper);
1022 case opc_anewarray: {
1023 int type = readUShortArg(byteCodes, i);
1025 generateANewArray(type, smapper);
1028 case opc_multianewarray: {
1029 int type = readUShortArg(byteCodes, i);
1031 i = generateMultiANewArray(type, byteCodes, i, smapper);
1034 case opc_arraylength:
1035 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1038 emit(smapper, this, "Array.at(@3, @2, @1);",
1039 smapper.popL(), smapper.popI(), smapper.popA());
1042 emit(smapper, this, "Array.at(@3, @2, @1);",
1043 smapper.popF(), smapper.popI(), smapper.popA());
1046 emit(smapper, this, "Array.at(@3, @2, @1);",
1047 smapper.popD(), smapper.popI(), smapper.popA());
1050 emit(smapper, this, "Array.at(@3, @2, @1);",
1051 smapper.popA(), smapper.popI(), smapper.popA());
1057 emit(smapper, this, "Array.at(@3, @2, @1);",
1058 smapper.popI(), smapper.popI(), smapper.popA());
1061 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1062 smapper.popI(), smapper.getA(0));
1065 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1066 smapper.popI(), smapper.getA(0));
1069 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1070 smapper.popI(), smapper.getA(0));
1073 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1074 smapper.popI(), smapper.getA(0));
1080 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1081 smapper.popI(), smapper.getA(0));
1089 final Variable v = smapper.get(0);
1090 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1094 final Variable vi1 = smapper.get(0);
1096 if (vi1.isCategory2()) {
1097 emit(smapper, this, "var @1 = @2;",
1098 smapper.pushT(vi1.getType()), vi1);
1100 final Variable vi2 = smapper.get(1);
1101 emit(smapper, this, "var @1 = @2, @3 = @4;",
1102 smapper.pushT(vi2.getType()), vi2,
1103 smapper.pushT(vi1.getType()), vi1);
1108 final Variable vi1 = smapper.pop(this);
1109 final Variable vi2 = smapper.pop(this);
1110 final Variable vo3 = smapper.pushT(vi1.getType());
1111 final Variable vo2 = smapper.pushT(vi2.getType());
1112 final Variable vo1 = smapper.pushT(vi1.getType());
1114 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1115 vo1, vi1, vo2, vi2, vo3, vo1);
1119 final Variable vi1 = smapper.pop(this);
1120 final Variable vi2 = smapper.pop(this);
1122 if (vi1.isCategory2()) {
1123 final Variable vo3 = smapper.pushT(vi1.getType());
1124 final Variable vo2 = smapper.pushT(vi2.getType());
1125 final Variable vo1 = smapper.pushT(vi1.getType());
1127 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1128 vo1, vi1, vo2, vi2, vo3, vo1);
1130 final Variable vi3 = smapper.pop(this);
1131 final Variable vo5 = smapper.pushT(vi2.getType());
1132 final Variable vo4 = smapper.pushT(vi1.getType());
1133 final Variable vo3 = smapper.pushT(vi3.getType());
1134 final Variable vo2 = smapper.pushT(vi2.getType());
1135 final Variable vo1 = smapper.pushT(vi1.getType());
1137 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1138 vo1, vi1, vo2, vi2, vo3, vi3);
1139 emit(smapper, this, " @1 = @2, @3 = @4;",
1140 vo4, vo1, vo5, vo2);
1145 final Variable vi1 = smapper.pop(this);
1146 final Variable vi2 = smapper.pop(this);
1148 if (vi2.isCategory2()) {
1149 final Variable vo3 = smapper.pushT(vi1.getType());
1150 final Variable vo2 = smapper.pushT(vi2.getType());
1151 final Variable vo1 = smapper.pushT(vi1.getType());
1153 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1154 vo1, vi1, vo2, vi2, vo3, vo1);
1156 final Variable vi3 = smapper.pop(this);
1157 final Variable vo4 = smapper.pushT(vi1.getType());
1158 final Variable vo3 = smapper.pushT(vi3.getType());
1159 final Variable vo2 = smapper.pushT(vi2.getType());
1160 final Variable vo1 = smapper.pushT(vi1.getType());
1162 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1163 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1168 final Variable vi1 = smapper.pop(this);
1169 final Variable vi2 = smapper.pop(this);
1171 if (vi1.isCategory2()) {
1172 if (vi2.isCategory2()) {
1173 final Variable vo3 = smapper.pushT(vi1.getType());
1174 final Variable vo2 = smapper.pushT(vi2.getType());
1175 final Variable vo1 = smapper.pushT(vi1.getType());
1177 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1178 vo1, vi1, vo2, vi2, vo3, vo1);
1180 final Variable vi3 = smapper.pop(this);
1181 final Variable vo4 = smapper.pushT(vi1.getType());
1182 final Variable vo3 = smapper.pushT(vi3.getType());
1183 final Variable vo2 = smapper.pushT(vi2.getType());
1184 final Variable vo1 = smapper.pushT(vi1.getType());
1186 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1187 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1190 final Variable vi3 = smapper.pop(this);
1192 if (vi3.isCategory2()) {
1193 final Variable vo5 = smapper.pushT(vi2.getType());
1194 final Variable vo4 = smapper.pushT(vi1.getType());
1195 final Variable vo3 = smapper.pushT(vi3.getType());
1196 final Variable vo2 = smapper.pushT(vi2.getType());
1197 final Variable vo1 = smapper.pushT(vi1.getType());
1199 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1200 vo1, vi1, vo2, vi2, vo3, vi3);
1201 emit(smapper, this, " @1 = @2, @3 = @4;",
1202 vo4, vo1, vo5, vo2);
1204 final Variable vi4 = smapper.pop(this);
1205 final Variable vo6 = smapper.pushT(vi2.getType());
1206 final Variable vo5 = smapper.pushT(vi1.getType());
1207 final Variable vo4 = smapper.pushT(vi4.getType());
1208 final Variable vo3 = smapper.pushT(vi3.getType());
1209 final Variable vo2 = smapper.pushT(vi2.getType());
1210 final Variable vo1 = smapper.pushT(vi1.getType());
1212 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1213 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1214 emit(smapper, this, " @1 = @2, @3 = @4;",
1215 vo5, vo1, vo6, vo2);
1221 final Variable vi1 = smapper.get(0);
1222 final Variable vi2 = smapper.get(1);
1224 if (vi1.getType() == vi2.getType()) {
1225 final Variable tmp = smapper.pushT(vi1.getType());
1227 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1232 smapper.pushT(vi1.getType());
1233 smapper.pushT(vi2.getType());
1238 smapper.assign(this, VarType.INTEGER,
1239 "(" + Integer.toString(byteCodes[++i]) + ")");
1242 smapper.assign(this, VarType.INTEGER,
1243 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1247 case opc_getfield: {
1248 int indx = readUShortArg(byteCodes, i);
1249 String[] fi = jc.getFieldInfoName(indx);
1250 final int type = VarType.fromFieldType(fi[2].charAt(0));
1251 final String mangleClass = mangleClassName(fi[0]);
1252 final String mangleClassAccess = accessClass(mangleClass);
1253 smapper.replace(this, type, "@3(false)._@2.call(@1)",
1255 fi[1], mangleClassAccess
1260 case opc_putfield: {
1261 int indx = readUShortArg(byteCodes, i);
1262 String[] fi = jc.getFieldInfoName(indx);
1263 final int type = VarType.fromFieldType(fi[2].charAt(0));
1264 final String mangleClass = mangleClassName(fi[0]);
1265 final String mangleClassAccess = accessClass(mangleClass);
1266 emit(smapper, this, "@4(false)._@3.call(@2, @1);",
1268 smapper.popA(), fi[1],
1274 case opc_getstatic: {
1275 int indx = readUShortArg(byteCodes, i);
1276 String[] fi = jc.getFieldInfoName(indx);
1277 final int type = VarType.fromFieldType(fi[2].charAt(0));
1278 String ac = accessClass(mangleClassName(fi[0]));
1279 smapper.assign(this, type, ac + "(false)._" + fi[1] + "()");
1281 addReference(fi[0]);
1284 case opc_putstatic: {
1285 int indx = readUShortArg(byteCodes, i);
1286 String[] fi = jc.getFieldInfoName(indx);
1287 final int type = VarType.fromFieldType(fi[2].charAt(0));
1288 emit(smapper, this, "@1(false)._@2(@3);",
1289 accessClass(mangleClassName(fi[0])), fi[1],
1290 smapper.popT(type));
1292 addReference(fi[0]);
1295 case opc_checkcast: {
1296 int indx = readUShortArg(byteCodes, i);
1297 generateCheckcast(indx, smapper);
1301 case opc_instanceof: {
1302 int indx = readUShortArg(byteCodes, i);
1303 generateInstanceOf(indx, smapper);
1308 final CharSequence v = smapper.popA();
1311 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1312 smapper.pushA(), v);
1316 case opc_monitorenter: {
1317 debug("/* monitor enter */");
1322 case opc_monitorexit: {
1323 debug("/* monitor exit */");
1334 emit(smapper, this, "throw 'unknown bytecode @1';",
1335 Integer.toString(c));
1339 generateByteCodeComment(prev, i, byteCodes);
1343 if (previousTrap != null) {
1344 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1349 while (openBraces-- > 0) {
1355 private int generateIf(StackMapper mapper, byte[] byteCodes,
1356 int i, final CharSequence v2, final CharSequence v1,
1357 final String test, int topMostLabel
1358 ) throws IOException {
1360 int indx = i + readShortArg(byteCodes, i);
1361 append("if ((").append(v1)
1362 .append(") ").append(test).append(" (")
1363 .append(v2).append(")) ");
1364 goTo(this, i, indx, topMostLabel);
1368 private int readInt4(byte[] byteCodes, int offset) {
1369 final int d = byteCodes[offset + 0] << 24;
1370 final int c = byteCodes[offset + 1] << 16;
1371 final int b = byteCodes[offset + 2] << 8;
1372 final int a = byteCodes[offset + 3];
1373 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1375 private static int readUByte(byte[] byteCodes, int offset) {
1376 return byteCodes[offset] & 0xff;
1379 private static int readUShort(byte[] byteCodes, int offset) {
1380 return ((byteCodes[offset] & 0xff) << 8)
1381 | (byteCodes[offset + 1] & 0xff);
1383 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1384 return readUShort(byteCodes, offsetInstruction + 1);
1387 private static int readShort(byte[] byteCodes, int offset) {
1388 int signed = byteCodes[offset];
1389 byte b0 = (byte)signed;
1390 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1392 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1393 return readShort(byteCodes, offsetInstruction + 1);
1396 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1398 Boolean count = null;
1399 boolean array = false;
1401 int firstPos = sig.length();
1402 while (i < descriptor.length()) {
1403 char ch = descriptor.charAt(i++);
1424 if (ch == 'J' || ch == 'D') {
1430 sig.insert(firstPos, ch);
1432 returnType[0] = '[';
1433 sig.insert(firstPos, "_3");
1442 returnType[0] = 'V';
1443 sig.insert(firstPos, 'V');
1446 int next = descriptor.indexOf(';', i);
1447 String realSig = mangleSig(descriptor, i - 1, next + 1);
1452 sig.append(realSig);
1455 sig.insert(firstPos, realSig);
1457 sig.insert(firstPos, "_3");
1459 returnType[0] = 'L';
1468 throw new IllegalStateException("Invalid char: " + ch);
1473 static String mangleSig(String sig) {
1474 return mangleSig(sig, 0, sig.length());
1477 private static String mangleMethodName(String name) {
1478 StringBuilder sb = new StringBuilder(name.length() * 2);
1479 int last = name.length();
1480 for (int i = 0; i < last; i++) {
1481 final char ch = name.charAt(i);
1483 case '_': sb.append("_1"); break;
1484 default: sb.append(ch); break;
1487 return sb.toString();
1489 private static String mangleSig(String txt, int first, int last) {
1490 StringBuilder sb = new StringBuilder((last - first) * 2);
1491 for (int i = first; i < last; i++) {
1492 final char ch = txt.charAt(i);
1494 case '/': sb.append('_'); break;
1495 case '_': sb.append("_1"); break;
1496 case ';': sb.append("_2"); break;
1497 case '[': sb.append("_3"); break;
1498 default: sb.append(ch); break;
1501 return sb.toString();
1504 private static String mangleClassName(String name) {
1505 return mangleSig(name);
1508 private static String findMethodName(MethodData m, StringBuilder cnt) {
1509 StringBuilder name = new StringBuilder();
1510 if ("<init>".equals(m.getName())) { // NOI18N
1511 name.append("cons"); // NOI18N
1512 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1513 name.append("class"); // NOI18N
1515 name.append(mangleMethodName(m.getName()));
1518 countArgs(m.getInternalSig(), new char[1], name, cnt);
1519 return name.toString();
1522 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1523 StringBuilder name = new StringBuilder();
1524 String descr = mi[2];//mi.getDescriptor();
1526 if ("<init>".equals(nm)) { // NOI18N
1527 name.append("cons"); // NOI18N
1529 name.append(mangleMethodName(nm));
1531 countArgs(descr, returnType, name, cnt);
1532 return name.toString();
1535 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1536 throws IOException {
1537 int methodIndex = readUShortArg(byteCodes, i);
1538 String[] mi = jc.getFieldInfoName(methodIndex);
1539 char[] returnType = { 'V' };
1540 StringBuilder cnt = new StringBuilder();
1541 String mn = findMethodName(mi, cnt, returnType);
1543 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1544 final CharSequence[] vars = new CharSequence[numArguments];
1546 for (int j = numArguments - 1; j >= 0; --j) {
1547 vars[j] = mapper.popValue();
1550 if (returnType[0] != 'V') {
1552 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1556 final String in = mi[0];
1557 append(accessClass(mangleClassName(in)));
1559 if (mn.startsWith("cons_")) {
1560 append("constructor.");
1568 if (numArguments > 0) {
1570 for (int j = 1; j < numArguments; ++j) {
1580 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1581 throws IOException {
1582 int methodIndex = readUShortArg(byteCodes, i);
1583 String[] mi = jc.getFieldInfoName(methodIndex);
1584 char[] returnType = { 'V' };
1585 StringBuilder cnt = new StringBuilder();
1586 String mn = findMethodName(mi, cnt, returnType);
1588 final int numArguments = cnt.length() + 1;
1589 final CharSequence[] vars = new CharSequence[numArguments];
1591 for (int j = numArguments - 1; j >= 0; --j) {
1592 vars[j] = mapper.popValue();
1595 if (returnType[0] != 'V') {
1597 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1601 append(vars[0]).append('.');
1605 for (int j = 1; j < numArguments; ++j) {
1615 private void addReference(String cn) throws IOException {
1616 if (requireReference(cn)) {
1617 debug(" /* needs " + cn + " */");
1621 private void outType(String d, StringBuilder out) {
1623 while (d.charAt(0) == '[') {
1627 if (d.charAt(0) == 'L') {
1628 assert d.charAt(d.length() - 1) == ';';
1629 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1635 private String encodeConstant(int entryIndex) throws IOException {
1636 String[] classRef = { null };
1637 String s = jc.stringValue(entryIndex, classRef);
1638 if (classRef[0] != null) {
1639 if (classRef[0].startsWith("[")) {
1640 s = accessClass("java_lang_Class") + "(false).forName__Ljava_lang_Class_2Ljava_lang_String_2('" + classRef[0] + "')";
1642 addReference(classRef[0]);
1643 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1649 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1650 byte[] arr = m.findAnnotationData(true);
1654 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1655 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1656 class P extends AnnotationParser {
1662 String[] args = new String[30];
1668 protected void visitAttr(String type, String attr, String at, String value) {
1669 if (type.equals(jvmType)) {
1670 if ("body".equals(attr)) {
1672 } else if ("args".equals(attr)) {
1673 args[cnt++] = value;
1675 throw new IllegalArgumentException(attr);
1678 if (type.equals(htmlType)) {
1680 if ("body".equals(attr)) {
1682 } else if ("args".equals(attr)) {
1683 args[cnt++] = value;
1684 } else if ("javacall".equals(attr)) {
1685 javacall = "1".equals(value);
1687 throw new IllegalArgumentException(attr);
1694 if (p.body == null) {
1697 StringBuilder cnt = new StringBuilder();
1698 final String mn = findMethodName(m, cnt);
1699 append(destObject).append(".").append(mn);
1700 append(" = function(");
1703 StringBuilder toValue = new StringBuilder();
1704 for (int i = 0; i < cnt.length(); i++) {
1706 space = outputArg(this, p.args, index);
1707 if (p.html4j && space.length() > 0) {
1708 toValue.append("\n ").append(p.args[index]).append(" = vm.org_apidesign_bck2brwsr_emul_lang_System(false).toJS(").
1709 append(p.args[index]).append(");");
1713 append(") {").append("\n");
1714 append(toValue.toString());
1716 int lastSlash = jc.getClassName().lastIndexOf('/');
1717 final String pkg = jc.getClassName().substring(0, lastSlash);
1718 append(mangleCallbacks(pkg, p.body));
1719 requireReference(pkg + "/$JsCallbacks$");
1727 private static CharSequence mangleCallbacks(String pkgName, String body) {
1728 StringBuilder sb = new StringBuilder();
1731 int next = body.indexOf(".@", pos);
1733 sb.append(body.substring(pos));
1734 body = sb.toString();
1739 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1744 String refId = body.substring(ident, next);
1746 sb.append(body.substring(pos, ident));
1748 int sigBeg = body.indexOf('(', next);
1749 int sigEnd = body.indexOf(')', sigBeg);
1750 int colon4 = body.indexOf("::", next);
1751 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1752 throw new IllegalStateException("Malformed body " + body);
1754 String fqn = body.substring(next + 2, colon4);
1755 String method = body.substring(colon4 + 2, sigBeg);
1756 String params = body.substring(sigBeg, sigEnd + 1);
1758 int paramBeg = body.indexOf('(', sigEnd + 1);
1760 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1761 sb.append(mangleJsCallbacks(fqn, method, params, false));
1762 sb.append("(").append(refId);
1763 if (body.charAt(paramBeg + 1) != ')') {
1771 int next = body.indexOf("@", pos);
1776 sb.append(body.substring(pos));
1780 sb = new StringBuilder();
1783 sb.append(body.substring(pos, next));
1785 int sigBeg = body.indexOf('(', next);
1786 int sigEnd = body.indexOf(')', sigBeg);
1787 int colon4 = body.indexOf("::", next);
1788 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1789 throw new IllegalStateException("Malformed body " + body);
1791 String fqn = body.substring(next + 1, colon4);
1792 String method = body.substring(colon4 + 2, sigBeg);
1793 String params = body.substring(sigBeg, sigEnd + 1);
1795 int paramBeg = body.indexOf('(', sigEnd + 1);
1797 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1798 sb.append(mangleJsCallbacks(fqn, method, params, true));
1804 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1805 if (params.startsWith("(")) {
1806 params = params.substring(1);
1808 if (params.endsWith(")")) {
1809 params = params.substring(0, params.length() - 1);
1811 StringBuilder sb = new StringBuilder();
1812 final String fqnu = fqn.replace('.', '_');
1813 final String rfqn = mangleClassName(fqnu);
1814 final String rm = mangleMethodName(method);
1817 StringBuilder pb = new StringBuilder();
1818 int len = params.length();
1820 while (indx < len) {
1821 char ch = params.charAt(indx);
1822 if (ch == '[' || ch == 'L') {
1823 pb.append("Ljava/lang/Object;");
1824 indx = params.indexOf(';', indx) + 1;
1830 srp = mangleSig(pb.toString());
1832 final String rp = mangleSig(params);
1833 final String mrp = mangleMethodName(rp);
1834 sb.append(rfqn).append("$").append(rm).
1835 append('$').append(mrp).append("__Ljava_lang_Object_2");
1837 sb.append('L').append(fqnu).append("_2");
1840 return sb.toString();
1843 private static String className(ClassData jc) {
1844 //return jc.getName().getInternalName().replace('/', '_');
1845 return mangleClassName(jc.getClassName());
1848 private static String[] findAnnotation(
1849 byte[] arr, ClassData cd, final String className,
1850 final String... attrNames
1851 ) throws IOException {
1855 final String[] values = new String[attrNames.length];
1856 final boolean[] found = { false };
1857 final String jvmType = "L" + className.replace('.', '/') + ";";
1858 AnnotationParser ap = new AnnotationParser(false, true) {
1860 protected void visitAttr(String type, String attr, String at, String value) {
1861 if (type.equals(jvmType)) {
1863 for (int i = 0; i < attrNames.length; i++) {
1864 if (attrNames[i].equals(attr)) {
1873 return found[0] ? values : null;
1876 private CharSequence initField(FieldData v) {
1877 final String is = v.getInternalSig();
1878 if (is.length() == 1) {
1879 switch (is.charAt(0)) {
1885 case 'I': return " = 0;";
1887 case 'D': return " = 0.0;";
1889 throw new IllegalStateException(is);
1895 private void generateAnno(ClassData cd, byte[] data) throws IOException {
1896 AnnotationParser ap = new AnnotationParser(true, false) {
1897 int[] cnt = new int[32];
1901 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
1902 final String slashType = attrType.substring(1, attrType.length() - 1);
1903 requireReference(slashType);
1905 if (cnt[depth]++ > 0) {
1909 append('"').append(attrType).append("\" : ");
1916 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
1922 protected void visitValueStart(String attrName, char type) throws IOException {
1923 if (cnt[depth]++ > 0) {
1927 if (attrName != null) {
1928 append(attrName).append(" : ");
1936 protected void visitValueEnd(String attrName, char type) throws IOException {
1944 protected void visitAttr(String type, String attr, String attrType, String value)
1945 throws IOException {
1946 if (attr == null && value == null) {
1953 protected void visitEnumAttr(String type, String attr, String attrType, String value)
1954 throws IOException {
1955 final String slashType = attrType.substring(1, attrType.length() - 1);
1956 requireReference(slashType);
1958 append(accessClass(mangleClassName(slashType)))
1959 .append("(false).constructor.fld_").append(value);
1965 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1966 final String name = args[indx];
1970 if (name.contains(",")) {
1971 throw new IOException("Wrong parameter with ',': " + name);
1977 final void emitNoFlush(
1979 final String format, final CharSequence... params
1980 ) throws IOException {
1981 emitImpl(this, format, params);
1983 static final void emit(
1985 final Appendable out,
1986 final String format, final CharSequence... params
1987 ) throws IOException {
1989 emitImpl(out, format, params);
1991 static void emitImpl(final Appendable out,
1992 final String format,
1993 final CharSequence... params) throws IOException {
1994 final int length = format.length();
1997 int paramOffset = format.indexOf('@');
1998 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
1999 final char paramChar = format.charAt(paramOffset + 1);
2000 if ((paramChar >= '1') && (paramChar <= '9')) {
2001 final int paramIndex = paramChar - '0' - 1;
2003 out.append(format, processed, paramOffset);
2004 out.append(params[paramIndex]);
2007 processed = paramOffset + 1;
2010 paramOffset = format.indexOf('@', paramOffset + 1);
2013 out.append(format, processed, length);
2016 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2017 append("} catch (e) {\n");
2019 for (TrapData e : traps) {
2023 if (e.catch_cpx != 0) { //not finally
2024 final String classInternalName = jc.getClassName(e.catch_cpx);
2025 addReference(classInternalName);
2026 append("e = vm.java_lang_Throwable(false).bck2BrwsrCnvrt(e);");
2027 append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
2028 append("var stA0 = e;");
2029 goTo(this, current, e.handler_pc, topMostLabel);
2032 finallyPC = e.handler_pc;
2035 if (finallyPC == -1) {
2038 append("var stA0 = e;");
2039 goTo(this, current, finallyPC, topMostLabel);
2044 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2047 out.append("{ gt = 0; continue X_" + to + "; }");
2049 out.append("{ gt = " + to + "; continue X_0; }");
2052 out.append("{ gt = " + to + "; break IF; }");
2056 private static void emitIf(
2058 Appendable out, String pattern,
2060 int current, int to, int canBack
2061 ) throws IOException {
2063 emitImpl(out, pattern, param);
2064 goTo(out, current, to, canBack);
2067 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2070 case 4: jvmType = "[Z"; break;
2071 case 5: jvmType = "[C"; break;
2072 case 6: jvmType = "[F"; break;
2073 case 7: jvmType = "[D"; break;
2074 case 8: jvmType = "[B"; break;
2075 case 9: jvmType = "[S"; break;
2076 case 10: jvmType = "[I"; break;
2077 case 11: jvmType = "[J"; break;
2078 default: throw new IllegalStateException("Array type: " + atype);
2080 emit(smapper, this, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(true, '@3', @1);",
2081 smapper.popI(), smapper.pushA(), jvmType);
2084 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2085 String typeName = jc.getClassName(type);
2086 if (typeName.startsWith("[")) {
2087 typeName = "[" + typeName;
2089 typeName = "[L" + typeName + ";";
2091 emit(smapper, this, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(false, '@3', @1);",
2092 smapper.popI(), smapper.pushA(), typeName);
2095 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2096 String typeName = jc.getClassName(type);
2097 int dim = readUByte(byteCodes, ++i);
2098 StringBuilder dims = new StringBuilder();
2100 for (int d = 0; d < dim; d++) {
2102 dims.insert(1, ",");
2104 dims.insert(1, smapper.popI());
2107 emit(smapper, this, "var @2 = Array.prototype.multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II('@3', @1, 0);",
2108 dims.toString(), smapper.pushA(), typeName);
2112 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2113 int table = i / 4 * 4 + 4;
2114 int dflt = i + readInt4(byteCodes, table);
2116 int low = readInt4(byteCodes, table);
2118 int high = readInt4(byteCodes, table);
2120 final CharSequence swVar = smapper.popValue();
2121 smapper.flush(this);
2122 append("switch (").append(swVar).append(") {\n");
2123 while (low <= high) {
2124 int offset = i + readInt4(byteCodes, table);
2126 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2129 append(" default: ");
2130 goTo(this, i, dflt, topMostLabel);
2136 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2137 int table = i / 4 * 4 + 4;
2138 int dflt = i + readInt4(byteCodes, table);
2140 int n = readInt4(byteCodes, table);
2142 final CharSequence swVar = smapper.popValue();
2143 smapper.flush(this);
2144 append("switch (").append(swVar).append(") {\n");
2146 int cnstnt = readInt4(byteCodes, table);
2148 int offset = i + readInt4(byteCodes, table);
2150 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2152 append(" default: ");
2153 goTo(this, i, dflt, topMostLabel);
2159 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2160 final String type = jc.getClassName(indx);
2161 if (!type.startsWith("[")) {
2162 emit(smapper, this, "var @2 = @1 != null && @1.$instOf_@3 ? 1 : 0;",
2163 smapper.popA(), smapper.pushI(),
2164 type.replace('/', '_'));
2166 emit(smapper, this, "var @2 = vm.java_lang_Class(false).forName__Ljava_lang_Class_2Ljava_lang_String_2('@3').isInstance__ZLjava_lang_Object_2(@1);",
2167 smapper.popA(), smapper.pushI(),
2173 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2174 final String type = jc.getClassName(indx);
2175 if (!type.startsWith("[")) {
2176 emitNoFlush(smapper,
2177 "if (@1 !== null && !@1.$instOf_@2) throw vm.java_lang_ClassCastException(true);",
2178 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2180 emitNoFlush(smapper, "vm.java_lang_Class(false).forName__Ljava_lang_Class_2Ljava_lang_String_2('@2').cast__Ljava_lang_Object_2Ljava_lang_Object_2(@1);",
2181 smapper.getT(0, VarType.REFERENCE, false), type
2186 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2187 for (int j = prev; j <= i; j++) {
2189 final int cc = readUByte(byteCodes, j);
2190 append(Integer.toString(cc));