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 java.util.Arrays;
23 import org.apidesign.bck2brwsr.core.JavaScriptBody;
24 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
26 /** Translator of the code inside class files to JavaScript.
28 * @author Jaroslav Tulach <jtulach@netbeans.org>
30 abstract class ByteCodeToJavaScript implements Appendable {
32 private final Appendable out;
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 String accessClassFalse(String classOperation) {
90 if (jc.getClassName().replace('/', '_').equals(classOperation)) {
93 return accessClass(classOperation) + "(false)";
96 protected String accessField(String object, String mangledName,
97 String[] fieldInfoName) throws IOException {
98 return object + "." + mangledName;
101 protected String accessStaticMethod(
104 String[] fieldInfoName) throws IOException {
105 return object + "." + mangledName;
108 protected String accessVirtualMethod(
111 String[] fieldInfoName,
113 ) throws IOException {
114 return object + "." + mangledName + '(';
117 protected void declaredClass(ClassData classData, String mangledName)
121 protected void declaredField(FieldData fieldData,
123 String mangledName) throws IOException {
126 protected void declaredMethod(MethodData methodData,
128 String mangledName) throws IOException {
131 /** Prints out a debug message.
133 * @param msg the message
134 * @return true if the message has been printed
135 * @throws IOException
137 boolean debug(String msg) throws IOException {
143 * Converts a given class file to a JavaScript version.
145 * @param classFile input stream with code of the .class file
146 * @return the initialization code for this class, if any. Otherwise <code>null</code>
148 * @throws IOException if something goes wrong during read or write or translating
151 public String compile(InputStream classFile) throws IOException {
152 return compile(new ClassData(classFile));
155 protected String compile(ClassData classData) throws IOException {
157 final String cn = this.jc.getClassName();
158 this.callbacks = cn.endsWith("/$JsCallbacks$");
159 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
160 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
161 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
164 byte[] arrData = jc.findAnnotationData(true);
166 String[] arr = findAnnotation(arrData, jc,
167 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
168 "resource", "processByteCode"
171 if (!arr[0].isEmpty()) {
172 requireScript(arr[0]);
174 if ("0".equals(arr[1])) {
179 final String jsResource;
181 String[] arr = findAnnotation(arrData, jc,
182 "net.java.html.js.JavaScriptResource",
186 if (arr[0].startsWith("/")) {
189 int last = cn.lastIndexOf('/');
190 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
196 String[] proto = findAnnotation(arrData, jc,
197 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
198 "container", "prototype"
200 StringArray toInitilize = new StringArray();
201 final String className = className(jc);
202 append("\n\n").append(assignClass(className));
203 append("function ").append(className).append("() {");
205 append("\n var CLS = ").append(className).append(';');
206 append("\n if (!CLS.$class) {");
208 String sc = jc.getSuperClassName(); // with _
209 append("\n var pp = ").
210 append(accessClass(mangleClassName(sc))).append("(true);");
211 append("\n var p = CLS.prototype = pp;");
212 append("\n var c = p;");
213 append("\n var sprcls = pp.constructor.$class;");
215 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
216 if (proto[0] == null) {
219 append("\n var c = ").append(proto[0]).append(";");
220 append("\n var sprcls = null;");
222 for (FieldData v : jc.getFields()) {
224 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
225 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
229 append("\n CLS.fld_").append(v.getName()).append(initField(v));
230 append("\n m = c._").append(v.getName()).append(" = function (v) {")
231 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
232 .append(" = v; return CLS.fld_").
233 append(v.getName()).append("; };");
235 append("\n m = c._").append(v.getName()).append(" = function (v) {")
236 .append(" if (arguments.length == 1) this.fld_").
237 append(className).append('_').append(v.getName())
238 .append(" = v; return this.fld_").
239 append(className).append('_').append(v.getName())
243 declaredField(v, "c", "_" + v.getName());
245 for (MethodData m : jc.getMethods()) {
246 byte[] onlyArr = m.findAnnotationData(true);
247 if (javaScriptOnly(onlyArr)) continue;
253 mn = generateStaticMethod(destObject, m, toInitilize);
255 if (m.isConstructor()) {
257 mn = generateInstanceMethod(destObject, m);
260 mn = generateInstanceMethod(destObject, m);
263 declaredMethod(m, destObject, mn);
264 byte[] runAnno = m.findAnnotationData(false);
265 if (runAnno != null) {
266 append("\n m.anno = {");
267 generateAnno(jc, runAnno);
270 append("\n m.access = " + m.getAccess()).append(";");
271 append("\n m.cls = CLS;");
273 append("\n c.constructor = CLS;");
274 append("\n function ").append(className).append("fillInstOf(x) {");
275 String instOfName = "$instOf_" + className;
276 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
277 if (jc.isInterface()) {
278 for (MethodData m : jc.getMethods()) {
279 if ((m.getAccess() & ACC_ABSTRACT) == 0
280 && (m.getAccess() & ACC_STATIC) == 0
281 && (m.getAccess() & ACC_PRIVATE) == 0) {
282 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("']});");
285 append("\n } catch (ignore) {");
290 for (String superInterface : jc.getSuperInterfaces()) {
291 String intrfc = superInterface.replace('/', '_');
292 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
293 requireReference(superInterface);
297 append("\n Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
298 append("\n ").append(className).append("fillInstOf(c);");
299 append("\n } catch (ignore) {");
301 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
302 append("\n CLS.$class = 'temp';");
303 append("\n CLS.$class = ");
304 append(accessClass("java_lang_Class(true);"));
305 append("\n CLS.$class.jvmName = '").append(cn).append("';");
306 append("\n CLS.$class.superclass = sprcls;");
307 append("\n CLS.$class.interfaces = function() { return [");
309 boolean first = true;
310 for (String intrfc : jc.getSuperInterfaces()) {
314 requireReference(intrfc);
315 String mangledIface = mangleClassName(intrfc);
317 append(accessClass(mangledIface)).append("(false).constructor.$class");
322 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
323 append("\n CLS.$class.cnstr = CLS;");
324 byte[] classAnno = jc.findAnnotationData(false);
325 if (classAnno != null) {
326 append("\n CLS.$class.anno = {");
327 generateAnno(jc, classAnno);
330 for (String init : toInitilize.toArray()) {
331 append("\n ").append(init).append("();");
334 if (jsResource != null) {
335 requireResource(jsResource);
339 append("\n if (arguments.length === 0) {");
340 append("\n if (!(this instanceof CLS)) {");
341 append("\n return new CLS();");
343 for (FieldData v : jc.getFields()) {
344 byte[] onlyArr = v.findAnnotationData(true);
345 if (javaScriptOnly(onlyArr)) continue;
347 append("\n this.fld_").
348 append(className).append('_').
349 append(v.getName()).append(initField(v));
352 append("\n return this;");
354 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
357 declaredClass(jc, className);
359 // StringBuilder sb = new StringBuilder();
360 // for (String init : toInitilize.toArray()) {
361 // sb.append("\n").append(init).append("();");
366 private boolean javaScriptOnly(byte[] anno) throws IOException {
367 String[] only = findAnnotation(anno, jc,
368 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
372 if (only[0] != null && only[1] != null) {
373 append("\n p.").append(only[0]).append(" = ")
374 .append(only[1]).append(";");
376 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
377 append("\n p['").append(only[0]).append("'] = p.")
378 .append(only[0]).append(";");
384 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
385 String jsb = javaScriptBody(destObject, m, true);
389 final String mn = findMethodName(m, new StringBuilder());
390 boolean defineProp = generateMethod(destObject, mn, m);
391 if (mn.equals("class__V")) {
393 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
395 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
401 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
402 String jsb = javaScriptBody(destObject, m, false);
406 final String mn = findMethodName(m, new StringBuilder());
407 generateMethod(destObject, mn, m);
411 private boolean generateMethod(String destObject, String name, MethodData m)
413 final StackMapIterator stackMapIterator = m.createStackMapIterator();
414 TrapDataIterator trap = m.getTrapDataIterator();
415 final LocalsMapper lmapper =
416 new LocalsMapper(stackMapIterator.getArguments());
419 "java/lang/Object".equals(jc.getClassName()) ||
420 "java/lang/reflect/Array".equals(jc.getClassName());
423 append("Object.defineProperty(").append(destObject).
424 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
426 append("m = ").append(destObject).append(".").append(name).append(" = function(");
428 lmapper.outputArguments(this, m.isStatic());
429 append(") {").append("\n");
431 final byte[] byteCodes = m.getCode();
432 if (byteCodes == null) {
433 append(" throw 'no code found for ")
434 .append(jc.getClassName()).append('.')
435 .append(m.getName()).append("';\n");
444 final StackMapper smapper = new StackMapper();
447 append(" var ").append(" lcA0 = this;\n");
451 TrapData[] previousTrap = null;
452 boolean wide = false;
454 if (stackMapIterator.isEmpty()) {
460 append("\n var gt = 0;\n");
464 int topMostLabel = 0;
465 for (int i = 0; i < byteCodes.length; i++) {
468 stackMapIterator.advanceTo(i);
469 boolean changeInCatch = trap.advanceTo(i);
470 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
471 if (previousTrap != null) {
472 generateCatch(previousTrap, i, topMostLabel);
476 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
481 if (openBraces > 64) {
482 for (int c = 0; c < 64; c++) {
489 lastStackFrame = stackMapIterator.getFrameIndex();
490 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
491 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
492 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
494 changeInCatch = true;
496 debug(" /* " + i + " */ ");
498 if (changeInCatch && trap.useTry()) {
500 previousTrap = trap.current();
502 final int c = readUByte(byteCodes, i);
505 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
508 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
511 smapper.assign(this, VarType.LONG, lmapper.getL(0));
514 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
517 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
520 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
523 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
526 smapper.assign(this, VarType.LONG, lmapper.getL(1));
529 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
532 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
535 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
538 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
541 smapper.assign(this, VarType.LONG, lmapper.getL(2));
544 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
547 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
550 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
553 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
556 smapper.assign(this, VarType.LONG, lmapper.getL(3));
559 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
562 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
566 final int indx = wide ? readUShort(byteCodes, i++)
567 : readUByte(byteCodes, i);
569 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
574 final int indx = wide ? readUShort(byteCodes, i++)
575 : readUByte(byteCodes, i);
577 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
582 final int indx = wide ? readUShort(byteCodes, i++)
583 : readUByte(byteCodes, i);
585 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
590 final int indx = wide ? readUShort(byteCodes, i++)
591 : readUByte(byteCodes, i);
593 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
598 final int indx = wide ? readUShort(byteCodes, i++)
599 : readUByte(byteCodes, i);
601 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
606 final int indx = wide ? readUShort(byteCodes, i++)
607 : readUByte(byteCodes, i);
609 emit(smapper, this, "var @1 = @2;",
610 lmapper.setI(indx), smapper.popI());
615 final int indx = wide ? readUShort(byteCodes, i++)
616 : readUByte(byteCodes, i);
618 emit(smapper, this, "var @1 = @2;",
619 lmapper.setL(indx), smapper.popL());
624 final int indx = wide ? readUShort(byteCodes, i++)
625 : readUByte(byteCodes, i);
627 emit(smapper, this, "var @1 = @2;",
628 lmapper.setF(indx), smapper.popF());
633 final int indx = wide ? readUShort(byteCodes, i++)
634 : readUByte(byteCodes, i);
636 emit(smapper, this, "var @1 = @2;",
637 lmapper.setD(indx), smapper.popD());
642 final int indx = wide ? readUShort(byteCodes, i++)
643 : readUByte(byteCodes, i);
645 emit(smapper, this, "var @1 = @2;",
646 lmapper.setA(indx), smapper.popA());
650 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
653 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
656 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
659 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
662 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
665 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
668 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
671 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
674 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
677 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
680 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
683 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
686 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
689 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
692 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
695 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
698 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
701 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
704 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
707 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
710 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
713 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
716 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
719 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
722 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
725 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
728 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
731 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
734 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
737 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
740 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
743 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
746 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
747 smapper.getI(1), smapper.popI());
750 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
751 smapper.getL(1), smapper.popL());
754 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
757 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
760 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
761 smapper.getI(1), smapper.popI());
764 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
765 smapper.getL(1), smapper.popL());
768 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
771 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
774 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
777 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
780 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
783 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
786 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
789 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
792 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
795 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
798 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
801 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
804 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
807 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
810 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
813 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
816 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
819 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
823 final int varIndx = wide ? readUShort(byteCodes, i++)
824 : readUByte(byteCodes, i);
826 final int incrBy = wide ? readShort(byteCodes, i++)
830 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
832 emit(smapper, this, "@1 += @2;",
833 lmapper.getI(varIndx),
834 Integer.toString(incrBy));
839 emit(smapper, this, "return;");
842 emit(smapper, this, "return @1;", smapper.popI());
845 emit(smapper, this, "return @1;", smapper.popL());
848 emit(smapper, this, "return @1;", smapper.popF());
851 emit(smapper, this, "return @1;", smapper.popD());
854 emit(smapper, this, "return @1;", smapper.popA());
857 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
860 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
863 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
866 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
870 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
873 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
876 smapper.replace(this, VarType.DOUBLE, "@1",
880 smapper.replace(this, VarType.FLOAT, "@1",
884 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
888 smapper.replace(this, VarType.LONG, "(@1).toLong()",
892 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
896 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
899 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
903 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
905 case opc_aconst_null:
906 smapper.assign(this, VarType.REFERENCE, "null");
909 smapper.assign(this, VarType.INTEGER, "-1");
912 smapper.assign(this, VarType.INTEGER, "0");
915 smapper.assign(this, VarType.DOUBLE, "0");
918 smapper.assign(this, VarType.LONG, "0");
921 smapper.assign(this, VarType.FLOAT, "0");
924 smapper.assign(this, VarType.INTEGER, "1");
927 smapper.assign(this, VarType.LONG, "1");
930 smapper.assign(this, VarType.FLOAT, "1");
933 smapper.assign(this, VarType.DOUBLE, "1");
936 smapper.assign(this, VarType.INTEGER, "2");
939 smapper.assign(this, VarType.FLOAT, "2");
942 smapper.assign(this, VarType.INTEGER, "3");
945 smapper.assign(this, VarType.INTEGER, "4");
948 smapper.assign(this, VarType.INTEGER, "5");
951 int indx = readUByte(byteCodes, ++i);
952 String v = encodeConstant(indx);
953 int type = VarType.fromConstantType(jc.getTag(indx));
954 smapper.assign(this, type, v);
959 int indx = readUShortArg(byteCodes, i);
961 String v = encodeConstant(indx);
962 int type = VarType.fromConstantType(jc.getTag(indx));
963 if (type == VarType.LONG) {
964 final Long lv = new Long(v);
965 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
966 final int hi = (int)(lv.longValue() >> 32);
968 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
970 smapper.assign(this, VarType.LONG,
971 "0x" + Integer.toHexString(hi) + ".next32(0x" +
972 Integer.toHexString(low) + ")"
976 smapper.assign(this, type, v);
981 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
985 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
989 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
992 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
993 "===", topMostLabel);
996 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
997 "!==", topMostLabel);
1000 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1001 "==", topMostLabel);
1004 int indx = i + readShortArg(byteCodes, i);
1005 emitIf(smapper, this, "if ((@1) == 0) ",
1006 smapper.popI(), i, indx, topMostLabel);
1011 int indx = i + readShortArg(byteCodes, i);
1012 emitIf(smapper, this, "if ((@1) != 0) ",
1013 smapper.popI(), i, indx, topMostLabel);
1018 int indx = i + readShortArg(byteCodes, i);
1019 emitIf(smapper, this, "if ((@1) < 0) ",
1020 smapper.popI(), i, indx, topMostLabel);
1025 int indx = i + readShortArg(byteCodes, i);
1026 emitIf(smapper, this, "if ((@1) <= 0) ",
1027 smapper.popI(), i, indx, topMostLabel);
1032 int indx = i + readShortArg(byteCodes, i);
1033 emitIf(smapper, this, "if ((@1) > 0) ",
1034 smapper.popI(), i, indx, topMostLabel);
1039 int indx = i + readShortArg(byteCodes, i);
1040 emitIf(smapper, this, "if ((@1) >= 0) ",
1041 smapper.popI(), i, indx, topMostLabel);
1045 case opc_ifnonnull: {
1046 int indx = i + readShortArg(byteCodes, i);
1047 emitIf(smapper, this, "if ((@1) !== null) ",
1048 smapper.popA(), i, indx, topMostLabel);
1053 int indx = i + readShortArg(byteCodes, i);
1054 emitIf(smapper, this, "if ((@1) === null) ",
1055 smapper.popA(), i, indx, topMostLabel);
1060 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1061 "!=", topMostLabel);
1064 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1068 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1069 "<=", topMostLabel);
1072 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1076 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1077 ">=", topMostLabel);
1080 smapper.flush(this);
1081 int indx = i + readShortArg(byteCodes, i);
1082 goTo(this, i, indx, topMostLabel);
1086 case opc_lookupswitch: {
1087 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1090 case opc_tableswitch: {
1091 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1094 case opc_invokeinterface: {
1095 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1098 case opc_invokevirtual:
1099 i = invokeVirtualMethod(byteCodes, i, smapper);
1101 case opc_invokespecial:
1102 i = invokeStaticMethod(byteCodes, i, smapper, false);
1104 case opc_invokestatic:
1105 i = invokeStaticMethod(byteCodes, i, smapper, true);
1107 case opc_invokedynamic: {
1108 int indx = readUShortArg(byteCodes, i);
1109 println("invoke dynamic: " + indx);
1110 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1111 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1112 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1113 println(" type: " + methodHandle.cpx1);
1114 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1115 String mcn = mangleClassName(mi[0]);
1116 char[] returnType = {'V'};
1117 StringBuilder cnt = new StringBuilder();
1118 String mn = findMethodName(mi, cnt, returnType);
1119 StringBuilder sb = new StringBuilder();
1120 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1121 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1122 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1123 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1124 sb.append(" mn : ").append(mn).append("\n");
1125 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1126 throw new IOException(sb.toString());
1128 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1129 String type = jc.StringValue(nameAndType.cpx2);
1130 String object = accessClass(mcn) + "(false)";
1131 if (mn.startsWith("cons_")) {
1132 object += ".constructor";
1134 append("var metHan = ");
1135 append(accessStaticMethod(object, mn, mi));
1137 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1139 append(", '").append(mi[1]).append("', ");
1140 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1141 append(methodType).append("'").append(type).append("', null)");
1142 // if (numArguments > 0) {
1144 // for (int j = 1; j < numArguments; ++j) {
1150 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1156 int indx = readUShortArg(byteCodes, i);
1157 String ci = jc.getClassName(indx);
1158 emit(smapper, this, "var @1 = new @2;",
1159 smapper.pushA(), accessClass(mangleClassName(ci)));
1165 int atype = readUByte(byteCodes, ++i);
1166 generateNewArray(atype, smapper);
1168 case opc_anewarray: {
1169 int type = readUShortArg(byteCodes, i);
1171 generateANewArray(type, smapper);
1174 case opc_multianewarray: {
1175 int type = readUShortArg(byteCodes, i);
1177 i = generateMultiANewArray(type, byteCodes, i, smapper);
1180 case opc_arraylength:
1181 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1184 emit(smapper, this, "Array.at(@3, @2, @1);",
1185 smapper.popL(), smapper.popI(), smapper.popA());
1188 emit(smapper, this, "Array.at(@3, @2, @1);",
1189 smapper.popF(), smapper.popI(), smapper.popA());
1192 emit(smapper, this, "Array.at(@3, @2, @1);",
1193 smapper.popD(), smapper.popI(), smapper.popA());
1196 emit(smapper, this, "Array.at(@3, @2, @1);",
1197 smapper.popA(), smapper.popI(), smapper.popA());
1203 emit(smapper, this, "Array.at(@3, @2, @1);",
1204 smapper.popI(), smapper.popI(), smapper.popA());
1207 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1208 smapper.popI(), smapper.getA(0));
1211 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1212 smapper.popI(), smapper.getA(0));
1215 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1216 smapper.popI(), smapper.getA(0));
1219 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1220 smapper.popI(), smapper.getA(0));
1226 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1227 smapper.popI(), smapper.getA(0));
1235 final Variable v = smapper.get(0);
1236 if (smapper.isDirty()) {
1237 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1239 smapper.assign(this, v.getType(), v);
1244 final Variable vi1 = smapper.get(0);
1246 if (vi1.isCategory2()) {
1247 emit(smapper, this, "var @1 = @2;",
1248 smapper.pushT(vi1.getType()), vi1);
1250 final Variable vi2 = smapper.get(1);
1251 emit(smapper, this, "var @1 = @2, @3 = @4;",
1252 smapper.pushT(vi2.getType()), vi2,
1253 smapper.pushT(vi1.getType()), vi1);
1258 final Variable vi1 = smapper.pop(this);
1259 final Variable vi2 = smapper.pop(this);
1260 final Variable vo3 = smapper.pushT(vi1.getType());
1261 final Variable vo2 = smapper.pushT(vi2.getType());
1262 final Variable vo1 = smapper.pushT(vi1.getType());
1264 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1265 vo1, vi1, vo2, vi2, vo3, vo1);
1269 final Variable vi1 = smapper.pop(this);
1270 final Variable vi2 = smapper.pop(this);
1272 if (vi1.isCategory2()) {
1273 final Variable vo3 = smapper.pushT(vi1.getType());
1274 final Variable vo2 = smapper.pushT(vi2.getType());
1275 final Variable vo1 = smapper.pushT(vi1.getType());
1277 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1278 vo1, vi1, vo2, vi2, vo3, vo1);
1280 final Variable vi3 = smapper.pop(this);
1281 final Variable vo5 = smapper.pushT(vi2.getType());
1282 final Variable vo4 = smapper.pushT(vi1.getType());
1283 final Variable vo3 = smapper.pushT(vi3.getType());
1284 final Variable vo2 = smapper.pushT(vi2.getType());
1285 final Variable vo1 = smapper.pushT(vi1.getType());
1287 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1288 vo1, vi1, vo2, vi2, vo3, vi3);
1289 emit(smapper, this, " @1 = @2, @3 = @4;",
1290 vo4, vo1, vo5, vo2);
1295 final Variable vi1 = smapper.pop(this);
1296 final Variable vi2 = smapper.pop(this);
1298 if (vi2.isCategory2()) {
1299 final Variable vo3 = smapper.pushT(vi1.getType());
1300 final Variable vo2 = smapper.pushT(vi2.getType());
1301 final Variable vo1 = smapper.pushT(vi1.getType());
1303 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1304 vo1, vi1, vo2, vi2, vo3, vo1);
1306 final Variable vi3 = smapper.pop(this);
1307 final Variable vo4 = smapper.pushT(vi1.getType());
1308 final Variable vo3 = smapper.pushT(vi3.getType());
1309 final Variable vo2 = smapper.pushT(vi2.getType());
1310 final Variable vo1 = smapper.pushT(vi1.getType());
1312 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1313 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1318 final Variable vi1 = smapper.pop(this);
1319 final Variable vi2 = smapper.pop(this);
1321 if (vi1.isCategory2()) {
1322 if (vi2.isCategory2()) {
1323 final Variable vo3 = smapper.pushT(vi1.getType());
1324 final Variable vo2 = smapper.pushT(vi2.getType());
1325 final Variable vo1 = smapper.pushT(vi1.getType());
1327 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1328 vo1, vi1, vo2, vi2, vo3, vo1);
1330 final Variable vi3 = smapper.pop(this);
1331 final Variable vo4 = smapper.pushT(vi1.getType());
1332 final Variable vo3 = smapper.pushT(vi3.getType());
1333 final Variable vo2 = smapper.pushT(vi2.getType());
1334 final Variable vo1 = smapper.pushT(vi1.getType());
1336 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1337 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1340 final Variable vi3 = smapper.pop(this);
1342 if (vi3.isCategory2()) {
1343 final Variable vo5 = smapper.pushT(vi2.getType());
1344 final Variable vo4 = smapper.pushT(vi1.getType());
1345 final Variable vo3 = smapper.pushT(vi3.getType());
1346 final Variable vo2 = smapper.pushT(vi2.getType());
1347 final Variable vo1 = smapper.pushT(vi1.getType());
1349 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1350 vo1, vi1, vo2, vi2, vo3, vi3);
1351 emit(smapper, this, " @1 = @2, @3 = @4;",
1352 vo4, vo1, vo5, vo2);
1354 final Variable vi4 = smapper.pop(this);
1355 final Variable vo6 = smapper.pushT(vi2.getType());
1356 final Variable vo5 = smapper.pushT(vi1.getType());
1357 final Variable vo4 = smapper.pushT(vi4.getType());
1358 final Variable vo3 = smapper.pushT(vi3.getType());
1359 final Variable vo2 = smapper.pushT(vi2.getType());
1360 final Variable vo1 = smapper.pushT(vi1.getType());
1362 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1363 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1364 emit(smapper, this, " @1 = @2, @3 = @4;",
1365 vo5, vo1, vo6, vo2);
1371 final Variable vi1 = smapper.get(0);
1372 final Variable vi2 = smapper.get(1);
1374 if (vi1.getType() == vi2.getType()) {
1375 final Variable tmp = smapper.pushT(vi1.getType());
1377 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1382 smapper.pushT(vi1.getType());
1383 smapper.pushT(vi2.getType());
1388 smapper.assign(this, VarType.INTEGER,
1389 "(" + Integer.toString(byteCodes[++i]) + ")");
1392 smapper.assign(this, VarType.INTEGER,
1393 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1397 case opc_getfield: {
1398 int indx = readUShortArg(byteCodes, i);
1399 String[] fi = jc.getFieldInfoName(indx);
1400 final int type = VarType.fromFieldType(fi[2].charAt(0));
1401 final String mangleClass = mangleClassName(fi[0]);
1402 final String mangleClassAccess = accessClassFalse(mangleClass);
1403 smapper.replace(this, type, "@2.call(@1)",
1405 accessField(mangleClassAccess,
1409 addReference(fi[0]);
1412 case opc_putfield: {
1413 int indx = readUShortArg(byteCodes, i);
1414 String[] fi = jc.getFieldInfoName(indx);
1415 final int type = VarType.fromFieldType(fi[2].charAt(0));
1416 final String mangleClass = mangleClassName(fi[0]);
1417 final String mangleClassAccess = accessClassFalse(mangleClass);
1418 emit(smapper, this, "@3.call(@2, @1);",
1421 accessField(mangleClassAccess,
1424 addReference(fi[0]);
1427 case opc_getstatic: {
1428 int indx = readUShortArg(byteCodes, i);
1429 String[] fi = jc.getFieldInfoName(indx);
1430 final int type = VarType.fromFieldType(fi[2].charAt(0));
1431 String ac = accessClassFalse(mangleClassName(fi[0]));
1432 String af = accessField(ac, "_" + fi[1], fi);
1433 smapper.assign(this, type, af + "()");
1435 addReference(fi[0]);
1438 case opc_putstatic: {
1439 int indx = readUShortArg(byteCodes, i);
1440 String[] fi = jc.getFieldInfoName(indx);
1441 final int type = VarType.fromFieldType(fi[2].charAt(0));
1442 emit(smapper, this, "@1._@2(@3);",
1443 accessClassFalse(mangleClassName(fi[0])), fi[1],
1444 smapper.popT(type));
1446 addReference(fi[0]);
1449 case opc_checkcast: {
1450 int indx = readUShortArg(byteCodes, i);
1451 generateCheckcast(indx, smapper);
1455 case opc_instanceof: {
1456 int indx = readUShortArg(byteCodes, i);
1457 generateInstanceOf(indx, smapper);
1462 final CharSequence v = smapper.popA();
1465 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1466 smapper.pushA(), v);
1470 case opc_monitorenter: {
1471 debug("/* monitor enter */");
1476 case opc_monitorexit: {
1477 debug("/* monitor exit */");
1488 emit(smapper, this, "throw 'unknown bytecode @1';",
1489 Integer.toString(c));
1493 generateByteCodeComment(prev, i, byteCodes);
1499 if (previousTrap != null) {
1500 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1505 while (openBraces-- > 0) {
1516 private int generateIf(StackMapper mapper, byte[] byteCodes,
1517 int i, final CharSequence v2, final CharSequence v1,
1518 final String test, int topMostLabel
1519 ) throws IOException {
1521 int indx = i + readShortArg(byteCodes, i);
1522 append("if ((").append(v1)
1523 .append(") ").append(test).append(" (")
1524 .append(v2).append(")) ");
1525 goTo(this, i, indx, topMostLabel);
1529 private int readInt4(byte[] byteCodes, int offset) {
1530 final int d = byteCodes[offset + 0] << 24;
1531 final int c = byteCodes[offset + 1] << 16;
1532 final int b = byteCodes[offset + 2] << 8;
1533 final int a = byteCodes[offset + 3];
1534 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1536 private static int readUByte(byte[] byteCodes, int offset) {
1537 return byteCodes[offset] & 0xff;
1540 private static int readUShort(byte[] byteCodes, int offset) {
1541 return ((byteCodes[offset] & 0xff) << 8)
1542 | (byteCodes[offset + 1] & 0xff);
1544 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1545 return readUShort(byteCodes, offsetInstruction + 1);
1548 private static int readShort(byte[] byteCodes, int offset) {
1549 int signed = byteCodes[offset];
1550 byte b0 = (byte)signed;
1551 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1553 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1554 return readShort(byteCodes, offsetInstruction + 1);
1557 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1559 Boolean count = null;
1560 boolean array = false;
1562 int firstPos = sig.length();
1563 while (i < descriptor.length()) {
1564 char ch = descriptor.charAt(i++);
1585 if (ch == 'J' || ch == 'D') {
1591 sig.insert(firstPos, ch);
1593 returnType[0] = '[';
1594 sig.insert(firstPos, "_3");
1603 returnType[0] = 'V';
1604 sig.insert(firstPos, 'V');
1607 int next = descriptor.indexOf(';', i);
1608 String realSig = mangleSig(descriptor, i - 1, next + 1);
1613 sig.append(realSig);
1616 sig.insert(firstPos, realSig);
1618 sig.insert(firstPos, "_3");
1620 returnType[0] = 'L';
1629 throw new IllegalStateException("Invalid char: " + ch);
1634 static String mangleSig(String sig) {
1635 return mangleSig(sig, 0, sig.length());
1638 private static String mangleMethodName(String name) {
1639 StringBuilder sb = new StringBuilder(name.length() * 2);
1640 int last = name.length();
1641 for (int i = 0; i < last; i++) {
1642 final char ch = name.charAt(i);
1644 case '_': sb.append("_1"); break;
1645 default: sb.append(ch); break;
1648 return sb.toString();
1650 private static String mangleSig(String txt, int first, int last) {
1651 StringBuilder sb = new StringBuilder((last - first) * 2);
1652 for (int i = first; i < last; i++) {
1653 final char ch = txt.charAt(i);
1655 case '/': sb.append('_'); break;
1656 case '_': sb.append("_1"); break;
1657 case ';': sb.append("_2"); break;
1658 case '[': sb.append("_3"); break;
1660 if (Character.isJavaIdentifierPart(ch)) {
1664 String hex = Integer.toHexString(ch).toLowerCase();
1665 for (int m = hex.length(); m < 4; m++) {
1673 return sb.toString();
1676 private static String mangleClassName(String name) {
1677 return mangleSig(name);
1680 private static String findMethodName(MethodData m, StringBuilder cnt) {
1681 StringBuilder name = new StringBuilder();
1682 if ("<init>".equals(m.getName())) { // NOI18N
1683 name.append("cons"); // NOI18N
1684 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1685 name.append("class"); // NOI18N
1687 name.append(mangleMethodName(m.getName()));
1690 countArgs(m.getInternalSig(), new char[1], name, cnt);
1691 return name.toString();
1694 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1695 StringBuilder name = new StringBuilder();
1696 String descr = mi[2];//mi.getDescriptor();
1698 if ("<init>".equals(nm)) { // NOI18N
1699 name.append("cons"); // NOI18N
1701 name.append(mangleMethodName(nm));
1703 countArgs(descr, returnType, name, cnt);
1704 return name.toString();
1707 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1708 throws IOException {
1709 int methodIndex = readUShortArg(byteCodes, i);
1710 String[] mi = jc.getFieldInfoName(methodIndex);
1711 char[] returnType = { 'V' };
1712 StringBuilder cnt = new StringBuilder();
1713 String mn = findMethodName(mi, cnt, returnType);
1715 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1716 final CharSequence[] vars = new CharSequence[numArguments];
1718 for (int j = numArguments - 1; j >= 0; --j) {
1719 vars[j] = mapper.popValue();
1723 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1724 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1726 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1727 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1729 if (vars[1] instanceof String) {
1730 String field = vars[1].toString();
1731 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1732 vars[1] = "c._" + field.substring(1, field.length() - 1);
1737 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1738 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1740 if (vars[1] instanceof String) {
1741 String field = vars[2].toString();
1742 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1743 vars[2] = "c._" + field.substring(1, field.length() - 1);
1748 if (returnType[0] != 'V') {
1751 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1755 final String in = mi[0];
1758 in.equals("org/apidesign/html/boot/spi/Fn") ||
1759 in.equals("org/netbeans/html/boot/spi/Fn")
1761 mcn = "java_lang_Class";
1763 mcn = mangleClassName(in);
1765 String object = accessClassFalse(mcn);
1766 if (mn.startsWith("cons_")) {
1767 object += ".constructor";
1769 append(accessStaticMethod(object, mn, mi));
1775 if (numArguments > 0) {
1777 for (int j = 1; j < numArguments; ++j) {
1787 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1788 throws IOException {
1789 int methodIndex = readUShortArg(byteCodes, i);
1790 String[] mi = jc.getFieldInfoName(methodIndex);
1791 char[] returnType = { 'V' };
1792 StringBuilder cnt = new StringBuilder();
1793 String mn = findMethodName(mi, cnt, returnType);
1795 final int numArguments = cnt.length() + 1;
1796 final CharSequence[] vars = new CharSequence[numArguments];
1798 for (int j = numArguments - 1; j >= 0; --j) {
1799 vars[j] = mapper.popValue();
1802 if (returnType[0] != 'V') {
1804 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1808 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1810 for (int j = 1; j < numArguments; ++j) {
1820 private void addReference(String cn) throws IOException {
1821 if (requireReference(cn)) {
1822 debug(" /* needs " + cn + " */");
1826 private void outType(String d, StringBuilder out) {
1828 while (d.charAt(0) == '[') {
1832 if (d.charAt(0) == 'L') {
1833 assert d.charAt(d.length() - 1) == ';';
1834 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1840 private String encodeConstant(int entryIndex) throws IOException {
1841 String[] classRef = { null };
1842 String s = jc.stringValue(entryIndex, classRef);
1843 if (classRef[0] != null) {
1844 if (classRef[0].startsWith("[")) {
1845 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1847 addReference(classRef[0]);
1848 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1854 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1855 byte[] arr = m.findAnnotationData(true);
1859 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1860 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1861 class P extends AnnotationParser {
1867 String[] args = new String[30];
1873 protected void visitAttr(String type, String attr, String at, String value) {
1874 if (type.equals(jvmType)) {
1875 if ("body".equals(attr)) {
1877 } else if ("args".equals(attr)) {
1878 args[cnt++] = value;
1880 throw new IllegalArgumentException(attr);
1883 if (type.equals(htmlType)) {
1885 if ("body".equals(attr)) {
1887 } else if ("args".equals(attr)) {
1888 args[cnt++] = value;
1889 } else if ("javacall".equals(attr)) {
1890 javacall = "1".equals(value);
1891 } else if ("wait4js".equals(attr)) {
1892 // ignore, we always invoke synchronously
1894 throw new IllegalArgumentException(attr);
1901 if (p.body == null) {
1904 StringBuilder cnt = new StringBuilder();
1905 final String mn = findMethodName(m, cnt);
1906 append("m = ").append(destObject).append(".").append(mn);
1907 append(" = function(");
1910 StringBuilder toValue = new StringBuilder();
1911 for (int i = 0; i < cnt.length(); i++) {
1913 space = outputArg(this, p.args, index);
1914 if (p.html4j && space.length() > 0) {
1915 toValue.append("\n ").append(p.args[index]).append(" = ")
1916 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1917 append(p.args[index]).append(");");
1921 append(") {").append("\n");
1922 append(toValue.toString());
1924 int lastSlash = jc.getClassName().lastIndexOf('/');
1925 final String pkg = jc.getClassName().substring(0, lastSlash);
1926 append(mangleCallbacks(pkg, p.body));
1927 requireReference(pkg + "/$JsCallbacks$");
1935 private static CharSequence mangleCallbacks(String pkgName, String body) {
1936 StringBuilder sb = new StringBuilder();
1939 int next = body.indexOf(".@", pos);
1941 sb.append(body.substring(pos));
1942 body = sb.toString();
1947 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1952 String refId = body.substring(ident, next);
1954 sb.append(body.substring(pos, ident));
1956 int sigBeg = body.indexOf('(', next);
1957 int sigEnd = body.indexOf(')', sigBeg);
1958 int colon4 = body.indexOf("::", next);
1959 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1960 throw new IllegalStateException("Malformed body " + body);
1962 String fqn = body.substring(next + 2, colon4);
1963 String method = body.substring(colon4 + 2, sigBeg);
1964 String params = body.substring(sigBeg, sigEnd + 1);
1966 int paramBeg = body.indexOf('(', sigEnd + 1);
1968 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1969 sb.append(mangleJsCallbacks(fqn, method, params, false));
1970 sb.append("(").append(refId);
1971 if (body.charAt(paramBeg + 1) != ')') {
1979 int next = body.indexOf("@", pos);
1984 sb.append(body.substring(pos));
1988 sb = new StringBuilder();
1991 sb.append(body.substring(pos, next));
1993 int sigBeg = body.indexOf('(', next);
1994 int sigEnd = body.indexOf(')', sigBeg);
1995 int colon4 = body.indexOf("::", next);
1996 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1997 throw new IllegalStateException("Malformed body " + body);
1999 String fqn = body.substring(next + 1, colon4);
2000 String method = body.substring(colon4 + 2, sigBeg);
2001 String params = body.substring(sigBeg, sigEnd + 1);
2003 int paramBeg = body.indexOf('(', sigEnd + 1);
2005 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2006 sb.append(mangleJsCallbacks(fqn, method, params, true));
2012 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2013 if (params.startsWith("(")) {
2014 params = params.substring(1);
2016 if (params.endsWith(")")) {
2017 params = params.substring(0, params.length() - 1);
2019 StringBuilder sb = new StringBuilder();
2020 final String fqnu = fqn.replace('.', '_');
2021 final String rfqn = mangleClassName(fqnu);
2022 final String rm = mangleMethodName(method);
2025 StringBuilder pb = new StringBuilder();
2026 int len = params.length();
2028 while (indx < len) {
2029 char ch = params.charAt(indx);
2030 if (ch == '[' || ch == 'L') {
2031 int column = params.indexOf(';', indx) + 1;
2032 if (column > indx) {
2033 String real = params.substring(indx, column);
2034 if ("Ljava/lang/String;".equals(real)) {
2035 pb.append("Ljava/lang/String;");
2040 pb.append("Ljava/lang/Object;");
2047 srp = mangleSig(pb.toString());
2049 final String rp = mangleSig(params);
2050 final String mrp = mangleMethodName(rp);
2051 sb.append(rfqn).append("$").append(rm).
2052 append('$').append(mrp).append("__Ljava_lang_Object_2");
2054 sb.append('L').append(fqnu).append("_2");
2057 return sb.toString();
2060 private static String className(ClassData jc) {
2061 //return jc.getName().getInternalName().replace('/', '_');
2062 return mangleClassName(jc.getClassName());
2065 private static String[] findAnnotation(
2066 byte[] arr, ClassData cd, final String className,
2067 final String... attrNames
2068 ) throws IOException {
2072 final String[] values = new String[attrNames.length];
2073 final boolean[] found = { false };
2074 final String jvmType = "L" + className.replace('.', '/') + ";";
2075 AnnotationParser ap = new AnnotationParser(false, true) {
2077 protected void visitAttr(String type, String attr, String at, String value) {
2078 if (type.equals(jvmType)) {
2080 for (int i = 0; i < attrNames.length; i++) {
2081 if (attrNames[i].equals(attr)) {
2090 return found[0] ? values : null;
2093 private CharSequence initField(FieldData v) {
2094 final String is = v.getInternalSig();
2095 if (is.length() == 1) {
2096 switch (is.charAt(0)) {
2102 case 'I': return " = 0;";
2104 case 'D': return " = 0.0;";
2106 throw new IllegalStateException(is);
2112 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2113 AnnotationParser ap = new AnnotationParser(true, false) {
2114 int[] cnt = new int[32];
2118 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2119 final String slashType = attrType.substring(1, attrType.length() - 1);
2120 requireReference(slashType);
2122 if (cnt[depth]++ > 0) {
2126 append('"').append(attrType).append("\" : ");
2133 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2139 protected void visitValueStart(String attrName, char type) throws IOException {
2140 if (cnt[depth]++ > 0) {
2144 if (attrName != null) {
2145 append('"').append(attrName).append("\" : ");
2153 protected void visitValueEnd(String attrName, char type) throws IOException {
2161 protected void visitAttr(String type, String attr, String attrType, String value)
2162 throws IOException {
2163 if (attr == null && value == null) {
2170 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2171 throws IOException {
2172 final String slashType = attrType.substring(1, attrType.length() - 1);
2173 requireReference(slashType);
2175 final String cn = mangleClassName(slashType);
2176 append(accessClassFalse(cn))
2177 .append("['valueOf__L").
2179 append("_2Ljava_lang_String_2']('").
2187 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2188 final String name = args[indx];
2192 if (name.contains(",")) {
2193 throw new IOException("Wrong parameter with ',': " + name);
2199 final void emitNoFlush(
2201 final String format, final CharSequence... params
2202 ) throws IOException {
2203 emitImpl(this, format, params);
2205 static final void emit(
2207 final Appendable out,
2208 final String format, final CharSequence... params
2209 ) throws IOException {
2211 emitImpl(out, format, params);
2213 static void emitImpl(final Appendable out,
2214 final String format,
2215 final CharSequence... params) throws IOException {
2216 final int length = format.length();
2219 int paramOffset = format.indexOf('@');
2220 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2221 final char paramChar = format.charAt(paramOffset + 1);
2222 if ((paramChar >= '1') && (paramChar <= '9')) {
2223 final int paramIndex = paramChar - '0' - 1;
2225 out.append(format, processed, paramOffset);
2226 out.append(params[paramIndex]);
2229 processed = paramOffset + 1;
2232 paramOffset = format.indexOf('@', paramOffset + 1);
2235 out.append(format, processed, length);
2238 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2239 append("} catch (e) {\n");
2241 for (TrapData e : traps) {
2245 if (e.catch_cpx != 0) { //not finally
2246 final String classInternalName = jc.getClassName(e.catch_cpx);
2247 addReference(classInternalName);
2248 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2249 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2250 append("var stA0 = e;");
2251 goTo(this, current, e.handler_pc, topMostLabel);
2254 finallyPC = e.handler_pc;
2257 if (finallyPC == -1) {
2260 append("var stA0 = e;");
2261 goTo(this, current, finallyPC, topMostLabel);
2266 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2269 out.append("{ gt = 0; continue X_" + to + "; }");
2271 out.append("{ gt = " + to + "; continue X_0; }");
2274 out.append("{ gt = " + to + "; break IF; }");
2278 private static void emitIf(
2280 Appendable out, String pattern,
2282 int current, int to, int canBack
2283 ) throws IOException {
2285 emitImpl(out, pattern, param);
2286 goTo(out, current, to, canBack);
2289 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2292 case 4: jvmType = "[Z"; break;
2293 case 5: jvmType = "[C"; break;
2294 case 6: jvmType = "[F"; break;
2295 case 7: jvmType = "[D"; break;
2296 case 8: jvmType = "[B"; break;
2297 case 9: jvmType = "[S"; break;
2298 case 10: jvmType = "[I"; break;
2299 case 11: jvmType = "[J"; break;
2300 default: throw new IllegalStateException("Array type: " + atype);
2303 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2304 smapper.popI(), smapper.pushA(), jvmType);
2307 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2308 String typeName = jc.getClassName(type);
2309 String ref = "null";
2310 if (typeName.startsWith("[")) {
2311 typeName = "'[" + typeName + "'";
2313 ref = "vm." + mangleClassName(typeName);
2314 typeName = "'[L" + typeName + ";'";
2317 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2318 smapper.popI(), smapper.pushA(), typeName, ref);
2321 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2322 String typeName = jc.getClassName(type);
2323 int dim = readUByte(byteCodes, ++i);
2324 StringBuilder dims = new StringBuilder();
2326 for (int d = 0; d < dim; d++) {
2328 dims.insert(1, ",");
2330 dims.insert(1, smapper.popI());
2334 if (typeName.charAt(dim) == 'L') {
2335 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2338 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2339 dims.toString(), smapper.pushA(), typeName, fn
2344 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2345 int table = i / 4 * 4 + 4;
2346 int dflt = i + readInt4(byteCodes, table);
2348 int low = readInt4(byteCodes, table);
2350 int high = readInt4(byteCodes, table);
2352 final CharSequence swVar = smapper.popValue();
2353 smapper.flush(this);
2354 append("switch (").append(swVar).append(") {\n");
2355 while (low <= high) {
2356 int offset = i + readInt4(byteCodes, table);
2358 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2361 append(" default: ");
2362 goTo(this, i, dflt, topMostLabel);
2368 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2369 int table = i / 4 * 4 + 4;
2370 int dflt = i + readInt4(byteCodes, table);
2372 int n = readInt4(byteCodes, table);
2374 final CharSequence swVar = smapper.popValue();
2375 smapper.flush(this);
2376 append("switch (").append(swVar).append(") {\n");
2378 int cnstnt = readInt4(byteCodes, table);
2380 int offset = i + readInt4(byteCodes, table);
2382 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2384 append(" default: ");
2385 goTo(this, i, dflt, topMostLabel);
2391 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2392 String type = jc.getClassName(indx);
2393 if (!type.startsWith("[")) {
2395 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2396 smapper.popA(), smapper.pushI(),
2397 type.replace('/', '_'));
2400 while (type.charAt(cnt) == '[') {
2403 if (type.charAt(cnt) == 'L') {
2404 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2406 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2407 smapper.popA(), smapper.pushI(),
2412 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2413 smapper.popA(), smapper.pushI(), type
2419 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2420 String type = jc.getClassName(indx);
2421 if (!type.startsWith("[")) {
2422 emitNoFlush(smapper,
2423 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2424 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2427 while (type.charAt(cnt) == '[') {
2430 if (type.charAt(cnt) == 'L') {
2431 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2432 emitNoFlush(smapper,
2433 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2434 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2437 emitNoFlush(smapper,
2438 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2439 smapper.getT(0, VarType.REFERENCE, false), type
2445 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2446 for (int j = prev; j <= i; j++) {
2448 final int cc = readUByte(byteCodes, j);
2449 append(Integer.toString(cc));
2453 @JavaScriptBody(args = "msg", body = "")
2454 private static void println(String msg) {
2455 System.err.println(msg);