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 StringBuilder sb = new StringBuilder();
1080 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1081 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1082 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1083 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1084 sb.append(" mn : ").append(mn).append("\n");
1085 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1086 throw new IOException(sb.toString());
1088 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1089 String type = jc.StringValue(nameAndType.cpx2);
1090 String object = accessClass(mcn) + "(false)";
1091 if (mn.startsWith("cons_")) {
1092 object += ".constructor";
1094 append("var metHan = ");
1095 append(accessStaticMethod(object, mn, mi));
1097 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1099 append(", '").append(mi[1]).append("', ");
1100 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1101 append(methodType).append("'").append(type).append("', null)");
1102 // if (numArguments > 0) {
1104 // for (int j = 1; j < numArguments; ++j) {
1110 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1116 int indx = readUShortArg(byteCodes, i);
1117 String ci = jc.getClassName(indx);
1118 emit(smapper, this, "var @1 = new @2;",
1119 smapper.pushA(), accessClass(mangleClassName(ci)));
1125 int atype = readUByte(byteCodes, ++i);
1126 generateNewArray(atype, smapper);
1128 case opc_anewarray: {
1129 int type = readUShortArg(byteCodes, i);
1131 generateANewArray(type, smapper);
1134 case opc_multianewarray: {
1135 int type = readUShortArg(byteCodes, i);
1137 i = generateMultiANewArray(type, byteCodes, i, smapper);
1140 case opc_arraylength:
1141 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1144 emit(smapper, this, "Array.at(@3, @2, @1);",
1145 smapper.popL(), smapper.popI(), smapper.popA());
1148 emit(smapper, this, "Array.at(@3, @2, @1);",
1149 smapper.popF(), smapper.popI(), smapper.popA());
1152 emit(smapper, this, "Array.at(@3, @2, @1);",
1153 smapper.popD(), smapper.popI(), smapper.popA());
1156 emit(smapper, this, "Array.at(@3, @2, @1);",
1157 smapper.popA(), smapper.popI(), smapper.popA());
1163 emit(smapper, this, "Array.at(@3, @2, @1);",
1164 smapper.popI(), smapper.popI(), smapper.popA());
1167 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1168 smapper.popI(), smapper.getA(0));
1171 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1172 smapper.popI(), smapper.getA(0));
1175 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1176 smapper.popI(), smapper.getA(0));
1179 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1180 smapper.popI(), smapper.getA(0));
1186 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1187 smapper.popI(), smapper.getA(0));
1195 final Variable v = smapper.get(0);
1196 if (smapper.isDirty()) {
1197 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1199 smapper.assign(this, v.getType(), v);
1204 final Variable vi1 = smapper.get(0);
1206 if (vi1.isCategory2()) {
1207 emit(smapper, this, "var @1 = @2;",
1208 smapper.pushT(vi1.getType()), vi1);
1210 final Variable vi2 = smapper.get(1);
1211 emit(smapper, this, "var @1 = @2, @3 = @4;",
1212 smapper.pushT(vi2.getType()), vi2,
1213 smapper.pushT(vi1.getType()), vi1);
1218 final Variable vi1 = smapper.pop(this);
1219 final Variable vi2 = smapper.pop(this);
1220 final Variable vo3 = smapper.pushT(vi1.getType());
1221 final Variable vo2 = smapper.pushT(vi2.getType());
1222 final Variable vo1 = smapper.pushT(vi1.getType());
1224 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1225 vo1, vi1, vo2, vi2, vo3, vo1);
1229 final Variable vi1 = smapper.pop(this);
1230 final Variable vi2 = smapper.pop(this);
1232 if (vi1.isCategory2()) {
1233 final Variable vo3 = smapper.pushT(vi1.getType());
1234 final Variable vo2 = smapper.pushT(vi2.getType());
1235 final Variable vo1 = smapper.pushT(vi1.getType());
1237 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1238 vo1, vi1, vo2, vi2, vo3, vo1);
1240 final Variable vi3 = smapper.pop(this);
1241 final Variable vo5 = smapper.pushT(vi2.getType());
1242 final Variable vo4 = smapper.pushT(vi1.getType());
1243 final Variable vo3 = smapper.pushT(vi3.getType());
1244 final Variable vo2 = smapper.pushT(vi2.getType());
1245 final Variable vo1 = smapper.pushT(vi1.getType());
1247 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1248 vo1, vi1, vo2, vi2, vo3, vi3);
1249 emit(smapper, this, " @1 = @2, @3 = @4;",
1250 vo4, vo1, vo5, vo2);
1255 final Variable vi1 = smapper.pop(this);
1256 final Variable vi2 = smapper.pop(this);
1258 if (vi2.isCategory2()) {
1259 final Variable vo3 = smapper.pushT(vi1.getType());
1260 final Variable vo2 = smapper.pushT(vi2.getType());
1261 final Variable vo1 = smapper.pushT(vi1.getType());
1263 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1264 vo1, vi1, vo2, vi2, vo3, vo1);
1266 final Variable vi3 = smapper.pop(this);
1267 final Variable vo4 = smapper.pushT(vi1.getType());
1268 final Variable vo3 = smapper.pushT(vi3.getType());
1269 final Variable vo2 = smapper.pushT(vi2.getType());
1270 final Variable vo1 = smapper.pushT(vi1.getType());
1272 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1273 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1278 final Variable vi1 = smapper.pop(this);
1279 final Variable vi2 = smapper.pop(this);
1281 if (vi1.isCategory2()) {
1282 if (vi2.isCategory2()) {
1283 final Variable vo3 = smapper.pushT(vi1.getType());
1284 final Variable vo2 = smapper.pushT(vi2.getType());
1285 final Variable vo1 = smapper.pushT(vi1.getType());
1287 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1288 vo1, vi1, vo2, vi2, vo3, vo1);
1290 final Variable vi3 = smapper.pop(this);
1291 final Variable vo4 = smapper.pushT(vi1.getType());
1292 final Variable vo3 = smapper.pushT(vi3.getType());
1293 final Variable vo2 = smapper.pushT(vi2.getType());
1294 final Variable vo1 = smapper.pushT(vi1.getType());
1296 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1297 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1300 final Variable vi3 = smapper.pop(this);
1302 if (vi3.isCategory2()) {
1303 final Variable vo5 = smapper.pushT(vi2.getType());
1304 final Variable vo4 = smapper.pushT(vi1.getType());
1305 final Variable vo3 = smapper.pushT(vi3.getType());
1306 final Variable vo2 = smapper.pushT(vi2.getType());
1307 final Variable vo1 = smapper.pushT(vi1.getType());
1309 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1310 vo1, vi1, vo2, vi2, vo3, vi3);
1311 emit(smapper, this, " @1 = @2, @3 = @4;",
1312 vo4, vo1, vo5, vo2);
1314 final Variable vi4 = smapper.pop(this);
1315 final Variable vo6 = smapper.pushT(vi2.getType());
1316 final Variable vo5 = smapper.pushT(vi1.getType());
1317 final Variable vo4 = smapper.pushT(vi4.getType());
1318 final Variable vo3 = smapper.pushT(vi3.getType());
1319 final Variable vo2 = smapper.pushT(vi2.getType());
1320 final Variable vo1 = smapper.pushT(vi1.getType());
1322 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1323 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1324 emit(smapper, this, " @1 = @2, @3 = @4;",
1325 vo5, vo1, vo6, vo2);
1331 final Variable vi1 = smapper.get(0);
1332 final Variable vi2 = smapper.get(1);
1334 if (vi1.getType() == vi2.getType()) {
1335 final Variable tmp = smapper.pushT(vi1.getType());
1337 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1342 smapper.pushT(vi1.getType());
1343 smapper.pushT(vi2.getType());
1348 smapper.assign(this, VarType.INTEGER,
1349 "(" + Integer.toString(byteCodes[++i]) + ")");
1352 smapper.assign(this, VarType.INTEGER,
1353 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1357 case opc_getfield: {
1358 int indx = readUShortArg(byteCodes, i);
1359 String[] fi = jc.getFieldInfoName(indx);
1360 final int type = VarType.fromFieldType(fi[2].charAt(0));
1361 final String mangleClass = mangleClassName(fi[0]);
1362 final String mangleClassAccess = accessClass(mangleClass);
1363 smapper.replace(this, type, "@2.call(@1)",
1365 accessField(mangleClassAccess + "(false)",
1371 case opc_putfield: {
1372 int indx = readUShortArg(byteCodes, i);
1373 String[] fi = jc.getFieldInfoName(indx);
1374 final int type = VarType.fromFieldType(fi[2].charAt(0));
1375 final String mangleClass = mangleClassName(fi[0]);
1376 final String mangleClassAccess = accessClass(mangleClass);
1377 emit(smapper, this, "@3.call(@2, @1);",
1380 accessField(mangleClassAccess + "(false)",
1385 case opc_getstatic: {
1386 int indx = readUShortArg(byteCodes, i);
1387 String[] fi = jc.getFieldInfoName(indx);
1388 final int type = VarType.fromFieldType(fi[2].charAt(0));
1389 String ac = accessClass(mangleClassName(fi[0]));
1390 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1391 smapper.assign(this, type, af + "()");
1393 addReference(fi[0]);
1396 case opc_putstatic: {
1397 int indx = readUShortArg(byteCodes, i);
1398 String[] fi = jc.getFieldInfoName(indx);
1399 final int type = VarType.fromFieldType(fi[2].charAt(0));
1400 emit(smapper, this, "@1(false)._@2(@3);",
1401 accessClass(mangleClassName(fi[0])), fi[1],
1402 smapper.popT(type));
1404 addReference(fi[0]);
1407 case opc_checkcast: {
1408 int indx = readUShortArg(byteCodes, i);
1409 generateCheckcast(indx, smapper);
1413 case opc_instanceof: {
1414 int indx = readUShortArg(byteCodes, i);
1415 generateInstanceOf(indx, smapper);
1420 final CharSequence v = smapper.popA();
1423 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1424 smapper.pushA(), v);
1428 case opc_monitorenter: {
1429 debug("/* monitor enter */");
1434 case opc_monitorexit: {
1435 debug("/* monitor exit */");
1446 emit(smapper, this, "throw 'unknown bytecode @1';",
1447 Integer.toString(c));
1451 generateByteCodeComment(prev, i, byteCodes);
1457 if (previousTrap != null) {
1458 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1463 while (openBraces-- > 0) {
1473 private int generateIf(StackMapper mapper, byte[] byteCodes,
1474 int i, final CharSequence v2, final CharSequence v1,
1475 final String test, int topMostLabel
1476 ) throws IOException {
1478 int indx = i + readShortArg(byteCodes, i);
1479 append("if ((").append(v1)
1480 .append(") ").append(test).append(" (")
1481 .append(v2).append(")) ");
1482 goTo(this, i, indx, topMostLabel);
1486 private int readInt4(byte[] byteCodes, int offset) {
1487 final int d = byteCodes[offset + 0] << 24;
1488 final int c = byteCodes[offset + 1] << 16;
1489 final int b = byteCodes[offset + 2] << 8;
1490 final int a = byteCodes[offset + 3];
1491 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1493 private static int readUByte(byte[] byteCodes, int offset) {
1494 return byteCodes[offset] & 0xff;
1497 private static int readUShort(byte[] byteCodes, int offset) {
1498 return ((byteCodes[offset] & 0xff) << 8)
1499 | (byteCodes[offset + 1] & 0xff);
1501 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1502 return readUShort(byteCodes, offsetInstruction + 1);
1505 private static int readShort(byte[] byteCodes, int offset) {
1506 int signed = byteCodes[offset];
1507 byte b0 = (byte)signed;
1508 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1510 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1511 return readShort(byteCodes, offsetInstruction + 1);
1514 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1516 Boolean count = null;
1517 boolean array = false;
1519 int firstPos = sig.length();
1520 while (i < descriptor.length()) {
1521 char ch = descriptor.charAt(i++);
1542 if (ch == 'J' || ch == 'D') {
1548 sig.insert(firstPos, ch);
1550 returnType[0] = '[';
1551 sig.insert(firstPos, "_3");
1560 returnType[0] = 'V';
1561 sig.insert(firstPos, 'V');
1564 int next = descriptor.indexOf(';', i);
1565 String realSig = mangleSig(descriptor, i - 1, next + 1);
1570 sig.append(realSig);
1573 sig.insert(firstPos, realSig);
1575 sig.insert(firstPos, "_3");
1577 returnType[0] = 'L';
1586 throw new IllegalStateException("Invalid char: " + ch);
1591 static String mangleSig(String sig) {
1592 return mangleSig(sig, 0, sig.length());
1595 private static String mangleMethodName(String name) {
1596 StringBuilder sb = new StringBuilder(name.length() * 2);
1597 int last = name.length();
1598 for (int i = 0; i < last; i++) {
1599 final char ch = name.charAt(i);
1601 case '_': sb.append("_1"); break;
1602 default: sb.append(ch); break;
1605 return sb.toString();
1607 private static String mangleSig(String txt, int first, int last) {
1608 StringBuilder sb = new StringBuilder((last - first) * 2);
1609 for (int i = first; i < last; i++) {
1610 final char ch = txt.charAt(i);
1612 case '/': sb.append('_'); break;
1613 case '_': sb.append("_1"); break;
1614 case ';': sb.append("_2"); break;
1615 case '[': sb.append("_3"); break;
1617 if (Character.isJavaIdentifierPart(ch)) {
1621 String hex = Integer.toHexString(ch).toLowerCase();
1622 for (int m = hex.length(); m < 4; m++) {
1630 return sb.toString();
1633 private static String mangleClassName(String name) {
1634 return mangleSig(name);
1637 private static String findMethodName(MethodData m, StringBuilder cnt) {
1638 StringBuilder name = new StringBuilder();
1639 if ("<init>".equals(m.getName())) { // NOI18N
1640 name.append("cons"); // NOI18N
1641 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1642 name.append("class"); // NOI18N
1644 name.append(mangleMethodName(m.getName()));
1647 countArgs(m.getInternalSig(), new char[1], name, cnt);
1648 return name.toString();
1651 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1652 StringBuilder name = new StringBuilder();
1653 String descr = mi[2];//mi.getDescriptor();
1655 if ("<init>".equals(nm)) { // NOI18N
1656 name.append("cons"); // NOI18N
1658 name.append(mangleMethodName(nm));
1660 countArgs(descr, returnType, name, cnt);
1661 return name.toString();
1664 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
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 = isStatic ? cnt.length() : 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') {
1682 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1686 final String in = mi[0];
1689 in.equals("org/apidesign/html/boot/spi/Fn") ||
1690 in.equals("org/netbeans/html/boot/spi/Fn")
1692 mcn = "java_lang_Class";
1694 mcn = mangleClassName(in);
1696 String object = accessClass(mcn) + "(false)";
1697 if (mn.startsWith("cons_")) {
1698 object += ".constructor";
1700 append(accessStaticMethod(object, mn, mi));
1706 if (numArguments > 0) {
1708 for (int j = 1; j < numArguments; ++j) {
1718 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1719 throws IOException {
1720 int methodIndex = readUShortArg(byteCodes, i);
1721 String[] mi = jc.getFieldInfoName(methodIndex);
1722 char[] returnType = { 'V' };
1723 StringBuilder cnt = new StringBuilder();
1724 String mn = findMethodName(mi, cnt, returnType);
1726 final int numArguments = cnt.length() + 1;
1727 final CharSequence[] vars = new CharSequence[numArguments];
1729 for (int j = numArguments - 1; j >= 0; --j) {
1730 vars[j] = mapper.popValue();
1733 if (returnType[0] != 'V') {
1735 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1739 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1741 for (int j = 1; j < numArguments; ++j) {
1751 private void addReference(String cn) throws IOException {
1752 if (requireReference(cn)) {
1753 debug(" /* needs " + cn + " */");
1757 private void outType(String d, StringBuilder out) {
1759 while (d.charAt(0) == '[') {
1763 if (d.charAt(0) == 'L') {
1764 assert d.charAt(d.length() - 1) == ';';
1765 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1771 private String encodeConstant(int entryIndex) throws IOException {
1772 String[] classRef = { null };
1773 String s = jc.stringValue(entryIndex, classRef);
1774 if (classRef[0] != null) {
1775 if (classRef[0].startsWith("[")) {
1776 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1778 addReference(classRef[0]);
1779 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1785 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1786 byte[] arr = m.findAnnotationData(true);
1790 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1791 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1792 class P extends AnnotationParser {
1798 String[] args = new String[30];
1804 protected void visitAttr(String type, String attr, String at, String value) {
1805 if (type.equals(jvmType)) {
1806 if ("body".equals(attr)) {
1808 } else if ("args".equals(attr)) {
1809 args[cnt++] = value;
1811 throw new IllegalArgumentException(attr);
1814 if (type.equals(htmlType)) {
1816 if ("body".equals(attr)) {
1818 } else if ("args".equals(attr)) {
1819 args[cnt++] = value;
1820 } else if ("javacall".equals(attr)) {
1821 javacall = "1".equals(value);
1822 } else if ("wait4js".equals(attr)) {
1823 // ignore, we always invoke synchronously
1825 throw new IllegalArgumentException(attr);
1832 if (p.body == null) {
1835 StringBuilder cnt = new StringBuilder();
1836 final String mn = findMethodName(m, cnt);
1837 append(destObject).append(".").append(mn);
1838 append(" = function(");
1841 StringBuilder toValue = new StringBuilder();
1842 for (int i = 0; i < cnt.length(); i++) {
1844 space = outputArg(this, p.args, index);
1845 if (p.html4j && space.length() > 0) {
1846 toValue.append("\n ").append(p.args[index]).append(" = ")
1847 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1848 append(p.args[index]).append(");");
1852 append(") {").append("\n");
1853 append(toValue.toString());
1855 int lastSlash = jc.getClassName().lastIndexOf('/');
1856 final String pkg = jc.getClassName().substring(0, lastSlash);
1857 append(mangleCallbacks(pkg, p.body));
1858 requireReference(pkg + "/$JsCallbacks$");
1866 private static CharSequence mangleCallbacks(String pkgName, String body) {
1867 StringBuilder sb = new StringBuilder();
1870 int next = body.indexOf(".@", pos);
1872 sb.append(body.substring(pos));
1873 body = sb.toString();
1878 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1883 String refId = body.substring(ident, next);
1885 sb.append(body.substring(pos, ident));
1887 int sigBeg = body.indexOf('(', next);
1888 int sigEnd = body.indexOf(')', sigBeg);
1889 int colon4 = body.indexOf("::", next);
1890 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1891 throw new IllegalStateException("Malformed body " + body);
1893 String fqn = body.substring(next + 2, colon4);
1894 String method = body.substring(colon4 + 2, sigBeg);
1895 String params = body.substring(sigBeg, sigEnd + 1);
1897 int paramBeg = body.indexOf('(', sigEnd + 1);
1899 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1900 sb.append(mangleJsCallbacks(fqn, method, params, false));
1901 sb.append("(").append(refId);
1902 if (body.charAt(paramBeg + 1) != ')') {
1910 int next = body.indexOf("@", pos);
1915 sb.append(body.substring(pos));
1919 sb = new StringBuilder();
1922 sb.append(body.substring(pos, next));
1924 int sigBeg = body.indexOf('(', next);
1925 int sigEnd = body.indexOf(')', sigBeg);
1926 int colon4 = body.indexOf("::", next);
1927 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1928 throw new IllegalStateException("Malformed body " + body);
1930 String fqn = body.substring(next + 1, colon4);
1931 String method = body.substring(colon4 + 2, sigBeg);
1932 String params = body.substring(sigBeg, sigEnd + 1);
1934 int paramBeg = body.indexOf('(', sigEnd + 1);
1936 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1937 sb.append(mangleJsCallbacks(fqn, method, params, true));
1943 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1944 if (params.startsWith("(")) {
1945 params = params.substring(1);
1947 if (params.endsWith(")")) {
1948 params = params.substring(0, params.length() - 1);
1950 StringBuilder sb = new StringBuilder();
1951 final String fqnu = fqn.replace('.', '_');
1952 final String rfqn = mangleClassName(fqnu);
1953 final String rm = mangleMethodName(method);
1956 StringBuilder pb = new StringBuilder();
1957 int len = params.length();
1959 while (indx < len) {
1960 char ch = params.charAt(indx);
1961 if (ch == '[' || ch == 'L') {
1962 pb.append("Ljava/lang/Object;");
1963 indx = params.indexOf(';', indx) + 1;
1969 srp = mangleSig(pb.toString());
1971 final String rp = mangleSig(params);
1972 final String mrp = mangleMethodName(rp);
1973 sb.append(rfqn).append("$").append(rm).
1974 append('$').append(mrp).append("__Ljava_lang_Object_2");
1976 sb.append('L').append(fqnu).append("_2");
1979 return sb.toString();
1982 private static String className(ClassData jc) {
1983 //return jc.getName().getInternalName().replace('/', '_');
1984 return mangleClassName(jc.getClassName());
1987 private static String[] findAnnotation(
1988 byte[] arr, ClassData cd, final String className,
1989 final String... attrNames
1990 ) throws IOException {
1994 final String[] values = new String[attrNames.length];
1995 final boolean[] found = { false };
1996 final String jvmType = "L" + className.replace('.', '/') + ";";
1997 AnnotationParser ap = new AnnotationParser(false, true) {
1999 protected void visitAttr(String type, String attr, String at, String value) {
2000 if (type.equals(jvmType)) {
2002 for (int i = 0; i < attrNames.length; i++) {
2003 if (attrNames[i].equals(attr)) {
2012 return found[0] ? values : null;
2015 private CharSequence initField(FieldData v) {
2016 final String is = v.getInternalSig();
2017 if (is.length() == 1) {
2018 switch (is.charAt(0)) {
2024 case 'I': return " = 0;";
2026 case 'D': return " = 0.0;";
2028 throw new IllegalStateException(is);
2034 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2035 AnnotationParser ap = new AnnotationParser(true, false) {
2036 int[] cnt = new int[32];
2040 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2041 final String slashType = attrType.substring(1, attrType.length() - 1);
2042 requireReference(slashType);
2044 if (cnt[depth]++ > 0) {
2048 append('"').append(attrType).append("\" : ");
2055 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2061 protected void visitValueStart(String attrName, char type) throws IOException {
2062 if (cnt[depth]++ > 0) {
2066 if (attrName != null) {
2067 append('"').append(attrName).append("\" : ");
2075 protected void visitValueEnd(String attrName, char type) throws IOException {
2083 protected void visitAttr(String type, String attr, String attrType, String value)
2084 throws IOException {
2085 if (attr == null && value == null) {
2092 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2093 throws IOException {
2094 final String slashType = attrType.substring(1, attrType.length() - 1);
2095 requireReference(slashType);
2097 final String cn = mangleClassName(slashType);
2098 append(accessClass(cn))
2099 .append("(false)['valueOf__L").
2101 append("_2Ljava_lang_String_2']('").
2109 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2110 final String name = args[indx];
2114 if (name.contains(",")) {
2115 throw new IOException("Wrong parameter with ',': " + name);
2121 final void emitNoFlush(
2123 final String format, final CharSequence... params
2124 ) throws IOException {
2125 emitImpl(this, format, params);
2127 static final void emit(
2129 final Appendable out,
2130 final String format, final CharSequence... params
2131 ) throws IOException {
2133 emitImpl(out, format, params);
2135 static void emitImpl(final Appendable out,
2136 final String format,
2137 final CharSequence... params) throws IOException {
2138 final int length = format.length();
2141 int paramOffset = format.indexOf('@');
2142 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2143 final char paramChar = format.charAt(paramOffset + 1);
2144 if ((paramChar >= '1') && (paramChar <= '9')) {
2145 final int paramIndex = paramChar - '0' - 1;
2147 out.append(format, processed, paramOffset);
2148 out.append(params[paramIndex]);
2151 processed = paramOffset + 1;
2154 paramOffset = format.indexOf('@', paramOffset + 1);
2157 out.append(format, processed, length);
2160 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2161 append("} catch (e) {\n");
2163 for (TrapData e : traps) {
2167 if (e.catch_cpx != 0) { //not finally
2168 final String classInternalName = jc.getClassName(e.catch_cpx);
2169 addReference(classInternalName);
2170 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2171 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2172 append("var stA0 = e;");
2173 goTo(this, current, e.handler_pc, topMostLabel);
2176 finallyPC = e.handler_pc;
2179 if (finallyPC == -1) {
2182 append("var stA0 = e;");
2183 goTo(this, current, finallyPC, topMostLabel);
2188 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2191 out.append("{ gt = 0; continue X_" + to + "; }");
2193 out.append("{ gt = " + to + "; continue X_0; }");
2196 out.append("{ gt = " + to + "; break IF; }");
2200 private static void emitIf(
2202 Appendable out, String pattern,
2204 int current, int to, int canBack
2205 ) throws IOException {
2207 emitImpl(out, pattern, param);
2208 goTo(out, current, to, canBack);
2211 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2214 case 4: jvmType = "[Z"; break;
2215 case 5: jvmType = "[C"; break;
2216 case 6: jvmType = "[F"; break;
2217 case 7: jvmType = "[D"; break;
2218 case 8: jvmType = "[B"; break;
2219 case 9: jvmType = "[S"; break;
2220 case 10: jvmType = "[I"; break;
2221 case 11: jvmType = "[J"; break;
2222 default: throw new IllegalStateException("Array type: " + atype);
2225 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2226 smapper.popI(), smapper.pushA(), jvmType);
2229 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2230 String typeName = jc.getClassName(type);
2231 String ref = "null";
2232 if (typeName.startsWith("[")) {
2233 typeName = "'[" + typeName + "'";
2235 ref = "vm." + mangleClassName(typeName);
2236 typeName = "'[L" + typeName + ";'";
2239 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2240 smapper.popI(), smapper.pushA(), typeName, ref);
2243 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2244 String typeName = jc.getClassName(type);
2245 int dim = readUByte(byteCodes, ++i);
2246 StringBuilder dims = new StringBuilder();
2248 for (int d = 0; d < dim; d++) {
2250 dims.insert(1, ",");
2252 dims.insert(1, smapper.popI());
2256 if (typeName.charAt(dim) == 'L') {
2257 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2260 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2261 dims.toString(), smapper.pushA(), typeName, fn
2266 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2267 int table = i / 4 * 4 + 4;
2268 int dflt = i + readInt4(byteCodes, table);
2270 int low = readInt4(byteCodes, table);
2272 int high = readInt4(byteCodes, table);
2274 final CharSequence swVar = smapper.popValue();
2275 smapper.flush(this);
2276 append("switch (").append(swVar).append(") {\n");
2277 while (low <= high) {
2278 int offset = i + readInt4(byteCodes, table);
2280 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2283 append(" default: ");
2284 goTo(this, i, dflt, topMostLabel);
2290 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2291 int table = i / 4 * 4 + 4;
2292 int dflt = i + readInt4(byteCodes, table);
2294 int n = readInt4(byteCodes, table);
2296 final CharSequence swVar = smapper.popValue();
2297 smapper.flush(this);
2298 append("switch (").append(swVar).append(") {\n");
2300 int cnstnt = readInt4(byteCodes, table);
2302 int offset = i + readInt4(byteCodes, table);
2304 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2306 append(" default: ");
2307 goTo(this, i, dflt, topMostLabel);
2313 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2314 String type = jc.getClassName(indx);
2315 if (!type.startsWith("[")) {
2317 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2318 smapper.popA(), smapper.pushI(),
2319 type.replace('/', '_'));
2322 while (type.charAt(cnt) == '[') {
2325 if (type.charAt(cnt) == 'L') {
2326 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2328 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2329 smapper.popA(), smapper.pushI(),
2334 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2335 smapper.popA(), smapper.pushI(), type
2341 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2342 String type = jc.getClassName(indx);
2343 if (!type.startsWith("[")) {
2344 emitNoFlush(smapper,
2345 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2346 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2349 while (type.charAt(cnt) == '[') {
2352 if (type.charAt(cnt) == 'L') {
2353 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2354 emitNoFlush(smapper,
2355 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2356 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2359 emitNoFlush(smapper,
2360 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2361 smapper.getT(0, VarType.REFERENCE, false), type
2367 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2368 for (int j = prev; j <= i; j++) {
2370 final int cc = readUByte(byteCodes, j);
2371 append(Integer.toString(cc));
2375 @JavaScriptBody(args = "msg", body = "")
2376 private static void println(String msg) {
2377 System.err.println(msg);