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 org.apidesign.bck2brwsr.core.JavaScriptBody;
23 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
25 /** Translator of the code inside class files to JavaScript.
27 * @author Jaroslav Tulach <jtulach@netbeans.org>
29 abstract class ByteCodeToJavaScript implements Appendable {
31 private final Appendable out;
32 private boolean outChanged;
33 private boolean callbacks;
35 protected ByteCodeToJavaScript(Appendable out) {
40 public final Appendable append(CharSequence csq) throws IOException {
47 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
48 out.append(csq, start, end);
54 public final Appendable append(char c) throws IOException {
60 /* Collects additional required resources.
62 * @param internalClassName classes that were referenced and should be loaded in order the
63 * generated JavaScript code works properly. The names are in internal
64 * JVM form so String is <code>java/lang/String</code>.
66 protected abstract boolean requireReference(String internalClassName);
69 * @param resourcePath name of resources to read
71 protected abstract void requireScript(String resourcePath) throws IOException;
73 /** Allows subclasses to redefine what field a function representing a
74 * class gets assigned. By default it returns the suggested name followed
75 * by <code>" = "</code>;
77 * @param className suggested name of the class
79 /* protected */ String assignClass(String className) {
80 return className + " = ";
82 /* protected */ String accessClass(String classOperation) {
83 return classOperation;
86 protected String accessField(String object, String mangledName,
87 String[] fieldInfoName) throws IOException {
88 return object + "." + mangledName;
91 protected String accessStaticMethod(
94 String[] fieldInfoName) throws IOException {
95 return object + "." + mangledName;
98 protected String accessVirtualMethod(
101 String[] fieldInfoName,
103 ) throws IOException {
104 return object + "." + mangledName + '(';
107 protected void declaredClass(ClassData classData, String mangledName)
111 protected void declaredField(FieldData fieldData,
113 String mangledName) throws IOException {
116 protected void declaredMethod(MethodData methodData,
118 String mangledName) throws IOException {
121 /** Prints out a debug message.
123 * @param msg the message
124 * @return true if the message has been printed
125 * @throws IOException
127 boolean debug(String msg) throws IOException {
133 * Converts a given class file to a JavaScript version.
135 * @param classFile input stream with code of the .class file
136 * @return the initialization code for this class, if any. Otherwise <code>null</code>
138 * @throws IOException if something goes wrong during read or write or translating
141 public String compile(InputStream classFile) throws IOException {
142 return compile(new ClassData(classFile));
145 protected String compile(ClassData classData) throws IOException {
147 this.callbacks = this.jc.getClassName().endsWith("/$JsCallbacks$");
148 if (jc.getMajor_version() < 50) {
149 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
150 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
153 byte[] arrData = jc.findAnnotationData(true);
155 String[] arr = findAnnotation(arrData, jc,
156 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
157 "resource", "processByteCode"
160 if (!arr[0].isEmpty()) {
161 requireScript(arr[0]);
163 if ("0".equals(arr[1])) {
169 String[] arr = findAnnotation(arrData, jc,
170 "net.java.html.js.JavaScriptResource",
174 if (arr[0].startsWith("/")) {
175 requireScript(arr[0]);
177 int last = jc.getClassName().lastIndexOf('/');
179 jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0]
184 String[] proto = findAnnotation(arrData, jc,
185 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
186 "container", "prototype"
188 StringArray toInitilize = new StringArray();
189 final String className = className(jc);
190 append("\n\n").append(assignClass(className));
191 append("function ").append(className).append("() {");
192 append("\n var CLS = ").append(className).append(';');
193 append("\n if (!CLS.$class) {");
195 String sc = jc.getSuperClassName(); // with _
196 append("\n var pp = ").
197 append(accessClass(mangleClassName(sc))).append("(true);");
198 append("\n var p = CLS.prototype = pp;");
199 append("\n var c = p;");
200 append("\n var sprcls = pp.constructor.$class;");
202 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
203 if (proto[0] == null) {
206 append("\n var c = ").append(proto[0]).append(";");
207 append("\n var sprcls = null;");
209 for (FieldData v : jc.getFields()) {
211 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
212 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
216 append("\n CLS.fld_").append(v.getName()).append(initField(v));
217 append("\n c._").append(v.getName()).append(" = function (v) {")
218 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
219 .append(" = v; return CLS.fld_").
220 append(v.getName()).append("; };");
222 append("\n c._").append(v.getName()).append(" = function (v) {")
223 .append(" if (arguments.length == 1) this.fld_").
224 append(className).append('_').append(v.getName())
225 .append(" = v; return this.fld_").
226 append(className).append('_').append(v.getName())
230 declaredField(v, "c", "_" + v.getName());
232 for (MethodData m : jc.getMethods()) {
233 byte[] onlyArr = m.findAnnotationData(true);
234 if (javaScriptOnly(onlyArr)) continue;
240 mn = generateStaticMethod(destObject, m, toInitilize);
242 if (m.isConstructor()) {
244 mn = generateInstanceMethod(destObject, m);
247 mn = generateInstanceMethod(destObject, m);
250 declaredMethod(m, destObject, mn);
251 byte[] runAnno = m.findAnnotationData(false);
252 if (runAnno != null) {
253 append("\n ").append(destObject).append(".").append(mn).append(".anno = {");
254 generateAnno(jc, runAnno);
257 append("\n ").append(destObject).append(".").append(mn).append(".access = " + m.getAccess()).append(";");
258 append("\n ").append(destObject).append(".").append(mn).append(".cls = CLS;");
260 append("\n c.constructor = CLS;");
261 append("\n function ").append(className).append("fillInstOf(x) {");
262 String instOfName = "$instOf_" + className;
263 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
264 if (jc.isInterface()) {
265 for (MethodData m : jc.getMethods()) {
266 if ((m.getAccess() & ACC_ABSTRACT) == 0
267 && (m.getAccess() & ACC_STATIC) == 0
268 && (m.getAccess() & ACC_PRIVATE) == 0) {
269 final String mn = findMethodName(m, new StringBuilder());
271 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
272 append("\n } catch (ignore) {");
277 for (String superInterface : jc.getSuperInterfaces()) {
278 String intrfc = superInterface.replace('/', '_');
279 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
280 requireReference(superInterface);
284 append("\n Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
285 append("\n ").append(className).append("fillInstOf(c);");
286 append("\n } catch (ignore) {");
288 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
289 append("\n CLS.$class = 'temp';");
290 append("\n CLS.$class = ");
291 append(accessClass("java_lang_Class(true);"));
292 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
293 append("\n CLS.$class.superclass = sprcls;");
294 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
295 append("\n CLS.$class.cnstr = CLS;");
296 byte[] classAnno = jc.findAnnotationData(false);
297 if (classAnno != null) {
298 append("\n CLS.$class.anno = {");
299 generateAnno(jc, classAnno);
302 for (String init : toInitilize.toArray()) {
303 append("\n ").append(init).append("();");
306 append("\n if (arguments.length === 0) {");
307 append("\n if (!(this instanceof CLS)) {");
308 append("\n return new CLS();");
310 for (FieldData v : jc.getFields()) {
311 byte[] onlyArr = v.findAnnotationData(true);
312 if (javaScriptOnly(onlyArr)) continue;
314 append("\n this.fld_").
315 append(className).append('_').
316 append(v.getName()).append(initField(v));
319 append("\n return this;");
321 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
324 declaredClass(jc, className);
326 // StringBuilder sb = new StringBuilder();
327 // for (String init : toInitilize.toArray()) {
328 // sb.append("\n").append(init).append("();");
333 private boolean javaScriptOnly(byte[] anno) throws IOException {
334 String[] only = findAnnotation(anno, jc,
335 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
339 if (only[0] != null && only[1] != null) {
340 append("\n p.").append(only[0]).append(" = ")
341 .append(only[1]).append(";");
343 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
344 append("\n p['").append(only[0]).append("'] = p.")
345 .append(only[0]).append(";");
351 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
352 String jsb = javaScriptBody(destObject, m, true);
356 final String mn = findMethodName(m, new StringBuilder());
357 if (mn.equals("class__V")) {
358 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
360 generateMethod(destObject, mn, m);
364 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
365 String jsb = javaScriptBody(destObject, m, false);
369 final String mn = findMethodName(m, new StringBuilder());
370 generateMethod(destObject, mn, m);
374 private void generateMethod(String destObject, String name, MethodData m)
376 final StackMapIterator stackMapIterator = m.createStackMapIterator();
377 TrapDataIterator trap = m.getTrapDataIterator();
378 final LocalsMapper lmapper =
379 new LocalsMapper(stackMapIterator.getArguments());
381 boolean obj = "java/lang/Object".equals(jc.getClassName());
384 append("Object.defineProperty(").append(destObject).
385 append(", '").append(name).append("', { configurable: true, writable: true, value: function(");
387 append(destObject).append(".").append(name).append(" = function(");
389 lmapper.outputArguments(this, m.isStatic());
390 append(") {").append("\n");
392 final byte[] byteCodes = m.getCode();
393 if (byteCodes == null) {
394 append(" throw 'no code found for ")
395 .append(jc.getClassName()).append('.')
396 .append(m.getName()).append("';\n");
404 final StackMapper smapper = new StackMapper();
407 append(" var ").append(" lcA0 = this;\n");
411 TrapData[] previousTrap = null;
412 boolean wide = false;
414 if (stackMapIterator.isEmpty()) {
420 append("\n var gt = 0;\n");
424 int topMostLabel = 0;
425 for (int i = 0; i < byteCodes.length; i++) {
428 stackMapIterator.advanceTo(i);
429 boolean changeInCatch = trap.advanceTo(i);
430 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
431 if (previousTrap != null) {
432 generateCatch(previousTrap, i, topMostLabel);
436 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
441 if (openBraces > 64) {
442 for (int c = 0; c < 64; c++) {
449 lastStackFrame = stackMapIterator.getFrameIndex();
450 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
451 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
452 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
454 changeInCatch = true;
456 debug(" /* " + i + " */ ");
458 if (changeInCatch && trap.useTry()) {
460 previousTrap = trap.current();
462 final int c = readUByte(byteCodes, i);
465 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
468 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
471 smapper.assign(this, VarType.LONG, lmapper.getL(0));
474 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
477 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
480 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
483 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
486 smapper.assign(this, VarType.LONG, lmapper.getL(1));
489 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
492 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
495 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
498 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
501 smapper.assign(this, VarType.LONG, lmapper.getL(2));
504 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
507 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
510 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
513 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
516 smapper.assign(this, VarType.LONG, lmapper.getL(3));
519 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
522 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
526 final int indx = wide ? readUShort(byteCodes, i++)
527 : readUByte(byteCodes, i);
529 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
534 final int indx = wide ? readUShort(byteCodes, i++)
535 : readUByte(byteCodes, i);
537 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
542 final int indx = wide ? readUShort(byteCodes, i++)
543 : readUByte(byteCodes, i);
545 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
550 final int indx = wide ? readUShort(byteCodes, i++)
551 : readUByte(byteCodes, i);
553 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
558 final int indx = wide ? readUShort(byteCodes, i++)
559 : readUByte(byteCodes, i);
561 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
566 final int indx = wide ? readUShort(byteCodes, i++)
567 : readUByte(byteCodes, i);
569 emit(smapper, this, "var @1 = @2;",
570 lmapper.setI(indx), smapper.popI());
575 final int indx = wide ? readUShort(byteCodes, i++)
576 : readUByte(byteCodes, i);
578 emit(smapper, this, "var @1 = @2;",
579 lmapper.setL(indx), smapper.popL());
584 final int indx = wide ? readUShort(byteCodes, i++)
585 : readUByte(byteCodes, i);
587 emit(smapper, this, "var @1 = @2;",
588 lmapper.setF(indx), smapper.popF());
593 final int indx = wide ? readUShort(byteCodes, i++)
594 : readUByte(byteCodes, i);
596 emit(smapper, this, "var @1 = @2;",
597 lmapper.setD(indx), smapper.popD());
602 final int indx = wide ? readUShort(byteCodes, i++)
603 : readUByte(byteCodes, i);
605 emit(smapper, this, "var @1 = @2;",
606 lmapper.setA(indx), smapper.popA());
610 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
613 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
616 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
619 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
622 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
625 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
628 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
631 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
634 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
637 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
640 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
643 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
646 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
649 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
652 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
655 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
658 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
661 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
664 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
667 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
670 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
673 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
676 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
679 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
682 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
685 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
688 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
691 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
694 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
697 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", 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).div32(@2)",
707 smapper.getI(1), smapper.popI());
710 smapper.replace(this, VarType.LONG, "(@1).div64(@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).mod32(@2)",
721 smapper.getI(1), smapper.popI());
724 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
725 smapper.getL(1), smapper.popL());
728 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
731 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
734 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
737 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
740 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
743 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
746 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
749 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
752 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
755 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
758 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
761 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
764 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
767 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
770 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
773 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
776 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
779 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
783 final int varIndx = wide ? readUShort(byteCodes, i++)
784 : readUByte(byteCodes, i);
786 final int incrBy = wide ? readShort(byteCodes, i++)
790 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
792 emit(smapper, this, "@1 += @2;",
793 lmapper.getI(varIndx),
794 Integer.toString(incrBy));
799 emit(smapper, this, "return;");
802 emit(smapper, this, "return @1;", smapper.popI());
805 emit(smapper, this, "return @1;", smapper.popL());
808 emit(smapper, this, "return @1;", smapper.popF());
811 emit(smapper, this, "return @1;", smapper.popD());
814 emit(smapper, this, "return @1;", smapper.popA());
817 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
820 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
823 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
826 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
830 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
833 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
836 smapper.replace(this, VarType.DOUBLE, "@1",
840 smapper.replace(this, VarType.FLOAT, "@1",
844 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
848 smapper.replace(this, VarType.LONG, "(@1).toLong()",
852 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
856 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
859 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
863 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
865 case opc_aconst_null:
866 smapper.assign(this, VarType.REFERENCE, "null");
869 smapper.assign(this, VarType.INTEGER, "-1");
872 smapper.assign(this, VarType.INTEGER, "0");
875 smapper.assign(this, VarType.DOUBLE, "0");
878 smapper.assign(this, VarType.LONG, "0");
881 smapper.assign(this, VarType.FLOAT, "0");
884 smapper.assign(this, VarType.INTEGER, "1");
887 smapper.assign(this, VarType.LONG, "1");
890 smapper.assign(this, VarType.FLOAT, "1");
893 smapper.assign(this, VarType.DOUBLE, "1");
896 smapper.assign(this, VarType.INTEGER, "2");
899 smapper.assign(this, VarType.FLOAT, "2");
902 smapper.assign(this, VarType.INTEGER, "3");
905 smapper.assign(this, VarType.INTEGER, "4");
908 smapper.assign(this, VarType.INTEGER, "5");
911 int indx = readUByte(byteCodes, ++i);
912 String v = encodeConstant(indx);
913 int type = VarType.fromConstantType(jc.getTag(indx));
914 smapper.assign(this, type, v);
919 int indx = readUShortArg(byteCodes, i);
921 String v = encodeConstant(indx);
922 int type = VarType.fromConstantType(jc.getTag(indx));
923 if (type == VarType.LONG) {
924 final Long lv = new Long(v);
925 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
926 final int hi = (int)(lv.longValue() >> 32);
928 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
930 smapper.assign(this, VarType.LONG,
931 "0x" + Integer.toHexString(hi) + ".next32(0x" +
932 Integer.toHexString(low) + ")"
936 smapper.assign(this, type, v);
941 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
945 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
949 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
952 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
953 "===", topMostLabel);
956 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
957 "!==", topMostLabel);
960 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
964 int indx = i + readShortArg(byteCodes, i);
965 emitIf(smapper, this, "if ((@1) == 0) ",
966 smapper.popI(), i, indx, topMostLabel);
971 int indx = i + readShortArg(byteCodes, i);
972 emitIf(smapper, this, "if ((@1) != 0) ",
973 smapper.popI(), i, indx, topMostLabel);
978 int indx = i + readShortArg(byteCodes, i);
979 emitIf(smapper, this, "if ((@1) < 0) ",
980 smapper.popI(), i, indx, topMostLabel);
985 int indx = i + readShortArg(byteCodes, i);
986 emitIf(smapper, this, "if ((@1) <= 0) ",
987 smapper.popI(), i, indx, topMostLabel);
992 int indx = i + readShortArg(byteCodes, i);
993 emitIf(smapper, this, "if ((@1) > 0) ",
994 smapper.popI(), i, indx, topMostLabel);
999 int indx = i + readShortArg(byteCodes, i);
1000 emitIf(smapper, this, "if ((@1) >= 0) ",
1001 smapper.popI(), i, indx, topMostLabel);
1005 case opc_ifnonnull: {
1006 int indx = i + readShortArg(byteCodes, i);
1007 emitIf(smapper, this, "if ((@1) !== null) ",
1008 smapper.popA(), i, indx, topMostLabel);
1013 int indx = i + readShortArg(byteCodes, i);
1014 emitIf(smapper, this, "if ((@1) === null) ",
1015 smapper.popA(), i, indx, topMostLabel);
1020 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1021 "!=", topMostLabel);
1024 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1028 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1029 "<=", topMostLabel);
1032 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1036 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1037 ">=", topMostLabel);
1040 smapper.flush(this);
1041 int indx = i + readShortArg(byteCodes, i);
1042 goTo(this, i, indx, topMostLabel);
1046 case opc_lookupswitch: {
1047 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1050 case opc_tableswitch: {
1051 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1054 case opc_invokeinterface: {
1055 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1058 case opc_invokevirtual:
1059 i = invokeVirtualMethod(byteCodes, i, smapper);
1061 case opc_invokespecial:
1062 i = invokeStaticMethod(byteCodes, i, smapper, false);
1064 case opc_invokestatic:
1065 i = invokeStaticMethod(byteCodes, i, smapper, true);
1067 case opc_invokedynamic: {
1068 int indx = readUShortArg(byteCodes, i);
1069 println("invoke dynamic: " + indx);
1070 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1071 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1072 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1073 println(" type: " + methodHandle.cpx1);
1074 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1075 String mcn = mangleClassName(mi[0]);
1076 char[] returnType = {'V'};
1077 StringBuilder cnt = new StringBuilder();
1078 String mn = findMethodName(mi, cnt, returnType);
1079 println(" mi[0]: " + mi[0]);
1080 println(" mi[1]: " + mi[1]);
1081 println(" mi[2]: " + mi[2]);
1082 println(" mn : " + mn);
1083 println(" name and type: " + jc.stringValue(c2.cpx2, true));
1084 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1085 String type = jc.StringValue(nameAndType.cpx2);
1086 String object = accessClass(mcn) + "(false)";
1087 if (mn.startsWith("cons_")) {
1088 object += ".constructor";
1090 append("var metHan = ");
1091 append(accessStaticMethod(object, mn, mi));
1093 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1095 append(", '").append(mi[1]).append("', ");
1096 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1097 append(methodType).append("'").append(type).append("', null)");
1098 // if (numArguments > 0) {
1100 // for (int j = 1; j < numArguments; ++j) {
1106 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1111 int indx = readUShortArg(byteCodes, i);
1112 String ci = jc.getClassName(indx);
1113 emit(smapper, this, "var @1 = new @2;",
1114 smapper.pushA(), accessClass(mangleClassName(ci)));
1120 int atype = readUByte(byteCodes, ++i);
1121 generateNewArray(atype, smapper);
1123 case opc_anewarray: {
1124 int type = readUShortArg(byteCodes, i);
1126 generateANewArray(type, smapper);
1129 case opc_multianewarray: {
1130 int type = readUShortArg(byteCodes, i);
1132 i = generateMultiANewArray(type, byteCodes, i, smapper);
1135 case opc_arraylength:
1136 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1139 emit(smapper, this, "Array.at(@3, @2, @1);",
1140 smapper.popL(), smapper.popI(), smapper.popA());
1143 emit(smapper, this, "Array.at(@3, @2, @1);",
1144 smapper.popF(), smapper.popI(), smapper.popA());
1147 emit(smapper, this, "Array.at(@3, @2, @1);",
1148 smapper.popD(), smapper.popI(), smapper.popA());
1151 emit(smapper, this, "Array.at(@3, @2, @1);",
1152 smapper.popA(), smapper.popI(), smapper.popA());
1158 emit(smapper, this, "Array.at(@3, @2, @1);",
1159 smapper.popI(), smapper.popI(), smapper.popA());
1162 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1163 smapper.popI(), smapper.getA(0));
1166 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1167 smapper.popI(), smapper.getA(0));
1170 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1171 smapper.popI(), smapper.getA(0));
1174 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1175 smapper.popI(), smapper.getA(0));
1181 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1182 smapper.popI(), smapper.getA(0));
1190 final Variable v = smapper.get(0);
1191 if (smapper.isDirty()) {
1192 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1194 smapper.assign(this, v.getType(), v);
1199 final Variable vi1 = smapper.get(0);
1201 if (vi1.isCategory2()) {
1202 emit(smapper, this, "var @1 = @2;",
1203 smapper.pushT(vi1.getType()), vi1);
1205 final Variable vi2 = smapper.get(1);
1206 emit(smapper, this, "var @1 = @2, @3 = @4;",
1207 smapper.pushT(vi2.getType()), vi2,
1208 smapper.pushT(vi1.getType()), vi1);
1213 final Variable vi1 = smapper.pop(this);
1214 final Variable vi2 = smapper.pop(this);
1215 final Variable vo3 = smapper.pushT(vi1.getType());
1216 final Variable vo2 = smapper.pushT(vi2.getType());
1217 final Variable vo1 = smapper.pushT(vi1.getType());
1219 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1220 vo1, vi1, vo2, vi2, vo3, vo1);
1224 final Variable vi1 = smapper.pop(this);
1225 final Variable vi2 = smapper.pop(this);
1227 if (vi1.isCategory2()) {
1228 final Variable vo3 = smapper.pushT(vi1.getType());
1229 final Variable vo2 = smapper.pushT(vi2.getType());
1230 final Variable vo1 = smapper.pushT(vi1.getType());
1232 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1233 vo1, vi1, vo2, vi2, vo3, vo1);
1235 final Variable vi3 = smapper.pop(this);
1236 final Variable vo5 = smapper.pushT(vi2.getType());
1237 final Variable vo4 = smapper.pushT(vi1.getType());
1238 final Variable vo3 = smapper.pushT(vi3.getType());
1239 final Variable vo2 = smapper.pushT(vi2.getType());
1240 final Variable vo1 = smapper.pushT(vi1.getType());
1242 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1243 vo1, vi1, vo2, vi2, vo3, vi3);
1244 emit(smapper, this, " @1 = @2, @3 = @4;",
1245 vo4, vo1, vo5, vo2);
1250 final Variable vi1 = smapper.pop(this);
1251 final Variable vi2 = smapper.pop(this);
1253 if (vi2.isCategory2()) {
1254 final Variable vo3 = smapper.pushT(vi1.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, vo1);
1261 final Variable vi3 = smapper.pop(this);
1262 final Variable vo4 = smapper.pushT(vi1.getType());
1263 final Variable vo3 = smapper.pushT(vi3.getType());
1264 final Variable vo2 = smapper.pushT(vi2.getType());
1265 final Variable vo1 = smapper.pushT(vi1.getType());
1267 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1268 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1273 final Variable vi1 = smapper.pop(this);
1274 final Variable vi2 = smapper.pop(this);
1276 if (vi1.isCategory2()) {
1277 if (vi2.isCategory2()) {
1278 final Variable vo3 = smapper.pushT(vi1.getType());
1279 final Variable vo2 = smapper.pushT(vi2.getType());
1280 final Variable vo1 = smapper.pushT(vi1.getType());
1282 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1283 vo1, vi1, vo2, vi2, vo3, vo1);
1285 final Variable vi3 = smapper.pop(this);
1286 final Variable vo4 = smapper.pushT(vi1.getType());
1287 final Variable vo3 = smapper.pushT(vi3.getType());
1288 final Variable vo2 = smapper.pushT(vi2.getType());
1289 final Variable vo1 = smapper.pushT(vi1.getType());
1291 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1292 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1295 final Variable vi3 = smapper.pop(this);
1297 if (vi3.isCategory2()) {
1298 final Variable vo5 = smapper.pushT(vi2.getType());
1299 final Variable vo4 = smapper.pushT(vi1.getType());
1300 final Variable vo3 = smapper.pushT(vi3.getType());
1301 final Variable vo2 = smapper.pushT(vi2.getType());
1302 final Variable vo1 = smapper.pushT(vi1.getType());
1304 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1305 vo1, vi1, vo2, vi2, vo3, vi3);
1306 emit(smapper, this, " @1 = @2, @3 = @4;",
1307 vo4, vo1, vo5, vo2);
1309 final Variable vi4 = smapper.pop(this);
1310 final Variable vo6 = smapper.pushT(vi2.getType());
1311 final Variable vo5 = smapper.pushT(vi1.getType());
1312 final Variable vo4 = smapper.pushT(vi4.getType());
1313 final Variable vo3 = smapper.pushT(vi3.getType());
1314 final Variable vo2 = smapper.pushT(vi2.getType());
1315 final Variable vo1 = smapper.pushT(vi1.getType());
1317 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1318 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1319 emit(smapper, this, " @1 = @2, @3 = @4;",
1320 vo5, vo1, vo6, vo2);
1326 final Variable vi1 = smapper.get(0);
1327 final Variable vi2 = smapper.get(1);
1329 if (vi1.getType() == vi2.getType()) {
1330 final Variable tmp = smapper.pushT(vi1.getType());
1332 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1337 smapper.pushT(vi1.getType());
1338 smapper.pushT(vi2.getType());
1343 smapper.assign(this, VarType.INTEGER,
1344 "(" + Integer.toString(byteCodes[++i]) + ")");
1347 smapper.assign(this, VarType.INTEGER,
1348 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1352 case opc_getfield: {
1353 int indx = readUShortArg(byteCodes, i);
1354 String[] fi = jc.getFieldInfoName(indx);
1355 final int type = VarType.fromFieldType(fi[2].charAt(0));
1356 final String mangleClass = mangleClassName(fi[0]);
1357 final String mangleClassAccess = accessClass(mangleClass);
1358 smapper.replace(this, type, "@2.call(@1)",
1360 accessField(mangleClassAccess + "(false)",
1366 case opc_putfield: {
1367 int indx = readUShortArg(byteCodes, i);
1368 String[] fi = jc.getFieldInfoName(indx);
1369 final int type = VarType.fromFieldType(fi[2].charAt(0));
1370 final String mangleClass = mangleClassName(fi[0]);
1371 final String mangleClassAccess = accessClass(mangleClass);
1372 emit(smapper, this, "@3.call(@2, @1);",
1375 accessField(mangleClassAccess + "(false)",
1380 case opc_getstatic: {
1381 int indx = readUShortArg(byteCodes, i);
1382 String[] fi = jc.getFieldInfoName(indx);
1383 final int type = VarType.fromFieldType(fi[2].charAt(0));
1384 String ac = accessClass(mangleClassName(fi[0]));
1385 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1386 smapper.assign(this, type, af + "()");
1388 addReference(fi[0]);
1391 case opc_putstatic: {
1392 int indx = readUShortArg(byteCodes, i);
1393 String[] fi = jc.getFieldInfoName(indx);
1394 final int type = VarType.fromFieldType(fi[2].charAt(0));
1395 emit(smapper, this, "@1(false)._@2(@3);",
1396 accessClass(mangleClassName(fi[0])), fi[1],
1397 smapper.popT(type));
1399 addReference(fi[0]);
1402 case opc_checkcast: {
1403 int indx = readUShortArg(byteCodes, i);
1404 generateCheckcast(indx, smapper);
1408 case opc_instanceof: {
1409 int indx = readUShortArg(byteCodes, i);
1410 generateInstanceOf(indx, smapper);
1415 final CharSequence v = smapper.popA();
1418 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1419 smapper.pushA(), v);
1423 case opc_monitorenter: {
1424 debug("/* monitor enter */");
1429 case opc_monitorexit: {
1430 debug("/* monitor exit */");
1441 emit(smapper, this, "throw 'unknown bytecode @1';",
1442 Integer.toString(c));
1446 generateByteCodeComment(prev, i, byteCodes);
1452 if (previousTrap != null) {
1453 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1458 while (openBraces-- > 0) {
1468 private int generateIf(StackMapper mapper, byte[] byteCodes,
1469 int i, final CharSequence v2, final CharSequence v1,
1470 final String test, int topMostLabel
1471 ) throws IOException {
1473 int indx = i + readShortArg(byteCodes, i);
1474 append("if ((").append(v1)
1475 .append(") ").append(test).append(" (")
1476 .append(v2).append(")) ");
1477 goTo(this, i, indx, topMostLabel);
1481 private int readInt4(byte[] byteCodes, int offset) {
1482 final int d = byteCodes[offset + 0] << 24;
1483 final int c = byteCodes[offset + 1] << 16;
1484 final int b = byteCodes[offset + 2] << 8;
1485 final int a = byteCodes[offset + 3];
1486 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1488 private static int readUByte(byte[] byteCodes, int offset) {
1489 return byteCodes[offset] & 0xff;
1492 private static int readUShort(byte[] byteCodes, int offset) {
1493 return ((byteCodes[offset] & 0xff) << 8)
1494 | (byteCodes[offset + 1] & 0xff);
1496 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1497 return readUShort(byteCodes, offsetInstruction + 1);
1500 private static int readShort(byte[] byteCodes, int offset) {
1501 int signed = byteCodes[offset];
1502 byte b0 = (byte)signed;
1503 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1505 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1506 return readShort(byteCodes, offsetInstruction + 1);
1509 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1511 Boolean count = null;
1512 boolean array = false;
1514 int firstPos = sig.length();
1515 while (i < descriptor.length()) {
1516 char ch = descriptor.charAt(i++);
1537 if (ch == 'J' || ch == 'D') {
1543 sig.insert(firstPos, ch);
1545 returnType[0] = '[';
1546 sig.insert(firstPos, "_3");
1555 returnType[0] = 'V';
1556 sig.insert(firstPos, 'V');
1559 int next = descriptor.indexOf(';', i);
1560 String realSig = mangleSig(descriptor, i - 1, next + 1);
1565 sig.append(realSig);
1568 sig.insert(firstPos, realSig);
1570 sig.insert(firstPos, "_3");
1572 returnType[0] = 'L';
1581 throw new IllegalStateException("Invalid char: " + ch);
1586 static String mangleSig(String sig) {
1587 return mangleSig(sig, 0, sig.length());
1590 private static String mangleMethodName(String name) {
1591 StringBuilder sb = new StringBuilder(name.length() * 2);
1592 int last = name.length();
1593 for (int i = 0; i < last; i++) {
1594 final char ch = name.charAt(i);
1596 case '_': sb.append("_1"); break;
1597 default: sb.append(ch); break;
1600 return sb.toString();
1602 private static String mangleSig(String txt, int first, int last) {
1603 StringBuilder sb = new StringBuilder((last - first) * 2);
1604 for (int i = first; i < last; i++) {
1605 final char ch = txt.charAt(i);
1607 case '/': sb.append('_'); break;
1608 case '_': sb.append("_1"); break;
1609 case ';': sb.append("_2"); break;
1610 case '[': sb.append("_3"); break;
1612 if (Character.isJavaIdentifierPart(ch)) {
1616 String hex = Integer.toHexString(ch).toLowerCase();
1617 for (int m = hex.length(); m < 4; m++) {
1625 return sb.toString();
1628 private static String mangleClassName(String name) {
1629 return mangleSig(name);
1632 private static String findMethodName(MethodData m, StringBuilder cnt) {
1633 StringBuilder name = new StringBuilder();
1634 if ("<init>".equals(m.getName())) { // NOI18N
1635 name.append("cons"); // NOI18N
1636 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1637 name.append("class"); // NOI18N
1639 name.append(mangleMethodName(m.getName()));
1642 countArgs(m.getInternalSig(), new char[1], name, cnt);
1643 return name.toString();
1646 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1647 StringBuilder name = new StringBuilder();
1648 String descr = mi[2];//mi.getDescriptor();
1650 if ("<init>".equals(nm)) { // NOI18N
1651 name.append("cons"); // NOI18N
1653 name.append(mangleMethodName(nm));
1655 countArgs(descr, returnType, name, cnt);
1656 return name.toString();
1659 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1660 throws IOException {
1661 int methodIndex = readUShortArg(byteCodes, i);
1662 String[] mi = jc.getFieldInfoName(methodIndex);
1663 char[] returnType = { 'V' };
1664 StringBuilder cnt = new StringBuilder();
1665 String mn = findMethodName(mi, cnt, returnType);
1667 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1668 final CharSequence[] vars = new CharSequence[numArguments];
1670 for (int j = numArguments - 1; j >= 0; --j) {
1671 vars[j] = mapper.popValue();
1674 if (returnType[0] != 'V') {
1677 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1681 final String in = mi[0];
1683 if (callbacks && in.equals("org/apidesign/html/boot/spi/Fn")) {
1684 mcn = "java_lang_Class";
1686 mcn = mangleClassName(in);
1688 String object = accessClass(mcn) + "(false)";
1689 if (mn.startsWith("cons_")) {
1690 object += ".constructor";
1692 append(accessStaticMethod(object, mn, mi));
1698 if (numArguments > 0) {
1700 for (int j = 1; j < numArguments; ++j) {
1710 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1711 throws IOException {
1712 int methodIndex = readUShortArg(byteCodes, i);
1713 String[] mi = jc.getFieldInfoName(methodIndex);
1714 char[] returnType = { 'V' };
1715 StringBuilder cnt = new StringBuilder();
1716 String mn = findMethodName(mi, cnt, returnType);
1718 final int numArguments = cnt.length() + 1;
1719 final CharSequence[] vars = new CharSequence[numArguments];
1721 for (int j = numArguments - 1; j >= 0; --j) {
1722 vars[j] = mapper.popValue();
1725 if (returnType[0] != 'V') {
1727 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1731 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1733 for (int j = 1; j < numArguments; ++j) {
1743 private void addReference(String cn) throws IOException {
1744 if (requireReference(cn)) {
1745 debug(" /* needs " + cn + " */");
1749 private void outType(String d, StringBuilder out) {
1751 while (d.charAt(0) == '[') {
1755 if (d.charAt(0) == 'L') {
1756 assert d.charAt(d.length() - 1) == ';';
1757 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1763 private String encodeConstant(int entryIndex) throws IOException {
1764 String[] classRef = { null };
1765 String s = jc.stringValue(entryIndex, classRef);
1766 if (classRef[0] != null) {
1767 if (classRef[0].startsWith("[")) {
1768 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1770 addReference(classRef[0]);
1771 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1777 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1778 byte[] arr = m.findAnnotationData(true);
1782 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1783 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1784 class P extends AnnotationParser {
1790 String[] args = new String[30];
1796 protected void visitAttr(String type, String attr, String at, String value) {
1797 if (type.equals(jvmType)) {
1798 if ("body".equals(attr)) {
1800 } else if ("args".equals(attr)) {
1801 args[cnt++] = value;
1803 throw new IllegalArgumentException(attr);
1806 if (type.equals(htmlType)) {
1808 if ("body".equals(attr)) {
1810 } else if ("args".equals(attr)) {
1811 args[cnt++] = value;
1812 } else if ("javacall".equals(attr)) {
1813 javacall = "1".equals(value);
1814 } else if ("wait4js".equals(attr)) {
1815 // ignore, we always invoke synchronously
1817 throw new IllegalArgumentException(attr);
1824 if (p.body == null) {
1827 StringBuilder cnt = new StringBuilder();
1828 final String mn = findMethodName(m, cnt);
1829 append(destObject).append(".").append(mn);
1830 append(" = function(");
1833 StringBuilder toValue = new StringBuilder();
1834 for (int i = 0; i < cnt.length(); i++) {
1836 space = outputArg(this, p.args, index);
1837 if (p.html4j && space.length() > 0) {
1838 toValue.append("\n ").append(p.args[index]).append(" = ")
1839 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1840 append(p.args[index]).append(");");
1844 append(") {").append("\n");
1845 append(toValue.toString());
1847 int lastSlash = jc.getClassName().lastIndexOf('/');
1848 final String pkg = jc.getClassName().substring(0, lastSlash);
1849 append(mangleCallbacks(pkg, p.body));
1850 requireReference(pkg + "/$JsCallbacks$");
1858 private static CharSequence mangleCallbacks(String pkgName, String body) {
1859 StringBuilder sb = new StringBuilder();
1862 int next = body.indexOf(".@", pos);
1864 sb.append(body.substring(pos));
1865 body = sb.toString();
1870 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1875 String refId = body.substring(ident, next);
1877 sb.append(body.substring(pos, ident));
1879 int sigBeg = body.indexOf('(', next);
1880 int sigEnd = body.indexOf(')', sigBeg);
1881 int colon4 = body.indexOf("::", next);
1882 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1883 throw new IllegalStateException("Malformed body " + body);
1885 String fqn = body.substring(next + 2, colon4);
1886 String method = body.substring(colon4 + 2, sigBeg);
1887 String params = body.substring(sigBeg, sigEnd + 1);
1889 int paramBeg = body.indexOf('(', sigEnd + 1);
1891 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1892 sb.append(mangleJsCallbacks(fqn, method, params, false));
1893 sb.append("(").append(refId);
1894 if (body.charAt(paramBeg + 1) != ')') {
1902 int next = body.indexOf("@", pos);
1907 sb.append(body.substring(pos));
1911 sb = new StringBuilder();
1914 sb.append(body.substring(pos, next));
1916 int sigBeg = body.indexOf('(', next);
1917 int sigEnd = body.indexOf(')', sigBeg);
1918 int colon4 = body.indexOf("::", next);
1919 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1920 throw new IllegalStateException("Malformed body " + body);
1922 String fqn = body.substring(next + 1, colon4);
1923 String method = body.substring(colon4 + 2, sigBeg);
1924 String params = body.substring(sigBeg, sigEnd + 1);
1926 int paramBeg = body.indexOf('(', sigEnd + 1);
1928 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1929 sb.append(mangleJsCallbacks(fqn, method, params, true));
1935 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1936 if (params.startsWith("(")) {
1937 params = params.substring(1);
1939 if (params.endsWith(")")) {
1940 params = params.substring(0, params.length() - 1);
1942 StringBuilder sb = new StringBuilder();
1943 final String fqnu = fqn.replace('.', '_');
1944 final String rfqn = mangleClassName(fqnu);
1945 final String rm = mangleMethodName(method);
1948 StringBuilder pb = new StringBuilder();
1949 int len = params.length();
1951 while (indx < len) {
1952 char ch = params.charAt(indx);
1953 if (ch == '[' || ch == 'L') {
1954 pb.append("Ljava/lang/Object;");
1955 indx = params.indexOf(';', indx) + 1;
1961 srp = mangleSig(pb.toString());
1963 final String rp = mangleSig(params);
1964 final String mrp = mangleMethodName(rp);
1965 sb.append(rfqn).append("$").append(rm).
1966 append('$').append(mrp).append("__Ljava_lang_Object_2");
1968 sb.append('L').append(fqnu).append("_2");
1971 return sb.toString();
1974 private static String className(ClassData jc) {
1975 //return jc.getName().getInternalName().replace('/', '_');
1976 return mangleClassName(jc.getClassName());
1979 private static String[] findAnnotation(
1980 byte[] arr, ClassData cd, final String className,
1981 final String... attrNames
1982 ) throws IOException {
1986 final String[] values = new String[attrNames.length];
1987 final boolean[] found = { false };
1988 final String jvmType = "L" + className.replace('.', '/') + ";";
1989 AnnotationParser ap = new AnnotationParser(false, true) {
1991 protected void visitAttr(String type, String attr, String at, String value) {
1992 if (type.equals(jvmType)) {
1994 for (int i = 0; i < attrNames.length; i++) {
1995 if (attrNames[i].equals(attr)) {
2004 return found[0] ? values : null;
2007 private CharSequence initField(FieldData v) {
2008 final String is = v.getInternalSig();
2009 if (is.length() == 1) {
2010 switch (is.charAt(0)) {
2016 case 'I': return " = 0;";
2018 case 'D': return " = 0.0;";
2020 throw new IllegalStateException(is);
2026 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2027 AnnotationParser ap = new AnnotationParser(true, false) {
2028 int[] cnt = new int[32];
2032 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2033 final String slashType = attrType.substring(1, attrType.length() - 1);
2034 requireReference(slashType);
2036 if (cnt[depth]++ > 0) {
2040 append('"').append(attrType).append("\" : ");
2047 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2053 protected void visitValueStart(String attrName, char type) throws IOException {
2054 if (cnt[depth]++ > 0) {
2058 if (attrName != null) {
2059 append('"').append(attrName).append("\" : ");
2067 protected void visitValueEnd(String attrName, char type) throws IOException {
2075 protected void visitAttr(String type, String attr, String attrType, String value)
2076 throws IOException {
2077 if (attr == null && value == null) {
2084 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2085 throws IOException {
2086 final String slashType = attrType.substring(1, attrType.length() - 1);
2087 requireReference(slashType);
2089 final String cn = mangleClassName(slashType);
2090 append(accessClass(cn))
2091 .append("(false)['valueOf__L").
2093 append("_2Ljava_lang_String_2']('").
2101 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2102 final String name = args[indx];
2106 if (name.contains(",")) {
2107 throw new IOException("Wrong parameter with ',': " + name);
2113 final void emitNoFlush(
2115 final String format, final CharSequence... params
2116 ) throws IOException {
2117 emitImpl(this, format, params);
2119 static final void emit(
2121 final Appendable out,
2122 final String format, final CharSequence... params
2123 ) throws IOException {
2125 emitImpl(out, format, params);
2127 static void emitImpl(final Appendable out,
2128 final String format,
2129 final CharSequence... params) throws IOException {
2130 final int length = format.length();
2133 int paramOffset = format.indexOf('@');
2134 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2135 final char paramChar = format.charAt(paramOffset + 1);
2136 if ((paramChar >= '1') && (paramChar <= '9')) {
2137 final int paramIndex = paramChar - '0' - 1;
2139 out.append(format, processed, paramOffset);
2140 out.append(params[paramIndex]);
2143 processed = paramOffset + 1;
2146 paramOffset = format.indexOf('@', paramOffset + 1);
2149 out.append(format, processed, length);
2152 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2153 append("} catch (e) {\n");
2155 for (TrapData e : traps) {
2159 if (e.catch_cpx != 0) { //not finally
2160 final String classInternalName = jc.getClassName(e.catch_cpx);
2161 addReference(classInternalName);
2162 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2163 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2164 append("var stA0 = e;");
2165 goTo(this, current, e.handler_pc, topMostLabel);
2168 finallyPC = e.handler_pc;
2171 if (finallyPC == -1) {
2174 append("var stA0 = e;");
2175 goTo(this, current, finallyPC, topMostLabel);
2180 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2183 out.append("{ gt = 0; continue X_" + to + "; }");
2185 out.append("{ gt = " + to + "; continue X_0; }");
2188 out.append("{ gt = " + to + "; break IF; }");
2192 private static void emitIf(
2194 Appendable out, String pattern,
2196 int current, int to, int canBack
2197 ) throws IOException {
2199 emitImpl(out, pattern, param);
2200 goTo(out, current, to, canBack);
2203 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2206 case 4: jvmType = "[Z"; break;
2207 case 5: jvmType = "[C"; break;
2208 case 6: jvmType = "[F"; break;
2209 case 7: jvmType = "[D"; break;
2210 case 8: jvmType = "[B"; break;
2211 case 9: jvmType = "[S"; break;
2212 case 10: jvmType = "[I"; break;
2213 case 11: jvmType = "[J"; break;
2214 default: throw new IllegalStateException("Array type: " + atype);
2217 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2218 smapper.popI(), smapper.pushA(), jvmType);
2221 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2222 String typeName = jc.getClassName(type);
2223 String ref = "null";
2224 if (typeName.startsWith("[")) {
2225 typeName = "'[" + typeName + "'";
2227 ref = "vm." + mangleClassName(typeName);
2228 typeName = "'[L" + typeName + ";'";
2231 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2232 smapper.popI(), smapper.pushA(), typeName, ref);
2235 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2236 String typeName = jc.getClassName(type);
2237 int dim = readUByte(byteCodes, ++i);
2238 StringBuilder dims = new StringBuilder();
2240 for (int d = 0; d < dim; d++) {
2242 dims.insert(1, ",");
2244 dims.insert(1, smapper.popI());
2248 if (typeName.charAt(dim) == 'L') {
2249 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2252 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2253 dims.toString(), smapper.pushA(), typeName, fn
2258 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2259 int table = i / 4 * 4 + 4;
2260 int dflt = i + readInt4(byteCodes, table);
2262 int low = readInt4(byteCodes, table);
2264 int high = readInt4(byteCodes, table);
2266 final CharSequence swVar = smapper.popValue();
2267 smapper.flush(this);
2268 append("switch (").append(swVar).append(") {\n");
2269 while (low <= high) {
2270 int offset = i + readInt4(byteCodes, table);
2272 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2275 append(" default: ");
2276 goTo(this, i, dflt, topMostLabel);
2282 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2283 int table = i / 4 * 4 + 4;
2284 int dflt = i + readInt4(byteCodes, table);
2286 int n = readInt4(byteCodes, table);
2288 final CharSequence swVar = smapper.popValue();
2289 smapper.flush(this);
2290 append("switch (").append(swVar).append(") {\n");
2292 int cnstnt = readInt4(byteCodes, table);
2294 int offset = i + readInt4(byteCodes, table);
2296 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2298 append(" default: ");
2299 goTo(this, i, dflt, topMostLabel);
2305 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2306 String type = jc.getClassName(indx);
2307 if (!type.startsWith("[")) {
2309 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2310 smapper.popA(), smapper.pushI(),
2311 type.replace('/', '_'));
2314 while (type.charAt(cnt) == '[') {
2317 if (type.charAt(cnt) == 'L') {
2318 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2320 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2321 smapper.popA(), smapper.pushI(),
2326 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2327 smapper.popA(), smapper.pushI(), type
2333 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2334 String type = jc.getClassName(indx);
2335 if (!type.startsWith("[")) {
2336 emitNoFlush(smapper,
2337 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2338 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2341 while (type.charAt(cnt) == '[') {
2344 if (type.charAt(cnt) == 'L') {
2345 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2346 emitNoFlush(smapper,
2347 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2348 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2351 emitNoFlush(smapper,
2352 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2353 smapper.getT(0, VarType.REFERENCE, false), type
2359 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2360 for (int j = prev; j <= i; j++) {
2362 final int cc = readUByte(byteCodes, j);
2363 append(Integer.toString(cc));
2367 @JavaScriptBody(args = "msg", body = "")
2368 private static void println(String msg) {
2369 System.err.println(msg);