Store just defined member in variable m and use it to assign access, cls and export the member
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("() {");
193 append("\n var CLS = ").append(className).append(';');
194 append("\n if (!CLS.$class) {");
196 String sc = jc.getSuperClassName(); // with _
197 append("\n var pp = ").
198 append(accessClass(mangleClassName(sc))).append("(true);");
199 append("\n var p = CLS.prototype = pp;");
200 append("\n var c = p;");
201 append("\n var sprcls = pp.constructor.$class;");
203 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
204 if (proto[0] == null) {
207 append("\n var c = ").append(proto[0]).append(";");
208 append("\n var sprcls = null;");
210 for (FieldData v : jc.getFields()) {
212 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
213 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
217 append("\n CLS.fld_").append(v.getName()).append(initField(v));
218 append("\n m = c._").append(v.getName()).append(" = function (v) {")
219 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
220 .append(" = v; return CLS.fld_").
221 append(v.getName()).append("; };");
223 append("\n m = c._").append(v.getName()).append(" = function (v) {")
224 .append(" if (arguments.length == 1) this.fld_").
225 append(className).append('_').append(v.getName())
226 .append(" = v; return this.fld_").
227 append(className).append('_').append(v.getName())
231 declaredField(v, "c", "_" + v.getName());
233 for (MethodData m : jc.getMethods()) {
234 byte[] onlyArr = m.findAnnotationData(true);
235 if (javaScriptOnly(onlyArr)) continue;
241 mn = generateStaticMethod(destObject, m, toInitilize);
243 if (m.isConstructor()) {
245 mn = generateInstanceMethod(destObject, m);
248 mn = generateInstanceMethod(destObject, m);
251 declaredMethod(m, destObject, mn);
252 byte[] runAnno = m.findAnnotationData(false);
253 if (runAnno != null) {
254 append("\n m.anno = {");
255 generateAnno(jc, runAnno);
258 append("\n m.access = " + m.getAccess()).append(";");
259 append("\n m.cls = CLS;");
261 append("\n c.constructor = CLS;");
262 append("\n function ").append(className).append("fillInstOf(x) {");
263 String instOfName = "$instOf_" + className;
264 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
265 if (jc.isInterface()) {
266 for (MethodData m : jc.getMethods()) {
267 if ((m.getAccess() & ACC_ABSTRACT) == 0
268 && (m.getAccess() & ACC_STATIC) == 0
269 && (m.getAccess() & ACC_PRIVATE) == 0) {
270 final String mn = findMethodName(m, new StringBuilder());
272 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
273 append("\n } catch (ignore) {");
278 for (String superInterface : jc.getSuperInterfaces()) {
279 String intrfc = superInterface.replace('/', '_');
280 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
281 requireReference(superInterface);
285 append("\n Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
286 append("\n ").append(className).append("fillInstOf(c);");
287 append("\n } catch (ignore) {");
289 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
290 append("\n CLS.$class = 'temp';");
291 append("\n CLS.$class = ");
292 append(accessClass("java_lang_Class(true);"));
293 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
294 append("\n CLS.$class.superclass = sprcls;");
295 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
296 append("\n CLS.$class.cnstr = CLS;");
297 byte[] classAnno = jc.findAnnotationData(false);
298 if (classAnno != null) {
299 append("\n CLS.$class.anno = {");
300 generateAnno(jc, classAnno);
303 for (String init : toInitilize.toArray()) {
304 append("\n ").append(init).append("();");
307 append("\n if (arguments.length === 0) {");
308 append("\n if (!(this instanceof CLS)) {");
309 append("\n return new CLS();");
311 for (FieldData v : jc.getFields()) {
312 byte[] onlyArr = v.findAnnotationData(true);
313 if (javaScriptOnly(onlyArr)) continue;
315 append("\n this.fld_").
316 append(className).append('_').
317 append(v.getName()).append(initField(v));
320 append("\n return this;");
322 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
325 declaredClass(jc, className);
327 // StringBuilder sb = new StringBuilder();
328 // for (String init : toInitilize.toArray()) {
329 // sb.append("\n").append(init).append("();");
334 private boolean javaScriptOnly(byte[] anno) throws IOException {
335 String[] only = findAnnotation(anno, jc,
336 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
340 if (only[0] != null && only[1] != null) {
341 append("\n p.").append(only[0]).append(" = ")
342 .append(only[1]).append(";");
344 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
345 append("\n p['").append(only[0]).append("'] = p.")
346 .append(only[0]).append(";");
352 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
353 String jsb = javaScriptBody(destObject, m, true);
357 final String mn = findMethodName(m, new StringBuilder());
358 if (mn.equals("class__V")) {
359 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
361 generateMethod(destObject, mn, m);
365 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
366 String jsb = javaScriptBody(destObject, m, false);
370 final String mn = findMethodName(m, new StringBuilder());
371 generateMethod(destObject, mn, m);
375 private void generateMethod(String destObject, String name, MethodData m)
377 final StackMapIterator stackMapIterator = m.createStackMapIterator();
378 TrapDataIterator trap = m.getTrapDataIterator();
379 final LocalsMapper lmapper =
380 new LocalsMapper(stackMapIterator.getArguments());
383 "java/lang/Object".equals(jc.getClassName()) ||
384 "java/lang/reflect/Array".equals(jc.getClassName());
387 append("Object.defineProperty(").append(destObject).
388 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
390 append("m = ").append(destObject).append(".").append(name).append(" = function(");
392 lmapper.outputArguments(this, m.isStatic());
393 append(") {").append("\n");
395 final byte[] byteCodes = m.getCode();
396 if (byteCodes == null) {
397 append(" throw 'no code found for ")
398 .append(jc.getClassName()).append('.')
399 .append(m.getName()).append("';\n");
408 final StackMapper smapper = new StackMapper();
411 append(" var ").append(" lcA0 = this;\n");
415 TrapData[] previousTrap = null;
416 boolean wide = false;
418 if (stackMapIterator.isEmpty()) {
424 append("\n var gt = 0;\n");
428 int topMostLabel = 0;
429 for (int i = 0; i < byteCodes.length; i++) {
432 stackMapIterator.advanceTo(i);
433 boolean changeInCatch = trap.advanceTo(i);
434 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
435 if (previousTrap != null) {
436 generateCatch(previousTrap, i, topMostLabel);
440 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
445 if (openBraces > 64) {
446 for (int c = 0; c < 64; c++) {
453 lastStackFrame = stackMapIterator.getFrameIndex();
454 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
455 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
456 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
458 changeInCatch = true;
460 debug(" /* " + i + " */ ");
462 if (changeInCatch && trap.useTry()) {
464 previousTrap = trap.current();
466 final int c = readUByte(byteCodes, i);
469 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
472 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
475 smapper.assign(this, VarType.LONG, lmapper.getL(0));
478 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
481 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
484 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
487 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
490 smapper.assign(this, VarType.LONG, lmapper.getL(1));
493 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
496 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
499 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
502 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
505 smapper.assign(this, VarType.LONG, lmapper.getL(2));
508 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
511 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
514 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
517 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
520 smapper.assign(this, VarType.LONG, lmapper.getL(3));
523 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
526 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
530 final int indx = wide ? readUShort(byteCodes, i++)
531 : readUByte(byteCodes, i);
533 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
538 final int indx = wide ? readUShort(byteCodes, i++)
539 : readUByte(byteCodes, i);
541 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
546 final int indx = wide ? readUShort(byteCodes, i++)
547 : readUByte(byteCodes, i);
549 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
554 final int indx = wide ? readUShort(byteCodes, i++)
555 : readUByte(byteCodes, i);
557 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
562 final int indx = wide ? readUShort(byteCodes, i++)
563 : readUByte(byteCodes, i);
565 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
570 final int indx = wide ? readUShort(byteCodes, i++)
571 : readUByte(byteCodes, i);
573 emit(smapper, this, "var @1 = @2;",
574 lmapper.setI(indx), smapper.popI());
579 final int indx = wide ? readUShort(byteCodes, i++)
580 : readUByte(byteCodes, i);
582 emit(smapper, this, "var @1 = @2;",
583 lmapper.setL(indx), smapper.popL());
588 final int indx = wide ? readUShort(byteCodes, i++)
589 : readUByte(byteCodes, i);
591 emit(smapper, this, "var @1 = @2;",
592 lmapper.setF(indx), smapper.popF());
597 final int indx = wide ? readUShort(byteCodes, i++)
598 : readUByte(byteCodes, i);
600 emit(smapper, this, "var @1 = @2;",
601 lmapper.setD(indx), smapper.popD());
606 final int indx = wide ? readUShort(byteCodes, i++)
607 : readUByte(byteCodes, i);
609 emit(smapper, this, "var @1 = @2;",
610 lmapper.setA(indx), smapper.popA());
614 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
617 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
620 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
623 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
626 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
629 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
632 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
635 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
638 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
641 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
644 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
647 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
650 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
653 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
656 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
659 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
662 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
665 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
668 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
671 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
674 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
677 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
680 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
683 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
686 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
689 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
692 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
695 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
698 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
701 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
704 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
707 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
710 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
711 smapper.getI(1), smapper.popI());
714 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
715 smapper.getL(1), smapper.popL());
718 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
721 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
724 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
725 smapper.getI(1), smapper.popI());
728 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
729 smapper.getL(1), smapper.popL());
732 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
735 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
738 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
741 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
744 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
747 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
750 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
753 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
756 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
759 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
762 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
765 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
768 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
771 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
774 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
777 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
780 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
783 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
787 final int varIndx = wide ? readUShort(byteCodes, i++)
788 : readUByte(byteCodes, i);
790 final int incrBy = wide ? readShort(byteCodes, i++)
794 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
796 emit(smapper, this, "@1 += @2;",
797 lmapper.getI(varIndx),
798 Integer.toString(incrBy));
803 emit(smapper, this, "return;");
806 emit(smapper, this, "return @1;", smapper.popI());
809 emit(smapper, this, "return @1;", smapper.popL());
812 emit(smapper, this, "return @1;", smapper.popF());
815 emit(smapper, this, "return @1;", smapper.popD());
818 emit(smapper, this, "return @1;", smapper.popA());
821 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
824 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
827 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
830 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
834 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
837 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
840 smapper.replace(this, VarType.DOUBLE, "@1",
844 smapper.replace(this, VarType.FLOAT, "@1",
848 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
852 smapper.replace(this, VarType.LONG, "(@1).toLong()",
856 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
860 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
863 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
867 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
869 case opc_aconst_null:
870 smapper.assign(this, VarType.REFERENCE, "null");
873 smapper.assign(this, VarType.INTEGER, "-1");
876 smapper.assign(this, VarType.INTEGER, "0");
879 smapper.assign(this, VarType.DOUBLE, "0");
882 smapper.assign(this, VarType.LONG, "0");
885 smapper.assign(this, VarType.FLOAT, "0");
888 smapper.assign(this, VarType.INTEGER, "1");
891 smapper.assign(this, VarType.LONG, "1");
894 smapper.assign(this, VarType.FLOAT, "1");
897 smapper.assign(this, VarType.DOUBLE, "1");
900 smapper.assign(this, VarType.INTEGER, "2");
903 smapper.assign(this, VarType.FLOAT, "2");
906 smapper.assign(this, VarType.INTEGER, "3");
909 smapper.assign(this, VarType.INTEGER, "4");
912 smapper.assign(this, VarType.INTEGER, "5");
915 int indx = readUByte(byteCodes, ++i);
916 String v = encodeConstant(indx);
917 int type = VarType.fromConstantType(jc.getTag(indx));
918 smapper.assign(this, type, v);
923 int indx = readUShortArg(byteCodes, i);
925 String v = encodeConstant(indx);
926 int type = VarType.fromConstantType(jc.getTag(indx));
927 if (type == VarType.LONG) {
928 final Long lv = new Long(v);
929 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
930 final int hi = (int)(lv.longValue() >> 32);
932 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
934 smapper.assign(this, VarType.LONG,
935 "0x" + Integer.toHexString(hi) + ".next32(0x" +
936 Integer.toHexString(low) + ")"
940 smapper.assign(this, type, v);
945 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
949 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
953 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
956 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
957 "===", topMostLabel);
960 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
961 "!==", topMostLabel);
964 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
968 int indx = i + readShortArg(byteCodes, i);
969 emitIf(smapper, this, "if ((@1) == 0) ",
970 smapper.popI(), i, indx, topMostLabel);
975 int indx = i + readShortArg(byteCodes, i);
976 emitIf(smapper, this, "if ((@1) != 0) ",
977 smapper.popI(), i, indx, topMostLabel);
982 int indx = i + readShortArg(byteCodes, i);
983 emitIf(smapper, this, "if ((@1) < 0) ",
984 smapper.popI(), i, indx, topMostLabel);
989 int indx = i + readShortArg(byteCodes, i);
990 emitIf(smapper, this, "if ((@1) <= 0) ",
991 smapper.popI(), i, indx, topMostLabel);
996 int indx = i + readShortArg(byteCodes, i);
997 emitIf(smapper, this, "if ((@1) > 0) ",
998 smapper.popI(), i, indx, topMostLabel);
1003 int indx = i + readShortArg(byteCodes, i);
1004 emitIf(smapper, this, "if ((@1) >= 0) ",
1005 smapper.popI(), i, indx, topMostLabel);
1009 case opc_ifnonnull: {
1010 int indx = i + readShortArg(byteCodes, i);
1011 emitIf(smapper, this, "if ((@1) !== null) ",
1012 smapper.popA(), i, indx, topMostLabel);
1017 int indx = i + readShortArg(byteCodes, i);
1018 emitIf(smapper, this, "if ((@1) === null) ",
1019 smapper.popA(), i, indx, topMostLabel);
1024 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1025 "!=", topMostLabel);
1028 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1032 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1033 "<=", topMostLabel);
1036 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1040 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1041 ">=", topMostLabel);
1044 smapper.flush(this);
1045 int indx = i + readShortArg(byteCodes, i);
1046 goTo(this, i, indx, topMostLabel);
1050 case opc_lookupswitch: {
1051 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1054 case opc_tableswitch: {
1055 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1058 case opc_invokeinterface: {
1059 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1062 case opc_invokevirtual:
1063 i = invokeVirtualMethod(byteCodes, i, smapper);
1065 case opc_invokespecial:
1066 i = invokeStaticMethod(byteCodes, i, smapper, false);
1068 case opc_invokestatic:
1069 i = invokeStaticMethod(byteCodes, i, smapper, true);
1071 case opc_invokedynamic: {
1072 int indx = readUShortArg(byteCodes, i);
1073 println("invoke dynamic: " + indx);
1074 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1075 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1076 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1077 println(" type: " + methodHandle.cpx1);
1078 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1079 String mcn = mangleClassName(mi[0]);
1080 char[] returnType = {'V'};
1081 StringBuilder cnt = new StringBuilder();
1082 String mn = findMethodName(mi, cnt, returnType);
1083 StringBuilder sb = new StringBuilder();
1084 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1085 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1086 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1087 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1088 sb.append(" mn : ").append(mn).append("\n");
1089 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1090 throw new IOException(sb.toString());
1092 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1093 String type = jc.StringValue(nameAndType.cpx2);
1094 String object = accessClass(mcn) + "(false)";
1095 if (mn.startsWith("cons_")) {
1096 object += ".constructor";
1098 append("var metHan = ");
1099 append(accessStaticMethod(object, mn, mi));
1101 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1103 append(", '").append(mi[1]).append("', ");
1104 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1105 append(methodType).append("'").append(type).append("', null)");
1106 // if (numArguments > 0) {
1108 // for (int j = 1; j < numArguments; ++j) {
1114 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1120 int indx = readUShortArg(byteCodes, i);
1121 String ci = jc.getClassName(indx);
1122 emit(smapper, this, "var @1 = new @2;",
1123 smapper.pushA(), accessClass(mangleClassName(ci)));
1129 int atype = readUByte(byteCodes, ++i);
1130 generateNewArray(atype, smapper);
1132 case opc_anewarray: {
1133 int type = readUShortArg(byteCodes, i);
1135 generateANewArray(type, smapper);
1138 case opc_multianewarray: {
1139 int type = readUShortArg(byteCodes, i);
1141 i = generateMultiANewArray(type, byteCodes, i, smapper);
1144 case opc_arraylength:
1145 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1148 emit(smapper, this, "Array.at(@3, @2, @1);",
1149 smapper.popL(), smapper.popI(), smapper.popA());
1152 emit(smapper, this, "Array.at(@3, @2, @1);",
1153 smapper.popF(), smapper.popI(), smapper.popA());
1156 emit(smapper, this, "Array.at(@3, @2, @1);",
1157 smapper.popD(), smapper.popI(), smapper.popA());
1160 emit(smapper, this, "Array.at(@3, @2, @1);",
1161 smapper.popA(), smapper.popI(), smapper.popA());
1167 emit(smapper, this, "Array.at(@3, @2, @1);",
1168 smapper.popI(), smapper.popI(), smapper.popA());
1171 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1172 smapper.popI(), smapper.getA(0));
1175 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1176 smapper.popI(), smapper.getA(0));
1179 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1180 smapper.popI(), smapper.getA(0));
1183 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1184 smapper.popI(), smapper.getA(0));
1190 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1191 smapper.popI(), smapper.getA(0));
1199 final Variable v = smapper.get(0);
1200 if (smapper.isDirty()) {
1201 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1203 smapper.assign(this, v.getType(), v);
1208 final Variable vi1 = smapper.get(0);
1210 if (vi1.isCategory2()) {
1211 emit(smapper, this, "var @1 = @2;",
1212 smapper.pushT(vi1.getType()), vi1);
1214 final Variable vi2 = smapper.get(1);
1215 emit(smapper, this, "var @1 = @2, @3 = @4;",
1216 smapper.pushT(vi2.getType()), vi2,
1217 smapper.pushT(vi1.getType()), vi1);
1222 final Variable vi1 = smapper.pop(this);
1223 final Variable vi2 = smapper.pop(this);
1224 final Variable vo3 = smapper.pushT(vi1.getType());
1225 final Variable vo2 = smapper.pushT(vi2.getType());
1226 final Variable vo1 = smapper.pushT(vi1.getType());
1228 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1229 vo1, vi1, vo2, vi2, vo3, vo1);
1233 final Variable vi1 = smapper.pop(this);
1234 final Variable vi2 = smapper.pop(this);
1236 if (vi1.isCategory2()) {
1237 final Variable vo3 = smapper.pushT(vi1.getType());
1238 final Variable vo2 = smapper.pushT(vi2.getType());
1239 final Variable vo1 = smapper.pushT(vi1.getType());
1241 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1242 vo1, vi1, vo2, vi2, vo3, vo1);
1244 final Variable vi3 = smapper.pop(this);
1245 final Variable vo5 = smapper.pushT(vi2.getType());
1246 final Variable vo4 = smapper.pushT(vi1.getType());
1247 final Variable vo3 = smapper.pushT(vi3.getType());
1248 final Variable vo2 = smapper.pushT(vi2.getType());
1249 final Variable vo1 = smapper.pushT(vi1.getType());
1251 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1252 vo1, vi1, vo2, vi2, vo3, vi3);
1253 emit(smapper, this, " @1 = @2, @3 = @4;",
1254 vo4, vo1, vo5, vo2);
1259 final Variable vi1 = smapper.pop(this);
1260 final Variable vi2 = smapper.pop(this);
1262 if (vi2.isCategory2()) {
1263 final Variable vo3 = smapper.pushT(vi1.getType());
1264 final Variable vo2 = smapper.pushT(vi2.getType());
1265 final Variable vo1 = smapper.pushT(vi1.getType());
1267 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1268 vo1, vi1, vo2, vi2, vo3, vo1);
1270 final Variable vi3 = smapper.pop(this);
1271 final Variable vo4 = smapper.pushT(vi1.getType());
1272 final Variable vo3 = smapper.pushT(vi3.getType());
1273 final Variable vo2 = smapper.pushT(vi2.getType());
1274 final Variable vo1 = smapper.pushT(vi1.getType());
1276 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1277 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1282 final Variable vi1 = smapper.pop(this);
1283 final Variable vi2 = smapper.pop(this);
1285 if (vi1.isCategory2()) {
1286 if (vi2.isCategory2()) {
1287 final Variable vo3 = smapper.pushT(vi1.getType());
1288 final Variable vo2 = smapper.pushT(vi2.getType());
1289 final Variable vo1 = smapper.pushT(vi1.getType());
1291 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1292 vo1, vi1, vo2, vi2, vo3, vo1);
1294 final Variable vi3 = smapper.pop(this);
1295 final Variable vo4 = smapper.pushT(vi1.getType());
1296 final Variable vo3 = smapper.pushT(vi3.getType());
1297 final Variable vo2 = smapper.pushT(vi2.getType());
1298 final Variable vo1 = smapper.pushT(vi1.getType());
1300 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1301 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1304 final Variable vi3 = smapper.pop(this);
1306 if (vi3.isCategory2()) {
1307 final Variable vo5 = smapper.pushT(vi2.getType());
1308 final Variable vo4 = smapper.pushT(vi1.getType());
1309 final Variable vo3 = smapper.pushT(vi3.getType());
1310 final Variable vo2 = smapper.pushT(vi2.getType());
1311 final Variable vo1 = smapper.pushT(vi1.getType());
1313 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1314 vo1, vi1, vo2, vi2, vo3, vi3);
1315 emit(smapper, this, " @1 = @2, @3 = @4;",
1316 vo4, vo1, vo5, vo2);
1318 final Variable vi4 = smapper.pop(this);
1319 final Variable vo6 = smapper.pushT(vi2.getType());
1320 final Variable vo5 = smapper.pushT(vi1.getType());
1321 final Variable vo4 = smapper.pushT(vi4.getType());
1322 final Variable vo3 = smapper.pushT(vi3.getType());
1323 final Variable vo2 = smapper.pushT(vi2.getType());
1324 final Variable vo1 = smapper.pushT(vi1.getType());
1326 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1327 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1328 emit(smapper, this, " @1 = @2, @3 = @4;",
1329 vo5, vo1, vo6, vo2);
1335 final Variable vi1 = smapper.get(0);
1336 final Variable vi2 = smapper.get(1);
1338 if (vi1.getType() == vi2.getType()) {
1339 final Variable tmp = smapper.pushT(vi1.getType());
1341 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1346 smapper.pushT(vi1.getType());
1347 smapper.pushT(vi2.getType());
1352 smapper.assign(this, VarType.INTEGER,
1353 "(" + Integer.toString(byteCodes[++i]) + ")");
1356 smapper.assign(this, VarType.INTEGER,
1357 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1361 case opc_getfield: {
1362 int indx = readUShortArg(byteCodes, i);
1363 String[] fi = jc.getFieldInfoName(indx);
1364 final int type = VarType.fromFieldType(fi[2].charAt(0));
1365 final String mangleClass = mangleClassName(fi[0]);
1366 final String mangleClassAccess = accessClass(mangleClass);
1367 smapper.replace(this, type, "@2.call(@1)",
1369 accessField(mangleClassAccess + "(false)",
1375 case opc_putfield: {
1376 int indx = readUShortArg(byteCodes, i);
1377 String[] fi = jc.getFieldInfoName(indx);
1378 final int type = VarType.fromFieldType(fi[2].charAt(0));
1379 final String mangleClass = mangleClassName(fi[0]);
1380 final String mangleClassAccess = accessClass(mangleClass);
1381 emit(smapper, this, "@3.call(@2, @1);",
1384 accessField(mangleClassAccess + "(false)",
1389 case opc_getstatic: {
1390 int indx = readUShortArg(byteCodes, i);
1391 String[] fi = jc.getFieldInfoName(indx);
1392 final int type = VarType.fromFieldType(fi[2].charAt(0));
1393 String ac = accessClass(mangleClassName(fi[0]));
1394 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1395 smapper.assign(this, type, af + "()");
1397 addReference(fi[0]);
1400 case opc_putstatic: {
1401 int indx = readUShortArg(byteCodes, i);
1402 String[] fi = jc.getFieldInfoName(indx);
1403 final int type = VarType.fromFieldType(fi[2].charAt(0));
1404 emit(smapper, this, "@1(false)._@2(@3);",
1405 accessClass(mangleClassName(fi[0])), fi[1],
1406 smapper.popT(type));
1408 addReference(fi[0]);
1411 case opc_checkcast: {
1412 int indx = readUShortArg(byteCodes, i);
1413 generateCheckcast(indx, smapper);
1417 case opc_instanceof: {
1418 int indx = readUShortArg(byteCodes, i);
1419 generateInstanceOf(indx, smapper);
1424 final CharSequence v = smapper.popA();
1427 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1428 smapper.pushA(), v);
1432 case opc_monitorenter: {
1433 debug("/* monitor enter */");
1438 case opc_monitorexit: {
1439 debug("/* monitor exit */");
1450 emit(smapper, this, "throw 'unknown bytecode @1';",
1451 Integer.toString(c));
1455 generateByteCodeComment(prev, i, byteCodes);
1461 if (previousTrap != null) {
1462 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1467 while (openBraces-- > 0) {
1477 private int generateIf(StackMapper mapper, byte[] byteCodes,
1478 int i, final CharSequence v2, final CharSequence v1,
1479 final String test, int topMostLabel
1480 ) throws IOException {
1482 int indx = i + readShortArg(byteCodes, i);
1483 append("if ((").append(v1)
1484 .append(") ").append(test).append(" (")
1485 .append(v2).append(")) ");
1486 goTo(this, i, indx, topMostLabel);
1490 private int readInt4(byte[] byteCodes, int offset) {
1491 final int d = byteCodes[offset + 0] << 24;
1492 final int c = byteCodes[offset + 1] << 16;
1493 final int b = byteCodes[offset + 2] << 8;
1494 final int a = byteCodes[offset + 3];
1495 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1497 private static int readUByte(byte[] byteCodes, int offset) {
1498 return byteCodes[offset] & 0xff;
1501 private static int readUShort(byte[] byteCodes, int offset) {
1502 return ((byteCodes[offset] & 0xff) << 8)
1503 | (byteCodes[offset + 1] & 0xff);
1505 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1506 return readUShort(byteCodes, offsetInstruction + 1);
1509 private static int readShort(byte[] byteCodes, int offset) {
1510 int signed = byteCodes[offset];
1511 byte b0 = (byte)signed;
1512 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1514 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1515 return readShort(byteCodes, offsetInstruction + 1);
1518 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1520 Boolean count = null;
1521 boolean array = false;
1523 int firstPos = sig.length();
1524 while (i < descriptor.length()) {
1525 char ch = descriptor.charAt(i++);
1546 if (ch == 'J' || ch == 'D') {
1552 sig.insert(firstPos, ch);
1554 returnType[0] = '[';
1555 sig.insert(firstPos, "_3");
1564 returnType[0] = 'V';
1565 sig.insert(firstPos, 'V');
1568 int next = descriptor.indexOf(';', i);
1569 String realSig = mangleSig(descriptor, i - 1, next + 1);
1574 sig.append(realSig);
1577 sig.insert(firstPos, realSig);
1579 sig.insert(firstPos, "_3");
1581 returnType[0] = 'L';
1590 throw new IllegalStateException("Invalid char: " + ch);
1595 static String mangleSig(String sig) {
1596 return mangleSig(sig, 0, sig.length());
1599 private static String mangleMethodName(String name) {
1600 StringBuilder sb = new StringBuilder(name.length() * 2);
1601 int last = name.length();
1602 for (int i = 0; i < last; i++) {
1603 final char ch = name.charAt(i);
1605 case '_': sb.append("_1"); break;
1606 default: sb.append(ch); break;
1609 return sb.toString();
1611 private static String mangleSig(String txt, int first, int last) {
1612 StringBuilder sb = new StringBuilder((last - first) * 2);
1613 for (int i = first; i < last; i++) {
1614 final char ch = txt.charAt(i);
1616 case '/': sb.append('_'); break;
1617 case '_': sb.append("_1"); break;
1618 case ';': sb.append("_2"); break;
1619 case '[': sb.append("_3"); break;
1621 if (Character.isJavaIdentifierPart(ch)) {
1625 String hex = Integer.toHexString(ch).toLowerCase();
1626 for (int m = hex.length(); m < 4; m++) {
1634 return sb.toString();
1637 private static String mangleClassName(String name) {
1638 return mangleSig(name);
1641 private static String findMethodName(MethodData m, StringBuilder cnt) {
1642 StringBuilder name = new StringBuilder();
1643 if ("<init>".equals(m.getName())) { // NOI18N
1644 name.append("cons"); // NOI18N
1645 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1646 name.append("class"); // NOI18N
1648 name.append(mangleMethodName(m.getName()));
1651 countArgs(m.getInternalSig(), new char[1], name, cnt);
1652 return name.toString();
1655 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1656 StringBuilder name = new StringBuilder();
1657 String descr = mi[2];//mi.getDescriptor();
1659 if ("<init>".equals(nm)) { // NOI18N
1660 name.append("cons"); // NOI18N
1662 name.append(mangleMethodName(nm));
1664 countArgs(descr, returnType, name, cnt);
1665 return name.toString();
1668 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1669 throws IOException {
1670 int methodIndex = readUShortArg(byteCodes, i);
1671 String[] mi = jc.getFieldInfoName(methodIndex);
1672 char[] returnType = { 'V' };
1673 StringBuilder cnt = new StringBuilder();
1674 String mn = findMethodName(mi, cnt, returnType);
1676 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1677 final CharSequence[] vars = new CharSequence[numArguments];
1679 for (int j = numArguments - 1; j >= 0; --j) {
1680 vars[j] = mapper.popValue();
1683 if (returnType[0] != 'V') {
1686 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1690 final String in = mi[0];
1693 in.equals("org/apidesign/html/boot/spi/Fn") ||
1694 in.equals("org/netbeans/html/boot/spi/Fn")
1696 mcn = "java_lang_Class";
1698 mcn = mangleClassName(in);
1700 String object = accessClass(mcn) + "(false)";
1701 if (mn.startsWith("cons_")) {
1702 object += ".constructor";
1704 append(accessStaticMethod(object, mn, mi));
1710 if (numArguments > 0) {
1712 for (int j = 1; j < numArguments; ++j) {
1722 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1723 throws IOException {
1724 int methodIndex = readUShortArg(byteCodes, i);
1725 String[] mi = jc.getFieldInfoName(methodIndex);
1726 char[] returnType = { 'V' };
1727 StringBuilder cnt = new StringBuilder();
1728 String mn = findMethodName(mi, cnt, returnType);
1730 final int numArguments = cnt.length() + 1;
1731 final CharSequence[] vars = new CharSequence[numArguments];
1733 for (int j = numArguments - 1; j >= 0; --j) {
1734 vars[j] = mapper.popValue();
1737 if (returnType[0] != 'V') {
1739 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1743 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1745 for (int j = 1; j < numArguments; ++j) {
1755 private void addReference(String cn) throws IOException {
1756 if (requireReference(cn)) {
1757 debug(" /* needs " + cn + " */");
1761 private void outType(String d, StringBuilder out) {
1763 while (d.charAt(0) == '[') {
1767 if (d.charAt(0) == 'L') {
1768 assert d.charAt(d.length() - 1) == ';';
1769 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1775 private String encodeConstant(int entryIndex) throws IOException {
1776 String[] classRef = { null };
1777 String s = jc.stringValue(entryIndex, classRef);
1778 if (classRef[0] != null) {
1779 if (classRef[0].startsWith("[")) {
1780 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1782 addReference(classRef[0]);
1783 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1789 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1790 byte[] arr = m.findAnnotationData(true);
1794 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1795 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1796 class P extends AnnotationParser {
1802 String[] args = new String[30];
1808 protected void visitAttr(String type, String attr, String at, String value) {
1809 if (type.equals(jvmType)) {
1810 if ("body".equals(attr)) {
1812 } else if ("args".equals(attr)) {
1813 args[cnt++] = value;
1815 throw new IllegalArgumentException(attr);
1818 if (type.equals(htmlType)) {
1820 if ("body".equals(attr)) {
1822 } else if ("args".equals(attr)) {
1823 args[cnt++] = value;
1824 } else if ("javacall".equals(attr)) {
1825 javacall = "1".equals(value);
1826 } else if ("wait4js".equals(attr)) {
1827 // ignore, we always invoke synchronously
1829 throw new IllegalArgumentException(attr);
1836 if (p.body == null) {
1839 StringBuilder cnt = new StringBuilder();
1840 final String mn = findMethodName(m, cnt);
1841 append("m = ").append(destObject).append(".").append(mn);
1842 append(" = function(");
1845 StringBuilder toValue = new StringBuilder();
1846 for (int i = 0; i < cnt.length(); i++) {
1848 space = outputArg(this, p.args, index);
1849 if (p.html4j && space.length() > 0) {
1850 toValue.append("\n ").append(p.args[index]).append(" = ")
1851 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1852 append(p.args[index]).append(");");
1856 append(") {").append("\n");
1857 append(toValue.toString());
1859 int lastSlash = jc.getClassName().lastIndexOf('/');
1860 final String pkg = jc.getClassName().substring(0, lastSlash);
1861 append(mangleCallbacks(pkg, p.body));
1862 requireReference(pkg + "/$JsCallbacks$");
1870 private static CharSequence mangleCallbacks(String pkgName, String body) {
1871 StringBuilder sb = new StringBuilder();
1874 int next = body.indexOf(".@", pos);
1876 sb.append(body.substring(pos));
1877 body = sb.toString();
1882 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1887 String refId = body.substring(ident, next);
1889 sb.append(body.substring(pos, ident));
1891 int sigBeg = body.indexOf('(', next);
1892 int sigEnd = body.indexOf(')', sigBeg);
1893 int colon4 = body.indexOf("::", next);
1894 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1895 throw new IllegalStateException("Malformed body " + body);
1897 String fqn = body.substring(next + 2, colon4);
1898 String method = body.substring(colon4 + 2, sigBeg);
1899 String params = body.substring(sigBeg, sigEnd + 1);
1901 int paramBeg = body.indexOf('(', sigEnd + 1);
1903 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1904 sb.append(mangleJsCallbacks(fqn, method, params, false));
1905 sb.append("(").append(refId);
1906 if (body.charAt(paramBeg + 1) != ')') {
1914 int next = body.indexOf("@", pos);
1919 sb.append(body.substring(pos));
1923 sb = new StringBuilder();
1926 sb.append(body.substring(pos, next));
1928 int sigBeg = body.indexOf('(', next);
1929 int sigEnd = body.indexOf(')', sigBeg);
1930 int colon4 = body.indexOf("::", next);
1931 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1932 throw new IllegalStateException("Malformed body " + body);
1934 String fqn = body.substring(next + 1, colon4);
1935 String method = body.substring(colon4 + 2, sigBeg);
1936 String params = body.substring(sigBeg, sigEnd + 1);
1938 int paramBeg = body.indexOf('(', sigEnd + 1);
1940 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1941 sb.append(mangleJsCallbacks(fqn, method, params, true));
1947 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1948 if (params.startsWith("(")) {
1949 params = params.substring(1);
1951 if (params.endsWith(")")) {
1952 params = params.substring(0, params.length() - 1);
1954 StringBuilder sb = new StringBuilder();
1955 final String fqnu = fqn.replace('.', '_');
1956 final String rfqn = mangleClassName(fqnu);
1957 final String rm = mangleMethodName(method);
1960 StringBuilder pb = new StringBuilder();
1961 int len = params.length();
1963 while (indx < len) {
1964 char ch = params.charAt(indx);
1965 if (ch == '[' || ch == 'L') {
1966 pb.append("Ljava/lang/Object;");
1967 indx = params.indexOf(';', indx) + 1;
1973 srp = mangleSig(pb.toString());
1975 final String rp = mangleSig(params);
1976 final String mrp = mangleMethodName(rp);
1977 sb.append(rfqn).append("$").append(rm).
1978 append('$').append(mrp).append("__Ljava_lang_Object_2");
1980 sb.append('L').append(fqnu).append("_2");
1983 return sb.toString();
1986 private static String className(ClassData jc) {
1987 //return jc.getName().getInternalName().replace('/', '_');
1988 return mangleClassName(jc.getClassName());
1991 private static String[] findAnnotation(
1992 byte[] arr, ClassData cd, final String className,
1993 final String... attrNames
1994 ) throws IOException {
1998 final String[] values = new String[attrNames.length];
1999 final boolean[] found = { false };
2000 final String jvmType = "L" + className.replace('.', '/') + ";";
2001 AnnotationParser ap = new AnnotationParser(false, true) {
2003 protected void visitAttr(String type, String attr, String at, String value) {
2004 if (type.equals(jvmType)) {
2006 for (int i = 0; i < attrNames.length; i++) {
2007 if (attrNames[i].equals(attr)) {
2016 return found[0] ? values : null;
2019 private CharSequence initField(FieldData v) {
2020 final String is = v.getInternalSig();
2021 if (is.length() == 1) {
2022 switch (is.charAt(0)) {
2028 case 'I': return " = 0;";
2030 case 'D': return " = 0.0;";
2032 throw new IllegalStateException(is);
2038 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2039 AnnotationParser ap = new AnnotationParser(true, false) {
2040 int[] cnt = new int[32];
2044 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2045 final String slashType = attrType.substring(1, attrType.length() - 1);
2046 requireReference(slashType);
2048 if (cnt[depth]++ > 0) {
2052 append('"').append(attrType).append("\" : ");
2059 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2065 protected void visitValueStart(String attrName, char type) throws IOException {
2066 if (cnt[depth]++ > 0) {
2070 if (attrName != null) {
2071 append('"').append(attrName).append("\" : ");
2079 protected void visitValueEnd(String attrName, char type) throws IOException {
2087 protected void visitAttr(String type, String attr, String attrType, String value)
2088 throws IOException {
2089 if (attr == null && value == null) {
2096 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2097 throws IOException {
2098 final String slashType = attrType.substring(1, attrType.length() - 1);
2099 requireReference(slashType);
2101 final String cn = mangleClassName(slashType);
2102 append(accessClass(cn))
2103 .append("(false)['valueOf__L").
2105 append("_2Ljava_lang_String_2']('").
2113 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2114 final String name = args[indx];
2118 if (name.contains(",")) {
2119 throw new IOException("Wrong parameter with ',': " + name);
2125 final void emitNoFlush(
2127 final String format, final CharSequence... params
2128 ) throws IOException {
2129 emitImpl(this, format, params);
2131 static final void emit(
2133 final Appendable out,
2134 final String format, final CharSequence... params
2135 ) throws IOException {
2137 emitImpl(out, format, params);
2139 static void emitImpl(final Appendable out,
2140 final String format,
2141 final CharSequence... params) throws IOException {
2142 final int length = format.length();
2145 int paramOffset = format.indexOf('@');
2146 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2147 final char paramChar = format.charAt(paramOffset + 1);
2148 if ((paramChar >= '1') && (paramChar <= '9')) {
2149 final int paramIndex = paramChar - '0' - 1;
2151 out.append(format, processed, paramOffset);
2152 out.append(params[paramIndex]);
2155 processed = paramOffset + 1;
2158 paramOffset = format.indexOf('@', paramOffset + 1);
2161 out.append(format, processed, length);
2164 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2165 append("} catch (e) {\n");
2167 for (TrapData e : traps) {
2171 if (e.catch_cpx != 0) { //not finally
2172 final String classInternalName = jc.getClassName(e.catch_cpx);
2173 addReference(classInternalName);
2174 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2175 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2176 append("var stA0 = e;");
2177 goTo(this, current, e.handler_pc, topMostLabel);
2180 finallyPC = e.handler_pc;
2183 if (finallyPC == -1) {
2186 append("var stA0 = e;");
2187 goTo(this, current, finallyPC, topMostLabel);
2192 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2195 out.append("{ gt = 0; continue X_" + to + "; }");
2197 out.append("{ gt = " + to + "; continue X_0; }");
2200 out.append("{ gt = " + to + "; break IF; }");
2204 private static void emitIf(
2206 Appendable out, String pattern,
2208 int current, int to, int canBack
2209 ) throws IOException {
2211 emitImpl(out, pattern, param);
2212 goTo(out, current, to, canBack);
2215 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2218 case 4: jvmType = "[Z"; break;
2219 case 5: jvmType = "[C"; break;
2220 case 6: jvmType = "[F"; break;
2221 case 7: jvmType = "[D"; break;
2222 case 8: jvmType = "[B"; break;
2223 case 9: jvmType = "[S"; break;
2224 case 10: jvmType = "[I"; break;
2225 case 11: jvmType = "[J"; break;
2226 default: throw new IllegalStateException("Array type: " + atype);
2229 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2230 smapper.popI(), smapper.pushA(), jvmType);
2233 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2234 String typeName = jc.getClassName(type);
2235 String ref = "null";
2236 if (typeName.startsWith("[")) {
2237 typeName = "'[" + typeName + "'";
2239 ref = "vm." + mangleClassName(typeName);
2240 typeName = "'[L" + typeName + ";'";
2243 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2244 smapper.popI(), smapper.pushA(), typeName, ref);
2247 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2248 String typeName = jc.getClassName(type);
2249 int dim = readUByte(byteCodes, ++i);
2250 StringBuilder dims = new StringBuilder();
2252 for (int d = 0; d < dim; d++) {
2254 dims.insert(1, ",");
2256 dims.insert(1, smapper.popI());
2260 if (typeName.charAt(dim) == 'L') {
2261 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2264 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2265 dims.toString(), smapper.pushA(), typeName, fn
2270 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2271 int table = i / 4 * 4 + 4;
2272 int dflt = i + readInt4(byteCodes, table);
2274 int low = readInt4(byteCodes, table);
2276 int high = readInt4(byteCodes, table);
2278 final CharSequence swVar = smapper.popValue();
2279 smapper.flush(this);
2280 append("switch (").append(swVar).append(") {\n");
2281 while (low <= high) {
2282 int offset = i + readInt4(byteCodes, table);
2284 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2287 append(" default: ");
2288 goTo(this, i, dflt, topMostLabel);
2294 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2295 int table = i / 4 * 4 + 4;
2296 int dflt = i + readInt4(byteCodes, table);
2298 int n = readInt4(byteCodes, table);
2300 final CharSequence swVar = smapper.popValue();
2301 smapper.flush(this);
2302 append("switch (").append(swVar).append(") {\n");
2304 int cnstnt = readInt4(byteCodes, table);
2306 int offset = i + readInt4(byteCodes, table);
2308 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2310 append(" default: ");
2311 goTo(this, i, dflt, topMostLabel);
2317 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2318 String type = jc.getClassName(indx);
2319 if (!type.startsWith("[")) {
2321 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2322 smapper.popA(), smapper.pushI(),
2323 type.replace('/', '_'));
2326 while (type.charAt(cnt) == '[') {
2329 if (type.charAt(cnt) == 'L') {
2330 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2332 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2333 smapper.popA(), smapper.pushI(),
2338 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2339 smapper.popA(), smapper.pushI(), type
2345 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2346 String type = jc.getClassName(indx);
2347 if (!type.startsWith("[")) {
2348 emitNoFlush(smapper,
2349 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2350 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2353 while (type.charAt(cnt) == '[') {
2356 if (type.charAt(cnt) == 'L') {
2357 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2358 emitNoFlush(smapper,
2359 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2360 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2363 emitNoFlush(smapper,
2364 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2365 smapper.getT(0, VarType.REFERENCE, false), type
2371 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2372 for (int j = prev; j <= i; j++) {
2374 final int cc = readUByte(byteCodes, j);
2375 append(Integer.toString(cc));
2379 @JavaScriptBody(args = "msg", body = "")
2380 private static void println(String msg) {
2381 System.err.println(msg);