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 java.util.Locale;
23 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
25 /** Translator of the code inside class files to JavaScript.
27 * @author Jaroslav Tulach <jtulach@netbeans.org>
29 abstract class ByteCodeToJavaScript implements Appendable {
31 private final Appendable out;
32 private boolean outChanged;
33 private boolean callbacks;
35 protected ByteCodeToJavaScript(Appendable out) {
40 public final Appendable append(CharSequence csq) throws IOException {
47 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
48 out.append(csq, start, end);
54 public final Appendable append(char c) throws IOException {
60 /* Collects additional required resources.
62 * @param internalClassName classes that were referenced and should be loaded in order the
63 * generated JavaScript code works properly. The names are in internal
64 * JVM form so String is <code>java/lang/String</code>.
66 protected abstract boolean requireReference(String internalClassName);
69 * @param resourcePath name of resources to read
71 protected abstract void requireScript(String resourcePath) throws IOException;
73 /** Allows subclasses to redefine what field a function representing a
74 * class gets assigned. By default it returns the suggested name followed
75 * by <code>" = "</code>;
77 * @param className suggested name of the class
79 /* protected */ String assignClass(String className) {
80 return className + " = ";
82 /* protected */ String accessClass(String classOperation) {
83 return classOperation;
86 protected String accessField(String object, String mangledName,
87 String[] fieldInfoName) throws IOException {
88 return object + "." + mangledName;
91 protected String accessStaticMethod(
94 String[] fieldInfoName) throws IOException {
95 return object + "." + mangledName;
98 protected String accessVirtualMethod(
101 String[] fieldInfoName) throws IOException {
102 return object + "." + mangledName;
105 protected void declaredClass(ClassData classData, String mangledName)
109 protected void declaredField(FieldData fieldData,
111 String mangledName) throws IOException {
114 protected void declaredMethod(MethodData methodData,
116 String mangledName) throws IOException {
119 /** Prints out a debug message.
121 * @param msg the message
122 * @return true if the message has been printed
123 * @throws IOException
125 boolean debug(String msg) throws IOException {
131 * Converts a given class file to a JavaScript version.
133 * @param classFile input stream with code of the .class file
134 * @return the initialization code for this class, if any. Otherwise <code>null</code>
136 * @throws IOException if something goes wrong during read or write or translating
139 public String compile(InputStream classFile) throws IOException {
140 return compile(new ClassData(classFile));
143 protected String compile(ClassData classData) throws IOException {
145 this.callbacks = this.jc.getClassName().endsWith("/$JsCallbacks$");
146 if (jc.getMajor_version() < 50) {
147 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
148 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
151 byte[] arrData = jc.findAnnotationData(true);
153 String[] arr = findAnnotation(arrData, jc,
154 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
155 "resource", "processByteCode"
158 if (!arr[0].isEmpty()) {
159 requireScript(arr[0]);
161 if ("0".equals(arr[1])) {
167 String[] arr = findAnnotation(arrData, jc,
168 "net.java.html.js.JavaScriptResource",
172 if (arr[0].startsWith("/")) {
173 requireScript(arr[0]);
175 int last = jc.getClassName().lastIndexOf('/');
177 jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0]
182 String[] proto = findAnnotation(arrData, jc,
183 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
184 "container", "prototype"
186 StringArray toInitilize = new StringArray();
187 final String className = className(jc);
188 append("\n\n").append(assignClass(className));
189 append("function ").append(className).append("() {");
190 append("\n var CLS = ").append(className).append(';');
191 append("\n if (!CLS.$class) {");
193 String sc = jc.getSuperClassName(); // with _
194 append("\n var pp = ").
195 append(accessClass(mangleClassName(sc))).append("(true);");
196 append("\n var p = CLS.prototype = pp;");
197 append("\n var c = p;");
198 append("\n var sprcls = pp.constructor.$class;");
200 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
201 if (proto[0] == null) {
204 append("\n var c = ").append(proto[0]).append(";");
205 append("\n var sprcls = null;");
207 for (FieldData v : jc.getFields()) {
209 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
210 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
214 append("\n CLS.fld_").append(v.getName()).append(initField(v));
215 append("\n c._").append(v.getName()).append(" = function (v) {")
216 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
217 .append(" = v; return CLS.fld_").
218 append(v.getName()).append("; };");
220 append("\n c._").append(v.getName()).append(" = function (v) {")
221 .append(" if (arguments.length == 1) this.fld_").
222 append(className).append('_').append(v.getName())
223 .append(" = v; return this.fld_").
224 append(className).append('_').append(v.getName())
228 declaredField(v, "c", "_" + v.getName());
230 for (MethodData m : jc.getMethods()) {
231 byte[] onlyArr = m.findAnnotationData(true);
232 if (javaScriptOnly(onlyArr)) continue;
238 mn = generateStaticMethod(destObject, m, toInitilize);
240 if (m.isConstructor()) {
242 mn = generateInstanceMethod(destObject, m);
245 mn = generateInstanceMethod(destObject, m);
248 declaredMethod(m, destObject, mn);
249 byte[] runAnno = m.findAnnotationData(false);
250 if (runAnno != null) {
251 append("\n ").append(destObject).append(".").append(mn).append(".anno = {");
252 generateAnno(jc, runAnno);
255 append("\n ").append(destObject).append(".").append(mn).append(".access = " + m.getAccess()).append(";");
256 append("\n ").append(destObject).append(".").append(mn).append(".cls = CLS;");
258 append("\n c.constructor = CLS;");
259 append("\n function fillInstOf(x) {");
260 String instOfName = "$instOf_" + className;
261 append("\n x['").append(instOfName).append("'] = true;");
262 for (String superInterface : jc.getSuperInterfaces()) {
263 String intrfc = superInterface.replace('/', '_');
264 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
265 requireReference(superInterface);
268 append("\n c['fillInstOf'] = fillInstOf;");
269 append("\n fillInstOf(c);");
270 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
271 append("\n CLS.$class = 'temp';");
272 append("\n CLS.$class = ");
273 append(accessClass("java_lang_Class(true);"));
274 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
275 append("\n CLS.$class.superclass = sprcls;");
276 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
277 append("\n CLS.$class.cnstr = CLS;");
278 byte[] classAnno = jc.findAnnotationData(false);
279 if (classAnno != null) {
280 append("\n CLS.$class.anno = {");
281 generateAnno(jc, classAnno);
284 for (String init : toInitilize.toArray()) {
285 append("\n ").append(init).append("();");
288 append("\n if (arguments.length === 0) {");
289 append("\n if (!(this instanceof CLS)) {");
290 append("\n return new CLS();");
292 for (FieldData v : jc.getFields()) {
293 byte[] onlyArr = v.findAnnotationData(true);
294 if (javaScriptOnly(onlyArr)) continue;
296 append("\n this.fld_").
297 append(className).append('_').
298 append(v.getName()).append(initField(v));
301 append("\n return this;");
303 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
306 declaredClass(jc, className);
308 // StringBuilder sb = new StringBuilder();
309 // for (String init : toInitilize.toArray()) {
310 // sb.append("\n").append(init).append("();");
315 private boolean javaScriptOnly(byte[] anno) throws IOException {
316 String[] only = findAnnotation(anno, jc,
317 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
321 if (only[0] != null && only[1] != null) {
322 append("\n p.").append(only[0]).append(" = ")
323 .append(only[1]).append(";");
325 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
326 append("\n p['").append(only[0]).append("'] = p.")
327 .append(only[0]).append(";");
333 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
334 String jsb = javaScriptBody(destObject, m, true);
338 final String mn = findMethodName(m, new StringBuilder());
339 if (mn.equals("class__V")) {
340 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
342 generateMethod(destObject, mn, m);
346 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
347 String jsb = javaScriptBody(destObject, m, false);
351 final String mn = findMethodName(m, new StringBuilder());
352 generateMethod(destObject, mn, m);
356 private void generateMethod(String destObject, String name, MethodData m)
358 final StackMapIterator stackMapIterator = m.createStackMapIterator();
359 TrapDataIterator trap = m.getTrapDataIterator();
360 final LocalsMapper lmapper =
361 new LocalsMapper(stackMapIterator.getArguments());
363 append(destObject).append(".").append(name).append(" = function(");
364 lmapper.outputArguments(this, m.isStatic());
365 append(") {").append("\n");
367 final byte[] byteCodes = m.getCode();
368 if (byteCodes == null) {
369 append(" throw 'no code found for ")
370 .append(jc.getClassName()).append('.')
371 .append(m.getName()).append("';\n");
376 final StackMapper smapper = new StackMapper();
379 append(" var ").append(" lcA0 = this;\n");
383 TrapData[] previousTrap = null;
384 boolean wide = false;
386 if (stackMapIterator.isEmpty()) {
392 append("\n var gt = 0;\n");
396 int topMostLabel = 0;
397 for (int i = 0; i < byteCodes.length; i++) {
400 stackMapIterator.advanceTo(i);
401 boolean changeInCatch = trap.advanceTo(i);
402 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
403 if (previousTrap != null) {
404 generateCatch(previousTrap, i, topMostLabel);
408 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
413 if (openBraces > 64) {
414 for (int c = 0; c < 64; c++) {
421 lastStackFrame = stackMapIterator.getFrameIndex();
422 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
423 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
424 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
426 changeInCatch = true;
428 debug(" /* " + i + " */ ");
430 if (changeInCatch && trap.useTry()) {
432 previousTrap = trap.current();
434 final int c = readUByte(byteCodes, i);
437 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
440 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
443 smapper.assign(this, VarType.LONG, lmapper.getL(0));
446 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
449 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
452 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
455 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
458 smapper.assign(this, VarType.LONG, lmapper.getL(1));
461 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
464 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
467 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
470 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
473 smapper.assign(this, VarType.LONG, lmapper.getL(2));
476 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
479 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
482 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
485 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
488 smapper.assign(this, VarType.LONG, lmapper.getL(3));
491 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
494 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
498 final int indx = wide ? readUShort(byteCodes, i++)
499 : readUByte(byteCodes, i);
501 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
506 final int indx = wide ? readUShort(byteCodes, i++)
507 : readUByte(byteCodes, i);
509 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
514 final int indx = wide ? readUShort(byteCodes, i++)
515 : readUByte(byteCodes, i);
517 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
522 final int indx = wide ? readUShort(byteCodes, i++)
523 : readUByte(byteCodes, i);
525 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
530 final int indx = wide ? readUShort(byteCodes, i++)
531 : readUByte(byteCodes, i);
533 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
538 final int indx = wide ? readUShort(byteCodes, i++)
539 : readUByte(byteCodes, i);
541 emit(smapper, this, "var @1 = @2;",
542 lmapper.setI(indx), smapper.popI());
547 final int indx = wide ? readUShort(byteCodes, i++)
548 : readUByte(byteCodes, i);
550 emit(smapper, this, "var @1 = @2;",
551 lmapper.setL(indx), smapper.popL());
556 final int indx = wide ? readUShort(byteCodes, i++)
557 : readUByte(byteCodes, i);
559 emit(smapper, this, "var @1 = @2;",
560 lmapper.setF(indx), smapper.popF());
565 final int indx = wide ? readUShort(byteCodes, i++)
566 : readUByte(byteCodes, i);
568 emit(smapper, this, "var @1 = @2;",
569 lmapper.setD(indx), smapper.popD());
574 final int indx = wide ? readUShort(byteCodes, i++)
575 : readUByte(byteCodes, i);
577 emit(smapper, this, "var @1 = @2;",
578 lmapper.setA(indx), smapper.popA());
582 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
585 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
588 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
591 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
594 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
597 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
600 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
603 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
606 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
609 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
612 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
615 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
618 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
621 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
624 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
627 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
630 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
633 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
636 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
639 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
642 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
645 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
648 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
651 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
654 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
657 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
660 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
663 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
666 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
669 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
672 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
675 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
678 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
679 smapper.getI(1), smapper.popI());
682 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
683 smapper.getL(1), smapper.popL());
686 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
689 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
692 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
693 smapper.getI(1), smapper.popI());
696 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
697 smapper.getL(1), smapper.popL());
700 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
703 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
706 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
709 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
712 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
715 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
718 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
721 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
724 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
727 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
730 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
733 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
736 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
739 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
742 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
745 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
748 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
751 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
755 final int varIndx = wide ? readUShort(byteCodes, i++)
756 : readUByte(byteCodes, i);
758 final int incrBy = wide ? readShort(byteCodes, i++)
762 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
764 emit(smapper, this, "@1 += @2;",
765 lmapper.getI(varIndx),
766 Integer.toString(incrBy));
771 emit(smapper, this, "return;");
774 emit(smapper, this, "return @1;", smapper.popI());
777 emit(smapper, this, "return @1;", smapper.popL());
780 emit(smapper, this, "return @1;", smapper.popF());
783 emit(smapper, this, "return @1;", smapper.popD());
786 emit(smapper, this, "return @1;", smapper.popA());
789 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
792 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
795 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
798 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
802 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
805 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
808 smapper.replace(this, VarType.DOUBLE, "@1",
812 smapper.replace(this, VarType.FLOAT, "@1",
816 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
820 smapper.replace(this, VarType.LONG, "(@1).toLong()",
824 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
828 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
831 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
836 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
838 case opc_aconst_null:
839 smapper.assign(this, VarType.REFERENCE, "null");
842 smapper.assign(this, VarType.INTEGER, "-1");
845 smapper.assign(this, VarType.INTEGER, "0");
848 smapper.assign(this, VarType.DOUBLE, "0");
851 smapper.assign(this, VarType.LONG, "0");
854 smapper.assign(this, VarType.FLOAT, "0");
857 smapper.assign(this, VarType.INTEGER, "1");
860 smapper.assign(this, VarType.LONG, "1");
863 smapper.assign(this, VarType.FLOAT, "1");
866 smapper.assign(this, VarType.DOUBLE, "1");
869 smapper.assign(this, VarType.INTEGER, "2");
872 smapper.assign(this, VarType.FLOAT, "2");
875 smapper.assign(this, VarType.INTEGER, "3");
878 smapper.assign(this, VarType.INTEGER, "4");
881 smapper.assign(this, VarType.INTEGER, "5");
884 int indx = readUByte(byteCodes, ++i);
885 String v = encodeConstant(indx);
886 int type = VarType.fromConstantType(jc.getTag(indx));
887 smapper.assign(this, type, v);
892 int indx = readUShortArg(byteCodes, i);
894 String v = encodeConstant(indx);
895 int type = VarType.fromConstantType(jc.getTag(indx));
896 if (type == VarType.LONG) {
897 final Long lv = new Long(v);
898 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
899 final int hi = (int)(lv.longValue() >> 32);
901 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
903 smapper.assign(this, VarType.LONG,
904 "0x" + Integer.toHexString(hi) + ".next32(0x" +
905 Integer.toHexString(low) + ")"
909 smapper.assign(this, type, v);
914 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
918 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
922 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
925 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
926 "===", topMostLabel);
929 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
930 "!==", topMostLabel);
933 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
937 int indx = i + readShortArg(byteCodes, i);
938 emitIf(smapper, this, "if ((@1) == 0) ",
939 smapper.popI(), i, indx, topMostLabel);
944 int indx = i + readShortArg(byteCodes, i);
945 emitIf(smapper, this, "if ((@1) != 0) ",
946 smapper.popI(), i, indx, topMostLabel);
951 int indx = i + readShortArg(byteCodes, i);
952 emitIf(smapper, this, "if ((@1) < 0) ",
953 smapper.popI(), i, indx, topMostLabel);
958 int indx = i + readShortArg(byteCodes, i);
959 emitIf(smapper, this, "if ((@1) <= 0) ",
960 smapper.popI(), i, indx, topMostLabel);
965 int indx = i + readShortArg(byteCodes, i);
966 emitIf(smapper, this, "if ((@1) > 0) ",
967 smapper.popI(), i, indx, topMostLabel);
972 int indx = i + readShortArg(byteCodes, i);
973 emitIf(smapper, this, "if ((@1) >= 0) ",
974 smapper.popI(), i, indx, topMostLabel);
978 case opc_ifnonnull: {
979 int indx = i + readShortArg(byteCodes, i);
980 emitIf(smapper, this, "if ((@1) !== null) ",
981 smapper.popA(), i, indx, topMostLabel);
986 int indx = i + readShortArg(byteCodes, i);
987 emitIf(smapper, this, "if ((@1) === null) ",
988 smapper.popA(), i, indx, topMostLabel);
993 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
997 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1001 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1002 "<=", topMostLabel);
1005 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1009 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1010 ">=", topMostLabel);
1013 smapper.flush(this);
1014 int indx = i + readShortArg(byteCodes, i);
1015 goTo(this, i, indx, topMostLabel);
1019 case opc_lookupswitch: {
1020 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1023 case opc_tableswitch: {
1024 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1027 case opc_invokeinterface: {
1028 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1031 case opc_invokevirtual:
1032 i = invokeVirtualMethod(byteCodes, i, smapper);
1034 case opc_invokespecial:
1035 i = invokeStaticMethod(byteCodes, i, smapper, false);
1037 case opc_invokestatic:
1038 i = invokeStaticMethod(byteCodes, i, smapper, true);
1041 int indx = readUShortArg(byteCodes, i);
1042 String ci = jc.getClassName(indx);
1043 emit(smapper, this, "var @1 = new @2;",
1044 smapper.pushA(), accessClass(mangleClassName(ci)));
1050 int atype = readUByte(byteCodes, ++i);
1051 generateNewArray(atype, smapper);
1053 case opc_anewarray: {
1054 int type = readUShortArg(byteCodes, i);
1056 generateANewArray(type, smapper);
1059 case opc_multianewarray: {
1060 int type = readUShortArg(byteCodes, i);
1062 i = generateMultiANewArray(type, byteCodes, i, smapper);
1065 case opc_arraylength:
1066 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1069 emit(smapper, this, "Array.at(@3, @2, @1);",
1070 smapper.popL(), smapper.popI(), smapper.popA());
1073 emit(smapper, this, "Array.at(@3, @2, @1);",
1074 smapper.popF(), smapper.popI(), smapper.popA());
1077 emit(smapper, this, "Array.at(@3, @2, @1);",
1078 smapper.popD(), smapper.popI(), smapper.popA());
1081 emit(smapper, this, "Array.at(@3, @2, @1);",
1082 smapper.popA(), smapper.popI(), smapper.popA());
1088 emit(smapper, this, "Array.at(@3, @2, @1);",
1089 smapper.popI(), smapper.popI(), smapper.popA());
1092 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1093 smapper.popI(), smapper.getA(0));
1096 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1097 smapper.popI(), smapper.getA(0));
1100 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1101 smapper.popI(), smapper.getA(0));
1104 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1105 smapper.popI(), smapper.getA(0));
1111 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1112 smapper.popI(), smapper.getA(0));
1120 final Variable v = smapper.get(0);
1121 if (smapper.isDirty()) {
1122 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1124 smapper.assign(this, v.getType(), v);
1129 final Variable vi1 = smapper.get(0);
1131 if (vi1.isCategory2()) {
1132 emit(smapper, this, "var @1 = @2;",
1133 smapper.pushT(vi1.getType()), vi1);
1135 final Variable vi2 = smapper.get(1);
1136 emit(smapper, this, "var @1 = @2, @3 = @4;",
1137 smapper.pushT(vi2.getType()), vi2,
1138 smapper.pushT(vi1.getType()), vi1);
1143 final Variable vi1 = smapper.pop(this);
1144 final Variable vi2 = smapper.pop(this);
1145 final Variable vo3 = smapper.pushT(vi1.getType());
1146 final Variable vo2 = smapper.pushT(vi2.getType());
1147 final Variable vo1 = smapper.pushT(vi1.getType());
1149 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1150 vo1, vi1, vo2, vi2, vo3, vo1);
1154 final Variable vi1 = smapper.pop(this);
1155 final Variable vi2 = smapper.pop(this);
1157 if (vi1.isCategory2()) {
1158 final Variable vo3 = smapper.pushT(vi1.getType());
1159 final Variable vo2 = smapper.pushT(vi2.getType());
1160 final Variable vo1 = smapper.pushT(vi1.getType());
1162 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1163 vo1, vi1, vo2, vi2, vo3, vo1);
1165 final Variable vi3 = smapper.pop(this);
1166 final Variable vo5 = smapper.pushT(vi2.getType());
1167 final Variable vo4 = smapper.pushT(vi1.getType());
1168 final Variable vo3 = smapper.pushT(vi3.getType());
1169 final Variable vo2 = smapper.pushT(vi2.getType());
1170 final Variable vo1 = smapper.pushT(vi1.getType());
1172 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1173 vo1, vi1, vo2, vi2, vo3, vi3);
1174 emit(smapper, this, " @1 = @2, @3 = @4;",
1175 vo4, vo1, vo5, vo2);
1180 final Variable vi1 = smapper.pop(this);
1181 final Variable vi2 = smapper.pop(this);
1183 if (vi2.isCategory2()) {
1184 final Variable vo3 = smapper.pushT(vi1.getType());
1185 final Variable vo2 = smapper.pushT(vi2.getType());
1186 final Variable vo1 = smapper.pushT(vi1.getType());
1188 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1189 vo1, vi1, vo2, vi2, vo3, vo1);
1191 final Variable vi3 = smapper.pop(this);
1192 final Variable vo4 = smapper.pushT(vi1.getType());
1193 final Variable vo3 = smapper.pushT(vi3.getType());
1194 final Variable vo2 = smapper.pushT(vi2.getType());
1195 final Variable vo1 = smapper.pushT(vi1.getType());
1197 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1198 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1203 final Variable vi1 = smapper.pop(this);
1204 final Variable vi2 = smapper.pop(this);
1206 if (vi1.isCategory2()) {
1207 if (vi2.isCategory2()) {
1208 final Variable vo3 = smapper.pushT(vi1.getType());
1209 final Variable vo2 = smapper.pushT(vi2.getType());
1210 final Variable vo1 = smapper.pushT(vi1.getType());
1212 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1213 vo1, vi1, vo2, vi2, vo3, vo1);
1215 final Variable vi3 = smapper.pop(this);
1216 final Variable vo4 = smapper.pushT(vi1.getType());
1217 final Variable vo3 = smapper.pushT(vi3.getType());
1218 final Variable vo2 = smapper.pushT(vi2.getType());
1219 final Variable vo1 = smapper.pushT(vi1.getType());
1221 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1222 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1225 final Variable vi3 = smapper.pop(this);
1227 if (vi3.isCategory2()) {
1228 final Variable vo5 = smapper.pushT(vi2.getType());
1229 final Variable vo4 = smapper.pushT(vi1.getType());
1230 final Variable vo3 = smapper.pushT(vi3.getType());
1231 final Variable vo2 = smapper.pushT(vi2.getType());
1232 final Variable vo1 = smapper.pushT(vi1.getType());
1234 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1235 vo1, vi1, vo2, vi2, vo3, vi3);
1236 emit(smapper, this, " @1 = @2, @3 = @4;",
1237 vo4, vo1, vo5, vo2);
1239 final Variable vi4 = smapper.pop(this);
1240 final Variable vo6 = smapper.pushT(vi2.getType());
1241 final Variable vo5 = smapper.pushT(vi1.getType());
1242 final Variable vo4 = smapper.pushT(vi4.getType());
1243 final Variable vo3 = smapper.pushT(vi3.getType());
1244 final Variable vo2 = smapper.pushT(vi2.getType());
1245 final Variable vo1 = smapper.pushT(vi1.getType());
1247 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1248 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1249 emit(smapper, this, " @1 = @2, @3 = @4;",
1250 vo5, vo1, vo6, vo2);
1256 final Variable vi1 = smapper.get(0);
1257 final Variable vi2 = smapper.get(1);
1259 if (vi1.getType() == vi2.getType()) {
1260 final Variable tmp = smapper.pushT(vi1.getType());
1262 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1267 smapper.pushT(vi1.getType());
1268 smapper.pushT(vi2.getType());
1273 smapper.assign(this, VarType.INTEGER,
1274 "(" + Integer.toString(byteCodes[++i]) + ")");
1277 smapper.assign(this, VarType.INTEGER,
1278 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1282 case opc_getfield: {
1283 int indx = readUShortArg(byteCodes, i);
1284 String[] fi = jc.getFieldInfoName(indx);
1285 final int type = VarType.fromFieldType(fi[2].charAt(0));
1286 final String mangleClass = mangleClassName(fi[0]);
1287 final String mangleClassAccess = accessClass(mangleClass);
1288 smapper.replace(this, type, "@2.call(@1)",
1290 accessField(mangleClassAccess + "(false)",
1296 case opc_putfield: {
1297 int indx = readUShortArg(byteCodes, i);
1298 String[] fi = jc.getFieldInfoName(indx);
1299 final int type = VarType.fromFieldType(fi[2].charAt(0));
1300 final String mangleClass = mangleClassName(fi[0]);
1301 final String mangleClassAccess = accessClass(mangleClass);
1302 emit(smapper, this, "@3.call(@2, @1);",
1305 accessField(mangleClassAccess + "(false)",
1310 case opc_getstatic: {
1311 int indx = readUShortArg(byteCodes, i);
1312 String[] fi = jc.getFieldInfoName(indx);
1313 final int type = VarType.fromFieldType(fi[2].charAt(0));
1314 String ac = accessClass(mangleClassName(fi[0]));
1315 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1316 smapper.assign(this, type, af + "()");
1318 addReference(fi[0]);
1321 case opc_putstatic: {
1322 int indx = readUShortArg(byteCodes, i);
1323 String[] fi = jc.getFieldInfoName(indx);
1324 final int type = VarType.fromFieldType(fi[2].charAt(0));
1325 emit(smapper, this, "@1(false)._@2(@3);",
1326 accessClass(mangleClassName(fi[0])), fi[1],
1327 smapper.popT(type));
1329 addReference(fi[0]);
1332 case opc_checkcast: {
1333 int indx = readUShortArg(byteCodes, i);
1334 generateCheckcast(indx, smapper);
1338 case opc_instanceof: {
1339 int indx = readUShortArg(byteCodes, i);
1340 generateInstanceOf(indx, smapper);
1345 final CharSequence v = smapper.popA();
1348 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1349 smapper.pushA(), v);
1353 case opc_monitorenter: {
1354 debug("/* monitor enter */");
1359 case opc_monitorexit: {
1360 debug("/* monitor exit */");
1371 emit(smapper, this, "throw 'unknown bytecode @1';",
1372 Integer.toString(c));
1376 generateByteCodeComment(prev, i, byteCodes);
1382 if (previousTrap != null) {
1383 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1388 while (openBraces-- > 0) {
1394 private int generateIf(StackMapper mapper, byte[] byteCodes,
1395 int i, final CharSequence v2, final CharSequence v1,
1396 final String test, int topMostLabel
1397 ) throws IOException {
1399 int indx = i + readShortArg(byteCodes, i);
1400 append("if ((").append(v1)
1401 .append(") ").append(test).append(" (")
1402 .append(v2).append(")) ");
1403 goTo(this, i, indx, topMostLabel);
1407 private int readInt4(byte[] byteCodes, int offset) {
1408 final int d = byteCodes[offset + 0] << 24;
1409 final int c = byteCodes[offset + 1] << 16;
1410 final int b = byteCodes[offset + 2] << 8;
1411 final int a = byteCodes[offset + 3];
1412 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1414 private static int readUByte(byte[] byteCodes, int offset) {
1415 return byteCodes[offset] & 0xff;
1418 private static int readUShort(byte[] byteCodes, int offset) {
1419 return ((byteCodes[offset] & 0xff) << 8)
1420 | (byteCodes[offset + 1] & 0xff);
1422 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1423 return readUShort(byteCodes, offsetInstruction + 1);
1426 private static int readShort(byte[] byteCodes, int offset) {
1427 int signed = byteCodes[offset];
1428 byte b0 = (byte)signed;
1429 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1431 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1432 return readShort(byteCodes, offsetInstruction + 1);
1435 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1437 Boolean count = null;
1438 boolean array = false;
1440 int firstPos = sig.length();
1441 while (i < descriptor.length()) {
1442 char ch = descriptor.charAt(i++);
1463 if (ch == 'J' || ch == 'D') {
1469 sig.insert(firstPos, ch);
1471 returnType[0] = '[';
1472 sig.insert(firstPos, "_3");
1481 returnType[0] = 'V';
1482 sig.insert(firstPos, 'V');
1485 int next = descriptor.indexOf(';', i);
1486 String realSig = mangleSig(descriptor, i - 1, next + 1);
1491 sig.append(realSig);
1494 sig.insert(firstPos, realSig);
1496 sig.insert(firstPos, "_3");
1498 returnType[0] = 'L';
1507 throw new IllegalStateException("Invalid char: " + ch);
1512 static String mangleSig(String sig) {
1513 return mangleSig(sig, 0, sig.length());
1516 private static String mangleMethodName(String name) {
1517 StringBuilder sb = new StringBuilder(name.length() * 2);
1518 int last = name.length();
1519 for (int i = 0; i < last; i++) {
1520 final char ch = name.charAt(i);
1522 case '_': sb.append("_1"); break;
1523 default: sb.append(ch); break;
1526 return sb.toString();
1528 private static String mangleSig(String txt, int first, int last) {
1529 StringBuilder sb = new StringBuilder((last - first) * 2);
1530 for (int i = first; i < last; i++) {
1531 final char ch = txt.charAt(i);
1533 case '/': sb.append('_'); break;
1534 case '_': sb.append("_1"); break;
1535 case ';': sb.append("_2"); break;
1536 case '[': sb.append("_3"); break;
1538 if (Character.isJavaIdentifierPart(ch)) {
1542 String hex = Integer.toHexString(ch).toLowerCase(Locale.ENGLISH);
1543 for (int m = hex.length(); m < 4; m++) {
1551 return sb.toString();
1554 private static String mangleClassName(String name) {
1555 return mangleSig(name);
1558 private static String findMethodName(MethodData m, StringBuilder cnt) {
1559 StringBuilder name = new StringBuilder();
1560 if ("<init>".equals(m.getName())) { // NOI18N
1561 name.append("cons"); // NOI18N
1562 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1563 name.append("class"); // NOI18N
1565 name.append(mangleMethodName(m.getName()));
1568 countArgs(m.getInternalSig(), new char[1], name, cnt);
1569 return name.toString();
1572 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1573 StringBuilder name = new StringBuilder();
1574 String descr = mi[2];//mi.getDescriptor();
1576 if ("<init>".equals(nm)) { // NOI18N
1577 name.append("cons"); // NOI18N
1579 name.append(mangleMethodName(nm));
1581 countArgs(descr, returnType, name, cnt);
1582 return name.toString();
1585 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1586 throws IOException {
1587 int methodIndex = readUShortArg(byteCodes, i);
1588 String[] mi = jc.getFieldInfoName(methodIndex);
1589 char[] returnType = { 'V' };
1590 StringBuilder cnt = new StringBuilder();
1591 String mn = findMethodName(mi, cnt, returnType);
1593 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1594 final CharSequence[] vars = new CharSequence[numArguments];
1596 for (int j = numArguments - 1; j >= 0; --j) {
1597 vars[j] = mapper.popValue();
1600 if (returnType[0] != 'V') {
1603 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1607 final String in = mi[0];
1609 if (callbacks && in.equals("org/apidesign/html/boot/spi/Fn")) {
1610 mcn = "java_lang_Class";
1612 mcn = mangleClassName(in);
1614 String object = accessClass(mcn) + "(false)";
1615 if (mn.startsWith("cons_")) {
1616 object += ".constructor";
1618 append(accessStaticMethod(object, mn, mi));
1624 if (numArguments > 0) {
1626 for (int j = 1; j < numArguments; ++j) {
1636 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1637 throws IOException {
1638 int methodIndex = readUShortArg(byteCodes, i);
1639 String[] mi = jc.getFieldInfoName(methodIndex);
1640 char[] returnType = { 'V' };
1641 StringBuilder cnt = new StringBuilder();
1642 String mn = findMethodName(mi, cnt, returnType);
1644 final int numArguments = cnt.length() + 1;
1645 final CharSequence[] vars = new CharSequence[numArguments];
1647 for (int j = numArguments - 1; j >= 0; --j) {
1648 vars[j] = mapper.popValue();
1651 if (returnType[0] != 'V') {
1653 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1657 append(accessVirtualMethod(vars[0].toString(), mn, mi));
1660 for (int j = 1; j < numArguments; ++j) {
1670 private void addReference(String cn) throws IOException {
1671 if (requireReference(cn)) {
1672 debug(" /* needs " + cn + " */");
1676 private void outType(String d, StringBuilder out) {
1678 while (d.charAt(0) == '[') {
1682 if (d.charAt(0) == 'L') {
1683 assert d.charAt(d.length() - 1) == ';';
1684 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1690 private String encodeConstant(int entryIndex) throws IOException {
1691 String[] classRef = { null };
1692 String s = jc.stringValue(entryIndex, classRef);
1693 if (classRef[0] != null) {
1694 if (classRef[0].startsWith("[")) {
1695 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1697 addReference(classRef[0]);
1698 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1704 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1705 byte[] arr = m.findAnnotationData(true);
1709 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1710 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1711 class P extends AnnotationParser {
1717 String[] args = new String[30];
1723 protected void visitAttr(String type, String attr, String at, String value) {
1724 if (type.equals(jvmType)) {
1725 if ("body".equals(attr)) {
1727 } else if ("args".equals(attr)) {
1728 args[cnt++] = value;
1730 throw new IllegalArgumentException(attr);
1733 if (type.equals(htmlType)) {
1735 if ("body".equals(attr)) {
1737 } else if ("args".equals(attr)) {
1738 args[cnt++] = value;
1739 } else if ("javacall".equals(attr)) {
1740 javacall = "1".equals(value);
1742 throw new IllegalArgumentException(attr);
1749 if (p.body == null) {
1752 StringBuilder cnt = new StringBuilder();
1753 final String mn = findMethodName(m, cnt);
1754 append(destObject).append(".").append(mn);
1755 append(" = function(");
1758 StringBuilder toValue = new StringBuilder();
1759 for (int i = 0; i < cnt.length(); i++) {
1761 space = outputArg(this, p.args, index);
1762 if (p.html4j && space.length() > 0) {
1763 toValue.append("\n ").append(p.args[index]).append(" = ")
1764 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1765 append(p.args[index]).append(");");
1769 append(") {").append("\n");
1770 append(toValue.toString());
1772 int lastSlash = jc.getClassName().lastIndexOf('/');
1773 final String pkg = jc.getClassName().substring(0, lastSlash);
1774 append(mangleCallbacks(pkg, p.body));
1775 requireReference(pkg + "/$JsCallbacks$");
1783 private static CharSequence mangleCallbacks(String pkgName, String body) {
1784 StringBuilder sb = new StringBuilder();
1787 int next = body.indexOf(".@", pos);
1789 sb.append(body.substring(pos));
1790 body = sb.toString();
1795 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1800 String refId = body.substring(ident, next);
1802 sb.append(body.substring(pos, ident));
1804 int sigBeg = body.indexOf('(', next);
1805 int sigEnd = body.indexOf(')', sigBeg);
1806 int colon4 = body.indexOf("::", next);
1807 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1808 throw new IllegalStateException("Malformed body " + body);
1810 String fqn = body.substring(next + 2, colon4);
1811 String method = body.substring(colon4 + 2, sigBeg);
1812 String params = body.substring(sigBeg, sigEnd + 1);
1814 int paramBeg = body.indexOf('(', sigEnd + 1);
1816 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1817 sb.append(mangleJsCallbacks(fqn, method, params, false));
1818 sb.append("(").append(refId);
1819 if (body.charAt(paramBeg + 1) != ')') {
1827 int next = body.indexOf("@", pos);
1832 sb.append(body.substring(pos));
1836 sb = new StringBuilder();
1839 sb.append(body.substring(pos, next));
1841 int sigBeg = body.indexOf('(', next);
1842 int sigEnd = body.indexOf(')', sigBeg);
1843 int colon4 = body.indexOf("::", next);
1844 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1845 throw new IllegalStateException("Malformed body " + body);
1847 String fqn = body.substring(next + 1, colon4);
1848 String method = body.substring(colon4 + 2, sigBeg);
1849 String params = body.substring(sigBeg, sigEnd + 1);
1851 int paramBeg = body.indexOf('(', sigEnd + 1);
1853 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1854 sb.append(mangleJsCallbacks(fqn, method, params, true));
1860 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1861 if (params.startsWith("(")) {
1862 params = params.substring(1);
1864 if (params.endsWith(")")) {
1865 params = params.substring(0, params.length() - 1);
1867 StringBuilder sb = new StringBuilder();
1868 final String fqnu = fqn.replace('.', '_');
1869 final String rfqn = mangleClassName(fqnu);
1870 final String rm = mangleMethodName(method);
1873 StringBuilder pb = new StringBuilder();
1874 int len = params.length();
1876 while (indx < len) {
1877 char ch = params.charAt(indx);
1878 if (ch == '[' || ch == 'L') {
1879 pb.append("Ljava/lang/Object;");
1880 indx = params.indexOf(';', indx) + 1;
1886 srp = mangleSig(pb.toString());
1888 final String rp = mangleSig(params);
1889 final String mrp = mangleMethodName(rp);
1890 sb.append(rfqn).append("$").append(rm).
1891 append('$').append(mrp).append("__Ljava_lang_Object_2");
1893 sb.append('L').append(fqnu).append("_2");
1896 return sb.toString();
1899 private static String className(ClassData jc) {
1900 //return jc.getName().getInternalName().replace('/', '_');
1901 return mangleClassName(jc.getClassName());
1904 private static String[] findAnnotation(
1905 byte[] arr, ClassData cd, final String className,
1906 final String... attrNames
1907 ) throws IOException {
1911 final String[] values = new String[attrNames.length];
1912 final boolean[] found = { false };
1913 final String jvmType = "L" + className.replace('.', '/') + ";";
1914 AnnotationParser ap = new AnnotationParser(false, true) {
1916 protected void visitAttr(String type, String attr, String at, String value) {
1917 if (type.equals(jvmType)) {
1919 for (int i = 0; i < attrNames.length; i++) {
1920 if (attrNames[i].equals(attr)) {
1929 return found[0] ? values : null;
1932 private CharSequence initField(FieldData v) {
1933 final String is = v.getInternalSig();
1934 if (is.length() == 1) {
1935 switch (is.charAt(0)) {
1941 case 'I': return " = 0;";
1943 case 'D': return " = 0.0;";
1945 throw new IllegalStateException(is);
1951 private void generateAnno(ClassData cd, byte[] data) throws IOException {
1952 AnnotationParser ap = new AnnotationParser(true, false) {
1953 int[] cnt = new int[32];
1957 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
1958 final String slashType = attrType.substring(1, attrType.length() - 1);
1959 requireReference(slashType);
1961 if (cnt[depth]++ > 0) {
1965 append('"').append(attrType).append("\" : ");
1972 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
1978 protected void visitValueStart(String attrName, char type) throws IOException {
1979 if (cnt[depth]++ > 0) {
1983 if (attrName != null) {
1984 append('"').append(attrName).append("\" : ");
1992 protected void visitValueEnd(String attrName, char type) throws IOException {
2000 protected void visitAttr(String type, String attr, String attrType, String value)
2001 throws IOException {
2002 if (attr == null && value == null) {
2009 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2010 throws IOException {
2011 final String slashType = attrType.substring(1, attrType.length() - 1);
2012 requireReference(slashType);
2014 final String cn = mangleClassName(slashType);
2015 append(accessClass(cn))
2016 .append("(false)['valueOf__L").
2018 append("_2Ljava_lang_String_2']('").
2026 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2027 final String name = args[indx];
2031 if (name.contains(",")) {
2032 throw new IOException("Wrong parameter with ',': " + name);
2038 final void emitNoFlush(
2040 final String format, final CharSequence... params
2041 ) throws IOException {
2042 emitImpl(this, format, params);
2044 static final void emit(
2046 final Appendable out,
2047 final String format, final CharSequence... params
2048 ) throws IOException {
2050 emitImpl(out, format, params);
2052 static void emitImpl(final Appendable out,
2053 final String format,
2054 final CharSequence... params) throws IOException {
2055 final int length = format.length();
2058 int paramOffset = format.indexOf('@');
2059 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2060 final char paramChar = format.charAt(paramOffset + 1);
2061 if ((paramChar >= '1') && (paramChar <= '9')) {
2062 final int paramIndex = paramChar - '0' - 1;
2064 out.append(format, processed, paramOffset);
2065 out.append(params[paramIndex]);
2068 processed = paramOffset + 1;
2071 paramOffset = format.indexOf('@', paramOffset + 1);
2074 out.append(format, processed, length);
2077 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2078 append("} catch (e) {\n");
2080 for (TrapData e : traps) {
2084 if (e.catch_cpx != 0) { //not finally
2085 final String classInternalName = jc.getClassName(e.catch_cpx);
2086 addReference(classInternalName);
2087 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2088 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2089 append("var stA0 = e;");
2090 goTo(this, current, e.handler_pc, topMostLabel);
2093 finallyPC = e.handler_pc;
2096 if (finallyPC == -1) {
2099 append("var stA0 = e;");
2100 goTo(this, current, finallyPC, topMostLabel);
2105 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2108 out.append("{ gt = 0; continue X_" + to + "; }");
2110 out.append("{ gt = " + to + "; continue X_0; }");
2113 out.append("{ gt = " + to + "; break IF; }");
2117 private static void emitIf(
2119 Appendable out, String pattern,
2121 int current, int to, int canBack
2122 ) throws IOException {
2124 emitImpl(out, pattern, param);
2125 goTo(out, current, to, canBack);
2128 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2131 case 4: jvmType = "[Z"; break;
2132 case 5: jvmType = "[C"; break;
2133 case 6: jvmType = "[F"; break;
2134 case 7: jvmType = "[D"; break;
2135 case 8: jvmType = "[B"; break;
2136 case 9: jvmType = "[S"; break;
2137 case 10: jvmType = "[I"; break;
2138 case 11: jvmType = "[J"; break;
2139 default: throw new IllegalStateException("Array type: " + atype);
2142 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2143 smapper.popI(), smapper.pushA(), jvmType);
2146 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2147 String typeName = jc.getClassName(type);
2148 String ref = "null";
2149 if (typeName.startsWith("[")) {
2150 typeName = "'[" + typeName + "'";
2152 ref = "vm." + mangleClassName(typeName);
2153 typeName = "'[L" + typeName + ";'";
2156 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2157 smapper.popI(), smapper.pushA(), typeName, ref);
2160 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2161 String typeName = jc.getClassName(type);
2162 int dim = readUByte(byteCodes, ++i);
2163 StringBuilder dims = new StringBuilder();
2165 for (int d = 0; d < dim; d++) {
2167 dims.insert(1, ",");
2169 dims.insert(1, smapper.popI());
2173 if (typeName.charAt(dim) == 'L') {
2174 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2177 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2178 dims.toString(), smapper.pushA(), typeName, fn
2183 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2184 int table = i / 4 * 4 + 4;
2185 int dflt = i + readInt4(byteCodes, table);
2187 int low = readInt4(byteCodes, table);
2189 int high = readInt4(byteCodes, table);
2191 final CharSequence swVar = smapper.popValue();
2192 smapper.flush(this);
2193 append("switch (").append(swVar).append(") {\n");
2194 while (low <= high) {
2195 int offset = i + readInt4(byteCodes, table);
2197 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2200 append(" default: ");
2201 goTo(this, i, dflt, topMostLabel);
2207 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2208 int table = i / 4 * 4 + 4;
2209 int dflt = i + readInt4(byteCodes, table);
2211 int n = readInt4(byteCodes, table);
2213 final CharSequence swVar = smapper.popValue();
2214 smapper.flush(this);
2215 append("switch (").append(swVar).append(") {\n");
2217 int cnstnt = readInt4(byteCodes, table);
2219 int offset = i + readInt4(byteCodes, table);
2221 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2223 append(" default: ");
2224 goTo(this, i, dflt, topMostLabel);
2230 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2231 String type = jc.getClassName(indx);
2232 if (!type.startsWith("[")) {
2234 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2235 smapper.popA(), smapper.pushI(),
2236 type.replace('/', '_'));
2239 while (type.charAt(cnt) == '[') {
2242 if (type.charAt(cnt) == 'L') {
2243 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2245 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2246 smapper.popA(), smapper.pushI(),
2251 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2252 smapper.popA(), smapper.pushI(), type
2258 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2259 String type = jc.getClassName(indx);
2260 if (!type.startsWith("[")) {
2261 emitNoFlush(smapper,
2262 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2263 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2266 while (type.charAt(cnt) == '[') {
2269 if (type.charAt(cnt) == 'L') {
2270 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2271 emitNoFlush(smapper,
2272 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2273 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2276 emitNoFlush(smapper,
2277 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2278 smapper.getT(0, VarType.REFERENCE, false), type
2284 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2285 for (int j = prev; j <= i; j++) {
2287 final int cc = readUByte(byteCodes, j);
2288 append(Integer.toString(cc));