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());
382 "java/lang/Object".equals(jc.getClassName()) ||
383 "java/lang/reflect/Array".equals(jc.getClassName());
386 append("Object.defineProperty(").append(destObject).
387 append(", '").append(name).append("', { configurable: true, writable: true, value: function(");
389 append(destObject).append(".").append(name).append(" = function(");
391 lmapper.outputArguments(this, m.isStatic());
392 append(") {").append("\n");
394 final byte[] byteCodes = m.getCode();
395 if (byteCodes == null) {
396 append(" throw 'no code found for ")
397 .append(jc.getClassName()).append('.')
398 .append(m.getName()).append("';\n");
407 final StackMapper smapper = new StackMapper();
410 append(" var ").append(" lcA0 = this;\n");
414 TrapData[] previousTrap = null;
415 boolean wide = false;
417 if (stackMapIterator.isEmpty()) {
423 append("\n var gt = 0;\n");
427 int topMostLabel = 0;
428 for (int i = 0; i < byteCodes.length; i++) {
431 stackMapIterator.advanceTo(i);
432 boolean changeInCatch = trap.advanceTo(i);
433 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
434 if (previousTrap != null) {
435 generateCatch(previousTrap, i, topMostLabel);
439 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
444 if (openBraces > 64) {
445 for (int c = 0; c < 64; c++) {
452 lastStackFrame = stackMapIterator.getFrameIndex();
453 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
454 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
455 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
457 changeInCatch = true;
459 debug(" /* " + i + " */ ");
461 if (changeInCatch && trap.useTry()) {
463 previousTrap = trap.current();
465 final int c = readUByte(byteCodes, i);
468 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
471 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
474 smapper.assign(this, VarType.LONG, lmapper.getL(0));
477 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
480 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
483 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
486 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
489 smapper.assign(this, VarType.LONG, lmapper.getL(1));
492 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
495 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
498 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
501 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
504 smapper.assign(this, VarType.LONG, lmapper.getL(2));
507 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
510 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
513 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
516 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
519 smapper.assign(this, VarType.LONG, lmapper.getL(3));
522 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
525 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
529 final int indx = wide ? readUShort(byteCodes, i++)
530 : readUByte(byteCodes, i);
532 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
537 final int indx = wide ? readUShort(byteCodes, i++)
538 : readUByte(byteCodes, i);
540 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
545 final int indx = wide ? readUShort(byteCodes, i++)
546 : readUByte(byteCodes, i);
548 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
553 final int indx = wide ? readUShort(byteCodes, i++)
554 : readUByte(byteCodes, i);
556 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
561 final int indx = wide ? readUShort(byteCodes, i++)
562 : readUByte(byteCodes, i);
564 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
569 final int indx = wide ? readUShort(byteCodes, i++)
570 : readUByte(byteCodes, i);
572 emit(smapper, this, "var @1 = @2;",
573 lmapper.setI(indx), smapper.popI());
578 final int indx = wide ? readUShort(byteCodes, i++)
579 : readUByte(byteCodes, i);
581 emit(smapper, this, "var @1 = @2;",
582 lmapper.setL(indx), smapper.popL());
587 final int indx = wide ? readUShort(byteCodes, i++)
588 : readUByte(byteCodes, i);
590 emit(smapper, this, "var @1 = @2;",
591 lmapper.setF(indx), smapper.popF());
596 final int indx = wide ? readUShort(byteCodes, i++)
597 : readUByte(byteCodes, i);
599 emit(smapper, this, "var @1 = @2;",
600 lmapper.setD(indx), smapper.popD());
605 final int indx = wide ? readUShort(byteCodes, i++)
606 : readUByte(byteCodes, i);
608 emit(smapper, this, "var @1 = @2;",
609 lmapper.setA(indx), smapper.popA());
613 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
616 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
619 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
622 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
625 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
628 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
631 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
634 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
637 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
640 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
643 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
646 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
649 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
652 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
655 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
658 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
661 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
664 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
667 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
670 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
673 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
676 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
679 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
682 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
685 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
688 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
691 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
694 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
697 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
700 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
703 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
706 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
709 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
710 smapper.getI(1), smapper.popI());
713 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
714 smapper.getL(1), smapper.popL());
717 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
720 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
723 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
724 smapper.getI(1), smapper.popI());
727 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
728 smapper.getL(1), smapper.popL());
731 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
734 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
737 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
740 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
743 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
746 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
749 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
752 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
755 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
758 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
761 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
764 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
767 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
770 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
773 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
776 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
779 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
782 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
786 final int varIndx = wide ? readUShort(byteCodes, i++)
787 : readUByte(byteCodes, i);
789 final int incrBy = wide ? readShort(byteCodes, i++)
793 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
795 emit(smapper, this, "@1 += @2;",
796 lmapper.getI(varIndx),
797 Integer.toString(incrBy));
802 emit(smapper, this, "return;");
805 emit(smapper, this, "return @1;", smapper.popI());
808 emit(smapper, this, "return @1;", smapper.popL());
811 emit(smapper, this, "return @1;", smapper.popF());
814 emit(smapper, this, "return @1;", smapper.popD());
817 emit(smapper, this, "return @1;", smapper.popA());
820 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
823 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
826 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
829 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
833 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
836 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
839 smapper.replace(this, VarType.DOUBLE, "@1",
843 smapper.replace(this, VarType.FLOAT, "@1",
847 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
851 smapper.replace(this, VarType.LONG, "(@1).toLong()",
855 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
859 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
862 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
866 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
868 case opc_aconst_null:
869 smapper.assign(this, VarType.REFERENCE, "null");
872 smapper.assign(this, VarType.INTEGER, "-1");
875 smapper.assign(this, VarType.INTEGER, "0");
878 smapper.assign(this, VarType.DOUBLE, "0");
881 smapper.assign(this, VarType.LONG, "0");
884 smapper.assign(this, VarType.FLOAT, "0");
887 smapper.assign(this, VarType.INTEGER, "1");
890 smapper.assign(this, VarType.LONG, "1");
893 smapper.assign(this, VarType.FLOAT, "1");
896 smapper.assign(this, VarType.DOUBLE, "1");
899 smapper.assign(this, VarType.INTEGER, "2");
902 smapper.assign(this, VarType.FLOAT, "2");
905 smapper.assign(this, VarType.INTEGER, "3");
908 smapper.assign(this, VarType.INTEGER, "4");
911 smapper.assign(this, VarType.INTEGER, "5");
914 int indx = readUByte(byteCodes, ++i);
915 String v = encodeConstant(indx);
916 int type = VarType.fromConstantType(jc.getTag(indx));
917 smapper.assign(this, type, v);
922 int indx = readUShortArg(byteCodes, i);
924 String v = encodeConstant(indx);
925 int type = VarType.fromConstantType(jc.getTag(indx));
926 if (type == VarType.LONG) {
927 final Long lv = new Long(v);
928 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
929 final int hi = (int)(lv.longValue() >> 32);
931 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
933 smapper.assign(this, VarType.LONG,
934 "0x" + Integer.toHexString(hi) + ".next32(0x" +
935 Integer.toHexString(low) + ")"
939 smapper.assign(this, type, v);
944 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
948 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
952 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
955 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
956 "===", topMostLabel);
959 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
960 "!==", topMostLabel);
963 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
967 int indx = i + readShortArg(byteCodes, i);
968 emitIf(smapper, this, "if ((@1) == 0) ",
969 smapper.popI(), i, indx, topMostLabel);
974 int indx = i + readShortArg(byteCodes, i);
975 emitIf(smapper, this, "if ((@1) != 0) ",
976 smapper.popI(), i, indx, topMostLabel);
981 int indx = i + readShortArg(byteCodes, i);
982 emitIf(smapper, this, "if ((@1) < 0) ",
983 smapper.popI(), i, indx, topMostLabel);
988 int indx = i + readShortArg(byteCodes, i);
989 emitIf(smapper, this, "if ((@1) <= 0) ",
990 smapper.popI(), i, indx, topMostLabel);
995 int indx = i + readShortArg(byteCodes, i);
996 emitIf(smapper, this, "if ((@1) > 0) ",
997 smapper.popI(), i, indx, topMostLabel);
1002 int indx = i + readShortArg(byteCodes, i);
1003 emitIf(smapper, this, "if ((@1) >= 0) ",
1004 smapper.popI(), i, indx, topMostLabel);
1008 case opc_ifnonnull: {
1009 int indx = i + readShortArg(byteCodes, i);
1010 emitIf(smapper, this, "if ((@1) !== null) ",
1011 smapper.popA(), i, indx, topMostLabel);
1016 int indx = i + readShortArg(byteCodes, i);
1017 emitIf(smapper, this, "if ((@1) === null) ",
1018 smapper.popA(), i, indx, topMostLabel);
1023 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1024 "!=", topMostLabel);
1027 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1031 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1032 "<=", topMostLabel);
1035 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1039 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1040 ">=", topMostLabel);
1043 smapper.flush(this);
1044 int indx = i + readShortArg(byteCodes, i);
1045 goTo(this, i, indx, topMostLabel);
1049 case opc_lookupswitch: {
1050 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1053 case opc_tableswitch: {
1054 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1057 case opc_invokeinterface: {
1058 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1061 case opc_invokevirtual:
1062 i = invokeVirtualMethod(byteCodes, i, smapper);
1064 case opc_invokespecial:
1065 i = invokeStaticMethod(byteCodes, i, smapper, false);
1067 case opc_invokestatic:
1068 i = invokeStaticMethod(byteCodes, i, smapper, true);
1070 case opc_invokedynamic: {
1071 int indx = readUShortArg(byteCodes, i);
1072 println("invoke dynamic: " + indx);
1073 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1074 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1075 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1076 println(" type: " + methodHandle.cpx1);
1077 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1078 String mcn = mangleClassName(mi[0]);
1079 char[] returnType = {'V'};
1080 StringBuilder cnt = new StringBuilder();
1081 String mn = findMethodName(mi, cnt, returnType);
1082 StringBuilder sb = new StringBuilder();
1083 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1084 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1085 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1086 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1087 sb.append(" mn : ").append(mn).append("\n");
1088 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1089 throw new IOException(sb.toString());
1091 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1092 String type = jc.StringValue(nameAndType.cpx2);
1093 String object = accessClass(mcn) + "(false)";
1094 if (mn.startsWith("cons_")) {
1095 object += ".constructor";
1097 append("var metHan = ");
1098 append(accessStaticMethod(object, mn, mi));
1100 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1102 append(", '").append(mi[1]).append("', ");
1103 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1104 append(methodType).append("'").append(type).append("', null)");
1105 // if (numArguments > 0) {
1107 // for (int j = 1; j < numArguments; ++j) {
1113 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1119 int indx = readUShortArg(byteCodes, i);
1120 String ci = jc.getClassName(indx);
1121 emit(smapper, this, "var @1 = new @2;",
1122 smapper.pushA(), accessClass(mangleClassName(ci)));
1128 int atype = readUByte(byteCodes, ++i);
1129 generateNewArray(atype, smapper);
1131 case opc_anewarray: {
1132 int type = readUShortArg(byteCodes, i);
1134 generateANewArray(type, smapper);
1137 case opc_multianewarray: {
1138 int type = readUShortArg(byteCodes, i);
1140 i = generateMultiANewArray(type, byteCodes, i, smapper);
1143 case opc_arraylength:
1144 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1147 emit(smapper, this, "Array.at(@3, @2, @1);",
1148 smapper.popL(), smapper.popI(), smapper.popA());
1151 emit(smapper, this, "Array.at(@3, @2, @1);",
1152 smapper.popF(), smapper.popI(), smapper.popA());
1155 emit(smapper, this, "Array.at(@3, @2, @1);",
1156 smapper.popD(), smapper.popI(), smapper.popA());
1159 emit(smapper, this, "Array.at(@3, @2, @1);",
1160 smapper.popA(), smapper.popI(), smapper.popA());
1166 emit(smapper, this, "Array.at(@3, @2, @1);",
1167 smapper.popI(), smapper.popI(), smapper.popA());
1170 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1171 smapper.popI(), smapper.getA(0));
1174 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1175 smapper.popI(), smapper.getA(0));
1178 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1179 smapper.popI(), smapper.getA(0));
1182 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1183 smapper.popI(), smapper.getA(0));
1189 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1190 smapper.popI(), smapper.getA(0));
1198 final Variable v = smapper.get(0);
1199 if (smapper.isDirty()) {
1200 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1202 smapper.assign(this, v.getType(), v);
1207 final Variable vi1 = smapper.get(0);
1209 if (vi1.isCategory2()) {
1210 emit(smapper, this, "var @1 = @2;",
1211 smapper.pushT(vi1.getType()), vi1);
1213 final Variable vi2 = smapper.get(1);
1214 emit(smapper, this, "var @1 = @2, @3 = @4;",
1215 smapper.pushT(vi2.getType()), vi2,
1216 smapper.pushT(vi1.getType()), vi1);
1221 final Variable vi1 = smapper.pop(this);
1222 final Variable vi2 = smapper.pop(this);
1223 final Variable vo3 = smapper.pushT(vi1.getType());
1224 final Variable vo2 = smapper.pushT(vi2.getType());
1225 final Variable vo1 = smapper.pushT(vi1.getType());
1227 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1228 vo1, vi1, vo2, vi2, vo3, vo1);
1232 final Variable vi1 = smapper.pop(this);
1233 final Variable vi2 = smapper.pop(this);
1235 if (vi1.isCategory2()) {
1236 final Variable vo3 = smapper.pushT(vi1.getType());
1237 final Variable vo2 = smapper.pushT(vi2.getType());
1238 final Variable vo1 = smapper.pushT(vi1.getType());
1240 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1241 vo1, vi1, vo2, vi2, vo3, vo1);
1243 final Variable vi3 = smapper.pop(this);
1244 final Variable vo5 = smapper.pushT(vi2.getType());
1245 final Variable vo4 = smapper.pushT(vi1.getType());
1246 final Variable vo3 = smapper.pushT(vi3.getType());
1247 final Variable vo2 = smapper.pushT(vi2.getType());
1248 final Variable vo1 = smapper.pushT(vi1.getType());
1250 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1251 vo1, vi1, vo2, vi2, vo3, vi3);
1252 emit(smapper, this, " @1 = @2, @3 = @4;",
1253 vo4, vo1, vo5, vo2);
1258 final Variable vi1 = smapper.pop(this);
1259 final Variable vi2 = smapper.pop(this);
1261 if (vi2.isCategory2()) {
1262 final Variable vo3 = smapper.pushT(vi1.getType());
1263 final Variable vo2 = smapper.pushT(vi2.getType());
1264 final Variable vo1 = smapper.pushT(vi1.getType());
1266 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1267 vo1, vi1, vo2, vi2, vo3, vo1);
1269 final Variable vi3 = smapper.pop(this);
1270 final Variable vo4 = smapper.pushT(vi1.getType());
1271 final Variable vo3 = smapper.pushT(vi3.getType());
1272 final Variable vo2 = smapper.pushT(vi2.getType());
1273 final Variable vo1 = smapper.pushT(vi1.getType());
1275 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1276 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1281 final Variable vi1 = smapper.pop(this);
1282 final Variable vi2 = smapper.pop(this);
1284 if (vi1.isCategory2()) {
1285 if (vi2.isCategory2()) {
1286 final Variable vo3 = smapper.pushT(vi1.getType());
1287 final Variable vo2 = smapper.pushT(vi2.getType());
1288 final Variable vo1 = smapper.pushT(vi1.getType());
1290 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1291 vo1, vi1, vo2, vi2, vo3, vo1);
1293 final Variable vi3 = smapper.pop(this);
1294 final Variable vo4 = smapper.pushT(vi1.getType());
1295 final Variable vo3 = smapper.pushT(vi3.getType());
1296 final Variable vo2 = smapper.pushT(vi2.getType());
1297 final Variable vo1 = smapper.pushT(vi1.getType());
1299 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1300 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1303 final Variable vi3 = smapper.pop(this);
1305 if (vi3.isCategory2()) {
1306 final Variable vo5 = smapper.pushT(vi2.getType());
1307 final Variable vo4 = smapper.pushT(vi1.getType());
1308 final Variable vo3 = smapper.pushT(vi3.getType());
1309 final Variable vo2 = smapper.pushT(vi2.getType());
1310 final Variable vo1 = smapper.pushT(vi1.getType());
1312 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1313 vo1, vi1, vo2, vi2, vo3, vi3);
1314 emit(smapper, this, " @1 = @2, @3 = @4;",
1315 vo4, vo1, vo5, vo2);
1317 final Variable vi4 = smapper.pop(this);
1318 final Variable vo6 = smapper.pushT(vi2.getType());
1319 final Variable vo5 = smapper.pushT(vi1.getType());
1320 final Variable vo4 = smapper.pushT(vi4.getType());
1321 final Variable vo3 = smapper.pushT(vi3.getType());
1322 final Variable vo2 = smapper.pushT(vi2.getType());
1323 final Variable vo1 = smapper.pushT(vi1.getType());
1325 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1326 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1327 emit(smapper, this, " @1 = @2, @3 = @4;",
1328 vo5, vo1, vo6, vo2);
1334 final Variable vi1 = smapper.get(0);
1335 final Variable vi2 = smapper.get(1);
1337 if (vi1.getType() == vi2.getType()) {
1338 final Variable tmp = smapper.pushT(vi1.getType());
1340 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1345 smapper.pushT(vi1.getType());
1346 smapper.pushT(vi2.getType());
1351 smapper.assign(this, VarType.INTEGER,
1352 "(" + Integer.toString(byteCodes[++i]) + ")");
1355 smapper.assign(this, VarType.INTEGER,
1356 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1360 case opc_getfield: {
1361 int indx = readUShortArg(byteCodes, i);
1362 String[] fi = jc.getFieldInfoName(indx);
1363 final int type = VarType.fromFieldType(fi[2].charAt(0));
1364 final String mangleClass = mangleClassName(fi[0]);
1365 final String mangleClassAccess = accessClass(mangleClass);
1366 smapper.replace(this, type, "@2.call(@1)",
1368 accessField(mangleClassAccess + "(false)",
1374 case opc_putfield: {
1375 int indx = readUShortArg(byteCodes, i);
1376 String[] fi = jc.getFieldInfoName(indx);
1377 final int type = VarType.fromFieldType(fi[2].charAt(0));
1378 final String mangleClass = mangleClassName(fi[0]);
1379 final String mangleClassAccess = accessClass(mangleClass);
1380 emit(smapper, this, "@3.call(@2, @1);",
1383 accessField(mangleClassAccess + "(false)",
1388 case opc_getstatic: {
1389 int indx = readUShortArg(byteCodes, i);
1390 String[] fi = jc.getFieldInfoName(indx);
1391 final int type = VarType.fromFieldType(fi[2].charAt(0));
1392 String ac = accessClass(mangleClassName(fi[0]));
1393 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1394 smapper.assign(this, type, af + "()");
1396 addReference(fi[0]);
1399 case opc_putstatic: {
1400 int indx = readUShortArg(byteCodes, i);
1401 String[] fi = jc.getFieldInfoName(indx);
1402 final int type = VarType.fromFieldType(fi[2].charAt(0));
1403 emit(smapper, this, "@1(false)._@2(@3);",
1404 accessClass(mangleClassName(fi[0])), fi[1],
1405 smapper.popT(type));
1407 addReference(fi[0]);
1410 case opc_checkcast: {
1411 int indx = readUShortArg(byteCodes, i);
1412 generateCheckcast(indx, smapper);
1416 case opc_instanceof: {
1417 int indx = readUShortArg(byteCodes, i);
1418 generateInstanceOf(indx, smapper);
1423 final CharSequence v = smapper.popA();
1426 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1427 smapper.pushA(), v);
1431 case opc_monitorenter: {
1432 debug("/* monitor enter */");
1437 case opc_monitorexit: {
1438 debug("/* monitor exit */");
1449 emit(smapper, this, "throw 'unknown bytecode @1';",
1450 Integer.toString(c));
1454 generateByteCodeComment(prev, i, byteCodes);
1460 if (previousTrap != null) {
1461 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1466 while (openBraces-- > 0) {
1476 private int generateIf(StackMapper mapper, byte[] byteCodes,
1477 int i, final CharSequence v2, final CharSequence v1,
1478 final String test, int topMostLabel
1479 ) throws IOException {
1481 int indx = i + readShortArg(byteCodes, i);
1482 append("if ((").append(v1)
1483 .append(") ").append(test).append(" (")
1484 .append(v2).append(")) ");
1485 goTo(this, i, indx, topMostLabel);
1489 private int readInt4(byte[] byteCodes, int offset) {
1490 final int d = byteCodes[offset + 0] << 24;
1491 final int c = byteCodes[offset + 1] << 16;
1492 final int b = byteCodes[offset + 2] << 8;
1493 final int a = byteCodes[offset + 3];
1494 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1496 private static int readUByte(byte[] byteCodes, int offset) {
1497 return byteCodes[offset] & 0xff;
1500 private static int readUShort(byte[] byteCodes, int offset) {
1501 return ((byteCodes[offset] & 0xff) << 8)
1502 | (byteCodes[offset + 1] & 0xff);
1504 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1505 return readUShort(byteCodes, offsetInstruction + 1);
1508 private static int readShort(byte[] byteCodes, int offset) {
1509 int signed = byteCodes[offset];
1510 byte b0 = (byte)signed;
1511 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1513 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1514 return readShort(byteCodes, offsetInstruction + 1);
1517 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1519 Boolean count = null;
1520 boolean array = false;
1522 int firstPos = sig.length();
1523 while (i < descriptor.length()) {
1524 char ch = descriptor.charAt(i++);
1545 if (ch == 'J' || ch == 'D') {
1551 sig.insert(firstPos, ch);
1553 returnType[0] = '[';
1554 sig.insert(firstPos, "_3");
1563 returnType[0] = 'V';
1564 sig.insert(firstPos, 'V');
1567 int next = descriptor.indexOf(';', i);
1568 String realSig = mangleSig(descriptor, i - 1, next + 1);
1573 sig.append(realSig);
1576 sig.insert(firstPos, realSig);
1578 sig.insert(firstPos, "_3");
1580 returnType[0] = 'L';
1589 throw new IllegalStateException("Invalid char: " + ch);
1594 static String mangleSig(String sig) {
1595 return mangleSig(sig, 0, sig.length());
1598 private static String mangleMethodName(String name) {
1599 StringBuilder sb = new StringBuilder(name.length() * 2);
1600 int last = name.length();
1601 for (int i = 0; i < last; i++) {
1602 final char ch = name.charAt(i);
1604 case '_': sb.append("_1"); break;
1605 default: sb.append(ch); break;
1608 return sb.toString();
1610 private static String mangleSig(String txt, int first, int last) {
1611 StringBuilder sb = new StringBuilder((last - first) * 2);
1612 for (int i = first; i < last; i++) {
1613 final char ch = txt.charAt(i);
1615 case '/': sb.append('_'); break;
1616 case '_': sb.append("_1"); break;
1617 case ';': sb.append("_2"); break;
1618 case '[': sb.append("_3"); break;
1620 if (Character.isJavaIdentifierPart(ch)) {
1624 String hex = Integer.toHexString(ch).toLowerCase();
1625 for (int m = hex.length(); m < 4; m++) {
1633 return sb.toString();
1636 private static String mangleClassName(String name) {
1637 return mangleSig(name);
1640 private static String findMethodName(MethodData m, StringBuilder cnt) {
1641 StringBuilder name = new StringBuilder();
1642 if ("<init>".equals(m.getName())) { // NOI18N
1643 name.append("cons"); // NOI18N
1644 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1645 name.append("class"); // NOI18N
1647 name.append(mangleMethodName(m.getName()));
1650 countArgs(m.getInternalSig(), new char[1], name, cnt);
1651 return name.toString();
1654 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1655 StringBuilder name = new StringBuilder();
1656 String descr = mi[2];//mi.getDescriptor();
1658 if ("<init>".equals(nm)) { // NOI18N
1659 name.append("cons"); // NOI18N
1661 name.append(mangleMethodName(nm));
1663 countArgs(descr, returnType, name, cnt);
1664 return name.toString();
1667 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1668 throws IOException {
1669 int methodIndex = readUShortArg(byteCodes, i);
1670 String[] mi = jc.getFieldInfoName(methodIndex);
1671 char[] returnType = { 'V' };
1672 StringBuilder cnt = new StringBuilder();
1673 String mn = findMethodName(mi, cnt, returnType);
1675 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1676 final CharSequence[] vars = new CharSequence[numArguments];
1678 for (int j = numArguments - 1; j >= 0; --j) {
1679 vars[j] = mapper.popValue();
1682 if (returnType[0] != 'V') {
1685 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1689 final String in = mi[0];
1692 in.equals("org/apidesign/html/boot/spi/Fn") ||
1693 in.equals("org/netbeans/html/boot/spi/Fn")
1695 mcn = "java_lang_Class";
1697 mcn = mangleClassName(in);
1699 String object = accessClass(mcn) + "(false)";
1700 if (mn.startsWith("cons_")) {
1701 object += ".constructor";
1703 append(accessStaticMethod(object, mn, mi));
1709 if (numArguments > 0) {
1711 for (int j = 1; j < numArguments; ++j) {
1721 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1722 throws IOException {
1723 int methodIndex = readUShortArg(byteCodes, i);
1724 String[] mi = jc.getFieldInfoName(methodIndex);
1725 char[] returnType = { 'V' };
1726 StringBuilder cnt = new StringBuilder();
1727 String mn = findMethodName(mi, cnt, returnType);
1729 final int numArguments = cnt.length() + 1;
1730 final CharSequence[] vars = new CharSequence[numArguments];
1732 for (int j = numArguments - 1; j >= 0; --j) {
1733 vars[j] = mapper.popValue();
1736 if (returnType[0] != 'V') {
1738 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1742 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1744 for (int j = 1; j < numArguments; ++j) {
1754 private void addReference(String cn) throws IOException {
1755 if (requireReference(cn)) {
1756 debug(" /* needs " + cn + " */");
1760 private void outType(String d, StringBuilder out) {
1762 while (d.charAt(0) == '[') {
1766 if (d.charAt(0) == 'L') {
1767 assert d.charAt(d.length() - 1) == ';';
1768 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1774 private String encodeConstant(int entryIndex) throws IOException {
1775 String[] classRef = { null };
1776 String s = jc.stringValue(entryIndex, classRef);
1777 if (classRef[0] != null) {
1778 if (classRef[0].startsWith("[")) {
1779 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1781 addReference(classRef[0]);
1782 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1788 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1789 byte[] arr = m.findAnnotationData(true);
1793 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1794 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1795 class P extends AnnotationParser {
1801 String[] args = new String[30];
1807 protected void visitAttr(String type, String attr, String at, String value) {
1808 if (type.equals(jvmType)) {
1809 if ("body".equals(attr)) {
1811 } else if ("args".equals(attr)) {
1812 args[cnt++] = value;
1814 throw new IllegalArgumentException(attr);
1817 if (type.equals(htmlType)) {
1819 if ("body".equals(attr)) {
1821 } else if ("args".equals(attr)) {
1822 args[cnt++] = value;
1823 } else if ("javacall".equals(attr)) {
1824 javacall = "1".equals(value);
1825 } else if ("wait4js".equals(attr)) {
1826 // ignore, we always invoke synchronously
1828 throw new IllegalArgumentException(attr);
1835 if (p.body == null) {
1838 StringBuilder cnt = new StringBuilder();
1839 final String mn = findMethodName(m, cnt);
1840 append(destObject).append(".").append(mn);
1841 append(" = function(");
1844 StringBuilder toValue = new StringBuilder();
1845 for (int i = 0; i < cnt.length(); i++) {
1847 space = outputArg(this, p.args, index);
1848 if (p.html4j && space.length() > 0) {
1849 toValue.append("\n ").append(p.args[index]).append(" = ")
1850 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1851 append(p.args[index]).append(");");
1855 append(") {").append("\n");
1856 append(toValue.toString());
1858 int lastSlash = jc.getClassName().lastIndexOf('/');
1859 final String pkg = jc.getClassName().substring(0, lastSlash);
1860 append(mangleCallbacks(pkg, p.body));
1861 requireReference(pkg + "/$JsCallbacks$");
1869 private static CharSequence mangleCallbacks(String pkgName, String body) {
1870 StringBuilder sb = new StringBuilder();
1873 int next = body.indexOf(".@", pos);
1875 sb.append(body.substring(pos));
1876 body = sb.toString();
1881 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1886 String refId = body.substring(ident, next);
1888 sb.append(body.substring(pos, ident));
1890 int sigBeg = body.indexOf('(', next);
1891 int sigEnd = body.indexOf(')', sigBeg);
1892 int colon4 = body.indexOf("::", next);
1893 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1894 throw new IllegalStateException("Malformed body " + body);
1896 String fqn = body.substring(next + 2, colon4);
1897 String method = body.substring(colon4 + 2, sigBeg);
1898 String params = body.substring(sigBeg, sigEnd + 1);
1900 int paramBeg = body.indexOf('(', sigEnd + 1);
1902 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1903 sb.append(mangleJsCallbacks(fqn, method, params, false));
1904 sb.append("(").append(refId);
1905 if (body.charAt(paramBeg + 1) != ')') {
1913 int next = body.indexOf("@", pos);
1918 sb.append(body.substring(pos));
1922 sb = new StringBuilder();
1925 sb.append(body.substring(pos, next));
1927 int sigBeg = body.indexOf('(', next);
1928 int sigEnd = body.indexOf(')', sigBeg);
1929 int colon4 = body.indexOf("::", next);
1930 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1931 throw new IllegalStateException("Malformed body " + body);
1933 String fqn = body.substring(next + 1, colon4);
1934 String method = body.substring(colon4 + 2, sigBeg);
1935 String params = body.substring(sigBeg, sigEnd + 1);
1937 int paramBeg = body.indexOf('(', sigEnd + 1);
1939 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1940 sb.append(mangleJsCallbacks(fqn, method, params, true));
1946 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1947 if (params.startsWith("(")) {
1948 params = params.substring(1);
1950 if (params.endsWith(")")) {
1951 params = params.substring(0, params.length() - 1);
1953 StringBuilder sb = new StringBuilder();
1954 final String fqnu = fqn.replace('.', '_');
1955 final String rfqn = mangleClassName(fqnu);
1956 final String rm = mangleMethodName(method);
1959 StringBuilder pb = new StringBuilder();
1960 int len = params.length();
1962 while (indx < len) {
1963 char ch = params.charAt(indx);
1964 if (ch == '[' || ch == 'L') {
1965 pb.append("Ljava/lang/Object;");
1966 indx = params.indexOf(';', indx) + 1;
1972 srp = mangleSig(pb.toString());
1974 final String rp = mangleSig(params);
1975 final String mrp = mangleMethodName(rp);
1976 sb.append(rfqn).append("$").append(rm).
1977 append('$').append(mrp).append("__Ljava_lang_Object_2");
1979 sb.append('L').append(fqnu).append("_2");
1982 return sb.toString();
1985 private static String className(ClassData jc) {
1986 //return jc.getName().getInternalName().replace('/', '_');
1987 return mangleClassName(jc.getClassName());
1990 private static String[] findAnnotation(
1991 byte[] arr, ClassData cd, final String className,
1992 final String... attrNames
1993 ) throws IOException {
1997 final String[] values = new String[attrNames.length];
1998 final boolean[] found = { false };
1999 final String jvmType = "L" + className.replace('.', '/') + ";";
2000 AnnotationParser ap = new AnnotationParser(false, true) {
2002 protected void visitAttr(String type, String attr, String at, String value) {
2003 if (type.equals(jvmType)) {
2005 for (int i = 0; i < attrNames.length; i++) {
2006 if (attrNames[i].equals(attr)) {
2015 return found[0] ? values : null;
2018 private CharSequence initField(FieldData v) {
2019 final String is = v.getInternalSig();
2020 if (is.length() == 1) {
2021 switch (is.charAt(0)) {
2027 case 'I': return " = 0;";
2029 case 'D': return " = 0.0;";
2031 throw new IllegalStateException(is);
2037 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2038 AnnotationParser ap = new AnnotationParser(true, false) {
2039 int[] cnt = new int[32];
2043 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2044 final String slashType = attrType.substring(1, attrType.length() - 1);
2045 requireReference(slashType);
2047 if (cnt[depth]++ > 0) {
2051 append('"').append(attrType).append("\" : ");
2058 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2064 protected void visitValueStart(String attrName, char type) throws IOException {
2065 if (cnt[depth]++ > 0) {
2069 if (attrName != null) {
2070 append('"').append(attrName).append("\" : ");
2078 protected void visitValueEnd(String attrName, char type) throws IOException {
2086 protected void visitAttr(String type, String attr, String attrType, String value)
2087 throws IOException {
2088 if (attr == null && value == null) {
2095 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2096 throws IOException {
2097 final String slashType = attrType.substring(1, attrType.length() - 1);
2098 requireReference(slashType);
2100 final String cn = mangleClassName(slashType);
2101 append(accessClass(cn))
2102 .append("(false)['valueOf__L").
2104 append("_2Ljava_lang_String_2']('").
2112 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2113 final String name = args[indx];
2117 if (name.contains(",")) {
2118 throw new IOException("Wrong parameter with ',': " + name);
2124 final void emitNoFlush(
2126 final String format, final CharSequence... params
2127 ) throws IOException {
2128 emitImpl(this, format, params);
2130 static final void emit(
2132 final Appendable out,
2133 final String format, final CharSequence... params
2134 ) throws IOException {
2136 emitImpl(out, format, params);
2138 static void emitImpl(final Appendable out,
2139 final String format,
2140 final CharSequence... params) throws IOException {
2141 final int length = format.length();
2144 int paramOffset = format.indexOf('@');
2145 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2146 final char paramChar = format.charAt(paramOffset + 1);
2147 if ((paramChar >= '1') && (paramChar <= '9')) {
2148 final int paramIndex = paramChar - '0' - 1;
2150 out.append(format, processed, paramOffset);
2151 out.append(params[paramIndex]);
2154 processed = paramOffset + 1;
2157 paramOffset = format.indexOf('@', paramOffset + 1);
2160 out.append(format, processed, length);
2163 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2164 append("} catch (e) {\n");
2166 for (TrapData e : traps) {
2170 if (e.catch_cpx != 0) { //not finally
2171 final String classInternalName = jc.getClassName(e.catch_cpx);
2172 addReference(classInternalName);
2173 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2174 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2175 append("var stA0 = e;");
2176 goTo(this, current, e.handler_pc, topMostLabel);
2179 finallyPC = e.handler_pc;
2182 if (finallyPC == -1) {
2185 append("var stA0 = e;");
2186 goTo(this, current, finallyPC, topMostLabel);
2191 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2194 out.append("{ gt = 0; continue X_" + to + "; }");
2196 out.append("{ gt = " + to + "; continue X_0; }");
2199 out.append("{ gt = " + to + "; break IF; }");
2203 private static void emitIf(
2205 Appendable out, String pattern,
2207 int current, int to, int canBack
2208 ) throws IOException {
2210 emitImpl(out, pattern, param);
2211 goTo(out, current, to, canBack);
2214 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2217 case 4: jvmType = "[Z"; break;
2218 case 5: jvmType = "[C"; break;
2219 case 6: jvmType = "[F"; break;
2220 case 7: jvmType = "[D"; break;
2221 case 8: jvmType = "[B"; break;
2222 case 9: jvmType = "[S"; break;
2223 case 10: jvmType = "[I"; break;
2224 case 11: jvmType = "[J"; break;
2225 default: throw new IllegalStateException("Array type: " + atype);
2228 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2229 smapper.popI(), smapper.pushA(), jvmType);
2232 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2233 String typeName = jc.getClassName(type);
2234 String ref = "null";
2235 if (typeName.startsWith("[")) {
2236 typeName = "'[" + typeName + "'";
2238 ref = "vm." + mangleClassName(typeName);
2239 typeName = "'[L" + typeName + ";'";
2242 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2243 smapper.popI(), smapper.pushA(), typeName, ref);
2246 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2247 String typeName = jc.getClassName(type);
2248 int dim = readUByte(byteCodes, ++i);
2249 StringBuilder dims = new StringBuilder();
2251 for (int d = 0; d < dim; d++) {
2253 dims.insert(1, ",");
2255 dims.insert(1, smapper.popI());
2259 if (typeName.charAt(dim) == 'L') {
2260 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2263 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2264 dims.toString(), smapper.pushA(), typeName, fn
2269 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2270 int table = i / 4 * 4 + 4;
2271 int dflt = i + readInt4(byteCodes, table);
2273 int low = readInt4(byteCodes, table);
2275 int high = readInt4(byteCodes, table);
2277 final CharSequence swVar = smapper.popValue();
2278 smapper.flush(this);
2279 append("switch (").append(swVar).append(") {\n");
2280 while (low <= high) {
2281 int offset = i + readInt4(byteCodes, table);
2283 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2286 append(" default: ");
2287 goTo(this, i, dflt, topMostLabel);
2293 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2294 int table = i / 4 * 4 + 4;
2295 int dflt = i + readInt4(byteCodes, table);
2297 int n = readInt4(byteCodes, table);
2299 final CharSequence swVar = smapper.popValue();
2300 smapper.flush(this);
2301 append("switch (").append(swVar).append(") {\n");
2303 int cnstnt = readInt4(byteCodes, table);
2305 int offset = i + readInt4(byteCodes, table);
2307 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2309 append(" default: ");
2310 goTo(this, i, dflt, topMostLabel);
2316 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2317 String type = jc.getClassName(indx);
2318 if (!type.startsWith("[")) {
2320 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2321 smapper.popA(), smapper.pushI(),
2322 type.replace('/', '_'));
2325 while (type.charAt(cnt) == '[') {
2328 if (type.charAt(cnt) == 'L') {
2329 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2331 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2332 smapper.popA(), smapper.pushI(),
2337 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2338 smapper.popA(), smapper.pushI(), type
2344 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2345 String type = jc.getClassName(indx);
2346 if (!type.startsWith("[")) {
2347 emitNoFlush(smapper,
2348 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2349 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2352 while (type.charAt(cnt) == '[') {
2355 if (type.charAt(cnt) == 'L') {
2356 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2357 emitNoFlush(smapper,
2358 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2359 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2362 emitNoFlush(smapper,
2363 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2364 smapper.getT(0, VarType.REFERENCE, false), type
2370 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2371 for (int j = prev; j <= i; j++) {
2373 final int cc = readUByte(byteCodes, j);
2374 append(Integer.toString(cc));
2378 @JavaScriptBody(args = "msg", body = "")
2379 private static void println(String msg) {
2380 System.err.println(msg);