1st step in eliminating Class.forName when working with array types. Class.getComponentType on directly allocated arrays does not need that.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
24 /** Translator of the code inside class files to JavaScript.
26 * @author Jaroslav Tulach <jtulach@netbeans.org>
28 abstract class ByteCodeToJavaScript implements Appendable {
30 private final Appendable out;
31 private boolean outChanged;
32 private boolean callbacks;
34 protected ByteCodeToJavaScript(Appendable out) {
39 public final Appendable append(CharSequence csq) throws IOException {
46 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
47 out.append(csq, start, end);
53 public final Appendable append(char c) throws IOException {
59 /* Collects additional required resources.
61 * @param internalClassName classes that were referenced and should be loaded in order the
62 * generated JavaScript code works properly. The names are in internal
63 * JVM form so String is <code>java/lang/String</code>.
65 protected abstract boolean requireReference(String internalClassName);
68 * @param resourcePath name of resources to read
70 protected abstract void requireScript(String resourcePath) throws IOException;
72 /** Allows subclasses to redefine what field a function representing a
73 * class gets assigned. By default it returns the suggested name followed
74 * by <code>" = "</code>;
76 * @param className suggested name of the class
78 /* protected */ String assignClass(String className) {
79 return className + " = ";
81 /* protected */ String accessClass(String classOperation) {
82 return classOperation;
85 protected String accessField(String object, String mangledName,
86 String[] fieldInfoName) throws IOException {
87 return object + "." + mangledName;
90 protected String accessStaticMethod(
93 String[] fieldInfoName) throws IOException {
94 return object + "." + mangledName;
97 protected String accessVirtualMethod(
100 String[] fieldInfoName) throws IOException {
101 return object + "." + mangledName;
104 protected void declaredClass(ClassData classData, String mangledName)
108 protected void declaredField(FieldData fieldData,
110 String mangledName) throws IOException {
113 protected void declaredMethod(MethodData methodData,
115 String mangledName) throws IOException {
118 /** Prints out a debug message.
120 * @param msg the message
121 * @return true if the message has been printed
122 * @throws IOException
124 boolean debug(String msg) throws IOException {
130 * Converts a given class file to a JavaScript version.
132 * @param classFile input stream with code of the .class file
133 * @return the initialization code for this class, if any. Otherwise <code>null</code>
135 * @throws IOException if something goes wrong during read or write or translating
138 public String compile(InputStream classFile) throws IOException {
139 return compile(new ClassData(classFile));
142 protected String compile(ClassData classData) throws IOException {
144 this.callbacks = this.jc.getClassName().endsWith("/$JsCallbacks$");
145 if (jc.getMajor_version() < 50) {
146 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
147 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
150 byte[] arrData = jc.findAnnotationData(true);
152 String[] arr = findAnnotation(arrData, jc,
153 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
154 "resource", "processByteCode"
157 if (!arr[0].isEmpty()) {
158 requireScript(arr[0]);
160 if ("0".equals(arr[1])) {
166 String[] arr = findAnnotation(arrData, jc,
167 "net.java.html.js.JavaScriptResource",
171 if (arr[0].startsWith("/")) {
172 requireScript(arr[0]);
174 int last = jc.getClassName().lastIndexOf('/');
176 jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0]
181 String[] proto = findAnnotation(arrData, jc,
182 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
183 "container", "prototype"
185 StringArray toInitilize = new StringArray();
186 final String className = className(jc);
187 append("\n\n").append(assignClass(className));
188 append("function ").append(className).append("() {");
189 append("\n var CLS = ").append(className).append(';');
190 append("\n if (!CLS.$class) {");
192 String sc = jc.getSuperClassName(); // with _
193 append("\n var pp = ").
194 append(accessClass(mangleClassName(sc))).append("(true);");
195 append("\n var p = CLS.prototype = pp;");
196 append("\n var c = p;");
197 append("\n var sprcls = pp.constructor.$class;");
199 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
200 if (proto[0] == null) {
203 append("\n var c = ").append(proto[0]).append(";");
204 append("\n var sprcls = null;");
206 for (FieldData v : jc.getFields()) {
208 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
209 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
213 append("\n CLS.fld_").append(v.getName()).append(initField(v));
214 append("\n c._").append(v.getName()).append(" = function (v) {")
215 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
216 .append(" = v; return CLS.fld_").
217 append(v.getName()).append("; };");
219 append("\n c._").append(v.getName()).append(" = function (v) {")
220 .append(" if (arguments.length == 1) this.fld_").
221 append(className).append('_').append(v.getName())
222 .append(" = v; return this.fld_").
223 append(className).append('_').append(v.getName())
227 declaredField(v, "c", "_" + v.getName());
229 for (MethodData m : jc.getMethods()) {
230 byte[] onlyArr = m.findAnnotationData(true);
231 String[] only = findAnnotation(onlyArr, jc,
232 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
236 if (only[0] != null && only[1] != null) {
237 append("\n p.").append(only[0]).append(" = ")
238 .append(only[1]).append(";");
247 mn = generateStaticMethod(destObject, m, toInitilize);
249 if (m.isConstructor()) {
251 mn = generateInstanceMethod(destObject, m);
254 mn = generateInstanceMethod(destObject, m);
257 declaredMethod(m, destObject, mn);
258 byte[] runAnno = m.findAnnotationData(false);
259 if (runAnno != null) {
260 append("\n ").append(destObject).append(".").append(mn).append(".anno = {");
261 generateAnno(jc, runAnno);
264 append("\n ").append(destObject).append(".").append(mn).append(".access = " + m.getAccess()).append(";");
265 append("\n ").append(destObject).append(".").append(mn).append(".cls = CLS;");
267 append("\n c.constructor = CLS;");
268 append("\n function fillInstOf(x) {");
269 String instOfName = "$instOf_" + className;
270 append("\n x['").append(instOfName).append("'] = true;");
271 for (String superInterface : jc.getSuperInterfaces()) {
272 String intrfc = superInterface.replace('/', '_');
273 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
274 requireReference(superInterface);
277 append("\n c['fillInstOf'] = fillInstOf;");
278 append("\n fillInstOf(c);");
279 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
280 append("\n CLS.$class = 'temp';");
281 append("\n CLS.$class = ");
282 append(accessClass("java_lang_Class(true);"));
283 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
284 append("\n CLS.$class.superclass = sprcls;");
285 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
286 append("\n CLS.$class.cnstr = CLS;");
287 byte[] classAnno = jc.findAnnotationData(false);
288 if (classAnno != null) {
289 append("\n CLS.$class.anno = {");
290 generateAnno(jc, classAnno);
293 for (String init : toInitilize.toArray()) {
294 append("\n ").append(init).append("();");
297 append("\n if (arguments.length === 0) {");
298 append("\n if (!(this instanceof CLS)) {");
299 append("\n return new CLS();");
301 for (FieldData v : jc.getFields()) {
302 byte[] onlyArr = v.findAnnotationData(true);
303 String[] only = findAnnotation(onlyArr, jc,
304 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
308 if (only[0] != null && only[1] != null) {
309 append("\n p.").append(only[0]).append(" = ")
310 .append(only[1]).append(";");
315 append("\n this.fld_").
316 append(className).append('_').
317 append(v.getName()).append(initField(v));
320 append("\n return this;");
322 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
325 declaredClass(jc, className);
327 // StringBuilder sb = new StringBuilder();
328 // for (String init : toInitilize.toArray()) {
329 // sb.append("\n").append(init).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 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1125 final Variable vi1 = smapper.get(0);
1127 if (vi1.isCategory2()) {
1128 emit(smapper, this, "var @1 = @2;",
1129 smapper.pushT(vi1.getType()), vi1);
1131 final Variable vi2 = smapper.get(1);
1132 emit(smapper, this, "var @1 = @2, @3 = @4;",
1133 smapper.pushT(vi2.getType()), vi2,
1134 smapper.pushT(vi1.getType()), vi1);
1139 final Variable vi1 = smapper.pop(this);
1140 final Variable vi2 = smapper.pop(this);
1141 final Variable vo3 = smapper.pushT(vi1.getType());
1142 final Variable vo2 = smapper.pushT(vi2.getType());
1143 final Variable vo1 = smapper.pushT(vi1.getType());
1145 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1146 vo1, vi1, vo2, vi2, vo3, vo1);
1150 final Variable vi1 = smapper.pop(this);
1151 final Variable vi2 = smapper.pop(this);
1153 if (vi1.isCategory2()) {
1154 final Variable vo3 = smapper.pushT(vi1.getType());
1155 final Variable vo2 = smapper.pushT(vi2.getType());
1156 final Variable vo1 = smapper.pushT(vi1.getType());
1158 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1159 vo1, vi1, vo2, vi2, vo3, vo1);
1161 final Variable vi3 = smapper.pop(this);
1162 final Variable vo5 = smapper.pushT(vi2.getType());
1163 final Variable vo4 = smapper.pushT(vi1.getType());
1164 final Variable vo3 = smapper.pushT(vi3.getType());
1165 final Variable vo2 = smapper.pushT(vi2.getType());
1166 final Variable vo1 = smapper.pushT(vi1.getType());
1168 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1169 vo1, vi1, vo2, vi2, vo3, vi3);
1170 emit(smapper, this, " @1 = @2, @3 = @4;",
1171 vo4, vo1, vo5, vo2);
1176 final Variable vi1 = smapper.pop(this);
1177 final Variable vi2 = smapper.pop(this);
1179 if (vi2.isCategory2()) {
1180 final Variable vo3 = smapper.pushT(vi1.getType());
1181 final Variable vo2 = smapper.pushT(vi2.getType());
1182 final Variable vo1 = smapper.pushT(vi1.getType());
1184 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1185 vo1, vi1, vo2, vi2, vo3, vo1);
1187 final Variable vi3 = smapper.pop(this);
1188 final Variable vo4 = smapper.pushT(vi1.getType());
1189 final Variable vo3 = smapper.pushT(vi3.getType());
1190 final Variable vo2 = smapper.pushT(vi2.getType());
1191 final Variable vo1 = smapper.pushT(vi1.getType());
1193 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1194 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1199 final Variable vi1 = smapper.pop(this);
1200 final Variable vi2 = smapper.pop(this);
1202 if (vi1.isCategory2()) {
1203 if (vi2.isCategory2()) {
1204 final Variable vo3 = smapper.pushT(vi1.getType());
1205 final Variable vo2 = smapper.pushT(vi2.getType());
1206 final Variable vo1 = smapper.pushT(vi1.getType());
1208 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1209 vo1, vi1, vo2, vi2, vo3, vo1);
1211 final Variable vi3 = smapper.pop(this);
1212 final Variable vo4 = smapper.pushT(vi1.getType());
1213 final Variable vo3 = smapper.pushT(vi3.getType());
1214 final Variable vo2 = smapper.pushT(vi2.getType());
1215 final Variable vo1 = smapper.pushT(vi1.getType());
1217 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1218 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1221 final Variable vi3 = smapper.pop(this);
1223 if (vi3.isCategory2()) {
1224 final Variable vo5 = smapper.pushT(vi2.getType());
1225 final Variable vo4 = smapper.pushT(vi1.getType());
1226 final Variable vo3 = smapper.pushT(vi3.getType());
1227 final Variable vo2 = smapper.pushT(vi2.getType());
1228 final Variable vo1 = smapper.pushT(vi1.getType());
1230 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1231 vo1, vi1, vo2, vi2, vo3, vi3);
1232 emit(smapper, this, " @1 = @2, @3 = @4;",
1233 vo4, vo1, vo5, vo2);
1235 final Variable vi4 = smapper.pop(this);
1236 final Variable vo6 = smapper.pushT(vi2.getType());
1237 final Variable vo5 = smapper.pushT(vi1.getType());
1238 final Variable vo4 = smapper.pushT(vi4.getType());
1239 final Variable vo3 = smapper.pushT(vi3.getType());
1240 final Variable vo2 = smapper.pushT(vi2.getType());
1241 final Variable vo1 = smapper.pushT(vi1.getType());
1243 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1244 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1245 emit(smapper, this, " @1 = @2, @3 = @4;",
1246 vo5, vo1, vo6, vo2);
1252 final Variable vi1 = smapper.get(0);
1253 final Variable vi2 = smapper.get(1);
1255 if (vi1.getType() == vi2.getType()) {
1256 final Variable tmp = smapper.pushT(vi1.getType());
1258 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1263 smapper.pushT(vi1.getType());
1264 smapper.pushT(vi2.getType());
1269 smapper.assign(this, VarType.INTEGER,
1270 "(" + Integer.toString(byteCodes[++i]) + ")");
1273 smapper.assign(this, VarType.INTEGER,
1274 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1278 case opc_getfield: {
1279 int indx = readUShortArg(byteCodes, i);
1280 String[] fi = jc.getFieldInfoName(indx);
1281 final int type = VarType.fromFieldType(fi[2].charAt(0));
1282 final String mangleClass = mangleClassName(fi[0]);
1283 final String mangleClassAccess = accessClass(mangleClass);
1284 smapper.replace(this, type, "@2.call(@1)",
1286 accessField(mangleClassAccess + "(false)",
1292 case opc_putfield: {
1293 int indx = readUShortArg(byteCodes, i);
1294 String[] fi = jc.getFieldInfoName(indx);
1295 final int type = VarType.fromFieldType(fi[2].charAt(0));
1296 final String mangleClass = mangleClassName(fi[0]);
1297 final String mangleClassAccess = accessClass(mangleClass);
1298 emit(smapper, this, "@3.call(@2, @1);",
1301 accessField(mangleClassAccess + "(false)",
1306 case opc_getstatic: {
1307 int indx = readUShortArg(byteCodes, i);
1308 String[] fi = jc.getFieldInfoName(indx);
1309 final int type = VarType.fromFieldType(fi[2].charAt(0));
1310 String ac = accessClass(mangleClassName(fi[0]));
1311 smapper.assign(this, type, ac + "(false)._" + fi[1] + "()");
1313 addReference(fi[0]);
1316 case opc_putstatic: {
1317 int indx = readUShortArg(byteCodes, i);
1318 String[] fi = jc.getFieldInfoName(indx);
1319 final int type = VarType.fromFieldType(fi[2].charAt(0));
1320 emit(smapper, this, "@1(false)._@2(@3);",
1321 accessClass(mangleClassName(fi[0])), fi[1],
1322 smapper.popT(type));
1324 addReference(fi[0]);
1327 case opc_checkcast: {
1328 int indx = readUShortArg(byteCodes, i);
1329 generateCheckcast(indx, smapper);
1333 case opc_instanceof: {
1334 int indx = readUShortArg(byteCodes, i);
1335 generateInstanceOf(indx, smapper);
1340 final CharSequence v = smapper.popA();
1343 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1344 smapper.pushA(), v);
1348 case opc_monitorenter: {
1349 debug("/* monitor enter */");
1354 case opc_monitorexit: {
1355 debug("/* monitor exit */");
1366 emit(smapper, this, "throw 'unknown bytecode @1';",
1367 Integer.toString(c));
1371 generateByteCodeComment(prev, i, byteCodes);
1377 if (previousTrap != null) {
1378 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1383 while (openBraces-- > 0) {
1389 private int generateIf(StackMapper mapper, byte[] byteCodes,
1390 int i, final CharSequence v2, final CharSequence v1,
1391 final String test, int topMostLabel
1392 ) throws IOException {
1394 int indx = i + readShortArg(byteCodes, i);
1395 append("if ((").append(v1)
1396 .append(") ").append(test).append(" (")
1397 .append(v2).append(")) ");
1398 goTo(this, i, indx, topMostLabel);
1402 private int readInt4(byte[] byteCodes, int offset) {
1403 final int d = byteCodes[offset + 0] << 24;
1404 final int c = byteCodes[offset + 1] << 16;
1405 final int b = byteCodes[offset + 2] << 8;
1406 final int a = byteCodes[offset + 3];
1407 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1409 private static int readUByte(byte[] byteCodes, int offset) {
1410 return byteCodes[offset] & 0xff;
1413 private static int readUShort(byte[] byteCodes, int offset) {
1414 return ((byteCodes[offset] & 0xff) << 8)
1415 | (byteCodes[offset + 1] & 0xff);
1417 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1418 return readUShort(byteCodes, offsetInstruction + 1);
1421 private static int readShort(byte[] byteCodes, int offset) {
1422 int signed = byteCodes[offset];
1423 byte b0 = (byte)signed;
1424 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1426 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1427 return readShort(byteCodes, offsetInstruction + 1);
1430 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1432 Boolean count = null;
1433 boolean array = false;
1435 int firstPos = sig.length();
1436 while (i < descriptor.length()) {
1437 char ch = descriptor.charAt(i++);
1458 if (ch == 'J' || ch == 'D') {
1464 sig.insert(firstPos, ch);
1466 returnType[0] = '[';
1467 sig.insert(firstPos, "_3");
1476 returnType[0] = 'V';
1477 sig.insert(firstPos, 'V');
1480 int next = descriptor.indexOf(';', i);
1481 String realSig = mangleSig(descriptor, i - 1, next + 1);
1486 sig.append(realSig);
1489 sig.insert(firstPos, realSig);
1491 sig.insert(firstPos, "_3");
1493 returnType[0] = 'L';
1502 throw new IllegalStateException("Invalid char: " + ch);
1507 static String mangleSig(String sig) {
1508 return mangleSig(sig, 0, sig.length());
1511 private static String mangleMethodName(String name) {
1512 StringBuilder sb = new StringBuilder(name.length() * 2);
1513 int last = name.length();
1514 for (int i = 0; i < last; i++) {
1515 final char ch = name.charAt(i);
1517 case '_': sb.append("_1"); break;
1518 default: sb.append(ch); break;
1521 return sb.toString();
1523 private static String mangleSig(String txt, int first, int last) {
1524 StringBuilder sb = new StringBuilder((last - first) * 2);
1525 for (int i = first; i < last; i++) {
1526 final char ch = txt.charAt(i);
1528 case '/': sb.append('_'); break;
1529 case '_': sb.append("_1"); break;
1530 case ';': sb.append("_2"); break;
1531 case '[': sb.append("_3"); break;
1532 default: sb.append(ch); break;
1535 return sb.toString();
1538 private static String mangleClassName(String name) {
1539 return mangleSig(name);
1542 private static String findMethodName(MethodData m, StringBuilder cnt) {
1543 StringBuilder name = new StringBuilder();
1544 if ("<init>".equals(m.getName())) { // NOI18N
1545 name.append("cons"); // NOI18N
1546 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1547 name.append("class"); // NOI18N
1549 name.append(mangleMethodName(m.getName()));
1552 countArgs(m.getInternalSig(), new char[1], name, cnt);
1553 return name.toString();
1556 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1557 StringBuilder name = new StringBuilder();
1558 String descr = mi[2];//mi.getDescriptor();
1560 if ("<init>".equals(nm)) { // NOI18N
1561 name.append("cons"); // NOI18N
1563 name.append(mangleMethodName(nm));
1565 countArgs(descr, returnType, name, cnt);
1566 return name.toString();
1569 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1570 throws IOException {
1571 int methodIndex = readUShortArg(byteCodes, i);
1572 String[] mi = jc.getFieldInfoName(methodIndex);
1573 char[] returnType = { 'V' };
1574 StringBuilder cnt = new StringBuilder();
1575 String mn = findMethodName(mi, cnt, returnType);
1577 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1578 final CharSequence[] vars = new CharSequence[numArguments];
1580 for (int j = numArguments - 1; j >= 0; --j) {
1581 vars[j] = mapper.popValue();
1584 if (returnType[0] != 'V') {
1586 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1590 final String in = mi[0];
1592 if (callbacks && in.equals("org/apidesign/html/boot/spi/Fn")) {
1593 mcn = "java_lang_Class";
1595 mcn = mangleClassName(in);
1597 String object = accessClass(mcn) + "(false)";
1598 if (mn.startsWith("cons_")) {
1599 object += ".constructor";
1601 append(accessStaticMethod(object, mn, mi));
1607 if (numArguments > 0) {
1609 for (int j = 1; j < numArguments; ++j) {
1619 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1620 throws IOException {
1621 int methodIndex = readUShortArg(byteCodes, i);
1622 String[] mi = jc.getFieldInfoName(methodIndex);
1623 char[] returnType = { 'V' };
1624 StringBuilder cnt = new StringBuilder();
1625 String mn = findMethodName(mi, cnt, returnType);
1627 final int numArguments = cnt.length() + 1;
1628 final CharSequence[] vars = new CharSequence[numArguments];
1630 for (int j = numArguments - 1; j >= 0; --j) {
1631 vars[j] = mapper.popValue();
1634 if (returnType[0] != 'V') {
1636 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1640 append(accessVirtualMethod(vars[0].toString(), mn, mi));
1643 for (int j = 1; j < numArguments; ++j) {
1653 private void addReference(String cn) throws IOException {
1654 if (requireReference(cn)) {
1655 debug(" /* needs " + cn + " */");
1659 private void outType(String d, StringBuilder out) {
1661 while (d.charAt(0) == '[') {
1665 if (d.charAt(0) == 'L') {
1666 assert d.charAt(d.length() - 1) == ';';
1667 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1673 private String encodeConstant(int entryIndex) throws IOException {
1674 String[] classRef = { null };
1675 String s = jc.stringValue(entryIndex, classRef);
1676 if (classRef[0] != null) {
1677 if (classRef[0].startsWith("[")) {
1678 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1680 addReference(classRef[0]);
1681 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1687 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1688 byte[] arr = m.findAnnotationData(true);
1692 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1693 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1694 class P extends AnnotationParser {
1700 String[] args = new String[30];
1706 protected void visitAttr(String type, String attr, String at, String value) {
1707 if (type.equals(jvmType)) {
1708 if ("body".equals(attr)) {
1710 } else if ("args".equals(attr)) {
1711 args[cnt++] = value;
1713 throw new IllegalArgumentException(attr);
1716 if (type.equals(htmlType)) {
1718 if ("body".equals(attr)) {
1720 } else if ("args".equals(attr)) {
1721 args[cnt++] = value;
1722 } else if ("javacall".equals(attr)) {
1723 javacall = "1".equals(value);
1725 throw new IllegalArgumentException(attr);
1732 if (p.body == null) {
1735 StringBuilder cnt = new StringBuilder();
1736 final String mn = findMethodName(m, cnt);
1737 append(destObject).append(".").append(mn);
1738 append(" = function(");
1741 StringBuilder toValue = new StringBuilder();
1742 for (int i = 0; i < cnt.length(); i++) {
1744 space = outputArg(this, p.args, index);
1745 if (p.html4j && space.length() > 0) {
1746 toValue.append("\n ").append(p.args[index]).append(" = ")
1747 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1748 append(p.args[index]).append(");");
1752 append(") {").append("\n");
1753 append(toValue.toString());
1755 int lastSlash = jc.getClassName().lastIndexOf('/');
1756 final String pkg = jc.getClassName().substring(0, lastSlash);
1757 append(mangleCallbacks(pkg, p.body));
1758 requireReference(pkg + "/$JsCallbacks$");
1766 private static CharSequence mangleCallbacks(String pkgName, String body) {
1767 StringBuilder sb = new StringBuilder();
1770 int next = body.indexOf(".@", pos);
1772 sb.append(body.substring(pos));
1773 body = sb.toString();
1778 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1783 String refId = body.substring(ident, next);
1785 sb.append(body.substring(pos, ident));
1787 int sigBeg = body.indexOf('(', next);
1788 int sigEnd = body.indexOf(')', sigBeg);
1789 int colon4 = body.indexOf("::", next);
1790 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1791 throw new IllegalStateException("Malformed body " + body);
1793 String fqn = body.substring(next + 2, colon4);
1794 String method = body.substring(colon4 + 2, sigBeg);
1795 String params = body.substring(sigBeg, sigEnd + 1);
1797 int paramBeg = body.indexOf('(', sigEnd + 1);
1799 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1800 sb.append(mangleJsCallbacks(fqn, method, params, false));
1801 sb.append("(").append(refId);
1802 if (body.charAt(paramBeg + 1) != ')') {
1810 int next = body.indexOf("@", pos);
1815 sb.append(body.substring(pos));
1819 sb = new StringBuilder();
1822 sb.append(body.substring(pos, next));
1824 int sigBeg = body.indexOf('(', next);
1825 int sigEnd = body.indexOf(')', sigBeg);
1826 int colon4 = body.indexOf("::", next);
1827 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1828 throw new IllegalStateException("Malformed body " + body);
1830 String fqn = body.substring(next + 1, colon4);
1831 String method = body.substring(colon4 + 2, sigBeg);
1832 String params = body.substring(sigBeg, sigEnd + 1);
1834 int paramBeg = body.indexOf('(', sigEnd + 1);
1836 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1837 sb.append(mangleJsCallbacks(fqn, method, params, true));
1843 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1844 if (params.startsWith("(")) {
1845 params = params.substring(1);
1847 if (params.endsWith(")")) {
1848 params = params.substring(0, params.length() - 1);
1850 StringBuilder sb = new StringBuilder();
1851 final String fqnu = fqn.replace('.', '_');
1852 final String rfqn = mangleClassName(fqnu);
1853 final String rm = mangleMethodName(method);
1856 StringBuilder pb = new StringBuilder();
1857 int len = params.length();
1859 while (indx < len) {
1860 char ch = params.charAt(indx);
1861 if (ch == '[' || ch == 'L') {
1862 pb.append("Ljava/lang/Object;");
1863 indx = params.indexOf(';', indx) + 1;
1869 srp = mangleSig(pb.toString());
1871 final String rp = mangleSig(params);
1872 final String mrp = mangleMethodName(rp);
1873 sb.append(rfqn).append("$").append(rm).
1874 append('$').append(mrp).append("__Ljava_lang_Object_2");
1876 sb.append('L').append(fqnu).append("_2");
1879 return sb.toString();
1882 private static String className(ClassData jc) {
1883 //return jc.getName().getInternalName().replace('/', '_');
1884 return mangleClassName(jc.getClassName());
1887 private static String[] findAnnotation(
1888 byte[] arr, ClassData cd, final String className,
1889 final String... attrNames
1890 ) throws IOException {
1894 final String[] values = new String[attrNames.length];
1895 final boolean[] found = { false };
1896 final String jvmType = "L" + className.replace('.', '/') + ";";
1897 AnnotationParser ap = new AnnotationParser(false, true) {
1899 protected void visitAttr(String type, String attr, String at, String value) {
1900 if (type.equals(jvmType)) {
1902 for (int i = 0; i < attrNames.length; i++) {
1903 if (attrNames[i].equals(attr)) {
1912 return found[0] ? values : null;
1915 private CharSequence initField(FieldData v) {
1916 final String is = v.getInternalSig();
1917 if (is.length() == 1) {
1918 switch (is.charAt(0)) {
1924 case 'I': return " = 0;";
1926 case 'D': return " = 0.0;";
1928 throw new IllegalStateException(is);
1934 private void generateAnno(ClassData cd, byte[] data) throws IOException {
1935 AnnotationParser ap = new AnnotationParser(true, false) {
1936 int[] cnt = new int[32];
1940 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
1941 final String slashType = attrType.substring(1, attrType.length() - 1);
1942 requireReference(slashType);
1944 if (cnt[depth]++ > 0) {
1948 append('"').append(attrType).append("\" : ");
1955 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
1961 protected void visitValueStart(String attrName, char type) throws IOException {
1962 if (cnt[depth]++ > 0) {
1966 if (attrName != null) {
1967 append(attrName).append(" : ");
1975 protected void visitValueEnd(String attrName, char type) throws IOException {
1983 protected void visitAttr(String type, String attr, String attrType, String value)
1984 throws IOException {
1985 if (attr == null && value == null) {
1992 protected void visitEnumAttr(String type, String attr, String attrType, String value)
1993 throws IOException {
1994 final String slashType = attrType.substring(1, attrType.length() - 1);
1995 requireReference(slashType);
1997 append(accessClass(mangleClassName(slashType)))
1998 .append("(false).constructor.fld_").append(value);
2004 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2005 final String name = args[indx];
2009 if (name.contains(",")) {
2010 throw new IOException("Wrong parameter with ',': " + name);
2016 final void emitNoFlush(
2018 final String format, final CharSequence... params
2019 ) throws IOException {
2020 emitImpl(this, format, params);
2022 static final void emit(
2024 final Appendable out,
2025 final String format, final CharSequence... params
2026 ) throws IOException {
2028 emitImpl(out, format, params);
2030 static void emitImpl(final Appendable out,
2031 final String format,
2032 final CharSequence... params) throws IOException {
2033 final int length = format.length();
2036 int paramOffset = format.indexOf('@');
2037 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2038 final char paramChar = format.charAt(paramOffset + 1);
2039 if ((paramChar >= '1') && (paramChar <= '9')) {
2040 final int paramIndex = paramChar - '0' - 1;
2042 out.append(format, processed, paramOffset);
2043 out.append(params[paramIndex]);
2046 processed = paramOffset + 1;
2049 paramOffset = format.indexOf('@', paramOffset + 1);
2052 out.append(format, processed, length);
2055 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2056 append("} catch (e) {\n");
2058 for (TrapData e : traps) {
2062 if (e.catch_cpx != 0) { //not finally
2063 final String classInternalName = jc.getClassName(e.catch_cpx);
2064 addReference(classInternalName);
2065 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2066 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2067 append("var stA0 = e;");
2068 goTo(this, current, e.handler_pc, topMostLabel);
2071 finallyPC = e.handler_pc;
2074 if (finallyPC == -1) {
2077 append("var stA0 = e;");
2078 goTo(this, current, finallyPC, topMostLabel);
2083 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2086 out.append("{ gt = 0; continue X_" + to + "; }");
2088 out.append("{ gt = " + to + "; continue X_0; }");
2091 out.append("{ gt = " + to + "; break IF; }");
2095 private static void emitIf(
2097 Appendable out, String pattern,
2099 int current, int to, int canBack
2100 ) throws IOException {
2102 emitImpl(out, pattern, param);
2103 goTo(out, current, to, canBack);
2106 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2109 case 4: jvmType = "[Z"; break;
2110 case 5: jvmType = "[C"; break;
2111 case 6: jvmType = "[F"; break;
2112 case 7: jvmType = "[D"; break;
2113 case 8: jvmType = "[B"; break;
2114 case 9: jvmType = "[S"; break;
2115 case 10: jvmType = "[I"; break;
2116 case 11: jvmType = "[J"; break;
2117 default: throw new IllegalStateException("Array type: " + atype);
2120 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2121 smapper.popI(), smapper.pushA(), jvmType);
2124 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2125 String typeName = jc.getClassName(type);
2126 String ref = "null";
2127 if (typeName.startsWith("[")) {
2128 typeName = "'[" + typeName + "'";
2130 ref = "vm." + mangleClassName(typeName);
2131 typeName = "'[L" + typeName + ";'";
2134 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2135 smapper.popI(), smapper.pushA(), typeName, ref);
2138 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2139 String typeName = jc.getClassName(type);
2140 int dim = readUByte(byteCodes, ++i);
2141 StringBuilder dims = new StringBuilder();
2143 for (int d = 0; d < dim; d++) {
2145 dims.insert(1, ",");
2147 dims.insert(1, smapper.popI());
2151 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3II']('@3', @1, 0);",
2152 dims.toString(), smapper.pushA(), typeName);
2156 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2157 int table = i / 4 * 4 + 4;
2158 int dflt = i + readInt4(byteCodes, table);
2160 int low = readInt4(byteCodes, table);
2162 int high = readInt4(byteCodes, table);
2164 final CharSequence swVar = smapper.popValue();
2165 smapper.flush(this);
2166 append("switch (").append(swVar).append(") {\n");
2167 while (low <= high) {
2168 int offset = i + readInt4(byteCodes, table);
2170 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2173 append(" default: ");
2174 goTo(this, i, dflt, topMostLabel);
2180 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2181 int table = i / 4 * 4 + 4;
2182 int dflt = i + readInt4(byteCodes, table);
2184 int n = readInt4(byteCodes, table);
2186 final CharSequence swVar = smapper.popValue();
2187 smapper.flush(this);
2188 append("switch (").append(swVar).append(") {\n");
2190 int cnstnt = readInt4(byteCodes, table);
2192 int offset = i + readInt4(byteCodes, table);
2194 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2196 append(" default: ");
2197 goTo(this, i, dflt, topMostLabel);
2203 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2204 final String type = jc.getClassName(indx);
2205 if (!type.startsWith("[")) {
2207 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2208 smapper.popA(), smapper.pushI(),
2209 type.replace('/', '_'));
2212 "var @2 = vm.java_lang_Class(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('@3')['isInstance__ZLjava_lang_Object_2'](@1);",
2213 smapper.popA(), smapper.pushI(),
2219 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2220 final String type = jc.getClassName(indx);
2221 if (!type.startsWith("[")) {
2222 emitNoFlush(smapper,
2223 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2224 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2226 emitNoFlush(smapper,
2227 "vm.java_lang_Class(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('@2')['cast__Ljava_lang_Object_2Ljava_lang_Object_2'](@1);",
2228 smapper.getT(0, VarType.REFERENCE, false), type
2233 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2234 for (int j = prev; j <= i; j++) {
2236 final int cc = readUByte(byteCodes, j);
2237 append(Integer.toString(cc));