2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 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 final StringArray classRefs = new StringArray();
33 private boolean outChanged;
34 private boolean callbacks;
36 protected ByteCodeToJavaScript(Appendable out) {
41 public final Appendable append(CharSequence csq) throws IOException {
48 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
49 out.append(csq, start, end);
55 public final Appendable append(char c) throws IOException {
61 /* Collects additional required resources.
63 * @param internalClassName classes that were referenced and should be loaded in order the
64 * generated JavaScript code works properly. The names are in internal
65 * JVM form so String is <code>java/lang/String</code>.
67 protected abstract boolean requireReference(String internalClassName);
70 * @param resourcePath name of resources to read
72 protected abstract void requireScript(String resourcePath) throws IOException;
74 protected abstract void requireResource(String resourcePath) throws IOException;
76 /** Allows subclasses to redefine what field a function representing a
77 * class gets assigned. By default it returns the suggested name followed
78 * by <code>" = "</code>;
80 * @param className suggested name of the class
82 /* protected */ String assignClass(String className) {
83 return className + " = ";
85 /* protected */ String accessClass(String classOperation) {
86 return classOperation;
89 final String accessClassFalse(String classOperation) {
90 if (jc.getClassName().replace('/', '_').equals(classOperation)) {
93 classRefs.addIfMissing(classOperation);
94 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
97 protected String accessField(String object, String mangledName,
98 String[] fieldInfoName) throws IOException {
99 return object + "." + mangledName;
102 protected String accessStaticMethod(
105 String[] fieldInfoName) throws IOException {
106 return object + "." + mangledName;
109 protected String accessVirtualMethod(
112 String[] fieldInfoName,
114 ) throws IOException {
115 return object + "." + mangledName + '(';
118 protected void declaredClass(ClassData classData, String mangledName)
122 protected void declaredField(FieldData fieldData,
124 String mangledName) throws IOException {
127 protected void declaredMethod(MethodData methodData,
129 String mangledName) throws IOException {
132 /** Prints out a debug message.
134 * @param msg the message
135 * @return true if the message has been printed
136 * @throws IOException
138 boolean debug(String msg) throws IOException {
144 * Converts a given class file to a JavaScript version.
146 * @param classFile input stream with code of the .class file
147 * @return the initialization code for this class, if any. Otherwise <code>null</code>
149 * @throws IOException if something goes wrong during read or write or translating
152 public String compile(InputStream classFile) throws IOException {
153 return compile(new ClassData(classFile));
156 protected String compile(ClassData classData) throws IOException {
158 final String cn = this.jc.getClassName();
159 this.callbacks = cn.endsWith("/$JsCallbacks$");
160 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
161 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
162 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
165 byte[] arrData = jc.findAnnotationData(true);
167 String[] arr = findAnnotation(arrData, jc,
168 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
169 "resource", "processByteCode"
172 if (!arr[0].isEmpty()) {
173 requireScript(arr[0]);
175 if ("0".equals(arr[1])) {
180 final String jsResource;
182 String[] arr = findAnnotation(arrData, jc,
183 "net.java.html.js.JavaScriptResource",
187 if (arr[0].startsWith("/")) {
190 int last = cn.lastIndexOf('/');
191 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
197 String[] proto = findAnnotation(arrData, jc,
198 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
199 "container", "prototype"
201 StringArray toInitilize = new StringArray();
202 final String className = className(jc);
203 append("\n\n").append(assignClass(className));
204 append("function ").append(className).append("() {");
206 append("\n var CLS = ").append(className).append(';');
207 append("\n if (!CLS.$class) {");
209 String sc = jc.getSuperClassName(); // with _
210 append("\n var pp = ").
211 append(accessClass(mangleClassName(sc))).append("(true);");
212 append("\n var p = CLS.prototype = pp;");
213 append("\n var c = p;");
214 append("\n var sprcls = pp.constructor.$class;");
216 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
217 if (proto[0] == null) {
220 append("\n var c = ").append(proto[0]).append(";");
221 append("\n var sprcls = null;");
223 for (FieldData v : jc.getFields()) {
225 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
226 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
230 append("\n CLS.fld_").append(v.getName()).append(initField(v));
231 append("\n m = c._").append(v.getName()).append(" = function (v) {")
232 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
233 .append(" = v; return CLS.fld_").
234 append(v.getName()).append("; };");
236 append("\n m = c._").append(v.getName()).append(" = function (v) {")
237 .append(" if (arguments.length == 1) this.fld_").
238 append(className).append('_').append(v.getName())
239 .append(" = v; return this.fld_").
240 append(className).append('_').append(v.getName())
244 declaredField(v, "c", "_" + v.getName());
246 for (MethodData m : jc.getMethods()) {
247 byte[] onlyArr = m.findAnnotationData(true);
248 if (javaScriptOnly(onlyArr)) continue;
254 mn = generateStaticMethod(destObject, m, toInitilize);
256 if (m.isConstructor()) {
258 mn = generateInstanceMethod(destObject, m);
261 mn = generateInstanceMethod(destObject, m);
264 declaredMethod(m, destObject, mn);
265 byte[] runAnno = m.findAnnotationData(false);
266 if (runAnno != null) {
267 append("\n m.anno = {");
268 generateAnno(jc, runAnno);
271 append("\n m.access = " + m.getAccess()).append(";");
272 append("\n m.cls = CLS;");
274 append("\n c.constructor = CLS;");
275 append("\n function ").append(className).append("fillInstOf(x) {");
276 String instOfName = "$instOf_" + className;
277 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
278 if (jc.isInterface()) {
279 for (MethodData m : jc.getMethods()) {
280 if ((m.getAccess() & ACC_ABSTRACT) == 0
281 && (m.getAccess() & ACC_STATIC) == 0
282 && (m.getAccess() & ACC_PRIVATE) == 0) {
283 final String mn = findMethodName(m, new StringBuilder());
284 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
288 for (String superInterface : jc.getSuperInterfaces()) {
289 String intrfc = superInterface.replace('/', '_');
290 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
291 requireReference(superInterface);
294 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
295 append("\n ").append(className).append("fillInstOf(c);");
296 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
297 append("\n CLS.$class = 'temp';");
298 append("\n CLS.$class = ");
299 append(accessClass("java_lang_Class(true);"));
300 append("\n CLS.$class.jvmName = '").append(cn).append("';");
301 append("\n CLS.$class.superclass = sprcls;");
302 append("\n CLS.$class.interfaces = function() { return [");
304 boolean first = true;
305 for (String intrfc : jc.getSuperInterfaces()) {
309 requireReference(intrfc);
310 String mangledIface = mangleClassName(intrfc);
312 append(accessClass(mangledIface)).append("(false).constructor.$class");
317 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
318 append("\n CLS.$class.cnstr = CLS;");
319 byte[] classAnno = jc.findAnnotationData(false);
320 if (classAnno != null) {
321 append("\n CLS.$class.anno = {");
322 generateAnno(jc, classAnno);
325 for (String init : toInitilize.toArray()) {
326 append("\n ").append(init).append("();");
328 for (String ref : classRefs.toArray()) {
329 append("\n var refs_").append(ref).append(";");
333 if (jsResource != null) {
334 requireResource(jsResource);
338 append("\n if (arguments.length === 0) {");
339 append("\n if (!(this instanceof CLS)) {");
340 append("\n return new CLS();");
342 for (FieldData v : jc.getFields()) {
343 byte[] onlyArr = v.findAnnotationData(true);
344 if (javaScriptOnly(onlyArr)) continue;
346 append("\n this.fld_").
347 append(className).append('_').
348 append(v.getName()).append(initField(v));
351 append("\n return this;");
353 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
356 declaredClass(jc, className);
358 // StringBuilder sb = new StringBuilder();
359 // for (String init : toInitilize.toArray()) {
360 // sb.append("\n").append(init).append("();");
365 private boolean javaScriptOnly(byte[] anno) throws IOException {
366 String[] only = findAnnotation(anno, jc,
367 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
371 if (only[0] != null && only[1] != null) {
372 append("\n p.").append(only[0]).append(" = ")
373 .append(only[1]).append(";");
375 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
376 append("\n p['").append(only[0]).append("'] = p.")
377 .append(only[0]).append(";");
383 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
384 String jsb = javaScriptBody(destObject, m, true);
388 final String mn = findMethodName(m, new StringBuilder());
389 boolean defineProp = generateMethod(destObject, mn, m);
390 if (mn.equals("class__V")) {
392 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
394 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
400 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
401 String jsb = javaScriptBody(destObject, m, false);
405 final String mn = findMethodName(m, new StringBuilder());
406 generateMethod(destObject, mn, m);
410 private boolean generateMethod(String destObject, String name, MethodData m)
412 final StackMapIterator stackMapIterator = m.createStackMapIterator();
413 TrapDataIterator trap = m.getTrapDataIterator();
414 final LocalsMapper lmapper =
415 new LocalsMapper(stackMapIterator.getArguments());
418 "java/lang/Object".equals(jc.getClassName()) ||
419 "java/lang/reflect/Array".equals(jc.getClassName());
422 append("Object.defineProperty(").append(destObject).
423 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
425 append("m = ").append(destObject).append(".").append(name).append(" = function(");
427 lmapper.outputArguments(this, m.isStatic());
428 append(") {").append("\n");
430 final byte[] byteCodes = m.getCode();
431 if (byteCodes == null) {
432 append(" throw 'no code found for ")
433 .append(jc.getClassName()).append('.')
434 .append(m.getName()).append("';\n");
443 final StackMapper smapper = new StackMapper();
446 append(" var ").append(" lcA0 = this;\n");
450 TrapData[] previousTrap = null;
451 boolean wide = false;
453 if (stackMapIterator.isEmpty()) {
459 append("\n var gt = 0;\n");
463 int topMostLabel = 0;
464 for (int i = 0; i < byteCodes.length; i++) {
467 stackMapIterator.advanceTo(i);
468 boolean changeInCatch = trap.advanceTo(i);
469 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
470 if (previousTrap != null) {
471 generateCatch(previousTrap, i, topMostLabel);
475 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
480 if (openBraces > 64) {
481 for (int c = 0; c < 64; c++) {
488 lastStackFrame = stackMapIterator.getFrameIndex();
489 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
490 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
491 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
493 changeInCatch = true;
495 debug(" /* " + i + " */ ");
497 if (changeInCatch && trap.useTry()) {
499 previousTrap = trap.current();
501 final int c = readUByte(byteCodes, i);
504 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
507 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
510 smapper.assign(this, VarType.LONG, lmapper.getL(0));
513 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
516 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
519 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
522 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
525 smapper.assign(this, VarType.LONG, lmapper.getL(1));
528 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
531 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
534 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
537 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
540 smapper.assign(this, VarType.LONG, lmapper.getL(2));
543 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
546 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
549 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
552 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
555 smapper.assign(this, VarType.LONG, lmapper.getL(3));
558 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
561 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
565 final int indx = wide ? readUShort(byteCodes, i++)
566 : readUByte(byteCodes, i);
568 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
573 final int indx = wide ? readUShort(byteCodes, i++)
574 : readUByte(byteCodes, i);
576 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
581 final int indx = wide ? readUShort(byteCodes, i++)
582 : readUByte(byteCodes, i);
584 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
589 final int indx = wide ? readUShort(byteCodes, i++)
590 : readUByte(byteCodes, i);
592 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
597 final int indx = wide ? readUShort(byteCodes, i++)
598 : readUByte(byteCodes, i);
600 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
605 final int indx = wide ? readUShort(byteCodes, i++)
606 : readUByte(byteCodes, i);
608 emit(smapper, this, "var @1 = @2;",
609 lmapper.setI(indx), smapper.popI());
614 final int indx = wide ? readUShort(byteCodes, i++)
615 : readUByte(byteCodes, i);
617 emit(smapper, this, "var @1 = @2;",
618 lmapper.setL(indx), smapper.popL());
623 final int indx = wide ? readUShort(byteCodes, i++)
624 : readUByte(byteCodes, i);
626 emit(smapper, this, "var @1 = @2;",
627 lmapper.setF(indx), smapper.popF());
632 final int indx = wide ? readUShort(byteCodes, i++)
633 : readUByte(byteCodes, i);
635 emit(smapper, this, "var @1 = @2;",
636 lmapper.setD(indx), smapper.popD());
641 final int indx = wide ? readUShort(byteCodes, i++)
642 : readUByte(byteCodes, i);
644 emit(smapper, this, "var @1 = @2;",
645 lmapper.setA(indx), smapper.popA());
649 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
652 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
655 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
658 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
661 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
664 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
667 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
670 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
673 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
676 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
679 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
682 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
685 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
688 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
691 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
694 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
697 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
700 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
703 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
706 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
709 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
712 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
715 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
718 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
721 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
724 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
727 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
730 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
733 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
736 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
739 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
742 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
745 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
746 smapper.getI(1), smapper.popI());
749 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
750 smapper.getL(1), smapper.popL());
753 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
756 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
759 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
760 smapper.getI(1), smapper.popI());
763 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
764 smapper.getL(1), smapper.popL());
767 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
770 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
773 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
776 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
779 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
782 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
785 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
788 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
791 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
794 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
797 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
800 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
803 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
806 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
809 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
812 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
815 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
818 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
822 final int varIndx = wide ? readUShort(byteCodes, i++)
823 : readUByte(byteCodes, i);
825 final int incrBy = wide ? readShort(byteCodes, i++)
829 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
831 emit(smapper, this, "@1 += @2;",
832 lmapper.getI(varIndx),
833 Integer.toString(incrBy));
838 emit(smapper, this, "return;");
841 emit(smapper, this, "return @1;", smapper.popI());
844 emit(smapper, this, "return @1;", smapper.popL());
847 emit(smapper, this, "return @1;", smapper.popF());
850 emit(smapper, this, "return @1;", smapper.popD());
853 emit(smapper, this, "return @1;", smapper.popA());
856 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
859 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
862 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
865 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
869 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
872 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
875 smapper.replace(this, VarType.DOUBLE, "@1",
879 smapper.replace(this, VarType.FLOAT, "@1",
883 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
887 smapper.replace(this, VarType.LONG, "(@1).toLong()",
891 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
895 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
898 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
902 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
904 case opc_aconst_null:
905 smapper.assign(this, VarType.REFERENCE, "null");
908 smapper.assign(this, VarType.INTEGER, "-1");
911 smapper.assign(this, VarType.INTEGER, "0");
914 smapper.assign(this, VarType.DOUBLE, "0");
917 smapper.assign(this, VarType.LONG, "0");
920 smapper.assign(this, VarType.FLOAT, "0");
923 smapper.assign(this, VarType.INTEGER, "1");
926 smapper.assign(this, VarType.LONG, "1");
929 smapper.assign(this, VarType.FLOAT, "1");
932 smapper.assign(this, VarType.DOUBLE, "1");
935 smapper.assign(this, VarType.INTEGER, "2");
938 smapper.assign(this, VarType.FLOAT, "2");
941 smapper.assign(this, VarType.INTEGER, "3");
944 smapper.assign(this, VarType.INTEGER, "4");
947 smapper.assign(this, VarType.INTEGER, "5");
950 int indx = readUByte(byteCodes, ++i);
951 String v = encodeConstant(indx);
952 int type = VarType.fromConstantType(jc.getTag(indx));
953 smapper.assign(this, type, v);
958 int indx = readUShortArg(byteCodes, i);
960 String v = encodeConstant(indx);
961 int type = VarType.fromConstantType(jc.getTag(indx));
962 if (type == VarType.LONG) {
963 final Long lv = new Long(v);
964 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
965 final int hi = (int)(lv.longValue() >> 32);
967 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
969 smapper.assign(this, VarType.LONG,
970 "0x" + Integer.toHexString(hi) + ".next32(0x" +
971 Integer.toHexString(low) + ")"
975 smapper.assign(this, type, v);
980 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
984 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
985 smapper.popF(), smapper.popF(), smapper.pushI());
989 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
990 smapper.popD(), smapper.popD(), smapper.pushI());
993 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
994 "===", topMostLabel);
997 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
998 "!==", topMostLabel);
1001 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1002 "==", topMostLabel);
1005 int indx = i + readShortArg(byteCodes, i);
1006 emitIf(smapper, this, "if ((@1) == 0) ",
1007 smapper.popI(), i, indx, topMostLabel);
1012 int indx = i + readShortArg(byteCodes, i);
1013 emitIf(smapper, this, "if ((@1) != 0) ",
1014 smapper.popI(), i, indx, topMostLabel);
1019 int indx = i + readShortArg(byteCodes, i);
1020 emitIf(smapper, this, "if ((@1) < 0) ",
1021 smapper.popI(), i, indx, topMostLabel);
1026 int indx = i + readShortArg(byteCodes, i);
1027 emitIf(smapper, this, "if ((@1) <= 0) ",
1028 smapper.popI(), i, indx, topMostLabel);
1033 int indx = i + readShortArg(byteCodes, i);
1034 emitIf(smapper, this, "if ((@1) > 0) ",
1035 smapper.popI(), i, indx, topMostLabel);
1040 int indx = i + readShortArg(byteCodes, i);
1041 emitIf(smapper, this, "if ((@1) >= 0) ",
1042 smapper.popI(), i, indx, topMostLabel);
1046 case opc_ifnonnull: {
1047 int indx = i + readShortArg(byteCodes, i);
1048 emitIf(smapper, this, "if ((@1) !== null) ",
1049 smapper.popA(), i, indx, topMostLabel);
1054 int indx = i + readShortArg(byteCodes, i);
1055 emitIf(smapper, this, "if ((@1) === null) ",
1056 smapper.popA(), i, indx, topMostLabel);
1061 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1062 "!=", topMostLabel);
1065 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1069 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1070 "<=", topMostLabel);
1073 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1077 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1078 ">=", topMostLabel);
1081 smapper.flush(this);
1082 int indx = i + readShortArg(byteCodes, i);
1083 goTo(this, i, indx, topMostLabel);
1087 case opc_lookupswitch: {
1088 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1091 case opc_tableswitch: {
1092 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1095 case opc_invokeinterface: {
1096 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1099 case opc_invokevirtual:
1100 i = invokeVirtualMethod(byteCodes, i, smapper);
1102 case opc_invokespecial:
1103 i = invokeStaticMethod(byteCodes, i, smapper, false);
1105 case opc_invokestatic:
1106 i = invokeStaticMethod(byteCodes, i, smapper, true);
1108 case opc_invokedynamic: {
1109 int indx = readUShortArg(byteCodes, i);
1110 println("invoke dynamic: " + indx);
1111 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1112 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1113 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1114 println(" type: " + methodHandle.cpx1);
1115 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1116 String mcn = mangleClassName(mi[0]);
1117 char[] returnType = {'V'};
1118 StringBuilder cnt = new StringBuilder();
1119 String mn = findMethodName(mi, cnt, returnType);
1120 StringBuilder sb = new StringBuilder();
1121 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1122 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1123 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1124 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1125 sb.append(" mn : ").append(mn).append("\n");
1126 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1127 throw new IOException(sb.toString());
1129 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1130 String type = jc.StringValue(nameAndType.cpx2);
1131 String object = accessClass(mcn) + "(false)";
1132 if (mn.startsWith("cons_")) {
1133 object += ".constructor";
1135 append("var metHan = ");
1136 append(accessStaticMethod(object, mn, mi));
1138 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1140 append(", '").append(mi[1]).append("', ");
1141 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1142 append(methodType).append("'").append(type).append("', null)");
1143 // if (numArguments > 0) {
1145 // for (int j = 1; j < numArguments; ++j) {
1151 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1157 int indx = readUShortArg(byteCodes, i);
1158 String ci = jc.getClassName(indx);
1159 emit(smapper, this, "var @1 = new @2;",
1160 smapper.pushA(), accessClass(mangleClassName(ci)));
1166 int atype = readUByte(byteCodes, ++i);
1167 generateNewArray(atype, smapper);
1169 case opc_anewarray: {
1170 int type = readUShortArg(byteCodes, i);
1172 generateANewArray(type, smapper);
1175 case opc_multianewarray: {
1176 int type = readUShortArg(byteCodes, i);
1178 i = generateMultiANewArray(type, byteCodes, i, smapper);
1181 case opc_arraylength:
1182 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1185 emit(smapper, this, "Array.at(@3, @2, @1);",
1186 smapper.popL(), smapper.popI(), smapper.popA());
1189 emit(smapper, this, "Array.at(@3, @2, @1);",
1190 smapper.popF(), smapper.popI(), smapper.popA());
1193 emit(smapper, this, "Array.at(@3, @2, @1);",
1194 smapper.popD(), smapper.popI(), smapper.popA());
1197 emit(smapper, this, "Array.at(@3, @2, @1);",
1198 smapper.popA(), smapper.popI(), smapper.popA());
1204 emit(smapper, this, "Array.at(@3, @2, @1);",
1205 smapper.popI(), smapper.popI(), smapper.popA());
1208 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1209 smapper.popI(), smapper.getA(0));
1212 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1213 smapper.popI(), smapper.getA(0));
1216 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1217 smapper.popI(), smapper.getA(0));
1220 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1221 smapper.popI(), smapper.getA(0));
1227 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1228 smapper.popI(), smapper.getA(0));
1236 final Variable v = smapper.get(0);
1237 if (smapper.isDirty()) {
1238 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1240 smapper.assign(this, v.getType(), v);
1245 final Variable vi1 = smapper.get(0);
1247 if (vi1.isCategory2()) {
1248 emit(smapper, this, "var @1 = @2;",
1249 smapper.pushT(vi1.getType()), vi1);
1251 final Variable vi2 = smapper.get(1);
1252 emit(smapper, this, "var @1 = @2, @3 = @4;",
1253 smapper.pushT(vi2.getType()), vi2,
1254 smapper.pushT(vi1.getType()), vi1);
1259 final Variable vi1 = smapper.pop(this);
1260 final Variable vi2 = smapper.pop(this);
1261 final Variable vo3 = smapper.pushT(vi1.getType());
1262 final Variable vo2 = smapper.pushT(vi2.getType());
1263 final Variable vo1 = smapper.pushT(vi1.getType());
1265 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1266 vo1, vi1, vo2, vi2, vo3, vo1);
1270 final Variable vi1 = smapper.pop(this);
1271 final Variable vi2 = smapper.pop(this);
1273 if (vi1.isCategory2()) {
1274 final Variable vo3 = smapper.pushT(vi1.getType());
1275 final Variable vo2 = smapper.pushT(vi2.getType());
1276 final Variable vo1 = smapper.pushT(vi1.getType());
1278 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1279 vo1, vi1, vo2, vi2, vo3, vo1);
1281 final Variable vi3 = smapper.pop(this);
1282 final Variable vo5 = smapper.pushT(vi2.getType());
1283 final Variable vo4 = smapper.pushT(vi1.getType());
1284 final Variable vo3 = smapper.pushT(vi3.getType());
1285 final Variable vo2 = smapper.pushT(vi2.getType());
1286 final Variable vo1 = smapper.pushT(vi1.getType());
1288 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1289 vo1, vi1, vo2, vi2, vo3, vi3);
1290 emit(smapper, this, " @1 = @2, @3 = @4;",
1291 vo4, vo1, vo5, vo2);
1296 final Variable vi1 = smapper.pop(this);
1297 final Variable vi2 = smapper.pop(this);
1299 if (vi2.isCategory2()) {
1300 final Variable vo3 = smapper.pushT(vi1.getType());
1301 final Variable vo2 = smapper.pushT(vi2.getType());
1302 final Variable vo1 = smapper.pushT(vi1.getType());
1304 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1305 vo1, vi1, vo2, vi2, vo3, vo1);
1307 final Variable vi3 = smapper.pop(this);
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, @7 = @8;",
1314 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1319 final Variable vi1 = smapper.pop(this);
1320 final Variable vi2 = smapper.pop(this);
1322 if (vi1.isCategory2()) {
1323 if (vi2.isCategory2()) {
1324 final Variable vo3 = smapper.pushT(vi1.getType());
1325 final Variable vo2 = smapper.pushT(vi2.getType());
1326 final Variable vo1 = smapper.pushT(vi1.getType());
1328 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1329 vo1, vi1, vo2, vi2, vo3, vo1);
1331 final Variable vi3 = smapper.pop(this);
1332 final Variable vo4 = smapper.pushT(vi1.getType());
1333 final Variable vo3 = smapper.pushT(vi3.getType());
1334 final Variable vo2 = smapper.pushT(vi2.getType());
1335 final Variable vo1 = smapper.pushT(vi1.getType());
1337 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1338 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1341 final Variable vi3 = smapper.pop(this);
1343 if (vi3.isCategory2()) {
1344 final Variable vo5 = smapper.pushT(vi2.getType());
1345 final Variable vo4 = smapper.pushT(vi1.getType());
1346 final Variable vo3 = smapper.pushT(vi3.getType());
1347 final Variable vo2 = smapper.pushT(vi2.getType());
1348 final Variable vo1 = smapper.pushT(vi1.getType());
1350 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1351 vo1, vi1, vo2, vi2, vo3, vi3);
1352 emit(smapper, this, " @1 = @2, @3 = @4;",
1353 vo4, vo1, vo5, vo2);
1355 final Variable vi4 = smapper.pop(this);
1356 final Variable vo6 = smapper.pushT(vi2.getType());
1357 final Variable vo5 = smapper.pushT(vi1.getType());
1358 final Variable vo4 = smapper.pushT(vi4.getType());
1359 final Variable vo3 = smapper.pushT(vi3.getType());
1360 final Variable vo2 = smapper.pushT(vi2.getType());
1361 final Variable vo1 = smapper.pushT(vi1.getType());
1363 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1364 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1365 emit(smapper, this, " @1 = @2, @3 = @4;",
1366 vo5, vo1, vo6, vo2);
1372 final Variable vi1 = smapper.get(0);
1373 final Variable vi2 = smapper.get(1);
1375 if (vi1.getType() == vi2.getType()) {
1376 final Variable tmp = smapper.pushT(vi1.getType());
1378 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1383 smapper.pushT(vi1.getType());
1384 smapper.pushT(vi2.getType());
1389 smapper.assign(this, VarType.INTEGER,
1390 "(" + Integer.toString(byteCodes[++i]) + ")");
1393 smapper.assign(this, VarType.INTEGER,
1394 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1398 case opc_getfield: {
1399 int indx = readUShortArg(byteCodes, i);
1400 String[] fi = jc.getFieldInfoName(indx);
1401 final int type = VarType.fromFieldType(fi[2].charAt(0));
1402 final String mangleClass = mangleClassName(fi[0]);
1403 final String mangleClassAccess = accessClassFalse(mangleClass);
1404 smapper.replace(this, type, "@2.call(@1)",
1406 accessField(mangleClassAccess,
1410 addReference(fi[0]);
1413 case opc_putfield: {
1414 int indx = readUShortArg(byteCodes, i);
1415 String[] fi = jc.getFieldInfoName(indx);
1416 final int type = VarType.fromFieldType(fi[2].charAt(0));
1417 final String mangleClass = mangleClassName(fi[0]);
1418 final String mangleClassAccess = accessClassFalse(mangleClass);
1419 emit(smapper, this, "@3.call(@2, @1);",
1422 accessField(mangleClassAccess,
1425 addReference(fi[0]);
1428 case opc_getstatic: {
1429 int indx = readUShortArg(byteCodes, i);
1430 String[] fi = jc.getFieldInfoName(indx);
1431 final int type = VarType.fromFieldType(fi[2].charAt(0));
1432 String ac = accessClassFalse(mangleClassName(fi[0]));
1433 String af = accessField(ac, "_" + fi[1], fi);
1434 smapper.assign(this, type, af + "()");
1436 addReference(fi[0]);
1439 case opc_putstatic: {
1440 int indx = readUShortArg(byteCodes, i);
1441 String[] fi = jc.getFieldInfoName(indx);
1442 final int type = VarType.fromFieldType(fi[2].charAt(0));
1443 emit(smapper, this, "@1._@2(@3);",
1444 accessClassFalse(mangleClassName(fi[0])), fi[1],
1445 smapper.popT(type));
1447 addReference(fi[0]);
1450 case opc_checkcast: {
1451 int indx = readUShortArg(byteCodes, i);
1452 generateCheckcast(indx, smapper);
1456 case opc_instanceof: {
1457 int indx = readUShortArg(byteCodes, i);
1458 generateInstanceOf(indx, smapper);
1463 final CharSequence v = smapper.popA();
1466 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1467 smapper.pushA(), v);
1471 case opc_monitorenter: {
1472 debug("/* monitor enter */");
1477 case opc_monitorexit: {
1478 debug("/* monitor exit */");
1489 emit(smapper, this, "throw 'unknown bytecode @1';",
1490 Integer.toString(c));
1494 generateByteCodeComment(prev, i, byteCodes);
1500 if (previousTrap != null) {
1501 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1506 while (openBraces-- > 0) {
1517 private int generateIf(StackMapper mapper, byte[] byteCodes,
1518 int i, final CharSequence v2, final CharSequence v1,
1519 final String test, int topMostLabel
1520 ) throws IOException {
1522 int indx = i + readShortArg(byteCodes, i);
1523 append("if ((").append(v1)
1524 .append(") ").append(test).append(" (")
1525 .append(v2).append(")) ");
1526 goTo(this, i, indx, topMostLabel);
1530 private int readInt4(byte[] byteCodes, int offset) {
1531 final int d = byteCodes[offset + 0] << 24;
1532 final int c = byteCodes[offset + 1] << 16;
1533 final int b = byteCodes[offset + 2] << 8;
1534 final int a = byteCodes[offset + 3];
1535 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1537 private static int readUByte(byte[] byteCodes, int offset) {
1538 return byteCodes[offset] & 0xff;
1541 private static int readUShort(byte[] byteCodes, int offset) {
1542 return ((byteCodes[offset] & 0xff) << 8)
1543 | (byteCodes[offset + 1] & 0xff);
1545 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1546 return readUShort(byteCodes, offsetInstruction + 1);
1549 private static int readShort(byte[] byteCodes, int offset) {
1550 int signed = byteCodes[offset];
1551 byte b0 = (byte)signed;
1552 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1554 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1555 return readShort(byteCodes, offsetInstruction + 1);
1558 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1560 Boolean count = null;
1561 boolean array = false;
1563 int firstPos = sig.length();
1564 while (i < descriptor.length()) {
1565 char ch = descriptor.charAt(i++);
1586 if (ch == 'J' || ch == 'D') {
1592 sig.insert(firstPos, ch);
1594 returnType[0] = '[';
1595 sig.insert(firstPos, "_3");
1604 returnType[0] = 'V';
1605 sig.insert(firstPos, 'V');
1608 int next = descriptor.indexOf(';', i);
1609 String realSig = mangleSig(descriptor, i - 1, next + 1);
1614 sig.append(realSig);
1617 sig.insert(firstPos, realSig);
1619 sig.insert(firstPos, "_3");
1621 returnType[0] = 'L';
1630 throw new IllegalStateException("Invalid char: " + ch);
1635 static String mangleSig(String sig) {
1636 return mangleSig(sig, 0, sig.length());
1639 private static String mangleMethodName(String name) {
1640 StringBuilder sb = new StringBuilder(name.length() * 2);
1641 int last = name.length();
1642 for (int i = 0; i < last; i++) {
1643 final char ch = name.charAt(i);
1645 case '_': sb.append("_1"); break;
1646 default: sb.append(ch); break;
1649 return sb.toString();
1651 private static String mangleSig(String txt, int first, int last) {
1652 StringBuilder sb = new StringBuilder((last - first) * 2);
1653 for (int i = first; i < last; i++) {
1654 final char ch = txt.charAt(i);
1656 case '/': sb.append('_'); break;
1657 case '_': sb.append("_1"); break;
1658 case ';': sb.append("_2"); break;
1659 case '[': sb.append("_3"); break;
1661 if (Character.isJavaIdentifierPart(ch)) {
1665 String hex = Integer.toHexString(ch).toLowerCase();
1666 for (int m = hex.length(); m < 4; m++) {
1674 return sb.toString();
1677 private static String mangleClassName(String name) {
1678 return mangleSig(name);
1681 private static String findMethodName(MethodData m, StringBuilder cnt) {
1682 StringBuilder name = new StringBuilder();
1683 if ("<init>".equals(m.getName())) { // NOI18N
1684 name.append("cons"); // NOI18N
1685 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1686 name.append("class"); // NOI18N
1688 name.append(mangleMethodName(m.getName()));
1691 countArgs(m.getInternalSig(), new char[1], name, cnt);
1692 return name.toString();
1695 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1696 StringBuilder name = new StringBuilder();
1697 String descr = mi[2];//mi.getDescriptor();
1699 if ("<init>".equals(nm)) { // NOI18N
1700 name.append("cons"); // NOI18N
1702 name.append(mangleMethodName(nm));
1704 countArgs(descr, returnType, name, cnt);
1705 return name.toString();
1708 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1709 throws IOException {
1710 int methodIndex = readUShortArg(byteCodes, i);
1711 String[] mi = jc.getFieldInfoName(methodIndex);
1712 char[] returnType = { 'V' };
1713 StringBuilder cnt = new StringBuilder();
1714 String mn = findMethodName(mi, cnt, returnType);
1716 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1717 final CharSequence[] vars = new CharSequence[numArguments];
1719 for (int j = numArguments - 1; j >= 0; --j) {
1720 vars[j] = mapper.popValue();
1724 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1725 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1727 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1728 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1730 if (vars[1] instanceof String) {
1731 String field = vars[1].toString();
1732 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1733 vars[1] = "c._" + field.substring(1, field.length() - 1);
1738 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1739 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1741 if (vars[1] instanceof String) {
1742 String field = vars[2].toString();
1743 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1744 vars[2] = "c._" + field.substring(1, field.length() - 1);
1749 if (returnType[0] != 'V') {
1752 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1756 final String in = mi[0];
1759 in.equals("org/apidesign/html/boot/spi/Fn") ||
1760 in.equals("org/netbeans/html/boot/spi/Fn")
1762 mcn = "java_lang_Class";
1764 mcn = mangleClassName(in);
1766 String object = accessClassFalse(mcn);
1767 if (mn.startsWith("cons_")) {
1768 object += ".constructor";
1770 append(accessStaticMethod(object, mn, mi));
1776 if (numArguments > 0) {
1778 for (int j = 1; j < numArguments; ++j) {
1788 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1789 throws IOException {
1790 int methodIndex = readUShortArg(byteCodes, i);
1791 String[] mi = jc.getFieldInfoName(methodIndex);
1792 char[] returnType = { 'V' };
1793 StringBuilder cnt = new StringBuilder();
1794 String mn = findMethodName(mi, cnt, returnType);
1796 final int numArguments = cnt.length() + 1;
1797 final CharSequence[] vars = new CharSequence[numArguments];
1799 for (int j = numArguments - 1; j >= 0; --j) {
1800 vars[j] = mapper.popValue();
1803 if (returnType[0] != 'V') {
1806 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1810 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1812 for (int j = 1; j < numArguments; ++j) {
1822 private void addReference(String cn) throws IOException {
1823 if (requireReference(cn)) {
1824 debug(" /* needs " + cn + " */");
1828 private void outType(String d, StringBuilder out) {
1830 while (d.charAt(0) == '[') {
1834 if (d.charAt(0) == 'L') {
1835 assert d.charAt(d.length() - 1) == ';';
1836 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1842 private String encodeConstant(int entryIndex) throws IOException {
1843 String[] classRef = { null };
1844 String s = jc.stringValue(entryIndex, classRef);
1845 if (classRef[0] != null) {
1846 if (classRef[0].startsWith("[")) {
1847 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1849 addReference(classRef[0]);
1850 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1856 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1857 byte[] arr = m.findAnnotationData(true);
1861 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1862 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1863 class P extends AnnotationParser {
1869 String[] args = new String[30];
1875 protected void visitAttr(String type, String attr, String at, String value) {
1876 if (type.equals(jvmType)) {
1877 if ("body".equals(attr)) {
1879 } else if ("args".equals(attr)) {
1880 args[cnt++] = value;
1882 throw new IllegalArgumentException(attr);
1885 if (type.equals(htmlType)) {
1887 if ("body".equals(attr)) {
1889 } else if ("args".equals(attr)) {
1890 args[cnt++] = value;
1891 } else if ("javacall".equals(attr)) {
1892 javacall = "1".equals(value);
1893 } else if ("wait4js".equals(attr)) {
1894 // ignore, we always invoke synchronously
1896 throw new IllegalArgumentException(attr);
1903 if (p.body == null) {
1906 StringBuilder cnt = new StringBuilder();
1907 final String mn = findMethodName(m, cnt);
1908 append("m = ").append(destObject).append(".").append(mn);
1909 append(" = function(");
1912 StringBuilder toValue = new StringBuilder();
1913 for (int i = 0; i < cnt.length(); i++) {
1915 space = outputArg(this, p.args, index);
1916 if (p.html4j && space.length() > 0) {
1917 toValue.append("\n ").append(p.args[index]).append(" = ")
1918 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1919 append(p.args[index]).append(");");
1923 append(") {").append("\n");
1924 append(toValue.toString());
1926 int lastSlash = jc.getClassName().lastIndexOf('/');
1927 final String pkg = jc.getClassName().substring(0, lastSlash);
1928 append(mangleCallbacks(pkg, p.body));
1929 requireReference(pkg + "/$JsCallbacks$");
1937 private static CharSequence mangleCallbacks(String pkgName, String body) {
1938 StringBuilder sb = new StringBuilder();
1941 int next = body.indexOf(".@", pos);
1943 sb.append(body.substring(pos));
1944 body = sb.toString();
1949 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1954 String refId = body.substring(ident, next);
1956 sb.append(body.substring(pos, ident));
1958 int sigBeg = body.indexOf('(', next);
1959 int sigEnd = body.indexOf(')', sigBeg);
1960 int colon4 = body.indexOf("::", next);
1961 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1962 throw new IllegalStateException("Malformed body " + body);
1964 String fqn = body.substring(next + 2, colon4);
1965 String method = body.substring(colon4 + 2, sigBeg);
1966 String params = body.substring(sigBeg, sigEnd + 1);
1968 int paramBeg = body.indexOf('(', sigEnd + 1);
1970 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1971 sb.append(mangleJsCallbacks(fqn, method, params, false));
1972 sb.append("(").append(refId);
1973 if (body.charAt(paramBeg + 1) != ')') {
1981 int next = body.indexOf("@", pos);
1986 sb.append(body.substring(pos));
1990 sb = new StringBuilder();
1993 sb.append(body.substring(pos, next));
1995 int sigBeg = body.indexOf('(', next);
1996 int sigEnd = body.indexOf(')', sigBeg);
1997 int colon4 = body.indexOf("::", next);
1998 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1999 throw new IllegalStateException("Malformed body " + body);
2001 String fqn = body.substring(next + 1, colon4);
2002 String method = body.substring(colon4 + 2, sigBeg);
2003 String params = body.substring(sigBeg, sigEnd + 1);
2005 int paramBeg = body.indexOf('(', sigEnd + 1);
2007 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2008 sb.append(mangleJsCallbacks(fqn, method, params, true));
2014 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2015 if (params.startsWith("(")) {
2016 params = params.substring(1);
2018 if (params.endsWith(")")) {
2019 params = params.substring(0, params.length() - 1);
2021 StringBuilder sb = new StringBuilder();
2022 final String fqnu = fqn.replace('.', '_');
2023 final String rfqn = mangleClassName(fqnu);
2024 final String rm = mangleMethodName(method);
2027 StringBuilder pb = new StringBuilder();
2028 int len = params.length();
2030 while (indx < len) {
2031 char ch = params.charAt(indx);
2032 if (ch == '[' || ch == 'L') {
2033 int column = params.indexOf(';', indx) + 1;
2034 if (column > indx) {
2035 String real = params.substring(indx, column);
2036 if ("Ljava/lang/String;".equals(real)) {
2037 pb.append("Ljava/lang/String;");
2042 pb.append("Ljava/lang/Object;");
2049 srp = mangleSig(pb.toString());
2051 final String rp = mangleSig(params);
2052 final String mrp = mangleMethodName(rp);
2053 sb.append(rfqn).append("$").append(rm).
2054 append('$').append(mrp).append("__Ljava_lang_Object_2");
2056 sb.append('L').append(fqnu).append("_2");
2059 return sb.toString();
2062 private static String className(ClassData jc) {
2063 //return jc.getName().getInternalName().replace('/', '_');
2064 return mangleClassName(jc.getClassName());
2067 private static String[] findAnnotation(
2068 byte[] arr, ClassData cd, final String className,
2069 final String... attrNames
2070 ) throws IOException {
2074 final String[] values = new String[attrNames.length];
2075 final boolean[] found = { false };
2076 final String jvmType = "L" + className.replace('.', '/') + ";";
2077 AnnotationParser ap = new AnnotationParser(false, true) {
2079 protected void visitAttr(String type, String attr, String at, String value) {
2080 if (type.equals(jvmType)) {
2082 for (int i = 0; i < attrNames.length; i++) {
2083 if (attrNames[i].equals(attr)) {
2092 return found[0] ? values : null;
2095 private CharSequence initField(FieldData v) {
2096 final String is = v.getInternalSig();
2097 if (is.length() == 1) {
2098 switch (is.charAt(0)) {
2104 case 'I': return " = 0;";
2106 case 'D': return " = 0.0;";
2108 throw new IllegalStateException(is);
2114 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2115 AnnotationParser ap = new AnnotationParser(true, false) {
2116 int[] cnt = new int[32];
2120 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2121 final String slashType = attrType.substring(1, attrType.length() - 1);
2122 requireReference(slashType);
2124 if (cnt[depth]++ > 0) {
2128 append('"').append(attrType).append("\" : ");
2135 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2141 protected void visitValueStart(String attrName, char type) throws IOException {
2142 if (cnt[depth]++ > 0) {
2146 if (attrName != null) {
2147 append('"').append(attrName).append("\" : ");
2155 protected void visitValueEnd(String attrName, char type) throws IOException {
2163 protected void visitAttr(String type, String attr, String attrType, String value)
2164 throws IOException {
2165 if (attr == null && value == null) {
2172 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2173 throws IOException {
2174 final String slashType = attrType.substring(1, attrType.length() - 1);
2175 requireReference(slashType);
2177 final String cn = mangleClassName(slashType);
2178 append(accessClassFalse(cn))
2179 .append("['valueOf__L").
2181 append("_2Ljava_lang_String_2']('").
2189 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2190 final String name = args[indx];
2194 if (name.contains(",")) {
2195 throw new IOException("Wrong parameter with ',': " + name);
2201 final void emitNoFlush(
2203 final String format, final CharSequence... params
2204 ) throws IOException {
2205 emitImpl(this, format, params);
2207 static final void emit(
2209 final Appendable out,
2210 final String format, final CharSequence... params
2211 ) throws IOException {
2213 emitImpl(out, format, params);
2215 static void emitImpl(final Appendable out,
2216 final String format,
2217 final CharSequence... params) throws IOException {
2218 final int length = format.length();
2221 int paramOffset = format.indexOf('@');
2222 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2223 final char paramChar = format.charAt(paramOffset + 1);
2224 if ((paramChar >= '1') && (paramChar <= '9')) {
2225 final int paramIndex = paramChar - '0' - 1;
2227 out.append(format, processed, paramOffset);
2228 out.append(params[paramIndex]);
2231 processed = paramOffset + 1;
2234 paramOffset = format.indexOf('@', paramOffset + 1);
2237 out.append(format, processed, length);
2240 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2241 append("} catch (e) {\n");
2243 for (TrapData e : traps) {
2247 if (e.catch_cpx != 0) { //not finally
2248 final String classInternalName = jc.getClassName(e.catch_cpx);
2249 addReference(classInternalName);
2250 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2251 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2252 append("var stA0 = e;");
2253 goTo(this, current, e.handler_pc, topMostLabel);
2256 finallyPC = e.handler_pc;
2259 if (finallyPC == -1) {
2262 append("var stA0 = e;");
2263 goTo(this, current, finallyPC, topMostLabel);
2268 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2271 out.append("{ gt = 0; continue X_" + to + "; }");
2273 out.append("{ gt = " + to + "; continue X_0; }");
2276 out.append("{ gt = " + to + "; break IF; }");
2280 private static void emitIf(
2282 Appendable out, String pattern,
2284 int current, int to, int canBack
2285 ) throws IOException {
2287 emitImpl(out, pattern, param);
2288 goTo(out, current, to, canBack);
2291 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2294 case 4: jvmType = "[Z"; break;
2295 case 5: jvmType = "[C"; break;
2296 case 6: jvmType = "[F"; break;
2297 case 7: jvmType = "[D"; break;
2298 case 8: jvmType = "[B"; break;
2299 case 9: jvmType = "[S"; break;
2300 case 10: jvmType = "[I"; break;
2301 case 11: jvmType = "[J"; break;
2302 default: throw new IllegalStateException("Array type: " + atype);
2305 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2306 smapper.popI(), smapper.pushA(), jvmType);
2309 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2310 String typeName = jc.getClassName(type);
2311 String ref = "null";
2312 if (typeName.startsWith("[")) {
2313 typeName = "'[" + typeName + "'";
2315 ref = "vm." + mangleClassName(typeName);
2316 typeName = "'[L" + typeName + ";'";
2319 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2320 smapper.popI(), smapper.pushA(), typeName, ref);
2323 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2324 String typeName = jc.getClassName(type);
2325 int dim = readUByte(byteCodes, ++i);
2326 StringBuilder dims = new StringBuilder();
2328 for (int d = 0; d < dim; d++) {
2330 dims.insert(1, ",");
2332 dims.insert(1, smapper.popI());
2336 if (typeName.charAt(dim) == 'L') {
2337 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2340 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2341 dims.toString(), smapper.pushA(), typeName, fn
2346 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2347 int table = i / 4 * 4 + 4;
2348 int dflt = i + readInt4(byteCodes, table);
2350 int low = readInt4(byteCodes, table);
2352 int high = readInt4(byteCodes, table);
2354 final CharSequence swVar = smapper.popValue();
2355 smapper.flush(this);
2356 append("switch (").append(swVar).append(") {\n");
2357 while (low <= high) {
2358 int offset = i + readInt4(byteCodes, table);
2360 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2363 append(" default: ");
2364 goTo(this, i, dflt, topMostLabel);
2370 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2371 int table = i / 4 * 4 + 4;
2372 int dflt = i + readInt4(byteCodes, table);
2374 int n = readInt4(byteCodes, table);
2376 final CharSequence swVar = smapper.popValue();
2377 smapper.flush(this);
2378 append("switch (").append(swVar).append(") {\n");
2380 int cnstnt = readInt4(byteCodes, table);
2382 int offset = i + readInt4(byteCodes, table);
2384 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2386 append(" default: ");
2387 goTo(this, i, dflt, topMostLabel);
2393 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2394 String type = jc.getClassName(indx);
2395 if (!type.startsWith("[")) {
2397 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2398 smapper.popA(), smapper.pushI(),
2399 type.replace('/', '_'));
2402 while (type.charAt(cnt) == '[') {
2405 if (type.charAt(cnt) == 'L') {
2406 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2408 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2409 smapper.popA(), smapper.pushI(),
2414 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2415 smapper.popA(), smapper.pushI(), type
2421 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2422 String type = jc.getClassName(indx);
2423 if (!type.startsWith("[")) {
2424 emitNoFlush(smapper,
2425 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2426 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2429 while (type.charAt(cnt) == '[') {
2432 if (type.charAt(cnt) == 'L') {
2433 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2434 emitNoFlush(smapper,
2435 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2436 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2439 emitNoFlush(smapper,
2440 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2441 smapper.getT(0, VarType.REFERENCE, false), type
2447 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2448 for (int j = prev; j <= i; j++) {
2450 final int cc = readUByte(byteCodes, j);
2451 append(Integer.toString(cc));
2455 @JavaScriptBody(args = "msg", body = "")
2456 private static void println(String msg) {
2457 System.err.println(msg);