Merging from default branch and resolving conflicts. mvn install -DskipTests passes OK.
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;
33 protected ByteCodeToJavaScript(Appendable out) {
38 public final Appendable append(CharSequence csq) throws IOException {
45 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
46 out.append(csq, start, end);
52 public final Appendable append(char c) throws IOException {
58 /* Collects additional required resources.
60 * @param internalClassName classes that were referenced and should be loaded in order the
61 * generated JavaScript code works properly. The names are in internal
62 * JVM form so String is <code>java/lang/String</code>.
64 protected abstract boolean requireReference(String internalClassName);
67 * @param resourcePath name of resources to read
69 protected abstract void requireScript(String resourcePath) throws IOException;
71 /** Allows subclasses to redefine what field a function representing a
72 * class gets assigned. By default it returns the suggested name followed
73 * by <code>" = "</code>;
75 * @param className suggested name of the class
77 /* protected */ String assignClass(String className) {
78 return className + " = ";
80 /* protected */ String accessClass(String classOperation) {
81 return classOperation;
84 protected String accessField(String object, String mangledName,
85 String[] fieldInfoName) throws IOException {
86 return object + "." + mangledName;
89 protected String accessStaticMethod(
92 String[] fieldInfoName) throws IOException {
93 return object + "." + mangledName;
96 protected String accessVirtualMethod(
99 String[] fieldInfoName) throws IOException {
100 return object + "." + mangledName;
103 protected void declaredClass(ClassData classData, String mangledName)
107 protected void declaredField(FieldData fieldData,
109 String mangledName) throws IOException {
112 protected void declaredMethod(MethodData methodData,
114 String mangledName) throws IOException {
117 /** Prints out a debug message.
119 * @param msg the message
120 * @return true if the message has been printed
121 * @throws IOException
123 boolean debug(String msg) throws IOException {
129 * Converts a given class file to a JavaScript version.
131 * @param classFile input stream with code of the .class file
132 * @return the initialization code for this class, if any. Otherwise <code>null</code>
134 * @throws IOException if something goes wrong during read or write or translating
137 public String compile(InputStream classFile) throws IOException {
138 return compile(new ClassData(classFile));
141 protected String compile(ClassData classData) throws IOException {
143 if (jc.getMajor_version() < 50) {
144 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
145 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
148 byte[] arrData = jc.findAnnotationData(true);
150 String[] arr = findAnnotation(arrData, jc,
151 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
152 "resource", "processByteCode"
155 if (!arr[0].isEmpty()) {
156 requireScript(arr[0]);
158 if ("0".equals(arr[1])) {
164 String[] arr = findAnnotation(arrData, jc,
165 "net.java.html.js.JavaScriptResource",
169 if (arr[0].startsWith("/")) {
170 requireScript(arr[0]);
172 int last = jc.getClassName().lastIndexOf('/');
174 jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0]
179 String[] proto = findAnnotation(arrData, jc,
180 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
181 "container", "prototype"
183 StringArray toInitilize = new StringArray();
184 final String className = className(jc);
185 append("\n\n").append(assignClass(className));
186 append("function ").append(className).append("() {");
187 append("\n var CLS = ").append(className).append(';');
188 append("\n if (!CLS.$class) {");
190 String sc = jc.getSuperClassName(); // with _
191 append("\n var pp = ").
192 append(accessClass(mangleClassName(sc))).append("(true);");
193 append("\n var p = CLS.prototype = pp;");
194 append("\n var c = p;");
195 append("\n var sprcls = pp.constructor.$class;");
197 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
198 if (proto[0] == null) {
201 append("\n var c = ").append(proto[0]).append(";");
202 append("\n var sprcls = null;");
204 for (FieldData v : jc.getFields()) {
206 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
207 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
211 append("\n CLS.fld_").append(v.getName()).append(initField(v));
212 append("\n c._").append(v.getName()).append(" = function (v) {")
213 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
214 .append(" = v; return CLS.fld_").
215 append(v.getName()).append("; };");
217 append("\n c._").append(v.getName()).append(" = function (v) {")
218 .append(" if (arguments.length == 1) this.fld_").
219 append(className).append('_').append(v.getName())
220 .append(" = v; return this.fld_").
221 append(className).append('_').append(v.getName())
225 declaredField(v, "c", "_" + v.getName());
227 for (MethodData m : jc.getMethods()) {
228 byte[] onlyArr = m.findAnnotationData(true);
229 String[] only = findAnnotation(onlyArr, jc,
230 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
234 if (only[0] != null && only[1] != null) {
235 append("\n p.").append(only[0]).append(" = ")
236 .append(only[1]).append(";");
245 mn = generateStaticMethod(destObject, m, toInitilize);
247 if (m.isConstructor()) {
249 mn = generateInstanceMethod(destObject, m);
252 mn = generateInstanceMethod(destObject, m);
255 declaredMethod(m, destObject, mn);
256 byte[] runAnno = m.findAnnotationData(false);
257 if (runAnno != null) {
258 append("\n ").append(destObject).append(".").append(mn).append(".anno = {");
259 generateAnno(jc, runAnno);
262 append("\n ").append(destObject).append(".").append(mn).append(".access = " + m.getAccess()).append(";");
263 append("\n ").append(destObject).append(".").append(mn).append(".cls = CLS;");
265 append("\n c.constructor = CLS;");
266 append("\n function fillInstOf(x) {");
267 String instOfName = "$instOf_" + className;
268 append("\n x['").append(instOfName).append("'] = true;");
269 for (String superInterface : jc.getSuperInterfaces()) {
270 String intrfc = superInterface.replace('/', '_');
271 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
272 requireReference(superInterface);
275 append("\n c['fillInstOf'] = fillInstOf;");
276 append("\n fillInstOf(c);");
277 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
278 append("\n CLS.$class = 'temp';");
279 append("\n CLS.$class = ");
280 append(accessClass("java_lang_Class(true);"));
281 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
282 append("\n CLS.$class.superclass = sprcls;");
283 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
284 append("\n CLS.$class.cnstr = CLS;");
285 byte[] classAnno = jc.findAnnotationData(false);
286 if (classAnno != null) {
287 append("\n CLS.$class.anno = {");
288 generateAnno(jc, classAnno);
291 for (String init : toInitilize.toArray()) {
292 append("\n ").append(init).append("();");
295 append("\n if (arguments.length === 0) {");
296 append("\n if (!(this instanceof CLS)) {");
297 append("\n return new CLS();");
299 for (FieldData v : jc.getFields()) {
300 byte[] onlyArr = v.findAnnotationData(true);
301 String[] only = findAnnotation(onlyArr, jc,
302 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
306 if (only[0] != null && only[1] != null) {
307 append("\n p.").append(only[0]).append(" = ")
308 .append(only[1]).append(";");
313 append("\n this.fld_").
314 append(className).append('_').
315 append(v.getName()).append(initField(v));
318 append("\n return this;");
320 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
323 declaredClass(jc, className);
325 // StringBuilder sb = new StringBuilder();
326 // for (String init : toInitilize.toArray()) {
327 // sb.append("\n").append(init).append("();");
331 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
332 String jsb = javaScriptBody(destObject, m, true);
336 final String mn = findMethodName(m, new StringBuilder());
337 if (mn.equals("class__V")) {
338 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
340 generateMethod(destObject, mn, m);
344 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
345 String jsb = javaScriptBody(destObject, m, false);
349 final String mn = findMethodName(m, new StringBuilder());
350 generateMethod(destObject, mn, m);
354 private void generateMethod(String destObject, String name, MethodData m)
356 final StackMapIterator stackMapIterator = m.createStackMapIterator();
357 TrapDataIterator trap = m.getTrapDataIterator();
358 final LocalsMapper lmapper =
359 new LocalsMapper(stackMapIterator.getArguments());
361 append(destObject).append(".").append(name).append(" = function(");
362 lmapper.outputArguments(this, m.isStatic());
363 append(") {").append("\n");
365 final byte[] byteCodes = m.getCode();
366 if (byteCodes == null) {
367 append(" throw 'no code found for ")
368 .append(jc.getClassName()).append('.')
369 .append(m.getName()).append("';\n");
374 final StackMapper smapper = new StackMapper();
377 append(" var ").append(" lcA0 = this;\n");
381 TrapData[] previousTrap = null;
382 boolean wide = false;
384 if (stackMapIterator.isEmpty()) {
390 append("\n var gt = 0;\n");
394 int topMostLabel = 0;
395 for (int i = 0; i < byteCodes.length; i++) {
398 stackMapIterator.advanceTo(i);
399 boolean changeInCatch = trap.advanceTo(i);
400 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
401 if (previousTrap != null) {
402 generateCatch(previousTrap, i, topMostLabel);
406 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
411 if (openBraces > 64) {
412 for (int c = 0; c < 64; c++) {
419 lastStackFrame = stackMapIterator.getFrameIndex();
420 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
421 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
422 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
424 changeInCatch = true;
426 debug(" /* " + i + " */ ");
428 if (changeInCatch && trap.useTry()) {
430 previousTrap = trap.current();
432 final int c = readUByte(byteCodes, i);
435 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
438 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
441 smapper.assign(this, VarType.LONG, lmapper.getL(0));
444 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
447 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
450 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
453 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
456 smapper.assign(this, VarType.LONG, lmapper.getL(1));
459 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
462 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
465 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
468 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
471 smapper.assign(this, VarType.LONG, lmapper.getL(2));
474 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
477 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
480 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
483 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
486 smapper.assign(this, VarType.LONG, lmapper.getL(3));
489 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
492 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
496 final int indx = wide ? readUShort(byteCodes, i++)
497 : readUByte(byteCodes, i);
499 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
504 final int indx = wide ? readUShort(byteCodes, i++)
505 : readUByte(byteCodes, i);
507 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
512 final int indx = wide ? readUShort(byteCodes, i++)
513 : readUByte(byteCodes, i);
515 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
520 final int indx = wide ? readUShort(byteCodes, i++)
521 : readUByte(byteCodes, i);
523 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
528 final int indx = wide ? readUShort(byteCodes, i++)
529 : readUByte(byteCodes, i);
531 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
536 final int indx = wide ? readUShort(byteCodes, i++)
537 : readUByte(byteCodes, i);
539 emit(smapper, this, "var @1 = @2;",
540 lmapper.setI(indx), smapper.popI());
545 final int indx = wide ? readUShort(byteCodes, i++)
546 : readUByte(byteCodes, i);
548 emit(smapper, this, "var @1 = @2;",
549 lmapper.setL(indx), smapper.popL());
554 final int indx = wide ? readUShort(byteCodes, i++)
555 : readUByte(byteCodes, i);
557 emit(smapper, this, "var @1 = @2;",
558 lmapper.setF(indx), smapper.popF());
563 final int indx = wide ? readUShort(byteCodes, i++)
564 : readUByte(byteCodes, i);
566 emit(smapper, this, "var @1 = @2;",
567 lmapper.setD(indx), smapper.popD());
572 final int indx = wide ? readUShort(byteCodes, i++)
573 : readUByte(byteCodes, i);
575 emit(smapper, this, "var @1 = @2;",
576 lmapper.setA(indx), smapper.popA());
580 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
583 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
586 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
589 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
592 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
595 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
598 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
601 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
604 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
607 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
610 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
613 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
616 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
619 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
622 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
625 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
628 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
631 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
634 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
637 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
640 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
643 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
646 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
649 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
652 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
655 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
658 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
661 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
664 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
667 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", 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).div32(@2)",
677 smapper.getI(1), smapper.popI());
680 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
681 smapper.getL(1), smapper.popL());
684 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
687 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
690 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
691 smapper.getI(1), smapper.popI());
694 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
695 smapper.getL(1), smapper.popL());
698 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
701 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
704 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
707 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
710 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
713 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
716 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
719 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
722 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
725 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
728 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
731 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
734 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
737 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
740 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
743 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
746 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
749 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
753 final int varIndx = wide ? readUShort(byteCodes, i++)
754 : readUByte(byteCodes, i);
756 final int incrBy = wide ? readShort(byteCodes, i++)
760 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
762 emit(smapper, this, "@1 += @2;",
763 lmapper.getI(varIndx),
764 Integer.toString(incrBy));
769 emit(smapper, this, "return;");
772 emit(smapper, this, "return @1;", smapper.popI());
775 emit(smapper, this, "return @1;", smapper.popL());
778 emit(smapper, this, "return @1;", smapper.popF());
781 emit(smapper, this, "return @1;", smapper.popD());
784 emit(smapper, this, "return @1;", smapper.popA());
787 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
790 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
793 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
796 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
800 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
803 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
806 smapper.replace(this, VarType.DOUBLE, "@1",
810 smapper.replace(this, VarType.FLOAT, "@1",
814 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
818 smapper.replace(this, VarType.LONG, "(@1).toLong()",
822 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
826 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
829 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
834 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
836 case opc_aconst_null:
837 smapper.assign(this, VarType.REFERENCE, "null");
840 smapper.assign(this, VarType.INTEGER, "-1");
843 smapper.assign(this, VarType.INTEGER, "0");
846 smapper.assign(this, VarType.DOUBLE, "0");
849 smapper.assign(this, VarType.LONG, "0");
852 smapper.assign(this, VarType.FLOAT, "0");
855 smapper.assign(this, VarType.INTEGER, "1");
858 smapper.assign(this, VarType.LONG, "1");
861 smapper.assign(this, VarType.FLOAT, "1");
864 smapper.assign(this, VarType.DOUBLE, "1");
867 smapper.assign(this, VarType.INTEGER, "2");
870 smapper.assign(this, VarType.FLOAT, "2");
873 smapper.assign(this, VarType.INTEGER, "3");
876 smapper.assign(this, VarType.INTEGER, "4");
879 smapper.assign(this, VarType.INTEGER, "5");
882 int indx = readUByte(byteCodes, ++i);
883 String v = encodeConstant(indx);
884 int type = VarType.fromConstantType(jc.getTag(indx));
885 smapper.assign(this, type, v);
890 int indx = readUShortArg(byteCodes, i);
892 String v = encodeConstant(indx);
893 int type = VarType.fromConstantType(jc.getTag(indx));
894 if (type == VarType.LONG) {
895 final Long lv = new Long(v);
896 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
897 final int hi = (int)(lv.longValue() >> 32);
899 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
901 smapper.assign(this, VarType.LONG,
902 "0x" + Integer.toHexString(hi) + ".next32(0x" +
903 Integer.toHexString(low) + ")"
907 smapper.assign(this, type, v);
912 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
916 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
920 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
923 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
924 "===", topMostLabel);
927 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
928 "!==", topMostLabel);
931 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
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);
949 int indx = i + readShortArg(byteCodes, i);
950 emitIf(smapper, this, "if ((@1) < 0) ",
951 smapper.popI(), i, indx, topMostLabel);
956 int indx = i + readShortArg(byteCodes, i);
957 emitIf(smapper, this, "if ((@1) <= 0) ",
958 smapper.popI(), i, indx, topMostLabel);
963 int indx = i + readShortArg(byteCodes, i);
964 emitIf(smapper, this, "if ((@1) > 0) ",
965 smapper.popI(), i, indx, topMostLabel);
970 int indx = i + readShortArg(byteCodes, i);
971 emitIf(smapper, this, "if ((@1) >= 0) ",
972 smapper.popI(), i, indx, topMostLabel);
976 case opc_ifnonnull: {
977 int indx = i + readShortArg(byteCodes, i);
978 emitIf(smapper, this, "if ((@1) !== null) ",
979 smapper.popA(), i, indx, topMostLabel);
984 int indx = i + readShortArg(byteCodes, i);
985 emitIf(smapper, this, "if ((@1) === null) ",
986 smapper.popA(), i, indx, topMostLabel);
991 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
995 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
999 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1000 "<=", topMostLabel);
1003 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1007 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1008 ">=", topMostLabel);
1011 smapper.flush(this);
1012 int indx = i + readShortArg(byteCodes, i);
1013 goTo(this, i, indx, topMostLabel);
1017 case opc_lookupswitch: {
1018 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1021 case opc_tableswitch: {
1022 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1025 case opc_invokeinterface: {
1026 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1029 case opc_invokevirtual:
1030 i = invokeVirtualMethod(byteCodes, i, smapper);
1032 case opc_invokespecial:
1033 i = invokeStaticMethod(byteCodes, i, smapper, false);
1035 case opc_invokestatic:
1036 i = invokeStaticMethod(byteCodes, i, smapper, true);
1039 int indx = readUShortArg(byteCodes, i);
1040 String ci = jc.getClassName(indx);
1041 emit(smapper, this, "var @1 = new @2;",
1042 smapper.pushA(), accessClass(mangleClassName(ci)));
1048 int atype = readUByte(byteCodes, ++i);
1049 generateNewArray(atype, smapper);
1051 case opc_anewarray: {
1052 int type = readUShortArg(byteCodes, i);
1054 generateANewArray(type, smapper);
1057 case opc_multianewarray: {
1058 int type = readUShortArg(byteCodes, i);
1060 i = generateMultiANewArray(type, byteCodes, i, smapper);
1063 case opc_arraylength:
1064 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1067 emit(smapper, this, "Array.at(@3, @2, @1);",
1068 smapper.popL(), smapper.popI(), smapper.popA());
1071 emit(smapper, this, "Array.at(@3, @2, @1);",
1072 smapper.popF(), smapper.popI(), smapper.popA());
1075 emit(smapper, this, "Array.at(@3, @2, @1);",
1076 smapper.popD(), smapper.popI(), smapper.popA());
1079 emit(smapper, this, "Array.at(@3, @2, @1);",
1080 smapper.popA(), smapper.popI(), smapper.popA());
1086 emit(smapper, this, "Array.at(@3, @2, @1);",
1087 smapper.popI(), smapper.popI(), smapper.popA());
1090 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1091 smapper.popI(), smapper.getA(0));
1094 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1095 smapper.popI(), smapper.getA(0));
1098 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1099 smapper.popI(), smapper.getA(0));
1102 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1103 smapper.popI(), smapper.getA(0));
1109 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1110 smapper.popI(), smapper.getA(0));
1118 final Variable v = smapper.get(0);
1119 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1123 final Variable vi1 = smapper.get(0);
1125 if (vi1.isCategory2()) {
1126 emit(smapper, this, "var @1 = @2;",
1127 smapper.pushT(vi1.getType()), vi1);
1129 final Variable vi2 = smapper.get(1);
1130 emit(smapper, this, "var @1 = @2, @3 = @4;",
1131 smapper.pushT(vi2.getType()), vi2,
1132 smapper.pushT(vi1.getType()), vi1);
1137 final Variable vi1 = smapper.pop(this);
1138 final Variable vi2 = smapper.pop(this);
1139 final Variable vo3 = smapper.pushT(vi1.getType());
1140 final Variable vo2 = smapper.pushT(vi2.getType());
1141 final Variable vo1 = smapper.pushT(vi1.getType());
1143 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1144 vo1, vi1, vo2, vi2, vo3, vo1);
1148 final Variable vi1 = smapper.pop(this);
1149 final Variable vi2 = smapper.pop(this);
1151 if (vi1.isCategory2()) {
1152 final Variable vo3 = smapper.pushT(vi1.getType());
1153 final Variable vo2 = smapper.pushT(vi2.getType());
1154 final Variable vo1 = smapper.pushT(vi1.getType());
1156 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1157 vo1, vi1, vo2, vi2, vo3, vo1);
1159 final Variable vi3 = smapper.pop(this);
1160 final Variable vo5 = smapper.pushT(vi2.getType());
1161 final Variable vo4 = smapper.pushT(vi1.getType());
1162 final Variable vo3 = smapper.pushT(vi3.getType());
1163 final Variable vo2 = smapper.pushT(vi2.getType());
1164 final Variable vo1 = smapper.pushT(vi1.getType());
1166 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1167 vo1, vi1, vo2, vi2, vo3, vi3);
1168 emit(smapper, this, " @1 = @2, @3 = @4;",
1169 vo4, vo1, vo5, vo2);
1174 final Variable vi1 = smapper.pop(this);
1175 final Variable vi2 = smapper.pop(this);
1177 if (vi2.isCategory2()) {
1178 final Variable vo3 = smapper.pushT(vi1.getType());
1179 final Variable vo2 = smapper.pushT(vi2.getType());
1180 final Variable vo1 = smapper.pushT(vi1.getType());
1182 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1183 vo1, vi1, vo2, vi2, vo3, vo1);
1185 final Variable vi3 = smapper.pop(this);
1186 final Variable vo4 = smapper.pushT(vi1.getType());
1187 final Variable vo3 = smapper.pushT(vi3.getType());
1188 final Variable vo2 = smapper.pushT(vi2.getType());
1189 final Variable vo1 = smapper.pushT(vi1.getType());
1191 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1192 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1197 final Variable vi1 = smapper.pop(this);
1198 final Variable vi2 = smapper.pop(this);
1200 if (vi1.isCategory2()) {
1201 if (vi2.isCategory2()) {
1202 final Variable vo3 = smapper.pushT(vi1.getType());
1203 final Variable vo2 = smapper.pushT(vi2.getType());
1204 final Variable vo1 = smapper.pushT(vi1.getType());
1206 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1207 vo1, vi1, vo2, vi2, vo3, vo1);
1209 final Variable vi3 = smapper.pop(this);
1210 final Variable vo4 = smapper.pushT(vi1.getType());
1211 final Variable vo3 = smapper.pushT(vi3.getType());
1212 final Variable vo2 = smapper.pushT(vi2.getType());
1213 final Variable vo1 = smapper.pushT(vi1.getType());
1215 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1216 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1219 final Variable vi3 = smapper.pop(this);
1221 if (vi3.isCategory2()) {
1222 final Variable vo5 = smapper.pushT(vi2.getType());
1223 final Variable vo4 = smapper.pushT(vi1.getType());
1224 final Variable vo3 = smapper.pushT(vi3.getType());
1225 final Variable vo2 = smapper.pushT(vi2.getType());
1226 final Variable vo1 = smapper.pushT(vi1.getType());
1228 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1229 vo1, vi1, vo2, vi2, vo3, vi3);
1230 emit(smapper, this, " @1 = @2, @3 = @4;",
1231 vo4, vo1, vo5, vo2);
1233 final Variable vi4 = smapper.pop(this);
1234 final Variable vo6 = smapper.pushT(vi2.getType());
1235 final Variable vo5 = smapper.pushT(vi1.getType());
1236 final Variable vo4 = smapper.pushT(vi4.getType());
1237 final Variable vo3 = smapper.pushT(vi3.getType());
1238 final Variable vo2 = smapper.pushT(vi2.getType());
1239 final Variable vo1 = smapper.pushT(vi1.getType());
1241 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1242 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1243 emit(smapper, this, " @1 = @2, @3 = @4;",
1244 vo5, vo1, vo6, vo2);
1250 final Variable vi1 = smapper.get(0);
1251 final Variable vi2 = smapper.get(1);
1253 if (vi1.getType() == vi2.getType()) {
1254 final Variable tmp = smapper.pushT(vi1.getType());
1256 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1261 smapper.pushT(vi1.getType());
1262 smapper.pushT(vi2.getType());
1267 smapper.assign(this, VarType.INTEGER,
1268 "(" + Integer.toString(byteCodes[++i]) + ")");
1271 smapper.assign(this, VarType.INTEGER,
1272 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1276 case opc_getfield: {
1277 int indx = readUShortArg(byteCodes, i);
1278 String[] fi = jc.getFieldInfoName(indx);
1279 final int type = VarType.fromFieldType(fi[2].charAt(0));
1280 final String mangleClass = mangleClassName(fi[0]);
1281 final String mangleClassAccess = accessClass(mangleClass);
1282 smapper.replace(this, type, "@2.call(@1)",
1284 accessField(mangleClassAccess + "(false)",
1290 case opc_putfield: {
1291 int indx = readUShortArg(byteCodes, i);
1292 String[] fi = jc.getFieldInfoName(indx);
1293 final int type = VarType.fromFieldType(fi[2].charAt(0));
1294 final String mangleClass = mangleClassName(fi[0]);
1295 final String mangleClassAccess = accessClass(mangleClass);
1296 emit(smapper, this, "@3.call(@2, @1);",
1299 accessField(mangleClassAccess + "(false)",
1304 case opc_getstatic: {
1305 int indx = readUShortArg(byteCodes, i);
1306 String[] fi = jc.getFieldInfoName(indx);
1307 final int type = VarType.fromFieldType(fi[2].charAt(0));
1308 String ac = accessClass(mangleClassName(fi[0]));
1309 smapper.assign(this, type, ac + "(false)._" + fi[1] + "()");
1311 addReference(fi[0]);
1314 case opc_putstatic: {
1315 int indx = readUShortArg(byteCodes, i);
1316 String[] fi = jc.getFieldInfoName(indx);
1317 final int type = VarType.fromFieldType(fi[2].charAt(0));
1318 emit(smapper, this, "@1(false)._@2(@3);",
1319 accessClass(mangleClassName(fi[0])), fi[1],
1320 smapper.popT(type));
1322 addReference(fi[0]);
1325 case opc_checkcast: {
1326 int indx = readUShortArg(byteCodes, i);
1327 generateCheckcast(indx, smapper);
1331 case opc_instanceof: {
1332 int indx = readUShortArg(byteCodes, i);
1333 generateInstanceOf(indx, smapper);
1338 final CharSequence v = smapper.popA();
1341 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1342 smapper.pushA(), v);
1346 case opc_monitorenter: {
1347 debug("/* monitor enter */");
1352 case opc_monitorexit: {
1353 debug("/* monitor exit */");
1364 emit(smapper, this, "throw 'unknown bytecode @1';",
1365 Integer.toString(c));
1369 generateByteCodeComment(prev, i, byteCodes);
1375 if (previousTrap != null) {
1376 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1381 while (openBraces-- > 0) {
1387 private int generateIf(StackMapper mapper, byte[] byteCodes,
1388 int i, final CharSequence v2, final CharSequence v1,
1389 final String test, int topMostLabel
1390 ) throws IOException {
1392 int indx = i + readShortArg(byteCodes, i);
1393 append("if ((").append(v1)
1394 .append(") ").append(test).append(" (")
1395 .append(v2).append(")) ");
1396 goTo(this, i, indx, topMostLabel);
1400 private int readInt4(byte[] byteCodes, int offset) {
1401 final int d = byteCodes[offset + 0] << 24;
1402 final int c = byteCodes[offset + 1] << 16;
1403 final int b = byteCodes[offset + 2] << 8;
1404 final int a = byteCodes[offset + 3];
1405 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1407 private static int readUByte(byte[] byteCodes, int offset) {
1408 return byteCodes[offset] & 0xff;
1411 private static int readUShort(byte[] byteCodes, int offset) {
1412 return ((byteCodes[offset] & 0xff) << 8)
1413 | (byteCodes[offset + 1] & 0xff);
1415 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1416 return readUShort(byteCodes, offsetInstruction + 1);
1419 private static int readShort(byte[] byteCodes, int offset) {
1420 int signed = byteCodes[offset];
1421 byte b0 = (byte)signed;
1422 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1424 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1425 return readShort(byteCodes, offsetInstruction + 1);
1428 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1430 Boolean count = null;
1431 boolean array = false;
1433 int firstPos = sig.length();
1434 while (i < descriptor.length()) {
1435 char ch = descriptor.charAt(i++);
1456 if (ch == 'J' || ch == 'D') {
1462 sig.insert(firstPos, ch);
1464 returnType[0] = '[';
1465 sig.insert(firstPos, "_3");
1474 returnType[0] = 'V';
1475 sig.insert(firstPos, 'V');
1478 int next = descriptor.indexOf(';', i);
1479 String realSig = mangleSig(descriptor, i - 1, next + 1);
1484 sig.append(realSig);
1487 sig.insert(firstPos, realSig);
1489 sig.insert(firstPos, "_3");
1491 returnType[0] = 'L';
1500 throw new IllegalStateException("Invalid char: " + ch);
1505 static String mangleSig(String sig) {
1506 return mangleSig(sig, 0, sig.length());
1509 private static String mangleMethodName(String name) {
1510 StringBuilder sb = new StringBuilder(name.length() * 2);
1511 int last = name.length();
1512 for (int i = 0; i < last; i++) {
1513 final char ch = name.charAt(i);
1515 case '_': sb.append("_1"); break;
1516 default: sb.append(ch); break;
1519 return sb.toString();
1521 private static String mangleSig(String txt, int first, int last) {
1522 StringBuilder sb = new StringBuilder((last - first) * 2);
1523 for (int i = first; i < last; i++) {
1524 final char ch = txt.charAt(i);
1526 case '/': sb.append('_'); break;
1527 case '_': sb.append("_1"); break;
1528 case ';': sb.append("_2"); break;
1529 case '[': sb.append("_3"); break;
1530 default: sb.append(ch); break;
1533 return sb.toString();
1536 private static String mangleClassName(String name) {
1537 return mangleSig(name);
1540 private static String findMethodName(MethodData m, StringBuilder cnt) {
1541 StringBuilder name = new StringBuilder();
1542 if ("<init>".equals(m.getName())) { // NOI18N
1543 name.append("cons"); // NOI18N
1544 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1545 name.append("class"); // NOI18N
1547 name.append(mangleMethodName(m.getName()));
1550 countArgs(m.getInternalSig(), new char[1], name, cnt);
1551 return name.toString();
1554 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1555 StringBuilder name = new StringBuilder();
1556 String descr = mi[2];//mi.getDescriptor();
1558 if ("<init>".equals(nm)) { // NOI18N
1559 name.append("cons"); // NOI18N
1561 name.append(mangleMethodName(nm));
1563 countArgs(descr, returnType, name, cnt);
1564 return name.toString();
1567 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1568 throws IOException {
1569 int methodIndex = readUShortArg(byteCodes, i);
1570 String[] mi = jc.getFieldInfoName(methodIndex);
1571 char[] returnType = { 'V' };
1572 StringBuilder cnt = new StringBuilder();
1573 String mn = findMethodName(mi, cnt, returnType);
1575 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1576 final CharSequence[] vars = new CharSequence[numArguments];
1578 for (int j = numArguments - 1; j >= 0; --j) {
1579 vars[j] = mapper.popValue();
1582 if (returnType[0] != 'V') {
1584 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1588 final String in = mi[0];
1589 String object = accessClass(in.replace('/', '_')) + "(false)";
1590 if (mn.startsWith("cons_")) {
1591 object += ".constructor";
1593 append(accessStaticMethod(object, mn, mi));
1599 if (numArguments > 0) {
1601 for (int j = 1; j < numArguments; ++j) {
1611 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1612 throws IOException {
1613 int methodIndex = readUShortArg(byteCodes, i);
1614 String[] mi = jc.getFieldInfoName(methodIndex);
1615 char[] returnType = { 'V' };
1616 StringBuilder cnt = new StringBuilder();
1617 String mn = findMethodName(mi, cnt, returnType);
1619 final int numArguments = cnt.length() + 1;
1620 final CharSequence[] vars = new CharSequence[numArguments];
1622 for (int j = numArguments - 1; j >= 0; --j) {
1623 vars[j] = mapper.popValue();
1626 if (returnType[0] != 'V') {
1628 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1632 append(accessVirtualMethod(vars[0].toString(), mn, mi));
1635 for (int j = 1; j < numArguments; ++j) {
1645 private void addReference(String cn) throws IOException {
1646 if (requireReference(cn)) {
1647 debug(" /* needs " + cn + " */");
1651 private void outType(String d, StringBuilder out) {
1653 while (d.charAt(0) == '[') {
1657 if (d.charAt(0) == 'L') {
1658 assert d.charAt(d.length() - 1) == ';';
1659 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1665 private String encodeConstant(int entryIndex) throws IOException {
1666 String[] classRef = { null };
1667 String s = jc.stringValue(entryIndex, classRef);
1668 if (classRef[0] != null) {
1669 if (classRef[0].startsWith("[")) {
1670 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1672 addReference(classRef[0]);
1673 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1679 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1680 byte[] arr = m.findAnnotationData(true);
1684 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1685 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1686 class P extends AnnotationParser {
1692 String[] args = new String[30];
1698 protected void visitAttr(String type, String attr, String at, String value) {
1699 if (type.equals(jvmType)) {
1700 if ("body".equals(attr)) {
1702 } else if ("args".equals(attr)) {
1703 args[cnt++] = value;
1705 throw new IllegalArgumentException(attr);
1708 if (type.equals(htmlType)) {
1710 if ("body".equals(attr)) {
1712 } else if ("args".equals(attr)) {
1713 args[cnt++] = value;
1714 } else if ("javacall".equals(attr)) {
1715 javacall = "1".equals(value);
1717 throw new IllegalArgumentException(attr);
1724 if (p.body == null) {
1727 StringBuilder cnt = new StringBuilder();
1728 final String mn = findMethodName(m, cnt);
1729 append(destObject).append(".").append(mn);
1730 append(" = function(");
1733 StringBuilder toValue = new StringBuilder();
1734 for (int i = 0; i < cnt.length(); i++) {
1736 space = outputArg(this, p.args, index);
1737 if (p.html4j && space.length() > 0) {
1738 toValue.append("\n ").append(p.args[index]).append(" = vm.org_apidesign_bck2brwsr_emul_lang_System(false).toJS(").
1739 append(p.args[index]).append(");");
1743 append(") {").append("\n");
1744 append(toValue.toString());
1746 int lastSlash = jc.getClassName().lastIndexOf('/');
1747 final String pkg = jc.getClassName().substring(0, lastSlash);
1748 append(mangleCallbacks(pkg, p.body));
1749 requireReference(pkg + "/$JsCallbacks$");
1757 private static CharSequence mangleCallbacks(String pkgName, String body) {
1758 StringBuilder sb = new StringBuilder();
1761 int next = body.indexOf(".@", pos);
1763 sb.append(body.substring(pos));
1764 body = sb.toString();
1769 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1774 String refId = body.substring(ident, next);
1776 sb.append(body.substring(pos, ident));
1778 int sigBeg = body.indexOf('(', next);
1779 int sigEnd = body.indexOf(')', sigBeg);
1780 int colon4 = body.indexOf("::", next);
1781 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1782 throw new IllegalStateException("Malformed body " + body);
1784 String fqn = body.substring(next + 2, colon4);
1785 String method = body.substring(colon4 + 2, sigBeg);
1786 String params = body.substring(sigBeg, sigEnd + 1);
1788 int paramBeg = body.indexOf('(', sigEnd + 1);
1790 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1791 sb.append(mangleJsCallbacks(fqn, method, params, false));
1792 sb.append("(").append(refId);
1793 if (body.charAt(paramBeg + 1) != ')') {
1801 int next = body.indexOf("@", pos);
1806 sb.append(body.substring(pos));
1810 sb = new StringBuilder();
1813 sb.append(body.substring(pos, next));
1815 int sigBeg = body.indexOf('(', next);
1816 int sigEnd = body.indexOf(')', sigBeg);
1817 int colon4 = body.indexOf("::", next);
1818 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1819 throw new IllegalStateException("Malformed body " + body);
1821 String fqn = body.substring(next + 1, colon4);
1822 String method = body.substring(colon4 + 2, sigBeg);
1823 String params = body.substring(sigBeg, sigEnd + 1);
1825 int paramBeg = body.indexOf('(', sigEnd + 1);
1827 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1828 sb.append(mangleJsCallbacks(fqn, method, params, true));
1834 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1835 if (params.startsWith("(")) {
1836 params = params.substring(1);
1838 if (params.endsWith(")")) {
1839 params = params.substring(0, params.length() - 1);
1841 StringBuilder sb = new StringBuilder();
1842 final String fqnu = fqn.replace('.', '_');
1843 final String rfqn = mangleClassName(fqnu);
1844 final String rm = mangleMethodName(method);
1847 StringBuilder pb = new StringBuilder();
1848 int len = params.length();
1850 while (indx < len) {
1851 char ch = params.charAt(indx);
1852 if (ch == '[' || ch == 'L') {
1853 pb.append("Ljava/lang/Object;");
1854 indx = params.indexOf(';', indx) + 1;
1860 srp = mangleSig(pb.toString());
1862 final String rp = mangleSig(params);
1863 final String mrp = mangleMethodName(rp);
1864 sb.append(rfqn).append("$").append(rm).
1865 append('$').append(mrp).append("__Ljava_lang_Object_2");
1867 sb.append('L').append(fqnu).append("_2");
1870 return sb.toString();
1873 private static String className(ClassData jc) {
1874 //return jc.getName().getInternalName().replace('/', '_');
1875 return mangleClassName(jc.getClassName());
1878 private static String[] findAnnotation(
1879 byte[] arr, ClassData cd, final String className,
1880 final String... attrNames
1881 ) throws IOException {
1885 final String[] values = new String[attrNames.length];
1886 final boolean[] found = { false };
1887 final String jvmType = "L" + className.replace('.', '/') + ";";
1888 AnnotationParser ap = new AnnotationParser(false, true) {
1890 protected void visitAttr(String type, String attr, String at, String value) {
1891 if (type.equals(jvmType)) {
1893 for (int i = 0; i < attrNames.length; i++) {
1894 if (attrNames[i].equals(attr)) {
1903 return found[0] ? values : null;
1906 private CharSequence initField(FieldData v) {
1907 final String is = v.getInternalSig();
1908 if (is.length() == 1) {
1909 switch (is.charAt(0)) {
1915 case 'I': return " = 0;";
1917 case 'D': return " = 0.0;";
1919 throw new IllegalStateException(is);
1925 private void generateAnno(ClassData cd, byte[] data) throws IOException {
1926 AnnotationParser ap = new AnnotationParser(true, false) {
1927 int[] cnt = new int[32];
1931 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
1932 final String slashType = attrType.substring(1, attrType.length() - 1);
1933 requireReference(slashType);
1935 if (cnt[depth]++ > 0) {
1939 append('"').append(attrType).append("\" : ");
1946 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
1952 protected void visitValueStart(String attrName, char type) throws IOException {
1953 if (cnt[depth]++ > 0) {
1957 if (attrName != null) {
1958 append(attrName).append(" : ");
1966 protected void visitValueEnd(String attrName, char type) throws IOException {
1974 protected void visitAttr(String type, String attr, String attrType, String value)
1975 throws IOException {
1976 if (attr == null && value == null) {
1983 protected void visitEnumAttr(String type, String attr, String attrType, String value)
1984 throws IOException {
1985 final String slashType = attrType.substring(1, attrType.length() - 1);
1986 requireReference(slashType);
1988 append(accessClass(mangleClassName(slashType)))
1989 .append("(false).constructor.fld_").append(value);
1995 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
1996 final String name = args[indx];
2000 if (name.contains(",")) {
2001 throw new IOException("Wrong parameter with ',': " + name);
2007 final void emitNoFlush(
2009 final String format, final CharSequence... params
2010 ) throws IOException {
2011 emitImpl(this, format, params);
2013 static final void emit(
2015 final Appendable out,
2016 final String format, final CharSequence... params
2017 ) throws IOException {
2019 emitImpl(out, format, params);
2021 static void emitImpl(final Appendable out,
2022 final String format,
2023 final CharSequence... params) throws IOException {
2024 final int length = format.length();
2027 int paramOffset = format.indexOf('@');
2028 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2029 final char paramChar = format.charAt(paramOffset + 1);
2030 if ((paramChar >= '1') && (paramChar <= '9')) {
2031 final int paramIndex = paramChar - '0' - 1;
2033 out.append(format, processed, paramOffset);
2034 out.append(params[paramIndex]);
2037 processed = paramOffset + 1;
2040 paramOffset = format.indexOf('@', paramOffset + 1);
2043 out.append(format, processed, length);
2046 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2047 append("} catch (e) {\n");
2049 for (TrapData e : traps) {
2053 if (e.catch_cpx != 0) { //not finally
2054 final String classInternalName = jc.getClassName(e.catch_cpx);
2055 addReference(classInternalName);
2056 append("e = vm.java_lang_Throwable(false).bck2BrwsrCnvrt(e);");
2057 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2058 append("var stA0 = e;");
2059 goTo(this, current, e.handler_pc, topMostLabel);
2062 finallyPC = e.handler_pc;
2065 if (finallyPC == -1) {
2068 append("var stA0 = e;");
2069 goTo(this, current, finallyPC, topMostLabel);
2074 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2077 out.append("{ gt = 0; continue X_" + to + "; }");
2079 out.append("{ gt = " + to + "; continue X_0; }");
2082 out.append("{ gt = " + to + "; break IF; }");
2086 private static void emitIf(
2088 Appendable out, String pattern,
2090 int current, int to, int canBack
2091 ) throws IOException {
2093 emitImpl(out, pattern, param);
2094 goTo(out, current, to, canBack);
2097 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2100 case 4: jvmType = "[Z"; break;
2101 case 5: jvmType = "[C"; break;
2102 case 6: jvmType = "[F"; break;
2103 case 7: jvmType = "[D"; break;
2104 case 8: jvmType = "[B"; break;
2105 case 9: jvmType = "[S"; break;
2106 case 10: jvmType = "[I"; break;
2107 case 11: jvmType = "[J"; break;
2108 default: throw new IllegalStateException("Array type: " + atype);
2111 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2I'](true, '@3', @1);",
2112 smapper.popI(), smapper.pushA(), jvmType);
2115 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2116 String typeName = jc.getClassName(type);
2117 if (typeName.startsWith("[")) {
2118 typeName = "[" + typeName;
2120 typeName = "[L" + typeName + ";";
2123 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2I'](false, '@3', @1);",
2124 smapper.popI(), smapper.pushA(), typeName);
2127 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2128 String typeName = jc.getClassName(type);
2129 int dim = readUByte(byteCodes, ++i);
2130 StringBuilder dims = new StringBuilder();
2132 for (int d = 0; d < dim; d++) {
2134 dims.insert(1, ",");
2136 dims.insert(1, smapper.popI());
2140 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II']('@3', @1, 0);",
2141 dims.toString(), smapper.pushA(), typeName);
2145 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2146 int table = i / 4 * 4 + 4;
2147 int dflt = i + readInt4(byteCodes, table);
2149 int low = readInt4(byteCodes, table);
2151 int high = readInt4(byteCodes, table);
2153 final CharSequence swVar = smapper.popValue();
2154 smapper.flush(this);
2155 append("switch (").append(swVar).append(") {\n");
2156 while (low <= high) {
2157 int offset = i + readInt4(byteCodes, table);
2159 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2162 append(" default: ");
2163 goTo(this, i, dflt, topMostLabel);
2169 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2170 int table = i / 4 * 4 + 4;
2171 int dflt = i + readInt4(byteCodes, table);
2173 int n = readInt4(byteCodes, table);
2175 final CharSequence swVar = smapper.popValue();
2176 smapper.flush(this);
2177 append("switch (").append(swVar).append(") {\n");
2179 int cnstnt = readInt4(byteCodes, table);
2181 int offset = i + readInt4(byteCodes, table);
2183 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2185 append(" default: ");
2186 goTo(this, i, dflt, topMostLabel);
2192 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2193 final String type = jc.getClassName(indx);
2194 if (!type.startsWith("[")) {
2196 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2197 smapper.popA(), smapper.pushI(),
2198 type.replace('/', '_'));
2201 "var @2 = vm.java_lang_Class(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('@3')['isInstance__ZLjava_lang_Object_2'](@1);",
2202 smapper.popA(), smapper.pushI(),
2208 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2209 final String type = jc.getClassName(indx);
2210 if (!type.startsWith("[")) {
2211 emitNoFlush(smapper,
2212 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2213 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2215 emitNoFlush(smapper,
2216 "vm.java_lang_Class(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('@2')['cast__Ljava_lang_Object_2Ljava_lang_Object_2'](@1);",
2217 smapper.getT(0, VarType.REFERENCE, false), type
2222 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2223 for (int j = prev; j <= i; j++) {
2225 final int cc = readUByte(byteCodes, j);
2226 append(Integer.toString(cc));