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();
160 return compileImpl(cn);
161 } catch (IOException ex) {
162 throw new IOException("Cannot compile " + cn + ":", ex);
166 private String compileImpl(final String cn) throws IOException {
167 this.callbacks = cn.endsWith("/$JsCallbacks$");
168 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
169 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
170 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
173 byte[] arrData = jc.findAnnotationData(true);
175 String[] arr = findAnnotation(arrData, jc,
176 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
177 "resource", "processByteCode"
180 if (!arr[0].isEmpty()) {
181 requireScript(arr[0]);
183 if ("0".equals(arr[1])) {
188 final String jsResource;
190 String[] arr = findAnnotation(arrData, jc,
191 "net.java.html.js.JavaScriptResource",
195 if (arr[0].startsWith("/")) {
198 int last = cn.lastIndexOf('/');
199 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
205 String[] proto = findAnnotation(arrData, jc,
206 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
207 "container", "prototype"
209 StringArray toInitilize = new StringArray();
210 final String className = className(jc);
211 append("\n\n").append(assignClass(className));
212 append("function ").append(className).append("() {");
214 append("\n var CLS = ").append(className).append(';');
215 append("\n if (!CLS.$class) {");
217 String sc = jc.getSuperClassName(); // with _
218 append("\n var pp = ").
219 append(accessClass(mangleClassName(sc))).append("(true);");
220 append("\n var p = CLS.prototype = pp;");
221 append("\n var c = p;");
222 append("\n var sprcls = pp.constructor.$class;");
224 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
225 if (proto[0] == null) {
228 append("\n var c = ").append(proto[0]).append(";");
229 append("\n var sprcls = null;");
231 for (FieldData v : jc.getFields()) {
233 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
234 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
238 append("\n CLS.fld_").append(v.getName()).append(initField(v));
239 append("\n m = c._").append(v.getName()).append(" = function (v) {")
240 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
241 .append(" = v; return CLS.fld_").
242 append(v.getName()).append("; };");
244 append("\n m = c._").append(v.getName()).append(" = function (v) {")
245 .append(" if (arguments.length == 1) this.fld_").
246 append(className).append('_').append(v.getName())
247 .append(" = v; return this.fld_").
248 append(className).append('_').append(v.getName())
252 declaredField(v, "c", "_" + v.getName());
254 for (MethodData m : jc.getMethods()) {
255 byte[] onlyArr = m.findAnnotationData(true);
256 if (javaScriptOnly(onlyArr)) continue;
262 mn = generateStaticMethod(destObject, m, toInitilize);
264 if (m.isConstructor()) {
266 mn = generateInstanceMethod(destObject, m);
269 mn = generateInstanceMethod(destObject, m);
272 declaredMethod(m, destObject, mn);
273 byte[] runAnno = m.findAnnotationData(false);
274 if (runAnno != null) {
275 append("\n m.anno = {");
276 generateAnno(jc, runAnno);
279 append("\n m.access = " + m.getAccess()).append(";");
280 append("\n m.cls = CLS;");
282 append("\n c.constructor = CLS;");
283 append("\n function ").append(className).append("fillInstOf(x) {");
284 String instOfName = "$instOf_" + className;
285 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
286 if (jc.isInterface()) {
287 for (MethodData m : jc.getMethods()) {
288 if ((m.getAccess() & ACC_ABSTRACT) == 0
289 && (m.getAccess() & ACC_STATIC) == 0
290 && (m.getAccess() & ACC_PRIVATE) == 0) {
291 final String mn = findMethodName(m, new StringBuilder());
292 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
296 for (String superInterface : jc.getSuperInterfaces()) {
297 String intrfc = superInterface.replace('/', '_');
298 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
299 requireReference(superInterface);
302 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
303 append("\n ").append(className).append("fillInstOf(c);");
304 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
305 append("\n CLS.$class = 'temp';");
306 append("\n CLS.$class = ");
307 append(accessClass("java_lang_Class(true);"));
308 append("\n CLS.$class.jvmName = '").append(cn).append("';");
309 append("\n CLS.$class.superclass = sprcls;");
310 append("\n CLS.$class.interfaces = function() { return [");
312 boolean first = true;
313 for (String intrfc : jc.getSuperInterfaces()) {
317 requireReference(intrfc);
318 String mangledIface = mangleClassName(intrfc);
320 append(accessClass(mangledIface)).append("(false).constructor.$class");
325 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
326 append("\n CLS.$class.cnstr = CLS;");
327 byte[] classAnno = jc.findAnnotationData(false);
328 if (classAnno != null) {
329 append("\n CLS.$class.anno = {");
330 generateAnno(jc, classAnno);
333 for (String init : toInitilize.toArray()) {
334 append("\n ").append(init).append("();");
336 for (String ref : classRefs.toArray()) {
337 append("\n var refs_").append(ref).append(";");
341 if (jsResource != null) {
342 requireResource(jsResource);
346 append("\n if (arguments.length === 0) {");
347 append("\n if (!(this instanceof CLS)) {");
348 append("\n return new CLS();");
350 for (FieldData v : jc.getFields()) {
351 byte[] onlyArr = v.findAnnotationData(true);
352 if (javaScriptOnly(onlyArr)) continue;
354 append("\n this.fld_").
355 append(className).append('_').
356 append(v.getName()).append(initField(v));
359 append("\n return this;");
361 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
364 declaredClass(jc, className);
366 // StringBuilder sb = new StringBuilder();
367 // for (String init : toInitilize.toArray()) {
368 // sb.append("\n").append(init).append("();");
373 private boolean javaScriptOnly(byte[] anno) throws IOException {
374 String[] only = findAnnotation(anno, jc,
375 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
379 if (only[0] != null && only[1] != null) {
380 append("\n p.").append(only[0]).append(" = ")
381 .append(only[1]).append(";");
383 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
384 append("\n p['").append(only[0]).append("'] = p.")
385 .append(only[0]).append(";");
391 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
392 String jsb = javaScriptBody(destObject, m, true);
396 final String mn = findMethodName(m, new StringBuilder());
397 boolean defineProp = generateMethod(destObject, mn, m);
398 if (mn.equals("class__V")) {
400 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
402 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
408 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
409 String jsb = javaScriptBody(destObject, m, false);
413 final String mn = findMethodName(m, new StringBuilder());
414 generateMethod(destObject, mn, m);
418 private boolean generateMethod(String destObject, String name, MethodData m)
420 final StackMapIterator stackMapIterator = m.createStackMapIterator();
421 TrapDataIterator trap = m.getTrapDataIterator();
422 final LocalsMapper lmapper =
423 new LocalsMapper(stackMapIterator.getArguments());
426 "java/lang/Object".equals(jc.getClassName()) ||
427 "java/lang/reflect/Array".equals(jc.getClassName());
430 append("Object.defineProperty(").append(destObject).
431 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
433 append("m = ").append(destObject).append(".").append(name).append(" = function(");
435 lmapper.outputArguments(this, m.isStatic());
436 append(") {").append("\n");
438 final byte[] byteCodes = m.getCode();
439 if (byteCodes == null) {
440 append(" throw 'no code found for ")
441 .append(jc.getClassName()).append('.')
442 .append(m.getName()).append("';\n");
451 final StackMapper smapper = new StackMapper();
454 append(" var ").append(" lcA0 = this;\n");
458 TrapData[] previousTrap = null;
459 boolean wide = false;
461 if (stackMapIterator.isEmpty()) {
467 append("\n var gt = 0;\n");
471 int topMostLabel = 0;
472 for (int i = 0; i < byteCodes.length; i++) {
475 stackMapIterator.advanceTo(i);
476 boolean changeInCatch = trap.advanceTo(i);
477 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
478 if (previousTrap != null) {
479 generateCatch(previousTrap, i, topMostLabel);
483 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
488 if (openBraces > 64) {
489 for (int c = 0; c < 64; c++) {
496 lastStackFrame = stackMapIterator.getFrameIndex();
497 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
498 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
499 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
501 changeInCatch = true;
503 debug(" /* " + i + " */ ");
505 if (changeInCatch && trap.useTry()) {
507 previousTrap = trap.current();
509 final int c = readUByte(byteCodes, i);
512 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
515 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
518 smapper.assign(this, VarType.LONG, lmapper.getL(0));
521 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
524 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
527 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
530 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
533 smapper.assign(this, VarType.LONG, lmapper.getL(1));
536 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
539 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
542 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
545 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
548 smapper.assign(this, VarType.LONG, lmapper.getL(2));
551 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
554 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
557 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
560 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
563 smapper.assign(this, VarType.LONG, lmapper.getL(3));
566 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
569 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
573 final int indx = wide ? readUShort(byteCodes, i++)
574 : readUByte(byteCodes, i);
576 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
581 final int indx = wide ? readUShort(byteCodes, i++)
582 : readUByte(byteCodes, i);
584 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
589 final int indx = wide ? readUShort(byteCodes, i++)
590 : readUByte(byteCodes, i);
592 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
597 final int indx = wide ? readUShort(byteCodes, i++)
598 : readUByte(byteCodes, i);
600 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
605 final int indx = wide ? readUShort(byteCodes, i++)
606 : readUByte(byteCodes, i);
608 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
613 final int indx = wide ? readUShort(byteCodes, i++)
614 : readUByte(byteCodes, i);
616 emit(smapper, this, "var @1 = @2;",
617 lmapper.setI(indx), smapper.popI());
622 final int indx = wide ? readUShort(byteCodes, i++)
623 : readUByte(byteCodes, i);
625 emit(smapper, this, "var @1 = @2;",
626 lmapper.setL(indx), smapper.popL());
631 final int indx = wide ? readUShort(byteCodes, i++)
632 : readUByte(byteCodes, i);
634 emit(smapper, this, "var @1 = @2;",
635 lmapper.setF(indx), smapper.popF());
640 final int indx = wide ? readUShort(byteCodes, i++)
641 : readUByte(byteCodes, i);
643 emit(smapper, this, "var @1 = @2;",
644 lmapper.setD(indx), smapper.popD());
649 final int indx = wide ? readUShort(byteCodes, i++)
650 : readUByte(byteCodes, i);
652 emit(smapper, this, "var @1 = @2;",
653 lmapper.setA(indx), smapper.popA());
657 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
660 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
663 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
666 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
669 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
672 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
675 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
678 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
681 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
684 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
687 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
690 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
693 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
696 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
699 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
702 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
705 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
708 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
711 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
714 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
717 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
720 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
723 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
726 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
729 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
732 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
735 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
738 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
741 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
744 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
747 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
750 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
753 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
754 smapper.getI(1), smapper.popI());
757 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
758 smapper.getL(1), smapper.popL());
761 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
764 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
767 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
768 smapper.getI(1), smapper.popI());
771 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
772 smapper.getL(1), smapper.popL());
775 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
778 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
781 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
784 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
787 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
790 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
793 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
796 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
799 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
802 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
805 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
808 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
811 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
814 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
817 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
820 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
823 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
826 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
830 final int varIndx = wide ? readUShort(byteCodes, i++)
831 : readUByte(byteCodes, i);
833 final int incrBy = wide ? readShort(byteCodes, i++)
837 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
839 emit(smapper, this, "@1 += @2;",
840 lmapper.getI(varIndx),
841 Integer.toString(incrBy));
846 emit(smapper, this, "return;");
849 emit(smapper, this, "return @1;", smapper.popI());
852 emit(smapper, this, "return @1;", smapper.popL());
855 emit(smapper, this, "return @1;", smapper.popF());
858 emit(smapper, this, "return @1;", smapper.popD());
861 emit(smapper, this, "return @1;", smapper.popA());
864 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
867 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
870 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
873 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
877 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
880 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
883 smapper.replace(this, VarType.DOUBLE, "@1",
887 smapper.replace(this, VarType.FLOAT, "@1",
891 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
895 smapper.replace(this, VarType.LONG, "(@1).toLong()",
899 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
903 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
906 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
910 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
912 case opc_aconst_null:
913 smapper.assign(this, VarType.REFERENCE, "null");
916 smapper.assign(this, VarType.INTEGER, "-1");
919 smapper.assign(this, VarType.INTEGER, "0");
922 smapper.assign(this, VarType.DOUBLE, "0");
925 smapper.assign(this, VarType.LONG, "0");
928 smapper.assign(this, VarType.FLOAT, "0");
931 smapper.assign(this, VarType.INTEGER, "1");
934 smapper.assign(this, VarType.LONG, "1");
937 smapper.assign(this, VarType.FLOAT, "1");
940 smapper.assign(this, VarType.DOUBLE, "1");
943 smapper.assign(this, VarType.INTEGER, "2");
946 smapper.assign(this, VarType.FLOAT, "2");
949 smapper.assign(this, VarType.INTEGER, "3");
952 smapper.assign(this, VarType.INTEGER, "4");
955 smapper.assign(this, VarType.INTEGER, "5");
958 int indx = readUByte(byteCodes, ++i);
959 String v = encodeConstant(indx);
960 int type = VarType.fromConstantType(jc.getTag(indx));
961 smapper.assign(this, type, v);
966 int indx = readUShortArg(byteCodes, i);
968 String v = encodeConstant(indx);
969 int type = VarType.fromConstantType(jc.getTag(indx));
970 if (type == VarType.LONG) {
971 final Long lv = new Long(v);
972 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
973 final int hi = (int)(lv.longValue() >> 32);
975 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
977 smapper.assign(this, VarType.LONG,
978 "0x" + Integer.toHexString(hi) + ".next32(0x" +
979 Integer.toHexString(low) + ")"
983 smapper.assign(this, type, v);
988 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
992 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
993 smapper.popF(), smapper.popF(), smapper.pushI());
997 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
998 smapper.popD(), smapper.popD(), smapper.pushI());
1001 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1002 "===", topMostLabel);
1005 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1006 "!==", topMostLabel);
1009 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1010 "==", topMostLabel);
1013 int indx = i + readShortArg(byteCodes, i);
1014 emitIf(smapper, this, "if ((@1) == 0) ",
1015 smapper.popI(), i, indx, topMostLabel);
1020 int indx = i + readShortArg(byteCodes, i);
1021 emitIf(smapper, this, "if ((@1) != 0) ",
1022 smapper.popI(), i, indx, topMostLabel);
1027 int indx = i + readShortArg(byteCodes, i);
1028 emitIf(smapper, this, "if ((@1) < 0) ",
1029 smapper.popI(), i, indx, topMostLabel);
1034 int indx = i + readShortArg(byteCodes, i);
1035 emitIf(smapper, this, "if ((@1) <= 0) ",
1036 smapper.popI(), i, indx, topMostLabel);
1041 int indx = i + readShortArg(byteCodes, i);
1042 emitIf(smapper, this, "if ((@1) > 0) ",
1043 smapper.popI(), i, indx, topMostLabel);
1048 int indx = i + readShortArg(byteCodes, i);
1049 emitIf(smapper, this, "if ((@1) >= 0) ",
1050 smapper.popI(), i, indx, topMostLabel);
1054 case opc_ifnonnull: {
1055 int indx = i + readShortArg(byteCodes, i);
1056 emitIf(smapper, this, "if ((@1) !== null) ",
1057 smapper.popA(), i, indx, topMostLabel);
1062 int indx = i + readShortArg(byteCodes, i);
1063 emitIf(smapper, this, "if ((@1) === null) ",
1064 smapper.popA(), i, indx, topMostLabel);
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 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1085 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1086 ">=", topMostLabel);
1089 smapper.flush(this);
1090 int indx = i + readShortArg(byteCodes, i);
1091 goTo(this, i, indx, topMostLabel);
1095 case opc_lookupswitch: {
1096 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1099 case opc_tableswitch: {
1100 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1103 case opc_invokeinterface: {
1104 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1107 case opc_invokevirtual:
1108 i = invokeVirtualMethod(byteCodes, i, smapper);
1110 case opc_invokespecial:
1111 i = invokeStaticMethod(byteCodes, i, smapper, false);
1113 case opc_invokestatic:
1114 i = invokeStaticMethod(byteCodes, i, smapper, true);
1116 case opc_invokedynamic: {
1117 int indx = readUShortArg(byteCodes, i);
1118 println("invoke dynamic: " + indx);
1119 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1120 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1121 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1122 println(" type: " + methodHandle.cpx1);
1123 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1124 String mcn = mangleClassName(mi[0]);
1125 char[] returnType = {'V'};
1126 StringBuilder cnt = new StringBuilder();
1127 String mn = findMethodName(mi, cnt, returnType);
1128 StringBuilder sb = new StringBuilder();
1129 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1130 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1131 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1132 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1133 sb.append(" mn : ").append(mn).append("\n");
1134 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1135 throw new IOException(sb.toString());
1137 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1138 String type = jc.StringValue(nameAndType.cpx2);
1139 String object = accessClass(mcn) + "(false)";
1140 if (mn.startsWith("cons_")) {
1141 object += ".constructor";
1143 append("var metHan = ");
1144 append(accessStaticMethod(object, mn, mi));
1146 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1148 append(", '").append(mi[1]).append("', ");
1149 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1150 append(methodType).append("'").append(type).append("', null)");
1151 // if (numArguments > 0) {
1153 // for (int j = 1; j < numArguments; ++j) {
1159 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1165 int indx = readUShortArg(byteCodes, i);
1166 String ci = jc.getClassName(indx);
1167 emit(smapper, this, "var @1 = new @2;",
1168 smapper.pushA(), accessClass(mangleClassName(ci)));
1174 int atype = readUByte(byteCodes, ++i);
1175 generateNewArray(atype, smapper);
1177 case opc_anewarray: {
1178 int type = readUShortArg(byteCodes, i);
1180 generateANewArray(type, smapper);
1183 case opc_multianewarray: {
1184 int type = readUShortArg(byteCodes, i);
1186 i = generateMultiANewArray(type, byteCodes, i, smapper);
1189 case opc_arraylength:
1190 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1193 emit(smapper, this, "Array.at(@3, @2, @1);",
1194 smapper.popL(), smapper.popI(), smapper.popA());
1197 emit(smapper, this, "Array.at(@3, @2, @1);",
1198 smapper.popF(), smapper.popI(), smapper.popA());
1201 emit(smapper, this, "Array.at(@3, @2, @1);",
1202 smapper.popD(), smapper.popI(), smapper.popA());
1205 emit(smapper, this, "Array.at(@3, @2, @1);",
1206 smapper.popA(), smapper.popI(), smapper.popA());
1212 emit(smapper, this, "Array.at(@3, @2, @1);",
1213 smapper.popI(), smapper.popI(), smapper.popA());
1216 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1217 smapper.popI(), smapper.getA(0));
1220 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1221 smapper.popI(), smapper.getA(0));
1224 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1225 smapper.popI(), smapper.getA(0));
1228 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1229 smapper.popI(), smapper.getA(0));
1235 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1236 smapper.popI(), smapper.getA(0));
1244 final Variable v = smapper.get(0);
1245 if (smapper.isDirty()) {
1246 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1248 smapper.assign(this, v.getType(), v);
1253 final Variable vi1 = smapper.get(0);
1255 if (vi1.isCategory2()) {
1256 emit(smapper, this, "var @1 = @2;",
1257 smapper.pushT(vi1.getType()), vi1);
1259 final Variable vi2 = smapper.get(1);
1260 emit(smapper, this, "var @1 = @2, @3 = @4;",
1261 smapper.pushT(vi2.getType()), vi2,
1262 smapper.pushT(vi1.getType()), vi1);
1267 final Variable vi1 = smapper.pop(this);
1268 final Variable vi2 = smapper.pop(this);
1269 final Variable vo3 = smapper.pushT(vi1.getType());
1270 final Variable vo2 = smapper.pushT(vi2.getType());
1271 final Variable vo1 = smapper.pushT(vi1.getType());
1273 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1274 vo1, vi1, vo2, vi2, vo3, vo1);
1278 final Variable vi1 = smapper.pop(this);
1279 final Variable vi2 = smapper.pop(this);
1281 if (vi1.isCategory2()) {
1282 final Variable vo3 = smapper.pushT(vi1.getType());
1283 final Variable vo2 = smapper.pushT(vi2.getType());
1284 final Variable vo1 = smapper.pushT(vi1.getType());
1286 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1287 vo1, vi1, vo2, vi2, vo3, vo1);
1289 final Variable vi3 = smapper.pop(this);
1290 final Variable vo5 = smapper.pushT(vi2.getType());
1291 final Variable vo4 = smapper.pushT(vi1.getType());
1292 final Variable vo3 = smapper.pushT(vi3.getType());
1293 final Variable vo2 = smapper.pushT(vi2.getType());
1294 final Variable vo1 = smapper.pushT(vi1.getType());
1296 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1297 vo1, vi1, vo2, vi2, vo3, vi3);
1298 emit(smapper, this, " @1 = @2, @3 = @4;",
1299 vo4, vo1, vo5, vo2);
1304 final Variable vi1 = smapper.pop(this);
1305 final Variable vi2 = smapper.pop(this);
1307 if (vi2.isCategory2()) {
1308 final Variable vo3 = smapper.pushT(vi1.getType());
1309 final Variable vo2 = smapper.pushT(vi2.getType());
1310 final Variable vo1 = smapper.pushT(vi1.getType());
1312 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1313 vo1, vi1, vo2, vi2, vo3, vo1);
1315 final Variable vi3 = smapper.pop(this);
1316 final Variable vo4 = smapper.pushT(vi1.getType());
1317 final Variable vo3 = smapper.pushT(vi3.getType());
1318 final Variable vo2 = smapper.pushT(vi2.getType());
1319 final Variable vo1 = smapper.pushT(vi1.getType());
1321 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1322 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1327 final Variable vi1 = smapper.pop(this);
1328 final Variable vi2 = smapper.pop(this);
1330 if (vi1.isCategory2()) {
1331 if (vi2.isCategory2()) {
1332 final Variable vo3 = smapper.pushT(vi1.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;",
1337 vo1, vi1, vo2, vi2, vo3, vo1);
1339 final Variable vi3 = smapper.pop(this);
1340 final Variable vo4 = smapper.pushT(vi1.getType());
1341 final Variable vo3 = smapper.pushT(vi3.getType());
1342 final Variable vo2 = smapper.pushT(vi2.getType());
1343 final Variable vo1 = smapper.pushT(vi1.getType());
1345 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1346 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1349 final Variable vi3 = smapper.pop(this);
1351 if (vi3.isCategory2()) {
1352 final Variable vo5 = smapper.pushT(vi2.getType());
1353 final Variable vo4 = smapper.pushT(vi1.getType());
1354 final Variable vo3 = smapper.pushT(vi3.getType());
1355 final Variable vo2 = smapper.pushT(vi2.getType());
1356 final Variable vo1 = smapper.pushT(vi1.getType());
1358 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1359 vo1, vi1, vo2, vi2, vo3, vi3);
1360 emit(smapper, this, " @1 = @2, @3 = @4;",
1361 vo4, vo1, vo5, vo2);
1363 final Variable vi4 = smapper.pop(this);
1364 final Variable vo6 = smapper.pushT(vi2.getType());
1365 final Variable vo5 = smapper.pushT(vi1.getType());
1366 final Variable vo4 = smapper.pushT(vi4.getType());
1367 final Variable vo3 = smapper.pushT(vi3.getType());
1368 final Variable vo2 = smapper.pushT(vi2.getType());
1369 final Variable vo1 = smapper.pushT(vi1.getType());
1371 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1372 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1373 emit(smapper, this, " @1 = @2, @3 = @4;",
1374 vo5, vo1, vo6, vo2);
1380 final Variable vi1 = smapper.get(0);
1381 final Variable vi2 = smapper.get(1);
1383 if (vi1.getType() == vi2.getType()) {
1384 final Variable tmp = smapper.pushT(vi1.getType());
1386 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1391 smapper.pushT(vi1.getType());
1392 smapper.pushT(vi2.getType());
1397 smapper.assign(this, VarType.INTEGER,
1398 "(" + Integer.toString(byteCodes[++i]) + ")");
1401 smapper.assign(this, VarType.INTEGER,
1402 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1406 case opc_getfield: {
1407 int indx = readUShortArg(byteCodes, i);
1408 String[] fi = jc.getFieldInfoName(indx);
1409 final int type = VarType.fromFieldType(fi[2].charAt(0));
1410 final String mangleClass = mangleClassName(fi[0]);
1411 final String mangleClassAccess = accessClassFalse(mangleClass);
1412 smapper.replace(this, type, "@2.call(@1)",
1414 accessField(mangleClassAccess,
1418 addReference(fi[0]);
1421 case opc_putfield: {
1422 int indx = readUShortArg(byteCodes, i);
1423 String[] fi = jc.getFieldInfoName(indx);
1424 final int type = VarType.fromFieldType(fi[2].charAt(0));
1425 final String mangleClass = mangleClassName(fi[0]);
1426 final String mangleClassAccess = accessClassFalse(mangleClass);
1427 emit(smapper, this, "@3.call(@2, @1);",
1430 accessField(mangleClassAccess,
1433 addReference(fi[0]);
1436 case opc_getstatic: {
1437 int indx = readUShortArg(byteCodes, i);
1438 String[] fi = jc.getFieldInfoName(indx);
1439 final int type = VarType.fromFieldType(fi[2].charAt(0));
1440 String ac = accessClassFalse(mangleClassName(fi[0]));
1441 String af = accessField(ac, "_" + fi[1], fi);
1442 smapper.assign(this, type, af + "()");
1444 addReference(fi[0]);
1447 case opc_putstatic: {
1448 int indx = readUShortArg(byteCodes, i);
1449 String[] fi = jc.getFieldInfoName(indx);
1450 final int type = VarType.fromFieldType(fi[2].charAt(0));
1451 emit(smapper, this, "@1._@2(@3);",
1452 accessClassFalse(mangleClassName(fi[0])), fi[1],
1453 smapper.popT(type));
1455 addReference(fi[0]);
1458 case opc_checkcast: {
1459 int indx = readUShortArg(byteCodes, i);
1460 generateCheckcast(indx, smapper);
1464 case opc_instanceof: {
1465 int indx = readUShortArg(byteCodes, i);
1466 generateInstanceOf(indx, smapper);
1471 final CharSequence v = smapper.popA();
1474 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1475 smapper.pushA(), v);
1479 case opc_monitorenter: {
1480 debug("/* monitor enter */");
1485 case opc_monitorexit: {
1486 debug("/* monitor exit */");
1497 emit(smapper, this, "throw 'unknown bytecode @1';",
1498 Integer.toString(c));
1502 generateByteCodeComment(prev, i, byteCodes);
1508 if (previousTrap != null) {
1509 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1514 while (openBraces-- > 0) {
1525 private int generateIf(StackMapper mapper, byte[] byteCodes,
1526 int i, final CharSequence v2, final CharSequence v1,
1527 final String test, int topMostLabel
1528 ) throws IOException {
1530 int indx = i + readShortArg(byteCodes, i);
1531 append("if ((").append(v1)
1532 .append(") ").append(test).append(" (")
1533 .append(v2).append(")) ");
1534 goTo(this, i, indx, topMostLabel);
1538 private int readInt4(byte[] byteCodes, int offset) {
1539 final int d = byteCodes[offset + 0] << 24;
1540 final int c = byteCodes[offset + 1] << 16;
1541 final int b = byteCodes[offset + 2] << 8;
1542 final int a = byteCodes[offset + 3];
1543 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1545 private static int readUByte(byte[] byteCodes, int offset) {
1546 return byteCodes[offset] & 0xff;
1549 private static int readUShort(byte[] byteCodes, int offset) {
1550 return ((byteCodes[offset] & 0xff) << 8)
1551 | (byteCodes[offset + 1] & 0xff);
1553 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1554 return readUShort(byteCodes, offsetInstruction + 1);
1557 private static int readShort(byte[] byteCodes, int offset) {
1558 int signed = byteCodes[offset];
1559 byte b0 = (byte)signed;
1560 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1562 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1563 return readShort(byteCodes, offsetInstruction + 1);
1566 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1568 Boolean count = null;
1569 boolean array = false;
1571 int firstPos = sig.length();
1572 while (i < descriptor.length()) {
1573 char ch = descriptor.charAt(i++);
1594 if (ch == 'J' || ch == 'D') {
1600 sig.insert(firstPos, ch);
1602 returnType[0] = '[';
1603 sig.insert(firstPos, "_3");
1612 returnType[0] = 'V';
1613 sig.insert(firstPos, 'V');
1616 int next = descriptor.indexOf(';', i);
1617 String realSig = mangleSig(descriptor, i - 1, next + 1);
1622 sig.append(realSig);
1625 sig.insert(firstPos, realSig);
1627 sig.insert(firstPos, "_3");
1629 returnType[0] = 'L';
1638 throw new IllegalStateException("Invalid char: " + ch);
1643 static String mangleSig(String sig) {
1644 return mangleSig(sig, 0, sig.length());
1647 private static String mangleMethodName(String name) {
1648 StringBuilder sb = new StringBuilder(name.length() * 2);
1649 int last = name.length();
1650 for (int i = 0; i < last; i++) {
1651 final char ch = name.charAt(i);
1653 case '_': sb.append("_1"); break;
1654 default: sb.append(ch); break;
1657 return sb.toString();
1659 private static String mangleSig(String txt, int first, int last) {
1660 StringBuilder sb = new StringBuilder((last - first) * 2);
1661 for (int i = first; i < last; i++) {
1662 final char ch = txt.charAt(i);
1664 case '/': sb.append('_'); break;
1665 case '_': sb.append("_1"); break;
1666 case ';': sb.append("_2"); break;
1667 case '[': sb.append("_3"); break;
1669 if (Character.isJavaIdentifierPart(ch)) {
1673 String hex = Integer.toHexString(ch).toLowerCase();
1674 for (int m = hex.length(); m < 4; m++) {
1682 return sb.toString();
1685 private static String mangleClassName(String name) {
1686 return mangleSig(name);
1689 private static String findMethodName(MethodData m, StringBuilder cnt) {
1690 StringBuilder name = new StringBuilder();
1691 if ("<init>".equals(m.getName())) { // NOI18N
1692 name.append("cons"); // NOI18N
1693 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1694 name.append("class"); // NOI18N
1696 name.append(mangleMethodName(m.getName()));
1699 countArgs(m.getInternalSig(), new char[1], name, cnt);
1700 return name.toString();
1703 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1704 StringBuilder name = new StringBuilder();
1705 String descr = mi[2];//mi.getDescriptor();
1707 if ("<init>".equals(nm)) { // NOI18N
1708 name.append("cons"); // NOI18N
1710 name.append(mangleMethodName(nm));
1712 countArgs(descr, returnType, name, cnt);
1713 return name.toString();
1716 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1717 throws IOException {
1718 int methodIndex = readUShortArg(byteCodes, i);
1719 String[] mi = jc.getFieldInfoName(methodIndex);
1720 char[] returnType = { 'V' };
1721 StringBuilder cnt = new StringBuilder();
1722 String mn = findMethodName(mi, cnt, returnType);
1724 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1725 final CharSequence[] vars = new CharSequence[numArguments];
1727 for (int j = numArguments - 1; j >= 0; --j) {
1728 vars[j] = mapper.popValue();
1732 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1733 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1735 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1736 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1738 if (vars[1] instanceof String) {
1739 String field = vars[1].toString();
1740 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1741 vars[1] = "c._" + field.substring(1, field.length() - 1);
1746 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1747 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1749 if (vars[1] instanceof String) {
1750 String field = vars[2].toString();
1751 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1752 vars[2] = "c._" + field.substring(1, field.length() - 1);
1757 if (returnType[0] != 'V') {
1760 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1764 final String in = mi[0];
1767 in.equals("org/apidesign/html/boot/spi/Fn") ||
1768 in.equals("org/netbeans/html/boot/spi/Fn")
1770 mcn = "java_lang_Class";
1772 mcn = mangleClassName(in);
1774 String object = accessClassFalse(mcn);
1775 if (mn.startsWith("cons_")) {
1776 object += ".constructor";
1778 append(accessStaticMethod(object, mn, mi));
1784 if (numArguments > 0) {
1786 for (int j = 1; j < numArguments; ++j) {
1796 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1797 throws IOException {
1798 int methodIndex = readUShortArg(byteCodes, i);
1799 String[] mi = jc.getFieldInfoName(methodIndex);
1800 char[] returnType = { 'V' };
1801 StringBuilder cnt = new StringBuilder();
1802 String mn = findMethodName(mi, cnt, returnType);
1804 final int numArguments = cnt.length() + 1;
1805 final CharSequence[] vars = new CharSequence[numArguments];
1807 for (int j = numArguments - 1; j >= 0; --j) {
1808 vars[j] = mapper.popValue();
1811 if (returnType[0] != 'V') {
1814 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1818 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1820 for (int j = 1; j < numArguments; ++j) {
1830 private void addReference(String cn) throws IOException {
1831 if (requireReference(cn)) {
1832 debug(" /* needs " + cn + " */");
1836 private void outType(String d, StringBuilder out) {
1838 while (d.charAt(0) == '[') {
1842 if (d.charAt(0) == 'L') {
1843 assert d.charAt(d.length() - 1) == ';';
1844 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1850 private String encodeConstant(int entryIndex) throws IOException {
1851 String[] classRef = { null };
1852 String s = jc.stringValue(entryIndex, classRef);
1853 if (classRef[0] != null) {
1854 if (classRef[0].startsWith("[")) {
1855 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1857 addReference(classRef[0]);
1858 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1864 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1865 byte[] arr = m.findAnnotationData(true);
1869 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1870 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1871 class P extends AnnotationParser {
1877 String[] args = new String[30];
1883 protected void visitAttr(String type, String attr, String at, String value) {
1884 if (type.equals(jvmType)) {
1885 if ("body".equals(attr)) {
1887 } else if ("args".equals(attr)) {
1888 args[cnt++] = value;
1890 throw new IllegalArgumentException(attr);
1893 if (type.equals(htmlType)) {
1895 if ("body".equals(attr)) {
1897 } else if ("args".equals(attr)) {
1898 args[cnt++] = value;
1899 } else if ("javacall".equals(attr)) {
1900 javacall = "1".equals(value);
1901 } else if ("wait4js".equals(attr)) {
1902 // ignore, we always invoke synchronously
1904 throw new IllegalArgumentException(attr);
1911 if (p.body == null) {
1914 StringBuilder cnt = new StringBuilder();
1915 final String mn = findMethodName(m, cnt);
1916 append("m = ").append(destObject).append(".").append(mn);
1917 append(" = function(");
1920 StringBuilder toValue = new StringBuilder();
1921 for (int i = 0; i < cnt.length(); i++) {
1923 space = outputArg(this, p.args, index);
1924 if (p.html4j && space.length() > 0) {
1925 toValue.append("\n ").append(p.args[index]).append(" = ")
1926 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1927 append(p.args[index]).append(");");
1931 append(") {").append("\n");
1932 append(toValue.toString());
1934 int lastSlash = jc.getClassName().lastIndexOf('/');
1935 final String pkg = jc.getClassName().substring(0, lastSlash);
1936 append(mangleCallbacks(pkg, p.body));
1937 requireReference(pkg + "/$JsCallbacks$");
1945 private static CharSequence mangleCallbacks(String pkgName, String body) {
1946 StringBuilder sb = new StringBuilder();
1949 int next = body.indexOf(".@", pos);
1951 sb.append(body.substring(pos));
1952 body = sb.toString();
1957 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1962 String refId = body.substring(ident, next);
1964 sb.append(body.substring(pos, ident));
1966 int sigBeg = body.indexOf('(', next);
1967 int sigEnd = body.indexOf(')', sigBeg);
1968 int colon4 = body.indexOf("::", next);
1969 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1970 throw new IllegalStateException("Malformed body " + body);
1972 String fqn = body.substring(next + 2, colon4);
1973 String method = body.substring(colon4 + 2, sigBeg);
1974 String params = body.substring(sigBeg, sigEnd + 1);
1976 int paramBeg = body.indexOf('(', sigEnd + 1);
1978 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1979 sb.append(mangleJsCallbacks(fqn, method, params, false));
1980 sb.append("(").append(refId);
1981 if (body.charAt(paramBeg + 1) != ')') {
1989 int next = body.indexOf("@", pos);
1994 sb.append(body.substring(pos));
1998 sb = new StringBuilder();
2001 sb.append(body.substring(pos, next));
2003 int sigBeg = body.indexOf('(', next);
2004 int sigEnd = body.indexOf(')', sigBeg);
2005 int colon4 = body.indexOf("::", next);
2006 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2007 throw new IllegalStateException("Malformed body " + body);
2009 String fqn = body.substring(next + 1, colon4);
2010 String method = body.substring(colon4 + 2, sigBeg);
2011 String params = body.substring(sigBeg, sigEnd + 1);
2013 int paramBeg = body.indexOf('(', sigEnd + 1);
2015 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2016 sb.append(mangleJsCallbacks(fqn, method, params, true));
2022 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2023 if (params.startsWith("(")) {
2024 params = params.substring(1);
2026 if (params.endsWith(")")) {
2027 params = params.substring(0, params.length() - 1);
2029 StringBuilder sb = new StringBuilder();
2030 final String fqnu = fqn.replace('.', '_');
2031 final String rfqn = mangleClassName(fqnu);
2032 final String rm = mangleMethodName(method);
2035 StringBuilder pb = new StringBuilder();
2036 int len = params.length();
2038 while (indx < len) {
2039 char ch = params.charAt(indx);
2040 if (ch == '[' || ch == 'L') {
2041 int column = params.indexOf(';', indx) + 1;
2042 if (column > indx) {
2043 String real = params.substring(indx, column);
2044 if ("Ljava/lang/String;".equals(real)) {
2045 pb.append("Ljava/lang/String;");
2050 pb.append("Ljava/lang/Object;");
2057 srp = mangleSig(pb.toString());
2059 final String rp = mangleSig(params);
2060 final String mrp = mangleMethodName(rp);
2061 sb.append(rfqn).append("$").append(rm).
2062 append('$').append(mrp).append("__Ljava_lang_Object_2");
2064 sb.append('L').append(fqnu).append("_2");
2067 return sb.toString();
2070 private static String className(ClassData jc) {
2071 //return jc.getName().getInternalName().replace('/', '_');
2072 return mangleClassName(jc.getClassName());
2075 private static String[] findAnnotation(
2076 byte[] arr, ClassData cd, final String className,
2077 final String... attrNames
2078 ) throws IOException {
2082 final String[] values = new String[attrNames.length];
2083 final boolean[] found = { false };
2084 final String jvmType = "L" + className.replace('.', '/') + ";";
2085 AnnotationParser ap = new AnnotationParser(false, true) {
2087 protected void visitAttr(String type, String attr, String at, String value) {
2088 if (type.equals(jvmType)) {
2090 for (int i = 0; i < attrNames.length; i++) {
2091 if (attrNames[i].equals(attr)) {
2100 return found[0] ? values : null;
2103 private CharSequence initField(FieldData v) {
2104 final String is = v.getInternalSig();
2105 if (is.length() == 1) {
2106 switch (is.charAt(0)) {
2112 case 'I': return " = 0;";
2114 case 'D': return " = 0.0;";
2116 throw new IllegalStateException(is);
2122 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2123 AnnotationParser ap = new AnnotationParser(true, false) {
2124 int[] cnt = new int[32];
2128 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2129 final String slashType = attrType.substring(1, attrType.length() - 1);
2130 requireReference(slashType);
2132 if (cnt[depth]++ > 0) {
2136 append('"').append(attrType).append("\" : ");
2143 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2149 protected void visitValueStart(String attrName, char type) throws IOException {
2150 if (cnt[depth]++ > 0) {
2154 if (attrName != null) {
2155 append('"').append(attrName).append("\" : ");
2163 protected void visitValueEnd(String attrName, char type) throws IOException {
2171 protected void visitAttr(String type, String attr, String attrType, String value)
2172 throws IOException {
2173 if (attr == null && value == null) {
2180 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2181 throws IOException {
2182 final String slashType = attrType.substring(1, attrType.length() - 1);
2183 requireReference(slashType);
2185 final String cn = mangleClassName(slashType);
2186 append(accessClassFalse(cn))
2187 .append("['valueOf__L").
2189 append("_2Ljava_lang_String_2']('").
2197 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2198 final String name = args[indx];
2202 if (name.contains(",")) {
2203 throw new IOException("Wrong parameter with ',': " + name);
2209 final void emitNoFlush(
2211 final String format, final CharSequence... params
2212 ) throws IOException {
2213 emitImpl(this, format, params);
2215 static final void emit(
2217 final Appendable out,
2218 final String format, final CharSequence... params
2219 ) throws IOException {
2221 emitImpl(out, format, params);
2223 static void emitImpl(final Appendable out,
2224 final String format,
2225 final CharSequence... params) throws IOException {
2226 final int length = format.length();
2229 int paramOffset = format.indexOf('@');
2230 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2231 final char paramChar = format.charAt(paramOffset + 1);
2232 if ((paramChar >= '1') && (paramChar <= '9')) {
2233 final int paramIndex = paramChar - '0' - 1;
2235 out.append(format, processed, paramOffset);
2236 out.append(params[paramIndex]);
2239 processed = paramOffset + 1;
2242 paramOffset = format.indexOf('@', paramOffset + 1);
2245 out.append(format, processed, length);
2248 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2249 append("} catch (e) {\n");
2251 for (TrapData e : traps) {
2255 if (e.catch_cpx != 0) { //not finally
2256 final String classInternalName = jc.getClassName(e.catch_cpx);
2257 addReference(classInternalName);
2258 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2259 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2260 append("var stA0 = e;");
2261 goTo(this, current, e.handler_pc, topMostLabel);
2264 finallyPC = e.handler_pc;
2267 if (finallyPC == -1) {
2270 append("var stA0 = e;");
2271 goTo(this, current, finallyPC, topMostLabel);
2276 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2279 out.append("{ gt = 0; continue X_" + to + "; }");
2281 out.append("{ gt = " + to + "; continue X_0; }");
2284 out.append("{ gt = " + to + "; break IF; }");
2288 private static void emitIf(
2290 Appendable out, String pattern,
2292 int current, int to, int canBack
2293 ) throws IOException {
2295 emitImpl(out, pattern, param);
2296 goTo(out, current, to, canBack);
2299 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2302 case 4: jvmType = "[Z"; break;
2303 case 5: jvmType = "[C"; break;
2304 case 6: jvmType = "[F"; break;
2305 case 7: jvmType = "[D"; break;
2306 case 8: jvmType = "[B"; break;
2307 case 9: jvmType = "[S"; break;
2308 case 10: jvmType = "[I"; break;
2309 case 11: jvmType = "[J"; break;
2310 default: throw new IllegalStateException("Array type: " + atype);
2313 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2314 smapper.popI(), smapper.pushA(), jvmType);
2317 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2318 String typeName = jc.getClassName(type);
2319 String ref = "null";
2320 if (typeName.startsWith("[")) {
2321 typeName = "'[" + typeName + "'";
2323 ref = "vm." + mangleClassName(typeName);
2324 typeName = "'[L" + typeName + ";'";
2327 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2328 smapper.popI(), smapper.pushA(), typeName, ref);
2331 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2332 String typeName = jc.getClassName(type);
2333 int dim = readUByte(byteCodes, ++i);
2334 StringBuilder dims = new StringBuilder();
2336 for (int d = 0; d < dim; d++) {
2338 dims.insert(1, ",");
2340 dims.insert(1, smapper.popI());
2344 if (typeName.charAt(dim) == 'L') {
2345 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2348 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2349 dims.toString(), smapper.pushA(), typeName, fn
2354 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2355 int table = i / 4 * 4 + 4;
2356 int dflt = i + readInt4(byteCodes, table);
2358 int low = readInt4(byteCodes, table);
2360 int high = readInt4(byteCodes, table);
2362 final CharSequence swVar = smapper.popValue();
2363 smapper.flush(this);
2364 append("switch (").append(swVar).append(") {\n");
2365 while (low <= high) {
2366 int offset = i + readInt4(byteCodes, table);
2368 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2371 append(" default: ");
2372 goTo(this, i, dflt, topMostLabel);
2378 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2379 int table = i / 4 * 4 + 4;
2380 int dflt = i + readInt4(byteCodes, table);
2382 int n = readInt4(byteCodes, table);
2384 final CharSequence swVar = smapper.popValue();
2385 smapper.flush(this);
2386 append("switch (").append(swVar).append(") {\n");
2388 int cnstnt = readInt4(byteCodes, table);
2390 int offset = i + readInt4(byteCodes, table);
2392 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2394 append(" default: ");
2395 goTo(this, i, dflt, topMostLabel);
2401 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2402 String type = jc.getClassName(indx);
2403 if (!type.startsWith("[")) {
2405 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2406 smapper.popA(), smapper.pushI(),
2407 type.replace('/', '_'));
2410 while (type.charAt(cnt) == '[') {
2413 if (type.charAt(cnt) == 'L') {
2414 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2416 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2417 smapper.popA(), smapper.pushI(),
2422 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2423 smapper.popA(), smapper.pushI(), type
2429 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2430 String type = jc.getClassName(indx);
2431 if (!type.startsWith("[")) {
2432 emitNoFlush(smapper,
2433 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2434 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2437 while (type.charAt(cnt) == '[') {
2440 if (type.charAt(cnt) == 'L') {
2441 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2442 emitNoFlush(smapper,
2443 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2444 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2447 emitNoFlush(smapper,
2448 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2449 smapper.getT(0, VarType.REFERENCE, false), type
2455 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2456 for (int j = prev; j <= i; j++) {
2458 final int cc = readUByte(byteCodes, j);
2459 append(Integer.toString(cc));
2463 @JavaScriptBody(args = "msg", body = "")
2464 private static void println(String msg) {
2465 System.err.println(msg);