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,
102 ) throws IOException {
103 return object + "." + mangledName + '(';
106 protected void declaredClass(ClassData classData, String mangledName)
110 protected void declaredField(FieldData fieldData,
112 String mangledName) throws IOException {
115 protected void declaredMethod(MethodData methodData,
117 String mangledName) throws IOException {
120 /** Prints out a debug message.
122 * @param msg the message
123 * @return true if the message has been printed
124 * @throws IOException
126 boolean debug(String msg) throws IOException {
132 * Converts a given class file to a JavaScript version.
134 * @param classFile input stream with code of the .class file
135 * @return the initialization code for this class, if any. Otherwise <code>null</code>
137 * @throws IOException if something goes wrong during read or write or translating
140 public String compile(InputStream classFile) throws IOException {
141 return compile(new ClassData(classFile));
144 protected String compile(ClassData classData) throws IOException {
146 this.callbacks = this.jc.getClassName().endsWith("/$JsCallbacks$");
147 if (jc.getMajor_version() < 50) {
148 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
149 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
152 byte[] arrData = jc.findAnnotationData(true);
154 String[] arr = findAnnotation(arrData, jc,
155 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
156 "resource", "processByteCode"
159 if (!arr[0].isEmpty()) {
160 requireScript(arr[0]);
162 if ("0".equals(arr[1])) {
168 String[] arr = findAnnotation(arrData, jc,
169 "net.java.html.js.JavaScriptResource",
173 if (arr[0].startsWith("/")) {
174 requireScript(arr[0]);
176 int last = jc.getClassName().lastIndexOf('/');
178 jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0]
183 String[] proto = findAnnotation(arrData, jc,
184 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
185 "container", "prototype"
187 StringArray toInitilize = new StringArray();
188 final String className = className(jc);
189 append("\n\n").append(assignClass(className));
190 append("function ").append(className).append("() {");
191 append("\n var CLS = ").append(className).append(';');
192 append("\n if (!CLS.$class) {");
194 String sc = jc.getSuperClassName(); // with _
195 append("\n var pp = ").
196 append(accessClass(mangleClassName(sc))).append("(true);");
197 append("\n var p = CLS.prototype = pp;");
198 append("\n var c = p;");
199 append("\n var sprcls = pp.constructor.$class;");
201 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
202 if (proto[0] == null) {
205 append("\n var c = ").append(proto[0]).append(";");
206 append("\n var sprcls = null;");
208 for (FieldData v : jc.getFields()) {
210 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
211 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
215 append("\n CLS.fld_").append(v.getName()).append(initField(v));
216 append("\n c._").append(v.getName()).append(" = function (v) {")
217 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
218 .append(" = v; return CLS.fld_").
219 append(v.getName()).append("; };");
221 append("\n c._").append(v.getName()).append(" = function (v) {")
222 .append(" if (arguments.length == 1) this.fld_").
223 append(className).append('_').append(v.getName())
224 .append(" = v; return this.fld_").
225 append(className).append('_').append(v.getName())
229 declaredField(v, "c", "_" + v.getName());
231 for (MethodData m : jc.getMethods()) {
232 byte[] onlyArr = m.findAnnotationData(true);
233 if (javaScriptOnly(onlyArr)) continue;
239 mn = generateStaticMethod(destObject, m, toInitilize);
241 if (m.isConstructor()) {
243 mn = generateInstanceMethod(destObject, m);
246 mn = generateInstanceMethod(destObject, m);
249 declaredMethod(m, destObject, mn);
250 byte[] runAnno = m.findAnnotationData(false);
251 if (runAnno != null) {
252 append("\n ").append(destObject).append(".").append(mn).append(".anno = {");
253 generateAnno(jc, runAnno);
256 append("\n ").append(destObject).append(".").append(mn).append(".access = " + m.getAccess()).append(";");
257 append("\n ").append(destObject).append(".").append(mn).append(".cls = CLS;");
259 append("\n c.constructor = CLS;");
260 append("\n function fillInstOf(x) {");
261 String instOfName = "$instOf_" + className;
262 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
263 for (String superInterface : jc.getSuperInterfaces()) {
264 String intrfc = superInterface.replace('/', '_');
265 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
266 requireReference(superInterface);
270 append("\n Object.defineProperty(c, 'fillInstOf', { value: fillInstOf });");
271 append("\n fillInstOf(c);");
272 append("\n } catch (ignore) {");
274 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
275 append("\n CLS.$class = 'temp';");
276 append("\n CLS.$class = ");
277 append(accessClass("java_lang_Class(true);"));
278 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
279 append("\n CLS.$class.superclass = sprcls;");
280 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
281 append("\n CLS.$class.cnstr = CLS;");
282 byte[] classAnno = jc.findAnnotationData(false);
283 if (classAnno != null) {
284 append("\n CLS.$class.anno = {");
285 generateAnno(jc, classAnno);
288 for (String init : toInitilize.toArray()) {
289 append("\n ").append(init).append("();");
292 append("\n if (arguments.length === 0) {");
293 append("\n if (!(this instanceof CLS)) {");
294 append("\n return new CLS();");
296 for (FieldData v : jc.getFields()) {
297 byte[] onlyArr = v.findAnnotationData(true);
298 if (javaScriptOnly(onlyArr)) continue;
300 append("\n this.fld_").
301 append(className).append('_').
302 append(v.getName()).append(initField(v));
305 append("\n return this;");
307 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
310 declaredClass(jc, className);
312 // StringBuilder sb = new StringBuilder();
313 // for (String init : toInitilize.toArray()) {
314 // sb.append("\n").append(init).append("();");
319 private boolean javaScriptOnly(byte[] anno) throws IOException {
320 String[] only = findAnnotation(anno, jc,
321 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
325 if (only[0] != null && only[1] != null) {
326 append("\n p.").append(only[0]).append(" = ")
327 .append(only[1]).append(";");
329 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
330 append("\n p['").append(only[0]).append("'] = p.")
331 .append(only[0]).append(";");
337 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
338 String jsb = javaScriptBody(destObject, m, true);
342 final String mn = findMethodName(m, new StringBuilder());
343 if (mn.equals("class__V")) {
344 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
346 generateMethod(destObject, mn, m);
350 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
351 String jsb = javaScriptBody(destObject, m, false);
355 final String mn = findMethodName(m, new StringBuilder());
356 generateMethod(destObject, mn, m);
360 private void generateMethod(String destObject, String name, MethodData m)
362 final StackMapIterator stackMapIterator = m.createStackMapIterator();
363 TrapDataIterator trap = m.getTrapDataIterator();
364 final LocalsMapper lmapper =
365 new LocalsMapper(stackMapIterator.getArguments());
367 boolean obj = "java/lang/Object".equals(jc.getClassName());
370 append("Object.defineProperty(").append(destObject).
371 append(", '").append(name).append("', { configurable: true, writable: true, value: function(");
373 append(destObject).append(".").append(name).append(" = function(");
375 lmapper.outputArguments(this, m.isStatic());
376 append(") {").append("\n");
378 final byte[] byteCodes = m.getCode();
379 if (byteCodes == null) {
380 append(" throw 'no code found for ")
381 .append(jc.getClassName()).append('.')
382 .append(m.getName()).append("';\n");
390 final StackMapper smapper = new StackMapper();
393 append(" var ").append(" lcA0 = this;\n");
397 TrapData[] previousTrap = null;
398 boolean wide = false;
400 if (stackMapIterator.isEmpty()) {
406 append("\n var gt = 0;\n");
410 int topMostLabel = 0;
411 for (int i = 0; i < byteCodes.length; i++) {
414 stackMapIterator.advanceTo(i);
415 boolean changeInCatch = trap.advanceTo(i);
416 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
417 if (previousTrap != null) {
418 generateCatch(previousTrap, i, topMostLabel);
422 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
427 if (openBraces > 64) {
428 for (int c = 0; c < 64; c++) {
435 lastStackFrame = stackMapIterator.getFrameIndex();
436 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
437 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
438 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
440 changeInCatch = true;
442 debug(" /* " + i + " */ ");
444 if (changeInCatch && trap.useTry()) {
446 previousTrap = trap.current();
448 final int c = readUByte(byteCodes, i);
451 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
454 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
457 smapper.assign(this, VarType.LONG, lmapper.getL(0));
460 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
463 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
466 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
469 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
472 smapper.assign(this, VarType.LONG, lmapper.getL(1));
475 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
478 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
481 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
484 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
487 smapper.assign(this, VarType.LONG, lmapper.getL(2));
490 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
493 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
496 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
499 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
502 smapper.assign(this, VarType.LONG, lmapper.getL(3));
505 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
508 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
512 final int indx = wide ? readUShort(byteCodes, i++)
513 : readUByte(byteCodes, i);
515 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
520 final int indx = wide ? readUShort(byteCodes, i++)
521 : readUByte(byteCodes, i);
523 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
528 final int indx = wide ? readUShort(byteCodes, i++)
529 : readUByte(byteCodes, i);
531 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
536 final int indx = wide ? readUShort(byteCodes, i++)
537 : readUByte(byteCodes, i);
539 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
544 final int indx = wide ? readUShort(byteCodes, i++)
545 : readUByte(byteCodes, i);
547 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
552 final int indx = wide ? readUShort(byteCodes, i++)
553 : readUByte(byteCodes, i);
555 emit(smapper, this, "var @1 = @2;",
556 lmapper.setI(indx), smapper.popI());
561 final int indx = wide ? readUShort(byteCodes, i++)
562 : readUByte(byteCodes, i);
564 emit(smapper, this, "var @1 = @2;",
565 lmapper.setL(indx), smapper.popL());
570 final int indx = wide ? readUShort(byteCodes, i++)
571 : readUByte(byteCodes, i);
573 emit(smapper, this, "var @1 = @2;",
574 lmapper.setF(indx), smapper.popF());
579 final int indx = wide ? readUShort(byteCodes, i++)
580 : readUByte(byteCodes, i);
582 emit(smapper, this, "var @1 = @2;",
583 lmapper.setD(indx), smapper.popD());
588 final int indx = wide ? readUShort(byteCodes, i++)
589 : readUByte(byteCodes, i);
591 emit(smapper, this, "var @1 = @2;",
592 lmapper.setA(indx), smapper.popA());
596 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
599 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
602 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
605 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
608 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
611 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
614 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
617 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
620 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
623 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
626 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
629 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
632 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
635 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
638 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
641 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
644 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
647 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
650 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
653 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
656 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
659 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
662 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
665 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
668 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
671 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
674 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
677 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
680 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
683 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", 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).div32(@2)",
693 smapper.getI(1), smapper.popI());
696 smapper.replace(this, VarType.LONG, "(@1).div64(@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).mod32(@2)",
707 smapper.getI(1), smapper.popI());
710 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
711 smapper.getL(1), smapper.popL());
714 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
717 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
720 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
723 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
726 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
729 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
732 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
735 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
738 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
741 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
744 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
747 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
750 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
753 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
756 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
759 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
762 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
765 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
769 final int varIndx = wide ? readUShort(byteCodes, i++)
770 : readUByte(byteCodes, i);
772 final int incrBy = wide ? readShort(byteCodes, i++)
776 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
778 emit(smapper, this, "@1 += @2;",
779 lmapper.getI(varIndx),
780 Integer.toString(incrBy));
785 emit(smapper, this, "return;");
788 emit(smapper, this, "return @1;", smapper.popI());
791 emit(smapper, this, "return @1;", smapper.popL());
794 emit(smapper, this, "return @1;", smapper.popF());
797 emit(smapper, this, "return @1;", smapper.popD());
800 emit(smapper, this, "return @1;", smapper.popA());
803 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
806 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
809 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
812 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
816 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
819 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
822 smapper.replace(this, VarType.DOUBLE, "@1",
826 smapper.replace(this, VarType.FLOAT, "@1",
830 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
834 smapper.replace(this, VarType.LONG, "(@1).toLong()",
838 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
842 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
845 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
850 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
852 case opc_aconst_null:
853 smapper.assign(this, VarType.REFERENCE, "null");
856 smapper.assign(this, VarType.INTEGER, "-1");
859 smapper.assign(this, VarType.INTEGER, "0");
862 smapper.assign(this, VarType.DOUBLE, "0");
865 smapper.assign(this, VarType.LONG, "0");
868 smapper.assign(this, VarType.FLOAT, "0");
871 smapper.assign(this, VarType.INTEGER, "1");
874 smapper.assign(this, VarType.LONG, "1");
877 smapper.assign(this, VarType.FLOAT, "1");
880 smapper.assign(this, VarType.DOUBLE, "1");
883 smapper.assign(this, VarType.INTEGER, "2");
886 smapper.assign(this, VarType.FLOAT, "2");
889 smapper.assign(this, VarType.INTEGER, "3");
892 smapper.assign(this, VarType.INTEGER, "4");
895 smapper.assign(this, VarType.INTEGER, "5");
898 int indx = readUByte(byteCodes, ++i);
899 String v = encodeConstant(indx);
900 int type = VarType.fromConstantType(jc.getTag(indx));
901 smapper.assign(this, type, v);
906 int indx = readUShortArg(byteCodes, i);
908 String v = encodeConstant(indx);
909 int type = VarType.fromConstantType(jc.getTag(indx));
910 if (type == VarType.LONG) {
911 final Long lv = new Long(v);
912 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
913 final int hi = (int)(lv.longValue() >> 32);
915 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
917 smapper.assign(this, VarType.LONG,
918 "0x" + Integer.toHexString(hi) + ".next32(0x" +
919 Integer.toHexString(low) + ")"
923 smapper.assign(this, type, v);
928 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
932 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
936 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
939 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
940 "===", topMostLabel);
943 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
944 "!==", topMostLabel);
947 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
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);
979 int indx = i + readShortArg(byteCodes, i);
980 emitIf(smapper, this, "if ((@1) > 0) ",
981 smapper.popI(), i, indx, topMostLabel);
986 int indx = i + readShortArg(byteCodes, i);
987 emitIf(smapper, this, "if ((@1) >= 0) ",
988 smapper.popI(), i, indx, topMostLabel);
992 case opc_ifnonnull: {
993 int indx = i + readShortArg(byteCodes, i);
994 emitIf(smapper, this, "if ((@1) !== null) ",
995 smapper.popA(), i, indx, topMostLabel);
1000 int indx = i + readShortArg(byteCodes, i);
1001 emitIf(smapper, this, "if ((@1) === null) ",
1002 smapper.popA(), i, indx, topMostLabel);
1007 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1008 "!=", topMostLabel);
1011 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1015 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1016 "<=", topMostLabel);
1019 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1023 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1024 ">=", topMostLabel);
1027 smapper.flush(this);
1028 int indx = i + readShortArg(byteCodes, i);
1029 goTo(this, i, indx, topMostLabel);
1033 case opc_lookupswitch: {
1034 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1037 case opc_tableswitch: {
1038 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1041 case opc_invokeinterface: {
1042 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1045 case opc_invokevirtual:
1046 i = invokeVirtualMethod(byteCodes, i, smapper);
1048 case opc_invokespecial:
1049 i = invokeStaticMethod(byteCodes, i, smapper, false);
1051 case opc_invokestatic:
1052 i = invokeStaticMethod(byteCodes, i, smapper, true);
1054 case opc_invokedynamic: {
1055 int indx = readUShortArg(byteCodes, i);
1056 System.err.println("invoke dynamic: " + indx);
1057 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1058 System.err.println(" bootmethod: " + jc.getBootMethod(c2.cpx1));
1059 System.err.println(" name and type: " + jc.stringValue(c2.cpx2, true));
1060 emit(smapper, this, "throw 'Invoke dynamic: ' + @1;", "" + indx);
1065 int indx = readUShortArg(byteCodes, i);
1066 String ci = jc.getClassName(indx);
1067 emit(smapper, this, "var @1 = new @2;",
1068 smapper.pushA(), accessClass(mangleClassName(ci)));
1074 int atype = readUByte(byteCodes, ++i);
1075 generateNewArray(atype, smapper);
1077 case opc_anewarray: {
1078 int type = readUShortArg(byteCodes, i);
1080 generateANewArray(type, smapper);
1083 case opc_multianewarray: {
1084 int type = readUShortArg(byteCodes, i);
1086 i = generateMultiANewArray(type, byteCodes, i, smapper);
1089 case opc_arraylength:
1090 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1093 emit(smapper, this, "Array.at(@3, @2, @1);",
1094 smapper.popL(), smapper.popI(), smapper.popA());
1097 emit(smapper, this, "Array.at(@3, @2, @1);",
1098 smapper.popF(), smapper.popI(), smapper.popA());
1101 emit(smapper, this, "Array.at(@3, @2, @1);",
1102 smapper.popD(), smapper.popI(), smapper.popA());
1105 emit(smapper, this, "Array.at(@3, @2, @1);",
1106 smapper.popA(), smapper.popI(), smapper.popA());
1112 emit(smapper, this, "Array.at(@3, @2, @1);",
1113 smapper.popI(), smapper.popI(), smapper.popA());
1116 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1117 smapper.popI(), smapper.getA(0));
1120 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1121 smapper.popI(), smapper.getA(0));
1124 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1125 smapper.popI(), smapper.getA(0));
1128 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1129 smapper.popI(), smapper.getA(0));
1135 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1136 smapper.popI(), smapper.getA(0));
1144 final Variable v = smapper.get(0);
1145 if (smapper.isDirty()) {
1146 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1148 smapper.assign(this, v.getType(), v);
1153 final Variable vi1 = smapper.get(0);
1155 if (vi1.isCategory2()) {
1156 emit(smapper, this, "var @1 = @2;",
1157 smapper.pushT(vi1.getType()), vi1);
1159 final Variable vi2 = smapper.get(1);
1160 emit(smapper, this, "var @1 = @2, @3 = @4;",
1161 smapper.pushT(vi2.getType()), vi2,
1162 smapper.pushT(vi1.getType()), vi1);
1167 final Variable vi1 = smapper.pop(this);
1168 final Variable vi2 = smapper.pop(this);
1169 final Variable vo3 = smapper.pushT(vi1.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, vo1);
1178 final Variable vi1 = smapper.pop(this);
1179 final Variable vi2 = smapper.pop(this);
1181 if (vi1.isCategory2()) {
1182 final Variable vo3 = smapper.pushT(vi1.getType());
1183 final Variable vo2 = smapper.pushT(vi2.getType());
1184 final Variable vo1 = smapper.pushT(vi1.getType());
1186 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1187 vo1, vi1, vo2, vi2, vo3, vo1);
1189 final Variable vi3 = smapper.pop(this);
1190 final Variable vo5 = smapper.pushT(vi2.getType());
1191 final Variable vo4 = smapper.pushT(vi1.getType());
1192 final Variable vo3 = smapper.pushT(vi3.getType());
1193 final Variable vo2 = smapper.pushT(vi2.getType());
1194 final Variable vo1 = smapper.pushT(vi1.getType());
1196 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1197 vo1, vi1, vo2, vi2, vo3, vi3);
1198 emit(smapper, this, " @1 = @2, @3 = @4;",
1199 vo4, vo1, vo5, vo2);
1204 final Variable vi1 = smapper.pop(this);
1205 final Variable vi2 = smapper.pop(this);
1207 if (vi2.isCategory2()) {
1208 final Variable vo3 = smapper.pushT(vi1.getType());
1209 final Variable vo2 = smapper.pushT(vi2.getType());
1210 final Variable vo1 = smapper.pushT(vi1.getType());
1212 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1213 vo1, vi1, vo2, vi2, vo3, vo1);
1215 final Variable vi3 = smapper.pop(this);
1216 final Variable vo4 = smapper.pushT(vi1.getType());
1217 final Variable vo3 = smapper.pushT(vi3.getType());
1218 final Variable vo2 = smapper.pushT(vi2.getType());
1219 final Variable vo1 = smapper.pushT(vi1.getType());
1221 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1222 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1227 final Variable vi1 = smapper.pop(this);
1228 final Variable vi2 = smapper.pop(this);
1230 if (vi1.isCategory2()) {
1231 if (vi2.isCategory2()) {
1232 final Variable vo3 = smapper.pushT(vi1.getType());
1233 final Variable vo2 = smapper.pushT(vi2.getType());
1234 final Variable vo1 = smapper.pushT(vi1.getType());
1236 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1237 vo1, vi1, vo2, vi2, vo3, vo1);
1239 final Variable vi3 = smapper.pop(this);
1240 final Variable vo4 = smapper.pushT(vi1.getType());
1241 final Variable vo3 = smapper.pushT(vi3.getType());
1242 final Variable vo2 = smapper.pushT(vi2.getType());
1243 final Variable vo1 = smapper.pushT(vi1.getType());
1245 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1246 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1249 final Variable vi3 = smapper.pop(this);
1251 if (vi3.isCategory2()) {
1252 final Variable vo5 = smapper.pushT(vi2.getType());
1253 final Variable vo4 = smapper.pushT(vi1.getType());
1254 final Variable vo3 = smapper.pushT(vi3.getType());
1255 final Variable vo2 = smapper.pushT(vi2.getType());
1256 final Variable vo1 = smapper.pushT(vi1.getType());
1258 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1259 vo1, vi1, vo2, vi2, vo3, vi3);
1260 emit(smapper, this, " @1 = @2, @3 = @4;",
1261 vo4, vo1, vo5, vo2);
1263 final Variable vi4 = smapper.pop(this);
1264 final Variable vo6 = smapper.pushT(vi2.getType());
1265 final Variable vo5 = smapper.pushT(vi1.getType());
1266 final Variable vo4 = smapper.pushT(vi4.getType());
1267 final Variable vo3 = smapper.pushT(vi3.getType());
1268 final Variable vo2 = smapper.pushT(vi2.getType());
1269 final Variable vo1 = smapper.pushT(vi1.getType());
1271 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1272 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1273 emit(smapper, this, " @1 = @2, @3 = @4;",
1274 vo5, vo1, vo6, vo2);
1280 final Variable vi1 = smapper.get(0);
1281 final Variable vi2 = smapper.get(1);
1283 if (vi1.getType() == vi2.getType()) {
1284 final Variable tmp = smapper.pushT(vi1.getType());
1286 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1291 smapper.pushT(vi1.getType());
1292 smapper.pushT(vi2.getType());
1297 smapper.assign(this, VarType.INTEGER,
1298 "(" + Integer.toString(byteCodes[++i]) + ")");
1301 smapper.assign(this, VarType.INTEGER,
1302 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1306 case opc_getfield: {
1307 int indx = readUShortArg(byteCodes, i);
1308 String[] fi = jc.getFieldInfoName(indx);
1309 final int type = VarType.fromFieldType(fi[2].charAt(0));
1310 final String mangleClass = mangleClassName(fi[0]);
1311 final String mangleClassAccess = accessClass(mangleClass);
1312 smapper.replace(this, type, "@2.call(@1)",
1314 accessField(mangleClassAccess + "(false)",
1320 case opc_putfield: {
1321 int indx = readUShortArg(byteCodes, i);
1322 String[] fi = jc.getFieldInfoName(indx);
1323 final int type = VarType.fromFieldType(fi[2].charAt(0));
1324 final String mangleClass = mangleClassName(fi[0]);
1325 final String mangleClassAccess = accessClass(mangleClass);
1326 emit(smapper, this, "@3.call(@2, @1);",
1329 accessField(mangleClassAccess + "(false)",
1334 case opc_getstatic: {
1335 int indx = readUShortArg(byteCodes, i);
1336 String[] fi = jc.getFieldInfoName(indx);
1337 final int type = VarType.fromFieldType(fi[2].charAt(0));
1338 String ac = accessClass(mangleClassName(fi[0]));
1339 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1340 smapper.assign(this, type, af + "()");
1342 addReference(fi[0]);
1345 case opc_putstatic: {
1346 int indx = readUShortArg(byteCodes, i);
1347 String[] fi = jc.getFieldInfoName(indx);
1348 final int type = VarType.fromFieldType(fi[2].charAt(0));
1349 emit(smapper, this, "@1(false)._@2(@3);",
1350 accessClass(mangleClassName(fi[0])), fi[1],
1351 smapper.popT(type));
1353 addReference(fi[0]);
1356 case opc_checkcast: {
1357 int indx = readUShortArg(byteCodes, i);
1358 generateCheckcast(indx, smapper);
1362 case opc_instanceof: {
1363 int indx = readUShortArg(byteCodes, i);
1364 generateInstanceOf(indx, smapper);
1369 final CharSequence v = smapper.popA();
1372 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1373 smapper.pushA(), v);
1377 case opc_monitorenter: {
1378 debug("/* monitor enter */");
1383 case opc_monitorexit: {
1384 debug("/* monitor exit */");
1395 emit(smapper, this, "throw 'unknown bytecode @1';",
1396 Integer.toString(c));
1400 generateByteCodeComment(prev, i, byteCodes);
1406 if (previousTrap != null) {
1407 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1412 while (openBraces-- > 0) {
1422 private int generateIf(StackMapper mapper, byte[] byteCodes,
1423 int i, final CharSequence v2, final CharSequence v1,
1424 final String test, int topMostLabel
1425 ) throws IOException {
1427 int indx = i + readShortArg(byteCodes, i);
1428 append("if ((").append(v1)
1429 .append(") ").append(test).append(" (")
1430 .append(v2).append(")) ");
1431 goTo(this, i, indx, topMostLabel);
1435 private int readInt4(byte[] byteCodes, int offset) {
1436 final int d = byteCodes[offset + 0] << 24;
1437 final int c = byteCodes[offset + 1] << 16;
1438 final int b = byteCodes[offset + 2] << 8;
1439 final int a = byteCodes[offset + 3];
1440 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1442 private static int readUByte(byte[] byteCodes, int offset) {
1443 return byteCodes[offset] & 0xff;
1446 private static int readUShort(byte[] byteCodes, int offset) {
1447 return ((byteCodes[offset] & 0xff) << 8)
1448 | (byteCodes[offset + 1] & 0xff);
1450 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1451 return readUShort(byteCodes, offsetInstruction + 1);
1454 private static int readShort(byte[] byteCodes, int offset) {
1455 int signed = byteCodes[offset];
1456 byte b0 = (byte)signed;
1457 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1459 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1460 return readShort(byteCodes, offsetInstruction + 1);
1463 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1465 Boolean count = null;
1466 boolean array = false;
1468 int firstPos = sig.length();
1469 while (i < descriptor.length()) {
1470 char ch = descriptor.charAt(i++);
1491 if (ch == 'J' || ch == 'D') {
1497 sig.insert(firstPos, ch);
1499 returnType[0] = '[';
1500 sig.insert(firstPos, "_3");
1509 returnType[0] = 'V';
1510 sig.insert(firstPos, 'V');
1513 int next = descriptor.indexOf(';', i);
1514 String realSig = mangleSig(descriptor, i - 1, next + 1);
1519 sig.append(realSig);
1522 sig.insert(firstPos, realSig);
1524 sig.insert(firstPos, "_3");
1526 returnType[0] = 'L';
1535 throw new IllegalStateException("Invalid char: " + ch);
1540 static String mangleSig(String sig) {
1541 return mangleSig(sig, 0, sig.length());
1544 private static String mangleMethodName(String name) {
1545 StringBuilder sb = new StringBuilder(name.length() * 2);
1546 int last = name.length();
1547 for (int i = 0; i < last; i++) {
1548 final char ch = name.charAt(i);
1550 case '_': sb.append("_1"); break;
1551 default: sb.append(ch); break;
1554 return sb.toString();
1556 private static String mangleSig(String txt, int first, int last) {
1557 StringBuilder sb = new StringBuilder((last - first) * 2);
1558 for (int i = first; i < last; i++) {
1559 final char ch = txt.charAt(i);
1561 case '/': sb.append('_'); break;
1562 case '_': sb.append("_1"); break;
1563 case ';': sb.append("_2"); break;
1564 case '[': sb.append("_3"); break;
1566 if (Character.isJavaIdentifierPart(ch)) {
1570 String hex = Integer.toHexString(ch).toLowerCase();
1571 for (int m = hex.length(); m < 4; m++) {
1579 return sb.toString();
1582 private static String mangleClassName(String name) {
1583 return mangleSig(name);
1586 private static String findMethodName(MethodData m, StringBuilder cnt) {
1587 StringBuilder name = new StringBuilder();
1588 if ("<init>".equals(m.getName())) { // NOI18N
1589 name.append("cons"); // NOI18N
1590 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1591 name.append("class"); // NOI18N
1593 name.append(mangleMethodName(m.getName()));
1596 countArgs(m.getInternalSig(), new char[1], name, cnt);
1597 return name.toString();
1600 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1601 StringBuilder name = new StringBuilder();
1602 String descr = mi[2];//mi.getDescriptor();
1604 if ("<init>".equals(nm)) { // NOI18N
1605 name.append("cons"); // NOI18N
1607 name.append(mangleMethodName(nm));
1609 countArgs(descr, returnType, name, cnt);
1610 return name.toString();
1613 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1614 throws IOException {
1615 int methodIndex = readUShortArg(byteCodes, i);
1616 String[] mi = jc.getFieldInfoName(methodIndex);
1617 char[] returnType = { 'V' };
1618 StringBuilder cnt = new StringBuilder();
1619 String mn = findMethodName(mi, cnt, returnType);
1621 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1622 final CharSequence[] vars = new CharSequence[numArguments];
1624 for (int j = numArguments - 1; j >= 0; --j) {
1625 vars[j] = mapper.popValue();
1628 if (returnType[0] != 'V') {
1631 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1635 final String in = mi[0];
1637 if (callbacks && in.equals("org/apidesign/html/boot/spi/Fn")) {
1638 mcn = "java_lang_Class";
1640 mcn = mangleClassName(in);
1642 String object = accessClass(mcn) + "(false)";
1643 if (mn.startsWith("cons_")) {
1644 object += ".constructor";
1646 append(accessStaticMethod(object, mn, mi));
1652 if (numArguments > 0) {
1654 for (int j = 1; j < numArguments; ++j) {
1664 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1665 throws IOException {
1666 int methodIndex = readUShortArg(byteCodes, i);
1667 String[] mi = jc.getFieldInfoName(methodIndex);
1668 char[] returnType = { 'V' };
1669 StringBuilder cnt = new StringBuilder();
1670 String mn = findMethodName(mi, cnt, returnType);
1672 final int numArguments = cnt.length() + 1;
1673 final CharSequence[] vars = new CharSequence[numArguments];
1675 for (int j = numArguments - 1; j >= 0; --j) {
1676 vars[j] = mapper.popValue();
1679 if (returnType[0] != 'V') {
1681 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1685 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1687 for (int j = 1; j < numArguments; ++j) {
1697 private void addReference(String cn) throws IOException {
1698 if (requireReference(cn)) {
1699 debug(" /* needs " + cn + " */");
1703 private void outType(String d, StringBuilder out) {
1705 while (d.charAt(0) == '[') {
1709 if (d.charAt(0) == 'L') {
1710 assert d.charAt(d.length() - 1) == ';';
1711 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1717 private String encodeConstant(int entryIndex) throws IOException {
1718 String[] classRef = { null };
1719 String s = jc.stringValue(entryIndex, classRef);
1720 if (classRef[0] != null) {
1721 if (classRef[0].startsWith("[")) {
1722 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1724 addReference(classRef[0]);
1725 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1731 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1732 byte[] arr = m.findAnnotationData(true);
1736 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1737 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1738 class P extends AnnotationParser {
1744 String[] args = new String[30];
1750 protected void visitAttr(String type, String attr, String at, String value) {
1751 if (type.equals(jvmType)) {
1752 if ("body".equals(attr)) {
1754 } else if ("args".equals(attr)) {
1755 args[cnt++] = value;
1757 throw new IllegalArgumentException(attr);
1760 if (type.equals(htmlType)) {
1762 if ("body".equals(attr)) {
1764 } else if ("args".equals(attr)) {
1765 args[cnt++] = value;
1766 } else if ("javacall".equals(attr)) {
1767 javacall = "1".equals(value);
1768 } else if ("wait4js".equals(attr)) {
1769 // ignore, we always invoke synchronously
1771 throw new IllegalArgumentException(attr);
1778 if (p.body == null) {
1781 StringBuilder cnt = new StringBuilder();
1782 final String mn = findMethodName(m, cnt);
1783 append(destObject).append(".").append(mn);
1784 append(" = function(");
1787 StringBuilder toValue = new StringBuilder();
1788 for (int i = 0; i < cnt.length(); i++) {
1790 space = outputArg(this, p.args, index);
1791 if (p.html4j && space.length() > 0) {
1792 toValue.append("\n ").append(p.args[index]).append(" = ")
1793 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1794 append(p.args[index]).append(");");
1798 append(") {").append("\n");
1799 append(toValue.toString());
1801 int lastSlash = jc.getClassName().lastIndexOf('/');
1802 final String pkg = jc.getClassName().substring(0, lastSlash);
1803 append(mangleCallbacks(pkg, p.body));
1804 requireReference(pkg + "/$JsCallbacks$");
1812 private static CharSequence mangleCallbacks(String pkgName, String body) {
1813 StringBuilder sb = new StringBuilder();
1816 int next = body.indexOf(".@", pos);
1818 sb.append(body.substring(pos));
1819 body = sb.toString();
1824 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1829 String refId = body.substring(ident, next);
1831 sb.append(body.substring(pos, ident));
1833 int sigBeg = body.indexOf('(', next);
1834 int sigEnd = body.indexOf(')', sigBeg);
1835 int colon4 = body.indexOf("::", next);
1836 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1837 throw new IllegalStateException("Malformed body " + body);
1839 String fqn = body.substring(next + 2, colon4);
1840 String method = body.substring(colon4 + 2, sigBeg);
1841 String params = body.substring(sigBeg, sigEnd + 1);
1843 int paramBeg = body.indexOf('(', sigEnd + 1);
1845 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1846 sb.append(mangleJsCallbacks(fqn, method, params, false));
1847 sb.append("(").append(refId);
1848 if (body.charAt(paramBeg + 1) != ')') {
1856 int next = body.indexOf("@", pos);
1861 sb.append(body.substring(pos));
1865 sb = new StringBuilder();
1868 sb.append(body.substring(pos, next));
1870 int sigBeg = body.indexOf('(', next);
1871 int sigEnd = body.indexOf(')', sigBeg);
1872 int colon4 = body.indexOf("::", next);
1873 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1874 throw new IllegalStateException("Malformed body " + body);
1876 String fqn = body.substring(next + 1, colon4);
1877 String method = body.substring(colon4 + 2, sigBeg);
1878 String params = body.substring(sigBeg, sigEnd + 1);
1880 int paramBeg = body.indexOf('(', sigEnd + 1);
1882 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1883 sb.append(mangleJsCallbacks(fqn, method, params, true));
1889 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1890 if (params.startsWith("(")) {
1891 params = params.substring(1);
1893 if (params.endsWith(")")) {
1894 params = params.substring(0, params.length() - 1);
1896 StringBuilder sb = new StringBuilder();
1897 final String fqnu = fqn.replace('.', '_');
1898 final String rfqn = mangleClassName(fqnu);
1899 final String rm = mangleMethodName(method);
1902 StringBuilder pb = new StringBuilder();
1903 int len = params.length();
1905 while (indx < len) {
1906 char ch = params.charAt(indx);
1907 if (ch == '[' || ch == 'L') {
1908 pb.append("Ljava/lang/Object;");
1909 indx = params.indexOf(';', indx) + 1;
1915 srp = mangleSig(pb.toString());
1917 final String rp = mangleSig(params);
1918 final String mrp = mangleMethodName(rp);
1919 sb.append(rfqn).append("$").append(rm).
1920 append('$').append(mrp).append("__Ljava_lang_Object_2");
1922 sb.append('L').append(fqnu).append("_2");
1925 return sb.toString();
1928 private static String className(ClassData jc) {
1929 //return jc.getName().getInternalName().replace('/', '_');
1930 return mangleClassName(jc.getClassName());
1933 private static String[] findAnnotation(
1934 byte[] arr, ClassData cd, final String className,
1935 final String... attrNames
1936 ) throws IOException {
1940 final String[] values = new String[attrNames.length];
1941 final boolean[] found = { false };
1942 final String jvmType = "L" + className.replace('.', '/') + ";";
1943 AnnotationParser ap = new AnnotationParser(false, true) {
1945 protected void visitAttr(String type, String attr, String at, String value) {
1946 if (type.equals(jvmType)) {
1948 for (int i = 0; i < attrNames.length; i++) {
1949 if (attrNames[i].equals(attr)) {
1958 return found[0] ? values : null;
1961 private CharSequence initField(FieldData v) {
1962 final String is = v.getInternalSig();
1963 if (is.length() == 1) {
1964 switch (is.charAt(0)) {
1970 case 'I': return " = 0;";
1972 case 'D': return " = 0.0;";
1974 throw new IllegalStateException(is);
1980 private void generateAnno(ClassData cd, byte[] data) throws IOException {
1981 AnnotationParser ap = new AnnotationParser(true, false) {
1982 int[] cnt = new int[32];
1986 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
1987 final String slashType = attrType.substring(1, attrType.length() - 1);
1988 requireReference(slashType);
1990 if (cnt[depth]++ > 0) {
1994 append('"').append(attrType).append("\" : ");
2001 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2007 protected void visitValueStart(String attrName, char type) throws IOException {
2008 if (cnt[depth]++ > 0) {
2012 if (attrName != null) {
2013 append('"').append(attrName).append("\" : ");
2021 protected void visitValueEnd(String attrName, char type) throws IOException {
2029 protected void visitAttr(String type, String attr, String attrType, String value)
2030 throws IOException {
2031 if (attr == null && value == null) {
2038 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2039 throws IOException {
2040 final String slashType = attrType.substring(1, attrType.length() - 1);
2041 requireReference(slashType);
2043 final String cn = mangleClassName(slashType);
2044 append(accessClass(cn))
2045 .append("(false)['valueOf__L").
2047 append("_2Ljava_lang_String_2']('").
2055 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2056 final String name = args[indx];
2060 if (name.contains(",")) {
2061 throw new IOException("Wrong parameter with ',': " + name);
2067 final void emitNoFlush(
2069 final String format, final CharSequence... params
2070 ) throws IOException {
2071 emitImpl(this, format, params);
2073 static final void emit(
2075 final Appendable out,
2076 final String format, final CharSequence... params
2077 ) throws IOException {
2079 emitImpl(out, format, params);
2081 static void emitImpl(final Appendable out,
2082 final String format,
2083 final CharSequence... params) throws IOException {
2084 final int length = format.length();
2087 int paramOffset = format.indexOf('@');
2088 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2089 final char paramChar = format.charAt(paramOffset + 1);
2090 if ((paramChar >= '1') && (paramChar <= '9')) {
2091 final int paramIndex = paramChar - '0' - 1;
2093 out.append(format, processed, paramOffset);
2094 out.append(params[paramIndex]);
2097 processed = paramOffset + 1;
2100 paramOffset = format.indexOf('@', paramOffset + 1);
2103 out.append(format, processed, length);
2106 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2107 append("} catch (e) {\n");
2109 for (TrapData e : traps) {
2113 if (e.catch_cpx != 0) { //not finally
2114 final String classInternalName = jc.getClassName(e.catch_cpx);
2115 addReference(classInternalName);
2116 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2117 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2118 append("var stA0 = e;");
2119 goTo(this, current, e.handler_pc, topMostLabel);
2122 finallyPC = e.handler_pc;
2125 if (finallyPC == -1) {
2128 append("var stA0 = e;");
2129 goTo(this, current, finallyPC, topMostLabel);
2134 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2137 out.append("{ gt = 0; continue X_" + to + "; }");
2139 out.append("{ gt = " + to + "; continue X_0; }");
2142 out.append("{ gt = " + to + "; break IF; }");
2146 private static void emitIf(
2148 Appendable out, String pattern,
2150 int current, int to, int canBack
2151 ) throws IOException {
2153 emitImpl(out, pattern, param);
2154 goTo(out, current, to, canBack);
2157 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2160 case 4: jvmType = "[Z"; break;
2161 case 5: jvmType = "[C"; break;
2162 case 6: jvmType = "[F"; break;
2163 case 7: jvmType = "[D"; break;
2164 case 8: jvmType = "[B"; break;
2165 case 9: jvmType = "[S"; break;
2166 case 10: jvmType = "[I"; break;
2167 case 11: jvmType = "[J"; break;
2168 default: throw new IllegalStateException("Array type: " + atype);
2171 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2172 smapper.popI(), smapper.pushA(), jvmType);
2175 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2176 String typeName = jc.getClassName(type);
2177 String ref = "null";
2178 if (typeName.startsWith("[")) {
2179 typeName = "'[" + typeName + "'";
2181 ref = "vm." + mangleClassName(typeName);
2182 typeName = "'[L" + typeName + ";'";
2185 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2186 smapper.popI(), smapper.pushA(), typeName, ref);
2189 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2190 String typeName = jc.getClassName(type);
2191 int dim = readUByte(byteCodes, ++i);
2192 StringBuilder dims = new StringBuilder();
2194 for (int d = 0; d < dim; d++) {
2196 dims.insert(1, ",");
2198 dims.insert(1, smapper.popI());
2202 if (typeName.charAt(dim) == 'L') {
2203 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2206 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2207 dims.toString(), smapper.pushA(), typeName, fn
2212 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2213 int table = i / 4 * 4 + 4;
2214 int dflt = i + readInt4(byteCodes, table);
2216 int low = readInt4(byteCodes, table);
2218 int high = readInt4(byteCodes, table);
2220 final CharSequence swVar = smapper.popValue();
2221 smapper.flush(this);
2222 append("switch (").append(swVar).append(") {\n");
2223 while (low <= high) {
2224 int offset = i + readInt4(byteCodes, table);
2226 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2229 append(" default: ");
2230 goTo(this, i, dflt, topMostLabel);
2236 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2237 int table = i / 4 * 4 + 4;
2238 int dflt = i + readInt4(byteCodes, table);
2240 int n = readInt4(byteCodes, table);
2242 final CharSequence swVar = smapper.popValue();
2243 smapper.flush(this);
2244 append("switch (").append(swVar).append(") {\n");
2246 int cnstnt = readInt4(byteCodes, table);
2248 int offset = i + readInt4(byteCodes, table);
2250 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2252 append(" default: ");
2253 goTo(this, i, dflt, topMostLabel);
2259 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2260 String type = jc.getClassName(indx);
2261 if (!type.startsWith("[")) {
2263 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2264 smapper.popA(), smapper.pushI(),
2265 type.replace('/', '_'));
2268 while (type.charAt(cnt) == '[') {
2271 if (type.charAt(cnt) == 'L') {
2272 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2274 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2275 smapper.popA(), smapper.pushI(),
2280 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2281 smapper.popA(), smapper.pushI(), type
2287 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2288 String type = jc.getClassName(indx);
2289 if (!type.startsWith("[")) {
2290 emitNoFlush(smapper,
2291 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2292 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2295 while (type.charAt(cnt) == '[') {
2298 if (type.charAt(cnt) == 'L') {
2299 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2300 emitNoFlush(smapper,
2301 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2302 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2305 emitNoFlush(smapper,
2306 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2307 smapper.getT(0, VarType.REFERENCE, false), type
2313 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2314 for (int j = prev; j <= i; j++) {
2316 final int cc = readUByte(byteCodes, j);
2317 append(Integer.toString(cc));