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.*;
24 import org.apidesign.vm4brwsr.ByteCodeParser.AnnotationParser;
25 import org.apidesign.vm4brwsr.ByteCodeParser.BootMethodData;
26 import org.apidesign.vm4brwsr.ByteCodeParser.CPX2;
27 import org.apidesign.vm4brwsr.ByteCodeParser.ClassData;
28 import org.apidesign.vm4brwsr.ByteCodeParser.FieldData;
29 import org.apidesign.vm4brwsr.ByteCodeParser.MethodData;
30 import org.apidesign.vm4brwsr.ByteCodeParser.StackMapIterator;
31 import org.apidesign.vm4brwsr.ByteCodeParser.TrapData;
32 import org.apidesign.vm4brwsr.ByteCodeParser.TrapDataIterator;
34 /** Translator of the code inside class files to JavaScript.
36 * @author Jaroslav Tulach <jtulach@netbeans.org>
38 abstract class ByteCodeToJavaScript implements Appendable {
40 private final Appendable out;
41 private final StringArray classRefs = new StringArray();
42 private boolean outChanged;
43 private boolean callbacks;
45 protected ByteCodeToJavaScript(Appendable out) {
50 public final Appendable append(CharSequence csq) throws IOException {
57 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
58 out.append(csq, start, end);
64 public final Appendable append(char c) throws IOException {
70 /* Collects additional required resources.
72 * @param internalClassName classes that were referenced and should be loaded in order the
73 * generated JavaScript code works properly. The names are in internal
74 * JVM form so String is <code>java/lang/String</code>.
76 protected abstract boolean requireReference(String internalClassName);
79 * @param resourcePath name of resources to read
81 protected abstract void requireScript(String resourcePath) throws IOException;
83 protected abstract void requireResource(String resourcePath) throws IOException;
85 /** Allows subclasses to redefine what field a function representing a
86 * class gets assigned. By default it returns the suggested name followed
87 * by <code>" = "</code>;
89 * @param className suggested name of the class
91 /* protected */ String assignClass(String className) {
92 return className + " = ";
94 /* protected */ String accessClass(String classOperation) {
95 return classOperation;
98 final String accessClassFalse(String classOperation) {
99 if (mangleClassName(jc.getClassName()).equals(classOperation)) {
102 classRefs.addIfMissing(classOperation);
103 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
106 protected String accessField(String object, String mangledName,
107 String[] fieldInfoName) throws IOException {
108 return object + "." + mangledName;
111 protected String accessStaticMethod(
114 String[] fieldInfoName) throws IOException {
115 return object + "." + mangledName;
118 protected String accessVirtualMethod(
121 String[] fieldInfoName,
123 ) throws IOException {
124 return object + "." + mangledName + '(';
127 protected void declaredClass(ClassData classData, String mangledName)
131 protected void declaredField(FieldData fieldData,
133 String mangledName) throws IOException {
136 protected void declaredMethod(MethodData methodData,
138 String mangledName) throws IOException {
141 /** Prints out a debug message.
143 * @param msg the message
144 * @return true if the message has been printed
145 * @throws IOException
147 boolean debug(String msg) throws IOException {
153 * Converts a given class file to a JavaScript version.
155 * @param classFile input stream with code of the .class file
156 * @return the initialization code for this class, if any. Otherwise <code>null</code>
158 * @throws IOException if something goes wrong during read or write or translating
161 public String compile(InputStream classFile) throws IOException {
162 return compile(new ClassData(classFile));
165 protected String compile(ClassData classData) throws IOException {
167 final String cn = this.jc.getClassName();
169 return compileImpl(cn);
170 } catch (IOException ex) {
171 throw new IOException("Cannot compile " + cn + ":", ex);
175 private String compileImpl(final String cn) throws IOException {
176 this.callbacks = cn.endsWith("/$JsCallbacks$");
177 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
178 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
179 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
182 byte[] arrData = jc.findAnnotationData(true);
184 String[] arr = findAnnotation(arrData, jc,
185 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
186 "resource", "processByteCode"
189 if (!arr[0].isEmpty()) {
190 requireScript(arr[0]);
192 if ("0".equals(arr[1])) {
197 final String jsResource;
199 String[] arr = findAnnotation(arrData, jc,
200 "net.java.html.js.JavaScriptResource",
204 if (arr[0].startsWith("/")) {
207 int last = cn.lastIndexOf('/');
208 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
214 String[] proto = findAnnotation(arrData, jc,
215 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
216 "container", "prototype"
218 StringArray toInitilize = new StringArray();
219 final String className = className(jc);
220 append("\n\n").append(assignClass(className));
221 append("function ").append(className).append("() {");
223 append("\n var CLS = ").append(className).append(';');
224 append("\n if (!CLS.$class) {");
226 String sc = jc.getSuperClassName(); // with _
227 append("\n var pp = ").
228 append(accessClass(mangleClassName(sc))).append("(true);");
229 append("\n var p = CLS.prototype = pp;");
230 append("\n var c = p;");
231 append("\n var sprcls = pp.constructor.$class;");
233 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
234 if (proto[0] == null) {
237 append("\n var c = ").append(proto[0]).append(";");
238 append("\n var sprcls = null;");
240 for (FieldData v : jc.getFields()) {
242 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
243 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
247 append("\n CLS.fld_").append(v.getName()).append(initField(v));
248 append("\n m = c._").append(v.getName()).append(" = function (v) {")
249 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
250 .append(" = v; return CLS.fld_").
251 append(v.getName()).append("; };");
253 append("\n m = c._").append(v.getName()).append(" = function (v) {")
254 .append(" if (arguments.length == 1) this.fld_").
255 append(className).append('_').append(v.getName())
256 .append(" = v; return this.fld_").
257 append(className).append('_').append(v.getName())
261 declaredField(v, "c", "_" + v.getName());
263 for (MethodData m : jc.getMethods()) {
264 byte[] onlyArr = m.findAnnotationData(true);
265 if (javaScriptOnly(onlyArr)) continue;
271 mn = generateStaticMethod(destObject, m, toInitilize);
273 if (m.isConstructor()) {
275 mn = generateInstanceMethod(destObject, m);
278 mn = generateInstanceMethod(destObject, m);
281 declaredMethod(m, destObject, mn);
282 byte[] runAnno = m.findAnnotationData(false);
283 if (runAnno != null) {
284 append("\n m.anno = {");
285 generateAnno(jc, runAnno);
288 append("\n m.access = " + m.getAccess()).append(";");
289 append("\n m.cls = CLS;");
291 append("\n c.constructor = CLS;");
292 append("\n function ").append(className).append("fillInstOf(x) {");
293 String instOfName = "$instOf_" + className;
294 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
295 if (jc.isInterface()) {
296 for (MethodData m : jc.getMethods()) {
297 if ((m.getAccess() & ACC_ABSTRACT) == 0
298 && (m.getAccess() & ACC_STATIC) == 0
299 && (m.getAccess() & ACC_PRIVATE) == 0) {
300 final String mn = findMethodName(m, new StringBuilder());
301 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
305 for (String superInterface : jc.getSuperInterfaces()) {
306 String intrfc = mangleClassName(superInterface);
307 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
308 requireReference(superInterface);
311 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
312 append("\n ").append(className).append("fillInstOf(c);");
313 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
314 append("\n CLS.$class = 'temp';");
315 append("\n CLS.$class = ");
316 append(accessClass("java_lang_Class(true);"));
317 append("\n CLS.$class.jvmName = '").append(cn).append("';");
318 append("\n CLS.$class.superclass = sprcls;");
319 append("\n CLS.$class.interfaces = function() { return [");
321 boolean first = true;
322 for (String intrfc : jc.getSuperInterfaces()) {
326 requireReference(intrfc);
327 String mangledIface = mangleClassName(intrfc);
329 append(accessClass(mangledIface)).append("(false).constructor.$class");
334 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
335 append("\n CLS.$class.cnstr = CLS;");
336 byte[] classAnno = jc.findAnnotationData(false);
337 if (classAnno != null) {
338 append("\n CLS.$class.anno = {");
339 generateAnno(jc, classAnno);
342 for (String init : toInitilize.toArray()) {
343 append("\n ").append(init).append("();");
345 for (String ref : classRefs.toArray()) {
346 append("\n var refs_").append(ref).append(";");
350 if (jsResource != null) {
351 requireResource(jsResource);
355 append("\n if (arguments.length === 0) {");
356 append("\n if (!(this instanceof CLS)) {");
357 append("\n return new CLS();");
359 for (FieldData v : jc.getFields()) {
360 byte[] onlyArr = v.findAnnotationData(true);
361 if (javaScriptOnly(onlyArr)) continue;
363 append("\n this.fld_").
364 append(className).append('_').
365 append(v.getName()).append(initField(v));
368 append("\n return this;");
370 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
373 declaredClass(jc, className);
375 // StringBuilder sb = new StringBuilder();
376 // for (String init : toInitilize.toArray()) {
377 // sb.append("\n").append(init).append("();");
382 private boolean javaScriptOnly(byte[] anno) throws IOException {
383 String[] only = findAnnotation(anno, jc,
384 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
388 if (only[0] != null && only[1] != null) {
389 append("\n p.").append(only[0]).append(" = ")
390 .append(only[1]).append(";");
392 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
393 append("\n p['").append(only[0]).append("'] = p.")
394 .append(only[0]).append(";");
400 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
401 String jsb = javaScriptBody(destObject, m, true);
405 final String mn = findMethodName(m, new StringBuilder());
406 boolean defineProp = generateMethod(destObject, mn, m);
407 if (mn.equals("class__V")) {
409 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
411 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
417 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
418 String jsb = javaScriptBody(destObject, m, false);
422 final String mn = findMethodName(m, new StringBuilder());
423 generateMethod(destObject, mn, m);
427 private boolean generateMethod(String destObject, String name, MethodData m)
429 final StackMapIterator stackMapIterator = m.createStackMapIterator();
430 TrapDataIterator trap = m.getTrapDataIterator();
431 final LocalsMapper lmapper =
432 new LocalsMapper(stackMapIterator.getArguments());
435 "java/lang/Object".equals(jc.getClassName()) ||
436 "java/lang/reflect/Array".equals(jc.getClassName());
439 append("Object.defineProperty(").append(destObject).
440 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
442 append("m = ").append(destObject).append(".").append(name).append(" = function(");
444 lmapper.outputArguments(this, m.isStatic());
445 append(") {").append("\n");
447 final byte[] byteCodes = m.getCode();
448 if (byteCodes == null) {
449 if (debug(" throw 'no code found for ")) {
451 .append(jc.getClassName()).append('.')
452 .append(m.getName()).append("';\n");
462 final StackMapper smapper = new StackMapper();
465 append(" var ").append(" lcA0 = this;\n");
469 TrapData[] previousTrap = null;
470 boolean wide = false;
472 if (stackMapIterator.isEmpty()) {
478 append("\n var gt = 0;\n");
482 int topMostLabel = 0;
483 for (int i = 0; i < byteCodes.length; i++) {
486 stackMapIterator.advanceTo(i);
487 boolean changeInCatch = trap.advanceTo(i);
488 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
489 if (previousTrap != null) {
490 generateCatch(previousTrap, i, topMostLabel);
494 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
499 if (openBraces > 64) {
500 for (int c = 0; c < 64; c++) {
507 lastStackFrame = stackMapIterator.getFrameIndex();
508 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
509 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
510 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
512 changeInCatch = true;
514 debug(" /* " + i + " */ ");
516 if (changeInCatch && trap.useTry()) {
518 previousTrap = trap.current();
520 final int c = readUByte(byteCodes, i);
523 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
526 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
529 smapper.assign(this, VarType.LONG, lmapper.getL(0));
532 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
535 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
538 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
541 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
544 smapper.assign(this, VarType.LONG, lmapper.getL(1));
547 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
550 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
553 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
556 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
559 smapper.assign(this, VarType.LONG, lmapper.getL(2));
562 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
565 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
568 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
571 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
574 smapper.assign(this, VarType.LONG, lmapper.getL(3));
577 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
580 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
584 final int indx = wide ? readUShort(byteCodes, i++)
585 : readUByte(byteCodes, i);
587 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
592 final int indx = wide ? readUShort(byteCodes, i++)
593 : readUByte(byteCodes, i);
595 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
600 final int indx = wide ? readUShort(byteCodes, i++)
601 : readUByte(byteCodes, i);
603 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
608 final int indx = wide ? readUShort(byteCodes, i++)
609 : readUByte(byteCodes, i);
611 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
616 final int indx = wide ? readUShort(byteCodes, i++)
617 : readUByte(byteCodes, i);
619 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
624 final int indx = wide ? readUShort(byteCodes, i++)
625 : readUByte(byteCodes, i);
627 emit(smapper, this, "var @1 = @2;",
628 lmapper.setI(indx), smapper.popI());
633 final int indx = wide ? readUShort(byteCodes, i++)
634 : readUByte(byteCodes, i);
636 emit(smapper, this, "var @1 = @2;",
637 lmapper.setL(indx), smapper.popL());
642 final int indx = wide ? readUShort(byteCodes, i++)
643 : readUByte(byteCodes, i);
645 emit(smapper, this, "var @1 = @2;",
646 lmapper.setF(indx), smapper.popF());
651 final int indx = wide ? readUShort(byteCodes, i++)
652 : readUByte(byteCodes, i);
654 emit(smapper, this, "var @1 = @2;",
655 lmapper.setD(indx), smapper.popD());
660 final int indx = wide ? readUShort(byteCodes, i++)
661 : readUByte(byteCodes, i);
663 emit(smapper, this, "var @1 = @2;",
664 lmapper.setA(indx), smapper.popA());
668 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
671 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
674 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
677 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
680 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
683 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
686 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
689 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
692 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
695 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
698 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
701 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
704 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
707 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
710 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
713 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
716 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
719 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
722 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
725 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
728 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
731 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
734 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
737 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
740 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
743 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
746 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
749 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
752 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
755 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
758 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
761 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
764 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
765 smapper.getI(1), smapper.popI());
768 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
769 smapper.getL(1), smapper.popL());
772 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
775 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
778 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
779 smapper.getI(1), smapper.popI());
782 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
783 smapper.getL(1), smapper.popL());
786 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
789 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
792 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
795 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
798 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
801 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
804 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
807 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
810 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
813 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
816 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
819 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
822 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
825 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
828 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
831 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
834 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
837 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
841 final int varIndx = wide ? readUShort(byteCodes, i++)
842 : readUByte(byteCodes, i);
844 final int incrBy = wide ? readShort(byteCodes, i++)
848 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
850 emit(smapper, this, "@1 += @2;",
851 lmapper.getI(varIndx),
852 Integer.toString(incrBy));
857 emit(smapper, this, "return;");
860 emit(smapper, this, "return @1;", smapper.popI());
863 emit(smapper, this, "return @1;", smapper.popL());
866 emit(smapper, this, "return @1;", smapper.popF());
869 emit(smapper, this, "return @1;", smapper.popD());
872 emit(smapper, this, "return @1;", smapper.popA());
875 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
878 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
881 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
884 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
888 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
891 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
894 smapper.replace(this, VarType.DOUBLE, "@1",
898 smapper.replace(this, VarType.FLOAT, "@1",
902 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
906 smapper.replace(this, VarType.LONG, "(@1).toLong()",
910 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
914 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
917 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
921 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
923 case opc_aconst_null:
924 smapper.assign(this, VarType.REFERENCE, "null");
927 smapper.assign(this, VarType.INTEGER, "-1");
930 smapper.assign(this, VarType.INTEGER, "0");
933 smapper.assign(this, VarType.DOUBLE, "0");
936 smapper.assign(this, VarType.LONG, "0");
939 smapper.assign(this, VarType.FLOAT, "0");
942 smapper.assign(this, VarType.INTEGER, "1");
945 smapper.assign(this, VarType.LONG, "1");
948 smapper.assign(this, VarType.FLOAT, "1");
951 smapper.assign(this, VarType.DOUBLE, "1");
954 smapper.assign(this, VarType.INTEGER, "2");
957 smapper.assign(this, VarType.FLOAT, "2");
960 smapper.assign(this, VarType.INTEGER, "3");
963 smapper.assign(this, VarType.INTEGER, "4");
966 smapper.assign(this, VarType.INTEGER, "5");
969 int indx = readUByte(byteCodes, ++i);
970 String v = encodeConstant(indx);
971 int type = VarType.fromConstantType(jc.getTag(indx));
972 smapper.assign(this, type, v);
977 int indx = readUShortArg(byteCodes, i);
979 String v = encodeConstant(indx);
980 int type = VarType.fromConstantType(jc.getTag(indx));
981 if (type == VarType.LONG) {
982 final Long lv = new Long(v);
983 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
984 final int hi = (int)(lv.longValue() >> 32);
986 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
988 smapper.assign(this, VarType.LONG,
989 "0x" + Integer.toHexString(hi) + ".next32(0x" +
990 Integer.toHexString(low) + ")"
994 smapper.assign(this, type, v);
999 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
1003 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1004 smapper.popF(), smapper.popF(), smapper.pushI());
1008 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1009 smapper.popD(), smapper.popD(), smapper.pushI());
1012 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1013 "===", topMostLabel);
1016 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1017 "!==", topMostLabel);
1020 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1021 "==", topMostLabel);
1024 int indx = i + readShortArg(byteCodes, i);
1025 emitIf(smapper, this, "if ((@1) == 0) ",
1026 smapper.popI(), i, indx, topMostLabel);
1031 int indx = i + readShortArg(byteCodes, i);
1032 emitIf(smapper, this, "if ((@1) != 0) ",
1033 smapper.popI(), i, indx, topMostLabel);
1038 int indx = i + readShortArg(byteCodes, i);
1039 emitIf(smapper, this, "if ((@1) < 0) ",
1040 smapper.popI(), i, indx, topMostLabel);
1045 int indx = i + readShortArg(byteCodes, i);
1046 emitIf(smapper, this, "if ((@1) <= 0) ",
1047 smapper.popI(), i, indx, topMostLabel);
1052 int indx = i + readShortArg(byteCodes, i);
1053 emitIf(smapper, this, "if ((@1) > 0) ",
1054 smapper.popI(), i, indx, topMostLabel);
1059 int indx = i + readShortArg(byteCodes, i);
1060 emitIf(smapper, this, "if ((@1) >= 0) ",
1061 smapper.popI(), i, indx, topMostLabel);
1065 case opc_ifnonnull: {
1066 int indx = i + readShortArg(byteCodes, i);
1067 emitIf(smapper, this, "if ((@1) !== null) ",
1068 smapper.popA(), i, indx, topMostLabel);
1073 int indx = i + readShortArg(byteCodes, i);
1074 emitIf(smapper, this, "if ((@1) === null) ",
1075 smapper.popA(), i, indx, topMostLabel);
1080 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1081 "!=", topMostLabel);
1084 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1088 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1089 "<=", topMostLabel);
1092 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1096 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1097 ">=", topMostLabel);
1100 smapper.flush(this);
1101 int indx = i + readShortArg(byteCodes, i);
1102 goTo(this, i, indx, topMostLabel);
1106 case opc_lookupswitch: {
1107 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1110 case opc_tableswitch: {
1111 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1114 case opc_invokeinterface: {
1115 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1118 case opc_invokevirtual:
1119 i = invokeVirtualMethod(byteCodes, i, smapper);
1121 case opc_invokespecial:
1122 i = invokeStaticMethod(byteCodes, i, smapper, false);
1124 case opc_invokestatic:
1125 i = invokeStaticMethod(byteCodes, i, smapper, true);
1127 case opc_invokedynamic: {
1128 int indx = readUShortArg(byteCodes, i);
1129 println("invoke dynamic: " + indx);
1130 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1131 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1132 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1133 println(" type: " + methodHandle.cpx1);
1134 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1135 String mcn = mangleClassName(mi[0]);
1136 char[] returnType = {'V'};
1137 StringBuilder cnt = new StringBuilder();
1138 String mn = findMethodName(mi, cnt, returnType);
1139 StringBuilder sb = new StringBuilder();
1140 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1141 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1142 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1143 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1144 sb.append(" mn : ").append(mn).append("\n");
1145 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1146 throw new IOException(sb.toString());
1148 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1149 String type = jc.StringValue(nameAndType.cpx2);
1150 String object = accessClass(mcn) + "(false)";
1151 if (mn.startsWith("cons_")) {
1152 object += ".constructor";
1154 append("var metHan = ");
1155 append(accessStaticMethod(object, mn, mi));
1157 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1159 append(", '").append(mi[1]).append("', ");
1160 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1161 append(methodType).append("'").append(type).append("', null)");
1162 // if (numArguments > 0) {
1164 // for (int j = 1; j < numArguments; ++j) {
1170 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1176 int indx = readUShortArg(byteCodes, i);
1177 String ci = jc.getClassName(indx);
1178 emit(smapper, this, "var @1 = new @2;",
1179 smapper.pushA(), accessClass(mangleClassName(ci)));
1185 int atype = readUByte(byteCodes, ++i);
1186 generateNewArray(atype, smapper);
1188 case opc_anewarray: {
1189 int type = readUShortArg(byteCodes, i);
1191 generateANewArray(type, smapper);
1194 case opc_multianewarray: {
1195 int type = readUShortArg(byteCodes, i);
1197 i = generateMultiANewArray(type, byteCodes, i, smapper);
1200 case opc_arraylength:
1201 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1204 emit(smapper, this, "Array.at(@3, @2, @1);",
1205 smapper.popL(), smapper.popI(), smapper.popA());
1208 emit(smapper, this, "Array.at(@3, @2, @1);",
1209 smapper.popF(), smapper.popI(), smapper.popA());
1212 emit(smapper, this, "Array.at(@3, @2, @1);",
1213 smapper.popD(), smapper.popI(), smapper.popA());
1216 emit(smapper, this, "Array.at(@3, @2, @1);",
1217 smapper.popA(), smapper.popI(), smapper.popA());
1223 emit(smapper, this, "Array.at(@3, @2, @1);",
1224 smapper.popI(), smapper.popI(), smapper.popA());
1227 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1228 smapper.popI(), smapper.getA(0));
1231 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1232 smapper.popI(), smapper.getA(0));
1235 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1236 smapper.popI(), smapper.getA(0));
1239 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1240 smapper.popI(), smapper.getA(0));
1246 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1247 smapper.popI(), smapper.getA(0));
1255 final Variable v = smapper.get(0);
1256 if (smapper.isDirty()) {
1257 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1259 smapper.assign(this, v.getType(), v);
1264 final Variable vi1 = smapper.get(0);
1266 if (vi1.isCategory2()) {
1267 emit(smapper, this, "var @1 = @2;",
1268 smapper.pushT(vi1.getType()), vi1);
1270 final Variable vi2 = smapper.get(1);
1271 emit(smapper, this, "var @1 = @2, @3 = @4;",
1272 smapper.pushT(vi2.getType()), vi2,
1273 smapper.pushT(vi1.getType()), vi1);
1278 final Variable vi1 = smapper.pop(this);
1279 final Variable vi2 = smapper.pop(this);
1280 final Variable vo3 = smapper.pushT(vi1.getType());
1281 final Variable vo2 = smapper.pushT(vi2.getType());
1282 final Variable vo1 = smapper.pushT(vi1.getType());
1284 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1285 vo1, vi1, vo2, vi2, vo3, vo1);
1289 final Variable vi1 = smapper.pop(this);
1290 final Variable vi2 = smapper.pop(this);
1292 if (vi1.isCategory2()) {
1293 final Variable vo3 = smapper.pushT(vi1.getType());
1294 final Variable vo2 = smapper.pushT(vi2.getType());
1295 final Variable vo1 = smapper.pushT(vi1.getType());
1297 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1298 vo1, vi1, vo2, vi2, vo3, vo1);
1300 final Variable vi3 = smapper.pop(this);
1301 final Variable vo5 = smapper.pushT(vi2.getType());
1302 final Variable vo4 = smapper.pushT(vi1.getType());
1303 final Variable vo3 = smapper.pushT(vi3.getType());
1304 final Variable vo2 = smapper.pushT(vi2.getType());
1305 final Variable vo1 = smapper.pushT(vi1.getType());
1307 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1308 vo1, vi1, vo2, vi2, vo3, vi3);
1309 emit(smapper, this, " @1 = @2, @3 = @4;",
1310 vo4, vo1, vo5, vo2);
1315 final Variable vi1 = smapper.pop(this);
1316 final Variable vi2 = smapper.pop(this);
1318 if (vi2.isCategory2()) {
1319 final Variable vo3 = smapper.pushT(vi1.getType());
1320 final Variable vo2 = smapper.pushT(vi2.getType());
1321 final Variable vo1 = smapper.pushT(vi1.getType());
1323 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1324 vo1, vi1, vo2, vi2, vo3, vo1);
1326 final Variable vi3 = smapper.pop(this);
1327 final Variable vo4 = smapper.pushT(vi1.getType());
1328 final Variable vo3 = smapper.pushT(vi3.getType());
1329 final Variable vo2 = smapper.pushT(vi2.getType());
1330 final Variable vo1 = smapper.pushT(vi1.getType());
1332 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1333 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1338 final Variable vi1 = smapper.pop(this);
1339 final Variable vi2 = smapper.pop(this);
1341 if (vi1.isCategory2()) {
1342 if (vi2.isCategory2()) {
1343 final Variable vo3 = smapper.pushT(vi1.getType());
1344 final Variable vo2 = smapper.pushT(vi2.getType());
1345 final Variable vo1 = smapper.pushT(vi1.getType());
1347 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1348 vo1, vi1, vo2, vi2, vo3, vo1);
1350 final Variable vi3 = smapper.pop(this);
1351 final Variable vo4 = smapper.pushT(vi1.getType());
1352 final Variable vo3 = smapper.pushT(vi3.getType());
1353 final Variable vo2 = smapper.pushT(vi2.getType());
1354 final Variable vo1 = smapper.pushT(vi1.getType());
1356 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1357 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1360 final Variable vi3 = smapper.pop(this);
1362 if (vi3.isCategory2()) {
1363 final Variable vo5 = smapper.pushT(vi2.getType());
1364 final Variable vo4 = smapper.pushT(vi1.getType());
1365 final Variable vo3 = smapper.pushT(vi3.getType());
1366 final Variable vo2 = smapper.pushT(vi2.getType());
1367 final Variable vo1 = smapper.pushT(vi1.getType());
1369 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1370 vo1, vi1, vo2, vi2, vo3, vi3);
1371 emit(smapper, this, " @1 = @2, @3 = @4;",
1372 vo4, vo1, vo5, vo2);
1374 final Variable vi4 = smapper.pop(this);
1375 final Variable vo6 = smapper.pushT(vi2.getType());
1376 final Variable vo5 = smapper.pushT(vi1.getType());
1377 final Variable vo4 = smapper.pushT(vi4.getType());
1378 final Variable vo3 = smapper.pushT(vi3.getType());
1379 final Variable vo2 = smapper.pushT(vi2.getType());
1380 final Variable vo1 = smapper.pushT(vi1.getType());
1382 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1383 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1384 emit(smapper, this, " @1 = @2, @3 = @4;",
1385 vo5, vo1, vo6, vo2);
1391 final Variable vi1 = smapper.get(0);
1392 final Variable vi2 = smapper.get(1);
1394 if (vi1.getType() == vi2.getType()) {
1395 final Variable tmp = smapper.pushT(vi1.getType());
1397 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1402 smapper.pushT(vi1.getType());
1403 smapper.pushT(vi2.getType());
1408 smapper.assign(this, VarType.INTEGER,
1409 "(" + Integer.toString(byteCodes[++i]) + ")");
1412 smapper.assign(this, VarType.INTEGER,
1413 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1417 case opc_getfield: {
1418 int indx = readUShortArg(byteCodes, i);
1419 String[] fi = jc.getFieldInfoName(indx);
1420 final int type = VarType.fromFieldType(fi[2].charAt(0));
1421 final String mangleClass = mangleClassName(fi[0]);
1422 final String mangleClassAccess = accessClassFalse(mangleClass);
1423 smapper.replace(this, type, "@2.call(@1)",
1425 accessField(mangleClassAccess,
1429 addReference(fi[0]);
1432 case opc_putfield: {
1433 int indx = readUShortArg(byteCodes, i);
1434 String[] fi = jc.getFieldInfoName(indx);
1435 final int type = VarType.fromFieldType(fi[2].charAt(0));
1436 final String mangleClass = mangleClassName(fi[0]);
1437 final String mangleClassAccess = accessClassFalse(mangleClass);
1438 emit(smapper, this, "@3.call(@2, @1);",
1441 accessField(mangleClassAccess,
1444 addReference(fi[0]);
1447 case opc_getstatic: {
1448 int indx = readUShortArg(byteCodes, i);
1449 String[] fi = jc.getFieldInfoName(indx);
1450 final int type = VarType.fromFieldType(fi[2].charAt(0));
1451 String ac = accessClassFalse(mangleClassName(fi[0]));
1452 String af = accessField(ac, "_" + fi[1], fi);
1453 smapper.assign(this, type, af + "()");
1455 addReference(fi[0]);
1458 case opc_putstatic: {
1459 int indx = readUShortArg(byteCodes, i);
1460 String[] fi = jc.getFieldInfoName(indx);
1461 final int type = VarType.fromFieldType(fi[2].charAt(0));
1462 emit(smapper, this, "@1._@2(@3);",
1463 accessClassFalse(mangleClassName(fi[0])), fi[1],
1464 smapper.popT(type));
1466 addReference(fi[0]);
1469 case opc_checkcast: {
1470 int indx = readUShortArg(byteCodes, i);
1471 generateCheckcast(indx, smapper);
1475 case opc_instanceof: {
1476 int indx = readUShortArg(byteCodes, i);
1477 generateInstanceOf(indx, smapper);
1482 final CharSequence v = smapper.popA();
1485 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1486 smapper.pushA(), v);
1490 case opc_monitorenter: {
1491 debug("/* monitor enter */");
1496 case opc_monitorexit: {
1497 debug("/* monitor exit */");
1508 emit(smapper, this, "throw 'unknown bytecode @1';",
1509 Integer.toString(c));
1513 generateByteCodeComment(prev, i, byteCodes);
1519 if (previousTrap != null) {
1520 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1525 while (openBraces-- > 0) {
1536 private int generateIf(StackMapper mapper, byte[] byteCodes,
1537 int i, final CharSequence v2, final CharSequence v1,
1538 final String test, int topMostLabel
1539 ) throws IOException {
1541 int indx = i + readShortArg(byteCodes, i);
1542 append("if ((").append(v1)
1543 .append(") ").append(test).append(" (")
1544 .append(v2).append(")) ");
1545 goTo(this, i, indx, topMostLabel);
1549 private int readInt4(byte[] byteCodes, int offset) {
1550 final int d = byteCodes[offset + 0] << 24;
1551 final int c = byteCodes[offset + 1] << 16;
1552 final int b = byteCodes[offset + 2] << 8;
1553 final int a = byteCodes[offset + 3];
1554 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1556 private static int readUByte(byte[] byteCodes, int offset) {
1557 return byteCodes[offset] & 0xff;
1560 private static int readUShort(byte[] byteCodes, int offset) {
1561 return ((byteCodes[offset] & 0xff) << 8)
1562 | (byteCodes[offset + 1] & 0xff);
1564 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1565 return readUShort(byteCodes, offsetInstruction + 1);
1568 private static int readShort(byte[] byteCodes, int offset) {
1569 int signed = byteCodes[offset];
1570 byte b0 = (byte)signed;
1571 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1573 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1574 return readShort(byteCodes, offsetInstruction + 1);
1577 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1579 Boolean count = null;
1580 boolean array = false;
1582 int firstPos = sig.length();
1583 while (i < descriptor.length()) {
1584 char ch = descriptor.charAt(i++);
1605 if (ch == 'J' || ch == 'D') {
1611 sig.insert(firstPos, ch);
1613 returnType[0] = '[';
1614 sig.insert(firstPos, "_3");
1623 returnType[0] = 'V';
1624 sig.insert(firstPos, 'V');
1627 int next = descriptor.indexOf(';', i);
1628 String realSig = mangleSig(descriptor, i - 1, next + 1);
1633 sig.append(realSig);
1636 sig.insert(firstPos, realSig);
1638 sig.insert(firstPos, "_3");
1640 returnType[0] = 'L';
1649 throw new IllegalStateException("Invalid char: " + ch);
1654 static String mangleSig(String sig) {
1655 return mangleSig(sig, 0, sig.length());
1658 private static String mangleMethodName(String name) {
1659 StringBuilder sb = new StringBuilder(name.length() * 2);
1660 int last = name.length();
1661 for (int i = 0; i < last; i++) {
1662 final char ch = name.charAt(i);
1664 case '_': sb.append("_1"); break;
1665 default: sb.append(ch); break;
1668 return sb.toString();
1670 private static String mangleSig(String txt, int first, int last) {
1671 StringBuilder sb = new StringBuilder((last - first) * 2);
1672 for (int i = first; i < last; i++) {
1673 final char ch = txt.charAt(i);
1675 case '/': sb.append('_'); break;
1676 case '_': sb.append("_1"); break;
1677 case ';': sb.append("_2"); break;
1678 case '[': sb.append("_3"); break;
1680 if (Character.isJavaIdentifierPart(ch)) {
1684 String hex = Integer.toHexString(ch).toLowerCase();
1685 for (int m = hex.length(); m < 4; m++) {
1693 return sb.toString();
1696 private static String mangleClassName(String name) {
1697 return mangleSig(name);
1700 private static String findMethodName(MethodData m, StringBuilder cnt) {
1701 StringBuilder name = new StringBuilder();
1702 if ("<init>".equals(m.getName())) { // NOI18N
1703 name.append("cons"); // NOI18N
1704 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1705 name.append("class"); // NOI18N
1707 name.append(mangleMethodName(m.getName()));
1710 countArgs(m.getInternalSig(), new char[1], name, cnt);
1711 return name.toString();
1714 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1715 StringBuilder name = new StringBuilder();
1716 String descr = mi[2];//mi.getDescriptor();
1718 if ("<init>".equals(nm)) { // NOI18N
1719 name.append("cons"); // NOI18N
1721 name.append(mangleMethodName(nm));
1723 countArgs(descr, returnType, name, cnt);
1724 return name.toString();
1727 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1728 throws IOException {
1729 int methodIndex = readUShortArg(byteCodes, i);
1730 String[] mi = jc.getFieldInfoName(methodIndex);
1731 char[] returnType = { 'V' };
1732 StringBuilder cnt = new StringBuilder();
1733 String mn = findMethodName(mi, cnt, returnType);
1735 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1736 final CharSequence[] vars = new CharSequence[numArguments];
1738 for (int j = numArguments - 1; j >= 0; --j) {
1739 vars[j] = mapper.popValue();
1743 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1744 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1746 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1747 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1749 if (vars[1] instanceof String) {
1750 String field = vars[1].toString();
1751 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1752 vars[1] = "c._" + field.substring(1, field.length() - 1);
1757 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1758 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1760 if (vars[1] instanceof String) {
1761 String field = vars[2].toString();
1762 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1763 vars[2] = "c._" + field.substring(1, field.length() - 1);
1768 if (returnType[0] != 'V') {
1771 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1775 final String in = mi[0];
1778 in.equals("org/apidesign/html/boot/spi/Fn") ||
1779 in.equals("org/netbeans/html/boot/spi/Fn")
1781 mcn = "java_lang_Class";
1783 mcn = mangleClassName(in);
1785 String object = accessClassFalse(mcn);
1786 if (mn.startsWith("cons_")) {
1787 object += ".constructor";
1789 append(accessStaticMethod(object, mn, mi));
1795 if (numArguments > 0) {
1797 for (int j = 1; j < numArguments; ++j) {
1807 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1808 throws IOException {
1809 int methodIndex = readUShortArg(byteCodes, i);
1810 String[] mi = jc.getFieldInfoName(methodIndex);
1811 char[] returnType = { 'V' };
1812 StringBuilder cnt = new StringBuilder();
1813 String mn = findMethodName(mi, cnt, returnType);
1815 final int numArguments = cnt.length() + 1;
1816 final CharSequence[] vars = new CharSequence[numArguments];
1818 for (int j = numArguments - 1; j >= 0; --j) {
1819 vars[j] = mapper.popValue();
1822 if (returnType[0] != 'V') {
1825 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1829 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1831 for (int j = 1; j < numArguments; ++j) {
1841 private void addReference(String cn) throws IOException {
1842 if (requireReference(cn)) {
1843 debug(" /* needs " + cn + " */");
1847 private void outType(String d, StringBuilder out) {
1849 while (d.charAt(0) == '[') {
1853 if (d.charAt(0) == 'L') {
1854 assert d.charAt(d.length() - 1) == ';';
1855 out.append(mangleClassName(d).substring(0, d.length() - 1));
1861 private String encodeConstant(int entryIndex) throws IOException {
1862 String[] classRef = { null };
1863 String s = jc.stringValue(entryIndex, classRef);
1864 if (classRef[0] != null) {
1865 if (classRef[0].startsWith("[")) {
1866 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1868 addReference(classRef[0]);
1869 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1875 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1876 byte[] arr = m.findAnnotationData(true);
1880 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1881 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1882 class P extends AnnotationParser {
1888 String[] args = new String[30];
1894 protected void visitAttr(String type, String attr, String at, String value) {
1895 if (type.equals(jvmType)) {
1896 if ("body".equals(attr)) {
1898 } else if ("args".equals(attr)) {
1899 args[cnt++] = value;
1901 throw new IllegalArgumentException(attr);
1904 if (type.equals(htmlType)) {
1906 if ("body".equals(attr)) {
1908 } else if ("args".equals(attr)) {
1909 args[cnt++] = value;
1910 } else if ("javacall".equals(attr)) {
1911 javacall = "1".equals(value);
1912 } else if ("wait4js".equals(attr)) {
1913 // ignore, we always invoke synchronously
1915 throw new IllegalArgumentException(attr);
1922 if (p.body == null) {
1925 StringBuilder cnt = new StringBuilder();
1926 final String mn = findMethodName(m, cnt);
1927 append("m = ").append(destObject).append(".").append(mn);
1928 append(" = function(");
1931 StringBuilder toValue = new StringBuilder();
1932 for (int i = 0; i < cnt.length(); i++) {
1934 space = outputArg(this, p.args, index);
1935 if (p.html4j && space.length() > 0) {
1936 toValue.append("\n ").append(p.args[index]).append(" = ")
1937 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1938 append(p.args[index]).append(");");
1942 append(") {").append("\n");
1943 append(toValue.toString());
1945 int lastSlash = jc.getClassName().lastIndexOf('/');
1946 final String pkg = jc.getClassName().substring(0, lastSlash);
1947 append(mangleCallbacks(pkg, p.body));
1948 requireReference(pkg + "/$JsCallbacks$");
1956 private static CharSequence mangleCallbacks(String pkgName, String body) {
1957 StringBuilder sb = new StringBuilder();
1960 int next = body.indexOf(".@", pos);
1962 sb.append(body.substring(pos));
1963 body = sb.toString();
1968 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1973 String refId = body.substring(ident, next);
1975 sb.append(body.substring(pos, ident));
1977 int sigBeg = body.indexOf('(', next);
1978 int sigEnd = body.indexOf(')', sigBeg);
1979 int colon4 = body.indexOf("::", next);
1980 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1981 throw new IllegalStateException("Malformed body " + body);
1983 String fqn = body.substring(next + 2, colon4);
1984 String method = body.substring(colon4 + 2, sigBeg);
1985 String params = body.substring(sigBeg, sigEnd + 1);
1987 int paramBeg = body.indexOf('(', sigEnd + 1);
1989 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
1990 sb.append(mangleJsCallbacks(fqn, method, params, false));
1991 sb.append("(").append(refId);
1992 if (body.charAt(paramBeg + 1) != ')') {
2000 int next = body.indexOf("@", pos);
2005 sb.append(body.substring(pos));
2009 sb = new StringBuilder();
2012 sb.append(body.substring(pos, next));
2014 int sigBeg = body.indexOf('(', next);
2015 int sigEnd = body.indexOf(')', sigBeg);
2016 int colon4 = body.indexOf("::", next);
2017 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2018 throw new IllegalStateException("Malformed body " + body);
2020 String fqn = body.substring(next + 1, colon4);
2021 String method = body.substring(colon4 + 2, sigBeg);
2022 String params = body.substring(sigBeg, sigEnd + 1);
2024 int paramBeg = body.indexOf('(', sigEnd + 1);
2026 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2027 sb.append(mangleJsCallbacks(fqn, method, params, true));
2033 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2034 if (params.startsWith("(")) {
2035 params = params.substring(1);
2037 if (params.endsWith(")")) {
2038 params = params.substring(0, params.length() - 1);
2040 StringBuilder sb = new StringBuilder();
2041 final String fqnu = fqn.replace('.', '_');
2042 final String rfqn = mangleClassName(fqnu);
2043 final String rm = mangleMethodName(method);
2046 StringBuilder pb = new StringBuilder();
2047 int len = params.length();
2049 while (indx < len) {
2050 char ch = params.charAt(indx);
2051 if (ch == '[' || ch == 'L') {
2052 int column = params.indexOf(';', indx) + 1;
2053 if (column > indx) {
2054 String real = params.substring(indx, column);
2055 if ("Ljava/lang/String;".equals(real)) {
2056 pb.append("Ljava/lang/String;");
2061 pb.append("Ljava/lang/Object;");
2068 srp = mangleSig(pb.toString());
2070 final String rp = mangleSig(params);
2071 final String mrp = mangleMethodName(rp);
2072 sb.append(rfqn).append("$").append(rm).
2073 append('$').append(mrp).append("__Ljava_lang_Object_2");
2075 sb.append('L').append(fqnu).append("_2");
2078 return sb.toString();
2081 private static String className(ClassData jc) {
2082 //return jc.getName().getInternalName().replace('/', '_');
2083 return mangleClassName(jc.getClassName());
2086 private static String[] findAnnotation(
2087 byte[] arr, ClassData cd, final String className,
2088 final String... attrNames
2089 ) throws IOException {
2093 final String[] values = new String[attrNames.length];
2094 final boolean[] found = { false };
2095 final String jvmType = "L" + className.replace('.', '/') + ";";
2096 AnnotationParser ap = new AnnotationParser(false, true) {
2098 protected void visitAttr(String type, String attr, String at, String value) {
2099 if (type.equals(jvmType)) {
2101 for (int i = 0; i < attrNames.length; i++) {
2102 if (attrNames[i].equals(attr)) {
2111 return found[0] ? values : null;
2114 private CharSequence initField(FieldData v) {
2115 final String is = v.getInternalSig();
2116 if (is.length() == 1) {
2117 switch (is.charAt(0)) {
2123 case 'I': return " = 0;";
2125 case 'D': return " = 0.0;";
2127 throw new IllegalStateException(is);
2133 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2134 AnnotationParser ap = new AnnotationParser(true, false) {
2135 int[] cnt = new int[32];
2139 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2140 final String slashType = attrType.substring(1, attrType.length() - 1);
2141 requireReference(slashType);
2143 if (cnt[depth]++ > 0) {
2147 append('"').append(attrType).append("\" : ");
2154 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2160 protected void visitValueStart(String attrName, char type) throws IOException {
2161 if (cnt[depth]++ > 0) {
2165 if (attrName != null) {
2166 append('"').append(attrName).append("\" : ");
2174 protected void visitValueEnd(String attrName, char type) throws IOException {
2182 protected void visitAttr(String type, String attr, String attrType, String value)
2183 throws IOException {
2184 if (attr == null && value == null) {
2191 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2192 throws IOException {
2193 final String slashType = attrType.substring(1, attrType.length() - 1);
2194 requireReference(slashType);
2196 final String cn = mangleClassName(slashType);
2197 append(accessClassFalse(cn))
2198 .append("['valueOf__L").
2200 append("_2Ljava_lang_String_2']('").
2208 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2209 final String name = args[indx];
2213 if (name.contains(",")) {
2214 throw new IOException("Wrong parameter with ',': " + name);
2220 final void emitNoFlush(
2222 final String format, final CharSequence... params
2223 ) throws IOException {
2224 emitImpl(this, format, params);
2226 static final void emit(
2228 final Appendable out,
2229 final String format, final CharSequence... params
2230 ) throws IOException {
2232 emitImpl(out, format, params);
2234 static void emitImpl(final Appendable out,
2235 final String format,
2236 final CharSequence... params) throws IOException {
2237 final int length = format.length();
2240 int paramOffset = format.indexOf('@');
2241 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2242 final char paramChar = format.charAt(paramOffset + 1);
2243 if ((paramChar >= '1') && (paramChar <= '9')) {
2244 final int paramIndex = paramChar - '0' - 1;
2246 out.append(format, processed, paramOffset);
2247 out.append(params[paramIndex]);
2250 processed = paramOffset + 1;
2253 paramOffset = format.indexOf('@', paramOffset + 1);
2256 out.append(format, processed, length);
2259 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2260 append("} catch (e) {\n");
2262 for (TrapData e : traps) {
2266 if (e.catch_cpx != 0) { //not finally
2267 final String classInternalName = jc.getClassName(e.catch_cpx);
2268 addReference(classInternalName);
2269 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2270 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2271 append("var stA0 = e;");
2272 goTo(this, current, e.handler_pc, topMostLabel);
2275 finallyPC = e.handler_pc;
2278 if (finallyPC == -1) {
2281 append("var stA0 = e;");
2282 goTo(this, current, finallyPC, topMostLabel);
2287 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2290 out.append("{ gt = 0; continue X_" + to + "; }");
2292 out.append("{ gt = " + to + "; continue X_0; }");
2295 out.append("{ gt = " + to + "; break IF; }");
2299 private static void emitIf(
2301 Appendable out, String pattern,
2303 int current, int to, int canBack
2304 ) throws IOException {
2306 emitImpl(out, pattern, param);
2307 goTo(out, current, to, canBack);
2310 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2313 case 4: jvmType = "[Z"; break;
2314 case 5: jvmType = "[C"; break;
2315 case 6: jvmType = "[F"; break;
2316 case 7: jvmType = "[D"; break;
2317 case 8: jvmType = "[B"; break;
2318 case 9: jvmType = "[S"; break;
2319 case 10: jvmType = "[I"; break;
2320 case 11: jvmType = "[J"; break;
2321 default: throw new IllegalStateException("Array type: " + atype);
2324 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2325 smapper.popI(), smapper.pushA(), jvmType);
2328 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2329 String typeName = jc.getClassName(type);
2330 String ref = "null";
2331 if (typeName.startsWith("[")) {
2332 typeName = "'[" + typeName + "'";
2334 ref = "vm." + mangleClassName(typeName);
2335 typeName = "'[L" + typeName + ";'";
2338 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2339 smapper.popI(), smapper.pushA(), typeName, ref);
2342 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2343 String typeName = jc.getClassName(type);
2344 int dim = readUByte(byteCodes, ++i);
2345 StringBuilder dims = new StringBuilder();
2347 for (int d = 0; d < dim; d++) {
2349 dims.insert(1, ",");
2351 dims.insert(1, smapper.popI());
2355 if (typeName.charAt(dim) == 'L') {
2356 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2359 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2360 dims.toString(), smapper.pushA(), typeName, fn
2365 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2366 int table = i / 4 * 4 + 4;
2367 int dflt = i + readInt4(byteCodes, table);
2369 int low = readInt4(byteCodes, table);
2371 int high = readInt4(byteCodes, table);
2373 final CharSequence swVar = smapper.popValue();
2374 smapper.flush(this);
2375 append("switch (").append(swVar).append(") {\n");
2376 while (low <= high) {
2377 int offset = i + readInt4(byteCodes, table);
2379 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2382 append(" default: ");
2383 goTo(this, i, dflt, topMostLabel);
2389 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2390 int table = i / 4 * 4 + 4;
2391 int dflt = i + readInt4(byteCodes, table);
2393 int n = readInt4(byteCodes, table);
2395 final CharSequence swVar = smapper.popValue();
2396 smapper.flush(this);
2397 append("switch (").append(swVar).append(") {\n");
2399 int cnstnt = readInt4(byteCodes, table);
2401 int offset = i + readInt4(byteCodes, table);
2403 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2405 append(" default: ");
2406 goTo(this, i, dflt, topMostLabel);
2412 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2413 String type = jc.getClassName(indx);
2414 if (!type.startsWith("[")) {
2416 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2417 smapper.popA(), smapper.pushI(),
2418 mangleClassName(type));
2421 while (type.charAt(cnt) == '[') {
2424 if (type.charAt(cnt) == 'L') {
2425 String component = type.substring(cnt + 1, type.length() - 1);
2426 requireReference(component);
2427 type = "vm." + mangleClassName(component);
2429 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2430 smapper.popA(), smapper.pushI(),
2435 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2436 smapper.popA(), smapper.pushI(), type
2442 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2443 String type = jc.getClassName(indx);
2444 if (!type.startsWith("[")) {
2445 emitNoFlush(smapper,
2446 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2447 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2450 while (type.charAt(cnt) == '[') {
2453 if (type.charAt(cnt) == 'L') {
2454 String component = type.substring(cnt + 1, type.length() - 1);
2455 requireReference(component);
2456 type = "vm." + mangleClassName(component);
2457 emitNoFlush(smapper,
2458 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2459 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2462 emitNoFlush(smapper,
2463 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2464 smapper.getT(0, VarType.REFERENCE, false), type
2470 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2471 for (int j = prev; j <= i; j++) {
2473 final int cc = readUByte(byteCodes, j);
2474 append(Integer.toString(cc));
2478 @JavaScriptBody(args = "msg", body = "")
2479 private static void println(String msg) {
2480 System.err.println(msg);