Decreasing the number of lines of core bck2brwsr.js to be under 65636. Should help debugging on Nashorn as it has problems with lines numbers over 16-bit numbers.
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++) {
370 stackMapIterator.advanceTo(i);
371 boolean changeInCatch = trap.advanceTo(i);
372 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
373 if (previousTrap != null) {
374 generateCatch(previousTrap, i, topMostLabel);
378 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
383 if (openBraces > 64) {
384 for (int c = 0; c < 64; c++) {
391 lastStackFrame = stackMapIterator.getFrameIndex();
392 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
393 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
394 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
396 changeInCatch = true;
398 debug(" /* " + i + " */ ");
400 if (changeInCatch && trap.useTry()) {
402 previousTrap = trap.current();
404 final int c = readUByte(byteCodes, i);
407 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
410 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
413 smapper.assign(this, VarType.LONG, lmapper.getL(0));
416 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
419 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
422 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
425 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
428 smapper.assign(this, VarType.LONG, lmapper.getL(1));
431 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
434 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
437 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
440 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
443 smapper.assign(this, VarType.LONG, lmapper.getL(2));
446 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
449 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
452 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
455 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
458 smapper.assign(this, VarType.LONG, lmapper.getL(3));
461 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
464 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
468 final int indx = wide ? readUShort(byteCodes, i++)
469 : readUByte(byteCodes, i);
471 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
476 final int indx = wide ? readUShort(byteCodes, i++)
477 : readUByte(byteCodes, i);
479 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
484 final int indx = wide ? readUShort(byteCodes, i++)
485 : readUByte(byteCodes, i);
487 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
492 final int indx = wide ? readUShort(byteCodes, i++)
493 : readUByte(byteCodes, i);
495 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
500 final int indx = wide ? readUShort(byteCodes, i++)
501 : readUByte(byteCodes, i);
503 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
508 final int indx = wide ? readUShort(byteCodes, i++)
509 : readUByte(byteCodes, i);
511 emit(smapper, this, "var @1 = @2;",
512 lmapper.setI(indx), smapper.popI());
517 final int indx = wide ? readUShort(byteCodes, i++)
518 : readUByte(byteCodes, i);
520 emit(smapper, this, "var @1 = @2;",
521 lmapper.setL(indx), smapper.popL());
526 final int indx = wide ? readUShort(byteCodes, i++)
527 : readUByte(byteCodes, i);
529 emit(smapper, this, "var @1 = @2;",
530 lmapper.setF(indx), smapper.popF());
535 final int indx = wide ? readUShort(byteCodes, i++)
536 : readUByte(byteCodes, i);
538 emit(smapper, this, "var @1 = @2;",
539 lmapper.setD(indx), smapper.popD());
544 final int indx = wide ? readUShort(byteCodes, i++)
545 : readUByte(byteCodes, i);
547 emit(smapper, this, "var @1 = @2;",
548 lmapper.setA(indx), smapper.popA());
552 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
555 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
558 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
561 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
564 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
567 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
570 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
573 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
576 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
579 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
582 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
585 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
588 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
591 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
594 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
597 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
600 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
603 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
606 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
609 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
612 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
615 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
618 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
621 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
624 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
627 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
630 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
633 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
636 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
639 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
642 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
645 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
648 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
649 smapper.getI(1), smapper.popI());
652 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
653 smapper.getL(1), smapper.popL());
656 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
659 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
662 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
663 smapper.getI(1), smapper.popI());
666 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
667 smapper.getL(1), smapper.popL());
670 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
673 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
676 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
679 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
682 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
685 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
688 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
691 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
694 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
697 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
700 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
703 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
706 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
709 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
712 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
715 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
718 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
721 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
725 final int varIndx = wide ? readUShort(byteCodes, i++)
726 : readUByte(byteCodes, i);
728 final int incrBy = wide ? readShort(byteCodes, i++)
732 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
734 emit(smapper, this, "@1 += @2;",
735 lmapper.getI(varIndx),
736 Integer.toString(incrBy));
741 emit(smapper, this, "return;");
744 emit(smapper, this, "return @1;", smapper.popI());
747 emit(smapper, this, "return @1;", smapper.popL());
750 emit(smapper, this, "return @1;", smapper.popF());
753 emit(smapper, this, "return @1;", smapper.popD());
756 emit(smapper, this, "return @1;", smapper.popA());
759 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
762 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
765 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
768 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
772 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
775 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
778 smapper.replace(this, VarType.DOUBLE, "@1",
782 smapper.replace(this, VarType.FLOAT, "@1",
786 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
790 smapper.replace(this, VarType.LONG, "(@1).toLong()",
794 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
798 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
801 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
806 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
808 case opc_aconst_null:
809 smapper.assign(this, VarType.REFERENCE, "null");
812 smapper.assign(this, VarType.INTEGER, "-1");
815 smapper.assign(this, VarType.INTEGER, "0");
818 smapper.assign(this, VarType.DOUBLE, "0");
821 smapper.assign(this, VarType.LONG, "0");
824 smapper.assign(this, VarType.FLOAT, "0");
827 smapper.assign(this, VarType.INTEGER, "1");
830 smapper.assign(this, VarType.LONG, "1");
833 smapper.assign(this, VarType.FLOAT, "1");
836 smapper.assign(this, VarType.DOUBLE, "1");
839 smapper.assign(this, VarType.INTEGER, "2");
842 smapper.assign(this, VarType.FLOAT, "2");
845 smapper.assign(this, VarType.INTEGER, "3");
848 smapper.assign(this, VarType.INTEGER, "4");
851 smapper.assign(this, VarType.INTEGER, "5");
854 int indx = readUByte(byteCodes, ++i);
855 String v = encodeConstant(indx);
856 int type = VarType.fromConstantType(jc.getTag(indx));
857 smapper.assign(this, type, v);
862 int indx = readUShortArg(byteCodes, i);
864 String v = encodeConstant(indx);
865 int type = VarType.fromConstantType(jc.getTag(indx));
866 if (type == VarType.LONG) {
867 final Long lv = new Long(v);
868 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
869 final int hi = (int)(lv.longValue() >> 32);
871 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
873 smapper.assign(this, VarType.LONG,
874 "0x" + Integer.toHexString(hi) + ".next32(0x" +
875 Integer.toHexString(low) + ")"
879 smapper.assign(this, type, v);
884 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
888 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
892 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
895 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
896 "===", topMostLabel);
899 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
900 "!==", topMostLabel);
903 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
907 int indx = i + readShortArg(byteCodes, i);
908 emitIf(smapper, this, "if ((@1) == 0) ",
909 smapper.popI(), i, indx, topMostLabel);
914 int indx = i + readShortArg(byteCodes, i);
915 emitIf(smapper, this, "if ((@1) != 0) ",
916 smapper.popI(), i, indx, topMostLabel);
921 int indx = i + readShortArg(byteCodes, i);
922 emitIf(smapper, this, "if ((@1) < 0) ",
923 smapper.popI(), i, indx, topMostLabel);
928 int indx = i + readShortArg(byteCodes, i);
929 emitIf(smapper, this, "if ((@1) <= 0) ",
930 smapper.popI(), i, indx, topMostLabel);
935 int indx = i + readShortArg(byteCodes, i);
936 emitIf(smapper, this, "if ((@1) > 0) ",
937 smapper.popI(), i, indx, topMostLabel);
942 int indx = i + readShortArg(byteCodes, i);
943 emitIf(smapper, this, "if ((@1) >= 0) ",
944 smapper.popI(), i, indx, topMostLabel);
948 case opc_ifnonnull: {
949 int indx = i + readShortArg(byteCodes, i);
950 emitIf(smapper, this, "if ((@1) !== null) ",
951 smapper.popA(), i, indx, topMostLabel);
956 int indx = i + readShortArg(byteCodes, i);
957 emitIf(smapper, this, "if ((@1) === null) ",
958 smapper.popA(), i, indx, topMostLabel);
963 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
967 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
971 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
975 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
979 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
984 int indx = i + readShortArg(byteCodes, i);
985 goTo(this, i, indx, topMostLabel);
989 case opc_lookupswitch: {
990 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
993 case opc_tableswitch: {
994 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
997 case opc_invokeinterface: {
998 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1001 case opc_invokevirtual:
1002 i = invokeVirtualMethod(byteCodes, i, smapper);
1004 case opc_invokespecial:
1005 i = invokeStaticMethod(byteCodes, i, smapper, false);
1007 case opc_invokestatic:
1008 i = invokeStaticMethod(byteCodes, i, smapper, true);
1011 int indx = readUShortArg(byteCodes, i);
1012 String ci = jc.getClassName(indx);
1013 emit(smapper, this, "var @1 = new @2;",
1014 smapper.pushA(), accessClass(mangleClassName(ci)));
1020 int atype = readUByte(byteCodes, ++i);
1021 generateNewArray(atype, smapper);
1023 case opc_anewarray: {
1024 int type = readUShortArg(byteCodes, i);
1026 generateANewArray(type, smapper);
1029 case opc_multianewarray: {
1030 int type = readUShortArg(byteCodes, i);
1032 i = generateMultiANewArray(type, byteCodes, i, smapper);
1035 case opc_arraylength:
1036 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1039 emit(smapper, this, "Array.at(@3, @2, @1);",
1040 smapper.popL(), smapper.popI(), smapper.popA());
1043 emit(smapper, this, "Array.at(@3, @2, @1);",
1044 smapper.popF(), smapper.popI(), smapper.popA());
1047 emit(smapper, this, "Array.at(@3, @2, @1);",
1048 smapper.popD(), smapper.popI(), smapper.popA());
1051 emit(smapper, this, "Array.at(@3, @2, @1);",
1052 smapper.popA(), smapper.popI(), smapper.popA());
1058 emit(smapper, this, "Array.at(@3, @2, @1);",
1059 smapper.popI(), smapper.popI(), smapper.popA());
1062 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1063 smapper.popI(), smapper.getA(0));
1066 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1067 smapper.popI(), smapper.getA(0));
1070 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1071 smapper.popI(), smapper.getA(0));
1074 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1075 smapper.popI(), smapper.getA(0));
1081 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1082 smapper.popI(), smapper.getA(0));
1090 final Variable v = smapper.get(0);
1091 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1095 final Variable vi1 = smapper.get(0);
1097 if (vi1.isCategory2()) {
1098 emit(smapper, this, "var @1 = @2;",
1099 smapper.pushT(vi1.getType()), vi1);
1101 final Variable vi2 = smapper.get(1);
1102 emit(smapper, this, "var @1 = @2, @3 = @4;",
1103 smapper.pushT(vi2.getType()), vi2,
1104 smapper.pushT(vi1.getType()), vi1);
1109 final Variable vi1 = smapper.pop(this);
1110 final Variable vi2 = smapper.pop(this);
1111 final Variable vo3 = smapper.pushT(vi1.getType());
1112 final Variable vo2 = smapper.pushT(vi2.getType());
1113 final Variable vo1 = smapper.pushT(vi1.getType());
1115 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1116 vo1, vi1, vo2, vi2, vo3, vo1);
1120 final Variable vi1 = smapper.pop(this);
1121 final Variable vi2 = smapper.pop(this);
1123 if (vi1.isCategory2()) {
1124 final Variable vo3 = smapper.pushT(vi1.getType());
1125 final Variable vo2 = smapper.pushT(vi2.getType());
1126 final Variable vo1 = smapper.pushT(vi1.getType());
1128 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1129 vo1, vi1, vo2, vi2, vo3, vo1);
1131 final Variable vi3 = smapper.pop(this);
1132 final Variable vo5 = smapper.pushT(vi2.getType());
1133 final Variable vo4 = smapper.pushT(vi1.getType());
1134 final Variable vo3 = smapper.pushT(vi3.getType());
1135 final Variable vo2 = smapper.pushT(vi2.getType());
1136 final Variable vo1 = smapper.pushT(vi1.getType());
1138 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1139 vo1, vi1, vo2, vi2, vo3, vi3);
1140 emit(smapper, this, " @1 = @2, @3 = @4;",
1141 vo4, vo1, vo5, vo2);
1146 final Variable vi1 = smapper.pop(this);
1147 final Variable vi2 = smapper.pop(this);
1149 if (vi2.isCategory2()) {
1150 final Variable vo3 = smapper.pushT(vi1.getType());
1151 final Variable vo2 = smapper.pushT(vi2.getType());
1152 final Variable vo1 = smapper.pushT(vi1.getType());
1154 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1155 vo1, vi1, vo2, vi2, vo3, vo1);
1157 final Variable vi3 = smapper.pop(this);
1158 final Variable vo4 = smapper.pushT(vi1.getType());
1159 final Variable vo3 = smapper.pushT(vi3.getType());
1160 final Variable vo2 = smapper.pushT(vi2.getType());
1161 final Variable vo1 = smapper.pushT(vi1.getType());
1163 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1164 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1169 final Variable vi1 = smapper.pop(this);
1170 final Variable vi2 = smapper.pop(this);
1172 if (vi1.isCategory2()) {
1173 if (vi2.isCategory2()) {
1174 final Variable vo3 = smapper.pushT(vi1.getType());
1175 final Variable vo2 = smapper.pushT(vi2.getType());
1176 final Variable vo1 = smapper.pushT(vi1.getType());
1178 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1179 vo1, vi1, vo2, vi2, vo3, vo1);
1181 final Variable vi3 = smapper.pop(this);
1182 final Variable vo4 = smapper.pushT(vi1.getType());
1183 final Variable vo3 = smapper.pushT(vi3.getType());
1184 final Variable vo2 = smapper.pushT(vi2.getType());
1185 final Variable vo1 = smapper.pushT(vi1.getType());
1187 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1188 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1191 final Variable vi3 = smapper.pop(this);
1193 if (vi3.isCategory2()) {
1194 final Variable vo5 = smapper.pushT(vi2.getType());
1195 final Variable vo4 = smapper.pushT(vi1.getType());
1196 final Variable vo3 = smapper.pushT(vi3.getType());
1197 final Variable vo2 = smapper.pushT(vi2.getType());
1198 final Variable vo1 = smapper.pushT(vi1.getType());
1200 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1201 vo1, vi1, vo2, vi2, vo3, vi3);
1202 emit(smapper, this, " @1 = @2, @3 = @4;",
1203 vo4, vo1, vo5, vo2);
1205 final Variable vi4 = smapper.pop(this);
1206 final Variable vo6 = smapper.pushT(vi2.getType());
1207 final Variable vo5 = smapper.pushT(vi1.getType());
1208 final Variable vo4 = smapper.pushT(vi4.getType());
1209 final Variable vo3 = smapper.pushT(vi3.getType());
1210 final Variable vo2 = smapper.pushT(vi2.getType());
1211 final Variable vo1 = smapper.pushT(vi1.getType());
1213 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1214 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1215 emit(smapper, this, " @1 = @2, @3 = @4;",
1216 vo5, vo1, vo6, vo2);
1222 final Variable vi1 = smapper.get(0);
1223 final Variable vi2 = smapper.get(1);
1225 if (vi1.getType() == vi2.getType()) {
1226 final Variable tmp = smapper.pushT(vi1.getType());
1228 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1233 smapper.pushT(vi1.getType());
1234 smapper.pushT(vi2.getType());
1239 smapper.assign(this, VarType.INTEGER,
1240 "(" + Integer.toString(byteCodes[++i]) + ")");
1243 smapper.assign(this, VarType.INTEGER,
1244 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1248 case opc_getfield: {
1249 int indx = readUShortArg(byteCodes, i);
1250 String[] fi = jc.getFieldInfoName(indx);
1251 final int type = VarType.fromFieldType(fi[2].charAt(0));
1252 final String mangleClass = mangleClassName(fi[0]);
1253 final String mangleClassAccess = accessClass(mangleClass);
1254 smapper.replace(this, type, "@3(false)._@2.call(@1)",
1256 fi[1], mangleClassAccess
1261 case opc_putfield: {
1262 int indx = readUShortArg(byteCodes, i);
1263 String[] fi = jc.getFieldInfoName(indx);
1264 final int type = VarType.fromFieldType(fi[2].charAt(0));
1265 final String mangleClass = mangleClassName(fi[0]);
1266 final String mangleClassAccess = accessClass(mangleClass);
1267 emit(smapper, this, "@4(false)._@3.call(@2, @1);",
1269 smapper.popA(), fi[1],
1275 case opc_getstatic: {
1276 int indx = readUShortArg(byteCodes, i);
1277 String[] fi = jc.getFieldInfoName(indx);
1278 final int type = VarType.fromFieldType(fi[2].charAt(0));
1279 String ac = accessClass(mangleClassName(fi[0]));
1280 smapper.assign(this, type, ac + "(false)._" + fi[1] + "()");
1282 addReference(fi[0]);
1285 case opc_putstatic: {
1286 int indx = readUShortArg(byteCodes, i);
1287 String[] fi = jc.getFieldInfoName(indx);
1288 final int type = VarType.fromFieldType(fi[2].charAt(0));
1289 emit(smapper, this, "@1(false)._@2(@3);",
1290 accessClass(mangleClassName(fi[0])), fi[1],
1291 smapper.popT(type));
1293 addReference(fi[0]);
1296 case opc_checkcast: {
1297 int indx = readUShortArg(byteCodes, i);
1298 generateCheckcast(indx, smapper);
1302 case opc_instanceof: {
1303 int indx = readUShortArg(byteCodes, i);
1304 generateInstanceOf(indx, smapper);
1309 final CharSequence v = smapper.popA();
1312 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1313 smapper.pushA(), v);
1317 case opc_monitorenter: {
1318 debug("/* monitor enter */");
1323 case opc_monitorexit: {
1324 debug("/* monitor exit */");
1335 emit(smapper, this, "throw 'unknown bytecode @1';",
1336 Integer.toString(c));
1340 generateByteCodeComment(prev, i, byteCodes);
1346 if (previousTrap != null) {
1347 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1352 while (openBraces-- > 0) {
1358 private int generateIf(StackMapper mapper, byte[] byteCodes,
1359 int i, final CharSequence v2, final CharSequence v1,
1360 final String test, int topMostLabel
1361 ) throws IOException {
1363 int indx = i + readShortArg(byteCodes, i);
1364 append("if ((").append(v1)
1365 .append(") ").append(test).append(" (")
1366 .append(v2).append(")) ");
1367 goTo(this, i, indx, topMostLabel);
1371 private int readInt4(byte[] byteCodes, int offset) {
1372 final int d = byteCodes[offset + 0] << 24;
1373 final int c = byteCodes[offset + 1] << 16;
1374 final int b = byteCodes[offset + 2] << 8;
1375 final int a = byteCodes[offset + 3];
1376 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1378 private static int readUByte(byte[] byteCodes, int offset) {
1379 return byteCodes[offset] & 0xff;
1382 private static int readUShort(byte[] byteCodes, int offset) {
1383 return ((byteCodes[offset] & 0xff) << 8)
1384 | (byteCodes[offset + 1] & 0xff);
1386 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1387 return readUShort(byteCodes, offsetInstruction + 1);
1390 private static int readShort(byte[] byteCodes, int offset) {
1391 int signed = byteCodes[offset];
1392 byte b0 = (byte)signed;
1393 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1395 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1396 return readShort(byteCodes, offsetInstruction + 1);
1399 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1401 Boolean count = null;
1402 boolean array = false;
1404 int firstPos = sig.length();
1405 while (i < descriptor.length()) {
1406 char ch = descriptor.charAt(i++);
1427 if (ch == 'J' || ch == 'D') {
1433 sig.insert(firstPos, ch);
1435 returnType[0] = '[';
1436 sig.insert(firstPos, "_3");
1445 returnType[0] = 'V';
1446 sig.insert(firstPos, 'V');
1449 int next = descriptor.indexOf(';', i);
1450 String realSig = mangleSig(descriptor, i - 1, next + 1);
1455 sig.append(realSig);
1458 sig.insert(firstPos, realSig);
1460 sig.insert(firstPos, "_3");
1462 returnType[0] = 'L';
1471 throw new IllegalStateException("Invalid char: " + ch);
1476 static String mangleSig(String sig) {
1477 return mangleSig(sig, 0, sig.length());
1480 private static String mangleMethodName(String name) {
1481 StringBuilder sb = new StringBuilder(name.length() * 2);
1482 int last = name.length();
1483 for (int i = 0; i < last; i++) {
1484 final char ch = name.charAt(i);
1486 case '_': sb.append("_1"); break;
1487 default: sb.append(ch); break;
1490 return sb.toString();
1492 private static String mangleSig(String txt, int first, int last) {
1493 StringBuilder sb = new StringBuilder((last - first) * 2);
1494 for (int i = first; i < last; i++) {
1495 final char ch = txt.charAt(i);
1497 case '/': sb.append('_'); break;
1498 case '_': sb.append("_1"); break;
1499 case ';': sb.append("_2"); break;
1500 case '[': sb.append("_3"); break;
1501 default: sb.append(ch); break;
1504 return sb.toString();
1507 private static String mangleClassName(String name) {
1508 return mangleSig(name);
1511 private static String findMethodName(MethodData m, StringBuilder cnt) {
1512 StringBuilder name = new StringBuilder();
1513 if ("<init>".equals(m.getName())) { // NOI18N
1514 name.append("cons"); // NOI18N
1515 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1516 name.append("class"); // NOI18N
1518 name.append(mangleMethodName(m.getName()));
1521 countArgs(m.getInternalSig(), new char[1], name, cnt);
1522 return name.toString();
1525 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1526 StringBuilder name = new StringBuilder();
1527 String descr = mi[2];//mi.getDescriptor();
1529 if ("<init>".equals(nm)) { // NOI18N
1530 name.append("cons"); // NOI18N
1532 name.append(mangleMethodName(nm));
1534 countArgs(descr, returnType, name, cnt);
1535 return name.toString();
1538 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1539 throws IOException {
1540 int methodIndex = readUShortArg(byteCodes, i);
1541 String[] mi = jc.getFieldInfoName(methodIndex);
1542 char[] returnType = { 'V' };
1543 StringBuilder cnt = new StringBuilder();
1544 String mn = findMethodName(mi, cnt, returnType);
1546 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1547 final CharSequence[] vars = new CharSequence[numArguments];
1549 for (int j = numArguments - 1; j >= 0; --j) {
1550 vars[j] = mapper.popValue();
1553 if (returnType[0] != 'V') {
1555 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1559 final String in = mi[0];
1560 append(accessClass(mangleClassName(in)));
1562 if (mn.startsWith("cons_")) {
1563 append("constructor.");
1571 if (numArguments > 0) {
1573 for (int j = 1; j < numArguments; ++j) {
1583 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1584 throws IOException {
1585 int methodIndex = readUShortArg(byteCodes, i);
1586 String[] mi = jc.getFieldInfoName(methodIndex);
1587 char[] returnType = { 'V' };
1588 StringBuilder cnt = new StringBuilder();
1589 String mn = findMethodName(mi, cnt, returnType);
1591 final int numArguments = cnt.length() + 1;
1592 final CharSequence[] vars = new CharSequence[numArguments];
1594 for (int j = numArguments - 1; j >= 0; --j) {
1595 vars[j] = mapper.popValue();
1598 if (returnType[0] != 'V') {
1600 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1604 append(vars[0]).append('.');
1608 for (int j = 1; j < numArguments; ++j) {
1618 private void addReference(String cn) throws IOException {
1619 if (requireReference(cn)) {
1620 debug(" /* needs " + cn + " */");
1624 private void outType(String d, StringBuilder out) {
1626 while (d.charAt(0) == '[') {
1630 if (d.charAt(0) == 'L') {
1631 assert d.charAt(d.length() - 1) == ';';
1632 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1638 private String encodeConstant(int entryIndex) throws IOException {
1639 String[] classRef = { null };
1640 String s = jc.stringValue(entryIndex, classRef);
1641 if (classRef[0] != null) {
1642 if (classRef[0].startsWith("[")) {
1643 s = accessClass("java_lang_Class") + "(false).forName__Ljava_lang_Class_2Ljava_lang_String_2('" + classRef[0] + "')";
1645 addReference(classRef[0]);
1646 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1652 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1653 byte[] arr = m.findAnnotationData(true);
1657 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1658 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1659 class P extends AnnotationParser {
1665 String[] args = new String[30];
1671 protected void visitAttr(String type, String attr, String at, String value) {
1672 if (type.equals(jvmType)) {
1673 if ("body".equals(attr)) {
1675 } else if ("args".equals(attr)) {
1676 args[cnt++] = value;
1678 throw new IllegalArgumentException(attr);
1681 if (type.equals(htmlType)) {
1683 if ("body".equals(attr)) {
1685 } else if ("args".equals(attr)) {
1686 args[cnt++] = value;
1687 } else if ("javacall".equals(attr)) {
1688 javacall = "1".equals(value);
1690 throw new IllegalArgumentException(attr);
1697 if (p.body == null) {
1700 StringBuilder cnt = new StringBuilder();
1701 final String mn = findMethodName(m, cnt);
1702 append(destObject).append(".").append(mn);
1703 append(" = function(");
1706 StringBuilder toValue = new StringBuilder();
1707 for (int i = 0; i < cnt.length(); i++) {
1709 space = outputArg(this, p.args, index);
1710 if (p.html4j && space.length() > 0) {
1711 toValue.append("\n ").append(p.args[index]).append(" = vm.org_apidesign_bck2brwsr_emul_lang_System(false).toJS(").
1712 append(p.args[index]).append(");");
1716 append(") {").append("\n");
1717 append(toValue.toString());
1719 int lastSlash = jc.getClassName().lastIndexOf('/');
1720 final String pkg = jc.getClassName().substring(0, lastSlash);
1721 append(mangleCallbacks(pkg, p.body));
1722 requireReference(pkg + "/$JsCallbacks$");
1730 private static CharSequence mangleCallbacks(String pkgName, String body) {
1731 StringBuilder sb = new StringBuilder();
1734 int next = body.indexOf(".@", pos);
1736 sb.append(body.substring(pos));
1737 body = sb.toString();
1742 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1747 String refId = body.substring(ident, next);
1749 sb.append(body.substring(pos, ident));
1751 int sigBeg = body.indexOf('(', next);
1752 int sigEnd = body.indexOf(')', sigBeg);
1753 int colon4 = body.indexOf("::", next);
1754 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1755 throw new IllegalStateException("Malformed body " + body);
1757 String fqn = body.substring(next + 2, colon4);
1758 String method = body.substring(colon4 + 2, sigBeg);
1759 String params = body.substring(sigBeg, sigEnd + 1);
1761 int paramBeg = body.indexOf('(', sigEnd + 1);
1763 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1764 sb.append(mangleJsCallbacks(fqn, method, params, false));
1765 sb.append("(").append(refId);
1766 if (body.charAt(paramBeg + 1) != ')') {
1774 int next = body.indexOf("@", pos);
1779 sb.append(body.substring(pos));
1783 sb = new StringBuilder();
1786 sb.append(body.substring(pos, next));
1788 int sigBeg = body.indexOf('(', next);
1789 int sigEnd = body.indexOf(')', sigBeg);
1790 int colon4 = body.indexOf("::", next);
1791 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1792 throw new IllegalStateException("Malformed body " + body);
1794 String fqn = body.substring(next + 1, colon4);
1795 String method = body.substring(colon4 + 2, sigBeg);
1796 String params = body.substring(sigBeg, sigEnd + 1);
1798 int paramBeg = body.indexOf('(', sigEnd + 1);
1800 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1801 sb.append(mangleJsCallbacks(fqn, method, params, true));
1807 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1808 if (params.startsWith("(")) {
1809 params = params.substring(1);
1811 if (params.endsWith(")")) {
1812 params = params.substring(0, params.length() - 1);
1814 StringBuilder sb = new StringBuilder();
1815 final String fqnu = fqn.replace('.', '_');
1816 final String rfqn = mangleClassName(fqnu);
1817 final String rm = mangleMethodName(method);
1820 StringBuilder pb = new StringBuilder();
1821 int len = params.length();
1823 while (indx < len) {
1824 char ch = params.charAt(indx);
1825 if (ch == '[' || ch == 'L') {
1826 pb.append("Ljava/lang/Object;");
1827 indx = params.indexOf(';', indx) + 1;
1833 srp = mangleSig(pb.toString());
1835 final String rp = mangleSig(params);
1836 final String mrp = mangleMethodName(rp);
1837 sb.append(rfqn).append("$").append(rm).
1838 append('$').append(mrp).append("__Ljava_lang_Object_2");
1840 sb.append('L').append(fqnu).append("_2");
1843 return sb.toString();
1846 private static String className(ClassData jc) {
1847 //return jc.getName().getInternalName().replace('/', '_');
1848 return mangleClassName(jc.getClassName());
1851 private static String[] findAnnotation(
1852 byte[] arr, ClassData cd, final String className,
1853 final String... attrNames
1854 ) throws IOException {
1858 final String[] values = new String[attrNames.length];
1859 final boolean[] found = { false };
1860 final String jvmType = "L" + className.replace('.', '/') + ";";
1861 AnnotationParser ap = new AnnotationParser(false, true) {
1863 protected void visitAttr(String type, String attr, String at, String value) {
1864 if (type.equals(jvmType)) {
1866 for (int i = 0; i < attrNames.length; i++) {
1867 if (attrNames[i].equals(attr)) {
1876 return found[0] ? values : null;
1879 private CharSequence initField(FieldData v) {
1880 final String is = v.getInternalSig();
1881 if (is.length() == 1) {
1882 switch (is.charAt(0)) {
1888 case 'I': return " = 0;";
1890 case 'D': return " = 0.0;";
1892 throw new IllegalStateException(is);
1898 private void generateAnno(ClassData cd, byte[] data) throws IOException {
1899 AnnotationParser ap = new AnnotationParser(true, false) {
1900 int[] cnt = new int[32];
1904 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
1905 final String slashType = attrType.substring(1, attrType.length() - 1);
1906 requireReference(slashType);
1908 if (cnt[depth]++ > 0) {
1912 append('"').append(attrType).append("\" : ");
1919 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
1925 protected void visitValueStart(String attrName, char type) throws IOException {
1926 if (cnt[depth]++ > 0) {
1930 if (attrName != null) {
1931 append(attrName).append(" : ");
1939 protected void visitValueEnd(String attrName, char type) throws IOException {
1947 protected void visitAttr(String type, String attr, String attrType, String value)
1948 throws IOException {
1949 if (attr == null && value == null) {
1956 protected void visitEnumAttr(String type, String attr, String attrType, String value)
1957 throws IOException {
1958 final String slashType = attrType.substring(1, attrType.length() - 1);
1959 requireReference(slashType);
1961 append(accessClass(mangleClassName(slashType)))
1962 .append("(false).constructor.fld_").append(value);
1968 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1969 final String name = args[indx];
1973 if (name.contains(",")) {
1974 throw new IOException("Wrong parameter with ',': " + name);
1980 final void emitNoFlush(
1982 final String format, final CharSequence... params
1983 ) throws IOException {
1984 emitImpl(this, format, params);
1986 static final void emit(
1988 final Appendable out,
1989 final String format, final CharSequence... params
1990 ) throws IOException {
1992 emitImpl(out, format, params);
1994 static void emitImpl(final Appendable out,
1995 final String format,
1996 final CharSequence... params) throws IOException {
1997 final int length = format.length();
2000 int paramOffset = format.indexOf('@');
2001 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2002 final char paramChar = format.charAt(paramOffset + 1);
2003 if ((paramChar >= '1') && (paramChar <= '9')) {
2004 final int paramIndex = paramChar - '0' - 1;
2006 out.append(format, processed, paramOffset);
2007 out.append(params[paramIndex]);
2010 processed = paramOffset + 1;
2013 paramOffset = format.indexOf('@', paramOffset + 1);
2016 out.append(format, processed, length);
2019 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2020 append("} catch (e) {\n");
2022 for (TrapData e : traps) {
2026 if (e.catch_cpx != 0) { //not finally
2027 final String classInternalName = jc.getClassName(e.catch_cpx);
2028 addReference(classInternalName);
2029 append("e = vm.java_lang_Throwable(false).bck2BrwsrCnvrt(e);");
2030 append("if (e.$instOf_" + classInternalName.replace('/', '_') + ") {");
2031 append("var stA0 = e;");
2032 goTo(this, current, e.handler_pc, topMostLabel);
2035 finallyPC = e.handler_pc;
2038 if (finallyPC == -1) {
2041 append("var stA0 = e;");
2042 goTo(this, current, finallyPC, topMostLabel);
2047 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2050 out.append("{ gt = 0; continue X_" + to + "; }");
2052 out.append("{ gt = " + to + "; continue X_0; }");
2055 out.append("{ gt = " + to + "; break IF; }");
2059 private static void emitIf(
2061 Appendable out, String pattern,
2063 int current, int to, int canBack
2064 ) throws IOException {
2066 emitImpl(out, pattern, param);
2067 goTo(out, current, to, canBack);
2070 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2073 case 4: jvmType = "[Z"; break;
2074 case 5: jvmType = "[C"; break;
2075 case 6: jvmType = "[F"; break;
2076 case 7: jvmType = "[D"; break;
2077 case 8: jvmType = "[B"; break;
2078 case 9: jvmType = "[S"; break;
2079 case 10: jvmType = "[I"; break;
2080 case 11: jvmType = "[J"; break;
2081 default: throw new IllegalStateException("Array type: " + atype);
2083 emit(smapper, this, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(true, '@3', @1);",
2084 smapper.popI(), smapper.pushA(), jvmType);
2087 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2088 String typeName = jc.getClassName(type);
2089 if (typeName.startsWith("[")) {
2090 typeName = "[" + typeName;
2092 typeName = "[L" + typeName + ";";
2094 emit(smapper, this, "var @2 = Array.prototype.newArray__Ljava_lang_Object_2ZLjava_lang_String_2I(false, '@3', @1);",
2095 smapper.popI(), smapper.pushA(), typeName);
2098 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2099 String typeName = jc.getClassName(type);
2100 int dim = readUByte(byteCodes, ++i);
2101 StringBuilder dims = new StringBuilder();
2103 for (int d = 0; d < dim; d++) {
2105 dims.insert(1, ",");
2107 dims.insert(1, smapper.popI());
2110 emit(smapper, this, "var @2 = Array.prototype.multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II('@3', @1, 0);",
2111 dims.toString(), smapper.pushA(), typeName);
2115 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2116 int table = i / 4 * 4 + 4;
2117 int dflt = i + readInt4(byteCodes, table);
2119 int low = readInt4(byteCodes, table);
2121 int high = readInt4(byteCodes, table);
2123 final CharSequence swVar = smapper.popValue();
2124 smapper.flush(this);
2125 append("switch (").append(swVar).append(") {\n");
2126 while (low <= high) {
2127 int offset = i + readInt4(byteCodes, table);
2129 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2132 append(" default: ");
2133 goTo(this, i, dflt, topMostLabel);
2139 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2140 int table = i / 4 * 4 + 4;
2141 int dflt = i + readInt4(byteCodes, table);
2143 int n = readInt4(byteCodes, table);
2145 final CharSequence swVar = smapper.popValue();
2146 smapper.flush(this);
2147 append("switch (").append(swVar).append(") {\n");
2149 int cnstnt = readInt4(byteCodes, table);
2151 int offset = i + readInt4(byteCodes, table);
2153 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2155 append(" default: ");
2156 goTo(this, i, dflt, topMostLabel);
2162 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2163 final String type = jc.getClassName(indx);
2164 if (!type.startsWith("[")) {
2165 emit(smapper, this, "var @2 = @1 != null && @1.$instOf_@3 ? 1 : 0;",
2166 smapper.popA(), smapper.pushI(),
2167 type.replace('/', '_'));
2169 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);",
2170 smapper.popA(), smapper.pushI(),
2176 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2177 final String type = jc.getClassName(indx);
2178 if (!type.startsWith("[")) {
2179 emitNoFlush(smapper,
2180 "if (@1 !== null && !@1.$instOf_@2) throw vm.java_lang_ClassCastException(true);",
2181 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2183 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);",
2184 smapper.getT(0, VarType.REFERENCE, false), type
2189 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2190 for (int j = prev; j <= i; j++) {
2192 final int cc = readUByte(byteCodes, j);
2193 append(Integer.toString(cc));