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 String[] only = findAnnotation(onlyArr, jc,
233 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
237 if (only[0] != null && only[1] != null) {
238 append("\n p.").append(only[0]).append(" = ")
239 .append(only[1]).append(";");
248 mn = generateStaticMethod(destObject, m, toInitilize);
250 if (m.isConstructor()) {
252 mn = generateInstanceMethod(destObject, m);
255 mn = generateInstanceMethod(destObject, m);
258 declaredMethod(m, destObject, mn);
259 byte[] runAnno = m.findAnnotationData(false);
260 if (runAnno != null) {
261 append("\n ").append(destObject).append(".").append(mn).append(".anno = {");
262 generateAnno(jc, runAnno);
265 append("\n ").append(destObject).append(".").append(mn).append(".access = " + m.getAccess()).append(";");
266 append("\n ").append(destObject).append(".").append(mn).append(".cls = CLS;");
268 append("\n c.constructor = CLS;");
269 append("\n function fillInstOf(x) {");
270 String instOfName = "$instOf_" + className;
271 append("\n x['").append(instOfName).append("'] = true;");
272 for (String superInterface : jc.getSuperInterfaces()) {
273 String intrfc = superInterface.replace('/', '_');
274 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
275 requireReference(superInterface);
278 append("\n c['fillInstOf'] = fillInstOf;");
279 append("\n fillInstOf(c);");
280 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
281 append("\n CLS.$class = 'temp';");
282 append("\n CLS.$class = ");
283 append(accessClass("java_lang_Class(true);"));
284 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
285 append("\n CLS.$class.superclass = sprcls;");
286 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
287 append("\n CLS.$class.cnstr = CLS;");
288 byte[] classAnno = jc.findAnnotationData(false);
289 if (classAnno != null) {
290 append("\n CLS.$class.anno = {");
291 generateAnno(jc, classAnno);
294 for (String init : toInitilize.toArray()) {
295 append("\n ").append(init).append("();");
298 append("\n if (arguments.length === 0) {");
299 append("\n if (!(this instanceof CLS)) {");
300 append("\n return new CLS();");
302 for (FieldData v : jc.getFields()) {
303 byte[] onlyArr = v.findAnnotationData(true);
304 String[] only = findAnnotation(onlyArr, jc,
305 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
309 if (only[0] != null && only[1] != null) {
310 append("\n p.").append(only[0]).append(" = ")
311 .append(only[1]).append(";");
316 append("\n this.fld_").
317 append(className).append('_').
318 append(v.getName()).append(initField(v));
321 append("\n return this;");
323 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
326 declaredClass(jc, className);
328 // StringBuilder sb = new StringBuilder();
329 // for (String init : toInitilize.toArray()) {
330 // sb.append("\n").append(init).append("();");
334 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
335 String jsb = javaScriptBody(destObject, m, true);
339 final String mn = findMethodName(m, new StringBuilder());
340 if (mn.equals("class__V")) {
341 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
343 generateMethod(destObject, mn, m);
347 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
348 String jsb = javaScriptBody(destObject, m, false);
352 final String mn = findMethodName(m, new StringBuilder());
353 generateMethod(destObject, mn, m);
357 private void generateMethod(String destObject, String name, MethodData m)
359 final StackMapIterator stackMapIterator = m.createStackMapIterator();
360 TrapDataIterator trap = m.getTrapDataIterator();
361 final LocalsMapper lmapper =
362 new LocalsMapper(stackMapIterator.getArguments());
364 append(destObject).append(".").append(name).append(" = function(");
365 lmapper.outputArguments(this, m.isStatic());
366 append(") {").append("\n");
368 final byte[] byteCodes = m.getCode();
369 if (byteCodes == null) {
370 append(" throw 'no code found for ")
371 .append(jc.getClassName()).append('.')
372 .append(m.getName()).append("';\n");
377 final StackMapper smapper = new StackMapper();
380 append(" var ").append(" lcA0 = this;\n");
384 TrapData[] previousTrap = null;
385 boolean wide = false;
387 if (stackMapIterator.isEmpty()) {
393 append("\n var gt = 0;\n");
397 int topMostLabel = 0;
398 for (int i = 0; i < byteCodes.length; i++) {
401 stackMapIterator.advanceTo(i);
402 boolean changeInCatch = trap.advanceTo(i);
403 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
404 if (previousTrap != null) {
405 generateCatch(previousTrap, i, topMostLabel);
409 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
414 if (openBraces > 64) {
415 for (int c = 0; c < 64; c++) {
422 lastStackFrame = stackMapIterator.getFrameIndex();
423 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
424 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
425 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
427 changeInCatch = true;
429 debug(" /* " + i + " */ ");
431 if (changeInCatch && trap.useTry()) {
433 previousTrap = trap.current();
435 final int c = readUByte(byteCodes, i);
438 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
441 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
444 smapper.assign(this, VarType.LONG, lmapper.getL(0));
447 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
450 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
453 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
456 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
459 smapper.assign(this, VarType.LONG, lmapper.getL(1));
462 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
465 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
468 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
471 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
474 smapper.assign(this, VarType.LONG, lmapper.getL(2));
477 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
480 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
483 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
486 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
489 smapper.assign(this, VarType.LONG, lmapper.getL(3));
492 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
495 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
499 final int indx = wide ? readUShort(byteCodes, i++)
500 : readUByte(byteCodes, i);
502 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
507 final int indx = wide ? readUShort(byteCodes, i++)
508 : readUByte(byteCodes, i);
510 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
515 final int indx = wide ? readUShort(byteCodes, i++)
516 : readUByte(byteCodes, i);
518 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
523 final int indx = wide ? readUShort(byteCodes, i++)
524 : readUByte(byteCodes, i);
526 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
531 final int indx = wide ? readUShort(byteCodes, i++)
532 : readUByte(byteCodes, i);
534 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
539 final int indx = wide ? readUShort(byteCodes, i++)
540 : readUByte(byteCodes, i);
542 emit(smapper, this, "var @1 = @2;",
543 lmapper.setI(indx), smapper.popI());
548 final int indx = wide ? readUShort(byteCodes, i++)
549 : readUByte(byteCodes, i);
551 emit(smapper, this, "var @1 = @2;",
552 lmapper.setL(indx), smapper.popL());
557 final int indx = wide ? readUShort(byteCodes, i++)
558 : readUByte(byteCodes, i);
560 emit(smapper, this, "var @1 = @2;",
561 lmapper.setF(indx), smapper.popF());
566 final int indx = wide ? readUShort(byteCodes, i++)
567 : readUByte(byteCodes, i);
569 emit(smapper, this, "var @1 = @2;",
570 lmapper.setD(indx), smapper.popD());
575 final int indx = wide ? readUShort(byteCodes, i++)
576 : readUByte(byteCodes, i);
578 emit(smapper, this, "var @1 = @2;",
579 lmapper.setA(indx), smapper.popA());
583 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
586 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
589 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
592 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
595 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
598 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
601 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
604 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
607 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
610 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
613 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
616 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
619 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
622 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
625 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
628 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
631 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
634 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
637 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
640 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
643 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
646 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
649 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
652 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
655 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
658 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
661 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
664 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
667 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
670 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
673 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
676 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
679 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
680 smapper.getI(1), smapper.popI());
683 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
684 smapper.getL(1), smapper.popL());
687 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
690 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
693 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
694 smapper.getI(1), smapper.popI());
697 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
698 smapper.getL(1), smapper.popL());
701 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
704 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
707 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
710 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
713 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
716 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
719 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
722 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
725 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
728 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
731 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
734 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
737 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
740 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
743 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
746 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
749 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
752 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
756 final int varIndx = wide ? readUShort(byteCodes, i++)
757 : readUByte(byteCodes, i);
759 final int incrBy = wide ? readShort(byteCodes, i++)
763 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
765 emit(smapper, this, "@1 += @2;",
766 lmapper.getI(varIndx),
767 Integer.toString(incrBy));
772 emit(smapper, this, "return;");
775 emit(smapper, this, "return @1;", smapper.popI());
778 emit(smapper, this, "return @1;", smapper.popL());
781 emit(smapper, this, "return @1;", smapper.popF());
784 emit(smapper, this, "return @1;", smapper.popD());
787 emit(smapper, this, "return @1;", smapper.popA());
790 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
793 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
796 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
799 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
803 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
806 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
809 smapper.replace(this, VarType.DOUBLE, "@1",
813 smapper.replace(this, VarType.FLOAT, "@1",
817 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
821 smapper.replace(this, VarType.LONG, "(@1).toLong()",
825 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
829 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
832 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
837 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
839 case opc_aconst_null:
840 smapper.assign(this, VarType.REFERENCE, "null");
843 smapper.assign(this, VarType.INTEGER, "-1");
846 smapper.assign(this, VarType.INTEGER, "0");
849 smapper.assign(this, VarType.DOUBLE, "0");
852 smapper.assign(this, VarType.LONG, "0");
855 smapper.assign(this, VarType.FLOAT, "0");
858 smapper.assign(this, VarType.INTEGER, "1");
861 smapper.assign(this, VarType.LONG, "1");
864 smapper.assign(this, VarType.FLOAT, "1");
867 smapper.assign(this, VarType.DOUBLE, "1");
870 smapper.assign(this, VarType.INTEGER, "2");
873 smapper.assign(this, VarType.FLOAT, "2");
876 smapper.assign(this, VarType.INTEGER, "3");
879 smapper.assign(this, VarType.INTEGER, "4");
882 smapper.assign(this, VarType.INTEGER, "5");
885 int indx = readUByte(byteCodes, ++i);
886 String v = encodeConstant(indx);
887 int type = VarType.fromConstantType(jc.getTag(indx));
888 smapper.assign(this, type, v);
893 int indx = readUShortArg(byteCodes, i);
895 String v = encodeConstant(indx);
896 int type = VarType.fromConstantType(jc.getTag(indx));
897 if (type == VarType.LONG) {
898 final Long lv = new Long(v);
899 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
900 final int hi = (int)(lv.longValue() >> 32);
902 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
904 smapper.assign(this, VarType.LONG,
905 "0x" + Integer.toHexString(hi) + ".next32(0x" +
906 Integer.toHexString(low) + ")"
910 smapper.assign(this, type, v);
915 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
919 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
923 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
926 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
927 "===", topMostLabel);
930 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
931 "!==", topMostLabel);
934 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
938 int indx = i + readShortArg(byteCodes, i);
939 emitIf(smapper, this, "if ((@1) == 0) ",
940 smapper.popI(), i, indx, topMostLabel);
945 int indx = i + readShortArg(byteCodes, i);
946 emitIf(smapper, this, "if ((@1) != 0) ",
947 smapper.popI(), i, indx, topMostLabel);
952 int indx = i + readShortArg(byteCodes, i);
953 emitIf(smapper, this, "if ((@1) < 0) ",
954 smapper.popI(), i, indx, topMostLabel);
959 int indx = i + readShortArg(byteCodes, i);
960 emitIf(smapper, this, "if ((@1) <= 0) ",
961 smapper.popI(), i, indx, topMostLabel);
966 int indx = i + readShortArg(byteCodes, i);
967 emitIf(smapper, this, "if ((@1) > 0) ",
968 smapper.popI(), i, indx, topMostLabel);
973 int indx = i + readShortArg(byteCodes, i);
974 emitIf(smapper, this, "if ((@1) >= 0) ",
975 smapper.popI(), i, indx, topMostLabel);
979 case opc_ifnonnull: {
980 int indx = i + readShortArg(byteCodes, i);
981 emitIf(smapper, this, "if ((@1) !== null) ",
982 smapper.popA(), i, indx, topMostLabel);
987 int indx = i + readShortArg(byteCodes, i);
988 emitIf(smapper, this, "if ((@1) === null) ",
989 smapper.popA(), i, indx, topMostLabel);
994 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
998 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1002 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1003 "<=", topMostLabel);
1006 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1010 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1011 ">=", topMostLabel);
1014 smapper.flush(this);
1015 int indx = i + readShortArg(byteCodes, i);
1016 goTo(this, i, indx, topMostLabel);
1020 case opc_lookupswitch: {
1021 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1024 case opc_tableswitch: {
1025 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1028 case opc_invokeinterface: {
1029 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1032 case opc_invokevirtual:
1033 i = invokeVirtualMethod(byteCodes, i, smapper);
1035 case opc_invokespecial:
1036 i = invokeStaticMethod(byteCodes, i, smapper, false);
1038 case opc_invokestatic:
1039 i = invokeStaticMethod(byteCodes, i, smapper, true);
1042 int indx = readUShortArg(byteCodes, i);
1043 String ci = jc.getClassName(indx);
1044 emit(smapper, this, "var @1 = new @2;",
1045 smapper.pushA(), accessClass(mangleClassName(ci)));
1051 int atype = readUByte(byteCodes, ++i);
1052 generateNewArray(atype, smapper);
1054 case opc_anewarray: {
1055 int type = readUShortArg(byteCodes, i);
1057 generateANewArray(type, smapper);
1060 case opc_multianewarray: {
1061 int type = readUShortArg(byteCodes, i);
1063 i = generateMultiANewArray(type, byteCodes, i, smapper);
1066 case opc_arraylength:
1067 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1070 emit(smapper, this, "Array.at(@3, @2, @1);",
1071 smapper.popL(), smapper.popI(), smapper.popA());
1074 emit(smapper, this, "Array.at(@3, @2, @1);",
1075 smapper.popF(), smapper.popI(), smapper.popA());
1078 emit(smapper, this, "Array.at(@3, @2, @1);",
1079 smapper.popD(), smapper.popI(), smapper.popA());
1082 emit(smapper, this, "Array.at(@3, @2, @1);",
1083 smapper.popA(), smapper.popI(), smapper.popA());
1089 emit(smapper, this, "Array.at(@3, @2, @1);",
1090 smapper.popI(), smapper.popI(), smapper.popA());
1093 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1094 smapper.popI(), smapper.getA(0));
1097 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1098 smapper.popI(), smapper.getA(0));
1101 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1102 smapper.popI(), smapper.getA(0));
1105 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1106 smapper.popI(), smapper.getA(0));
1112 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1113 smapper.popI(), smapper.getA(0));
1121 final Variable v = smapper.get(0);
1122 if (smapper.isDirty()) {
1123 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1125 smapper.assign(this, v.getType(), v);
1130 final Variable vi1 = smapper.get(0);
1132 if (vi1.isCategory2()) {
1133 emit(smapper, this, "var @1 = @2;",
1134 smapper.pushT(vi1.getType()), vi1);
1136 final Variable vi2 = smapper.get(1);
1137 emit(smapper, this, "var @1 = @2, @3 = @4;",
1138 smapper.pushT(vi2.getType()), vi2,
1139 smapper.pushT(vi1.getType()), vi1);
1144 final Variable vi1 = smapper.pop(this);
1145 final Variable vi2 = smapper.pop(this);
1146 final Variable vo3 = smapper.pushT(vi1.getType());
1147 final Variable vo2 = smapper.pushT(vi2.getType());
1148 final Variable vo1 = smapper.pushT(vi1.getType());
1150 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1151 vo1, vi1, vo2, vi2, vo3, vo1);
1155 final Variable vi1 = smapper.pop(this);
1156 final Variable vi2 = smapper.pop(this);
1158 if (vi1.isCategory2()) {
1159 final Variable vo3 = smapper.pushT(vi1.getType());
1160 final Variable vo2 = smapper.pushT(vi2.getType());
1161 final Variable vo1 = smapper.pushT(vi1.getType());
1163 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1164 vo1, vi1, vo2, vi2, vo3, vo1);
1166 final Variable vi3 = smapper.pop(this);
1167 final Variable vo5 = smapper.pushT(vi2.getType());
1168 final Variable vo4 = smapper.pushT(vi1.getType());
1169 final Variable vo3 = smapper.pushT(vi3.getType());
1170 final Variable vo2 = smapper.pushT(vi2.getType());
1171 final Variable vo1 = smapper.pushT(vi1.getType());
1173 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1174 vo1, vi1, vo2, vi2, vo3, vi3);
1175 emit(smapper, this, " @1 = @2, @3 = @4;",
1176 vo4, vo1, vo5, vo2);
1181 final Variable vi1 = smapper.pop(this);
1182 final Variable vi2 = smapper.pop(this);
1184 if (vi2.isCategory2()) {
1185 final Variable vo3 = smapper.pushT(vi1.getType());
1186 final Variable vo2 = smapper.pushT(vi2.getType());
1187 final Variable vo1 = smapper.pushT(vi1.getType());
1189 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1190 vo1, vi1, vo2, vi2, vo3, vo1);
1192 final Variable vi3 = smapper.pop(this);
1193 final Variable vo4 = smapper.pushT(vi1.getType());
1194 final Variable vo3 = smapper.pushT(vi3.getType());
1195 final Variable vo2 = smapper.pushT(vi2.getType());
1196 final Variable vo1 = smapper.pushT(vi1.getType());
1198 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1199 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1204 final Variable vi1 = smapper.pop(this);
1205 final Variable vi2 = smapper.pop(this);
1207 if (vi1.isCategory2()) {
1208 if (vi2.isCategory2()) {
1209 final Variable vo3 = smapper.pushT(vi1.getType());
1210 final Variable vo2 = smapper.pushT(vi2.getType());
1211 final Variable vo1 = smapper.pushT(vi1.getType());
1213 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1214 vo1, vi1, vo2, vi2, vo3, vo1);
1216 final Variable vi3 = smapper.pop(this);
1217 final Variable vo4 = smapper.pushT(vi1.getType());
1218 final Variable vo3 = smapper.pushT(vi3.getType());
1219 final Variable vo2 = smapper.pushT(vi2.getType());
1220 final Variable vo1 = smapper.pushT(vi1.getType());
1222 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1223 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1226 final Variable vi3 = smapper.pop(this);
1228 if (vi3.isCategory2()) {
1229 final Variable vo5 = smapper.pushT(vi2.getType());
1230 final Variable vo4 = smapper.pushT(vi1.getType());
1231 final Variable vo3 = smapper.pushT(vi3.getType());
1232 final Variable vo2 = smapper.pushT(vi2.getType());
1233 final Variable vo1 = smapper.pushT(vi1.getType());
1235 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1236 vo1, vi1, vo2, vi2, vo3, vi3);
1237 emit(smapper, this, " @1 = @2, @3 = @4;",
1238 vo4, vo1, vo5, vo2);
1240 final Variable vi4 = smapper.pop(this);
1241 final Variable vo6 = smapper.pushT(vi2.getType());
1242 final Variable vo5 = smapper.pushT(vi1.getType());
1243 final Variable vo4 = smapper.pushT(vi4.getType());
1244 final Variable vo3 = smapper.pushT(vi3.getType());
1245 final Variable vo2 = smapper.pushT(vi2.getType());
1246 final Variable vo1 = smapper.pushT(vi1.getType());
1248 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1249 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1250 emit(smapper, this, " @1 = @2, @3 = @4;",
1251 vo5, vo1, vo6, vo2);
1257 final Variable vi1 = smapper.get(0);
1258 final Variable vi2 = smapper.get(1);
1260 if (vi1.getType() == vi2.getType()) {
1261 final Variable tmp = smapper.pushT(vi1.getType());
1263 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1268 smapper.pushT(vi1.getType());
1269 smapper.pushT(vi2.getType());
1274 smapper.assign(this, VarType.INTEGER,
1275 "(" + Integer.toString(byteCodes[++i]) + ")");
1278 smapper.assign(this, VarType.INTEGER,
1279 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1283 case opc_getfield: {
1284 int indx = readUShortArg(byteCodes, i);
1285 String[] fi = jc.getFieldInfoName(indx);
1286 final int type = VarType.fromFieldType(fi[2].charAt(0));
1287 final String mangleClass = mangleClassName(fi[0]);
1288 final String mangleClassAccess = accessClass(mangleClass);
1289 smapper.replace(this, type, "@2.call(@1)",
1291 accessField(mangleClassAccess + "(false)",
1297 case opc_putfield: {
1298 int indx = readUShortArg(byteCodes, i);
1299 String[] fi = jc.getFieldInfoName(indx);
1300 final int type = VarType.fromFieldType(fi[2].charAt(0));
1301 final String mangleClass = mangleClassName(fi[0]);
1302 final String mangleClassAccess = accessClass(mangleClass);
1303 emit(smapper, this, "@3.call(@2, @1);",
1306 accessField(mangleClassAccess + "(false)",
1311 case opc_getstatic: {
1312 int indx = readUShortArg(byteCodes, i);
1313 String[] fi = jc.getFieldInfoName(indx);
1314 final int type = VarType.fromFieldType(fi[2].charAt(0));
1315 String ac = accessClass(mangleClassName(fi[0]));
1316 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1317 smapper.assign(this, type, af + "()");
1319 addReference(fi[0]);
1322 case opc_putstatic: {
1323 int indx = readUShortArg(byteCodes, i);
1324 String[] fi = jc.getFieldInfoName(indx);
1325 final int type = VarType.fromFieldType(fi[2].charAt(0));
1326 emit(smapper, this, "@1(false)._@2(@3);",
1327 accessClass(mangleClassName(fi[0])), fi[1],
1328 smapper.popT(type));
1330 addReference(fi[0]);
1333 case opc_checkcast: {
1334 int indx = readUShortArg(byteCodes, i);
1335 generateCheckcast(indx, smapper);
1339 case opc_instanceof: {
1340 int indx = readUShortArg(byteCodes, i);
1341 generateInstanceOf(indx, smapper);
1346 final CharSequence v = smapper.popA();
1349 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1350 smapper.pushA(), v);
1354 case opc_monitorenter: {
1355 debug("/* monitor enter */");
1360 case opc_monitorexit: {
1361 debug("/* monitor exit */");
1372 emit(smapper, this, "throw 'unknown bytecode @1';",
1373 Integer.toString(c));
1377 generateByteCodeComment(prev, i, byteCodes);
1383 if (previousTrap != null) {
1384 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1389 while (openBraces-- > 0) {
1395 private int generateIf(StackMapper mapper, byte[] byteCodes,
1396 int i, final CharSequence v2, final CharSequence v1,
1397 final String test, int topMostLabel
1398 ) throws IOException {
1400 int indx = i + readShortArg(byteCodes, i);
1401 append("if ((").append(v1)
1402 .append(") ").append(test).append(" (")
1403 .append(v2).append(")) ");
1404 goTo(this, i, indx, topMostLabel);
1408 private int readInt4(byte[] byteCodes, int offset) {
1409 final int d = byteCodes[offset + 0] << 24;
1410 final int c = byteCodes[offset + 1] << 16;
1411 final int b = byteCodes[offset + 2] << 8;
1412 final int a = byteCodes[offset + 3];
1413 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1415 private static int readUByte(byte[] byteCodes, int offset) {
1416 return byteCodes[offset] & 0xff;
1419 private static int readUShort(byte[] byteCodes, int offset) {
1420 return ((byteCodes[offset] & 0xff) << 8)
1421 | (byteCodes[offset + 1] & 0xff);
1423 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1424 return readUShort(byteCodes, offsetInstruction + 1);
1427 private static int readShort(byte[] byteCodes, int offset) {
1428 int signed = byteCodes[offset];
1429 byte b0 = (byte)signed;
1430 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1432 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1433 return readShort(byteCodes, offsetInstruction + 1);
1436 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1438 Boolean count = null;
1439 boolean array = false;
1441 int firstPos = sig.length();
1442 while (i < descriptor.length()) {
1443 char ch = descriptor.charAt(i++);
1464 if (ch == 'J' || ch == 'D') {
1470 sig.insert(firstPos, ch);
1472 returnType[0] = '[';
1473 sig.insert(firstPos, "_3");
1482 returnType[0] = 'V';
1483 sig.insert(firstPos, 'V');
1486 int next = descriptor.indexOf(';', i);
1487 String realSig = mangleSig(descriptor, i - 1, next + 1);
1492 sig.append(realSig);
1495 sig.insert(firstPos, realSig);
1497 sig.insert(firstPos, "_3");
1499 returnType[0] = 'L';
1508 throw new IllegalStateException("Invalid char: " + ch);
1513 static String mangleSig(String sig) {
1514 return mangleSig(sig, 0, sig.length());
1517 private static String mangleMethodName(String name) {
1518 StringBuilder sb = new StringBuilder(name.length() * 2);
1519 int last = name.length();
1520 for (int i = 0; i < last; i++) {
1521 final char ch = name.charAt(i);
1523 case '_': sb.append("_1"); break;
1524 default: sb.append(ch); break;
1527 return sb.toString();
1529 private static String mangleSig(String txt, int first, int last) {
1530 StringBuilder sb = new StringBuilder((last - first) * 2);
1531 for (int i = first; i < last; i++) {
1532 final char ch = txt.charAt(i);
1534 case '/': sb.append('_'); break;
1535 case '_': sb.append("_1"); break;
1536 case ';': sb.append("_2"); break;
1537 case '[': sb.append("_3"); break;
1539 if (Character.isJavaIdentifierPart(ch)) {
1543 String hex = Integer.toHexString(ch).toLowerCase(Locale.ENGLISH);
1544 for (int m = hex.length(); m < 4; m++) {
1552 return sb.toString();
1555 private static String mangleClassName(String name) {
1556 return mangleSig(name);
1559 private static String findMethodName(MethodData m, StringBuilder cnt) {
1560 StringBuilder name = new StringBuilder();
1561 if ("<init>".equals(m.getName())) { // NOI18N
1562 name.append("cons"); // NOI18N
1563 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1564 name.append("class"); // NOI18N
1566 name.append(mangleMethodName(m.getName()));
1569 countArgs(m.getInternalSig(), new char[1], name, cnt);
1570 return name.toString();
1573 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1574 StringBuilder name = new StringBuilder();
1575 String descr = mi[2];//mi.getDescriptor();
1577 if ("<init>".equals(nm)) { // NOI18N
1578 name.append("cons"); // NOI18N
1580 name.append(mangleMethodName(nm));
1582 countArgs(descr, returnType, name, cnt);
1583 return name.toString();
1586 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1587 throws IOException {
1588 int methodIndex = readUShortArg(byteCodes, i);
1589 String[] mi = jc.getFieldInfoName(methodIndex);
1590 char[] returnType = { 'V' };
1591 StringBuilder cnt = new StringBuilder();
1592 String mn = findMethodName(mi, cnt, returnType);
1594 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1595 final CharSequence[] vars = new CharSequence[numArguments];
1597 for (int j = numArguments - 1; j >= 0; --j) {
1598 vars[j] = mapper.popValue();
1601 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(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 append(accessClass(mangleClassName(slashType)))
2015 .append("(false).constructor.fld_").append(value);
2021 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2022 final String name = args[indx];
2026 if (name.contains(",")) {
2027 throw new IOException("Wrong parameter with ',': " + name);
2033 final void emitNoFlush(
2035 final String format, final CharSequence... params
2036 ) throws IOException {
2037 emitImpl(this, format, params);
2039 static final void emit(
2041 final Appendable out,
2042 final String format, final CharSequence... params
2043 ) throws IOException {
2045 emitImpl(out, format, params);
2047 static void emitImpl(final Appendable out,
2048 final String format,
2049 final CharSequence... params) throws IOException {
2050 final int length = format.length();
2053 int paramOffset = format.indexOf('@');
2054 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2055 final char paramChar = format.charAt(paramOffset + 1);
2056 if ((paramChar >= '1') && (paramChar <= '9')) {
2057 final int paramIndex = paramChar - '0' - 1;
2059 out.append(format, processed, paramOffset);
2060 out.append(params[paramIndex]);
2063 processed = paramOffset + 1;
2066 paramOffset = format.indexOf('@', paramOffset + 1);
2069 out.append(format, processed, length);
2072 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2073 append("} catch (e) {\n");
2075 for (TrapData e : traps) {
2079 if (e.catch_cpx != 0) { //not finally
2080 final String classInternalName = jc.getClassName(e.catch_cpx);
2081 addReference(classInternalName);
2082 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2083 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2084 append("var stA0 = e;");
2085 goTo(this, current, e.handler_pc, topMostLabel);
2088 finallyPC = e.handler_pc;
2091 if (finallyPC == -1) {
2094 append("var stA0 = e;");
2095 goTo(this, current, finallyPC, topMostLabel);
2100 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2103 out.append("{ gt = 0; continue X_" + to + "; }");
2105 out.append("{ gt = " + to + "; continue X_0; }");
2108 out.append("{ gt = " + to + "; break IF; }");
2112 private static void emitIf(
2114 Appendable out, String pattern,
2116 int current, int to, int canBack
2117 ) throws IOException {
2119 emitImpl(out, pattern, param);
2120 goTo(out, current, to, canBack);
2123 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2126 case 4: jvmType = "[Z"; break;
2127 case 5: jvmType = "[C"; break;
2128 case 6: jvmType = "[F"; break;
2129 case 7: jvmType = "[D"; break;
2130 case 8: jvmType = "[B"; break;
2131 case 9: jvmType = "[S"; break;
2132 case 10: jvmType = "[I"; break;
2133 case 11: jvmType = "[J"; break;
2134 default: throw new IllegalStateException("Array type: " + atype);
2137 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2138 smapper.popI(), smapper.pushA(), jvmType);
2141 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2142 String typeName = jc.getClassName(type);
2143 String ref = "null";
2144 if (typeName.startsWith("[")) {
2145 typeName = "'[" + typeName + "'";
2147 ref = "vm." + mangleClassName(typeName);
2148 typeName = "'[L" + typeName + ";'";
2151 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2152 smapper.popI(), smapper.pushA(), typeName, ref);
2155 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2156 String typeName = jc.getClassName(type);
2157 int dim = readUByte(byteCodes, ++i);
2158 StringBuilder dims = new StringBuilder();
2160 for (int d = 0; d < dim; d++) {
2162 dims.insert(1, ",");
2164 dims.insert(1, smapper.popI());
2168 if (typeName.charAt(dim) == 'L') {
2169 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2172 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2173 dims.toString(), smapper.pushA(), typeName, fn
2178 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2179 int table = i / 4 * 4 + 4;
2180 int dflt = i + readInt4(byteCodes, table);
2182 int low = readInt4(byteCodes, table);
2184 int high = readInt4(byteCodes, table);
2186 final CharSequence swVar = smapper.popValue();
2187 smapper.flush(this);
2188 append("switch (").append(swVar).append(") {\n");
2189 while (low <= high) {
2190 int offset = i + readInt4(byteCodes, table);
2192 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2195 append(" default: ");
2196 goTo(this, i, dflt, topMostLabel);
2202 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2203 int table = i / 4 * 4 + 4;
2204 int dflt = i + readInt4(byteCodes, table);
2206 int n = readInt4(byteCodes, table);
2208 final CharSequence swVar = smapper.popValue();
2209 smapper.flush(this);
2210 append("switch (").append(swVar).append(") {\n");
2212 int cnstnt = readInt4(byteCodes, table);
2214 int offset = i + readInt4(byteCodes, table);
2216 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2218 append(" default: ");
2219 goTo(this, i, dflt, topMostLabel);
2225 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2226 String type = jc.getClassName(indx);
2227 if (!type.startsWith("[")) {
2229 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2230 smapper.popA(), smapper.pushI(),
2231 type.replace('/', '_'));
2234 while (type.charAt(cnt) == '[') {
2237 if (type.charAt(cnt) == 'L') {
2238 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2240 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2241 smapper.popA(), smapper.pushI(),
2246 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2247 smapper.popA(), smapper.pushI(), type
2253 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2254 String type = jc.getClassName(indx);
2255 if (!type.startsWith("[")) {
2256 emitNoFlush(smapper,
2257 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2258 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2261 while (type.charAt(cnt) == '[') {
2264 if (type.charAt(cnt) == 'L') {
2265 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2266 emitNoFlush(smapper,
2267 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2268 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2271 emitNoFlush(smapper,
2272 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2273 smapper.getT(0, VarType.REFERENCE, false), type
2279 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2280 for (int j = prev; j <= i; j++) {
2282 final int cc = readUByte(byteCodes, j);
2283 append(Integer.toString(cc));