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;
44 private final NumberOperations numbers = new NumberOperations();
46 protected ByteCodeToJavaScript(Appendable out) {
51 public final Appendable append(CharSequence csq) throws IOException {
58 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
59 out.append(csq, start, end);
65 public final Appendable append(char c) throws IOException {
71 /* Collects additional required resources.
73 * @param internalClassName classes that were referenced and should be loaded in order the
74 * generated JavaScript code works properly. The names are in internal
75 * JVM form so String is <code>java/lang/String</code>.
77 protected abstract boolean requireReference(String internalClassName);
80 * @param resourcePath name of resources to read
82 protected abstract void requireScript(String resourcePath) throws IOException;
84 protected abstract void requireResource(String resourcePath) throws IOException;
86 /** Allows subclasses to redefine what field a function representing a
87 * class gets assigned. By default it returns the suggested name followed
88 * by <code>" = "</code>;
90 * @param className suggested name of the class
92 /* protected */ String assignClass(String className) {
93 return className + " = ";
95 /* protected */ String accessClass(String classOperation) {
96 return classOperation;
99 final String accessClassFalse(String classOperation) {
100 if (mangleClassName(jc.getClassName()).equals(classOperation)) {
103 classRefs.addIfMissing(classOperation);
104 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
107 protected FieldData findField(String[] fieldInfoName) throws IOException {
111 protected String accessField(String object, FieldData data, String[] fieldInfoName)
113 String mangledName = "_" + fieldInfoName[1];
114 return object + "." + mangledName;
117 protected String accessStaticMethod(
120 String[] fieldInfoName) throws IOException {
121 return object + "." + mangledName;
124 protected String accessVirtualMethod(
127 String[] fieldInfoName,
129 ) throws IOException {
130 return object + "." + mangledName + '(';
133 protected void declareClass(ClassData classData, String mangledName)
138 protected void declaredField(FieldData fieldData,
140 String mangledName) throws IOException {
143 protected void declaredMethod(MethodData methodData,
145 String mangledName) throws IOException {
148 /** Prints out a debug message.
150 * @param msg the message
151 * @return true if the message has been printed
152 * @throws IOException
154 boolean debug(String msg) throws IOException {
160 * Converts a given class file to a JavaScript version.
162 * @param classFile input stream with code of the .class file
163 * @return the initialization code for this class, if any. Otherwise <code>null</code>
165 * @throws IOException if something goes wrong during read or write or translating
168 public String compile(InputStream classFile) throws IOException {
169 return compile(new ClassData(classFile));
172 protected String compile(ClassData classData) throws IOException {
174 final String cn = this.jc.getClassName();
176 return compileImpl(cn);
177 } catch (IOException ex) {
178 throw new IOException("Cannot compile " + cn + ":", ex);
182 private String compileImpl(final String cn) throws IOException {
183 this.callbacks = cn.endsWith("/$JsCallbacks$");
184 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
185 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
186 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
189 byte[] arrData = jc.findAnnotationData(true);
191 String[] arr = findAnnotation(arrData, jc,
192 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
193 "resource", "processByteCode"
196 if (!arr[0].isEmpty()) {
197 requireScript(arr[0]);
199 if ("0".equals(arr[1])) {
204 final String jsResource;
206 String[] arr = findAnnotation(arrData, jc,
207 "net.java.html.js.JavaScriptResource",
211 if (arr[0].startsWith("/")) {
214 int last = cn.lastIndexOf('/');
215 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
221 String[] proto = findAnnotation(arrData, jc,
222 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
223 "container", "prototype"
225 StringArray toInitilize = new StringArray();
226 final String className = className(jc);
228 append("function ").append(className).append("() {");
230 append("\n var CLS = ").append(className).append(';');
231 append("\n if (!CLS.$class) {");
233 String sc = jc.getSuperClassName(); // with _
234 append("\n var pp = ").
235 append(accessClass(mangleClassName(sc))).append("(true);");
236 append("\n var p = CLS.prototype = pp;");
237 append("\n var c = p;");
238 append("\n var sprcls = pp.constructor.$class;");
240 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
241 if (proto[0] == null) {
244 append("\n var c = ").append(proto[0]).append(";");
245 append("\n var sprcls = null;");
247 for (FieldData v : jc.getFields()) {
249 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
250 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
254 append("\n CLS.fld_").append(v.getName()).append(initField(v));
255 append("\n m = c._").append(v.getName()).append(" = function (v) {")
256 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
257 .append(" = v; return CLS.fld_").
258 append(v.getName()).append("; };");
260 append("\n m = c._").append(v.getName()).append(" = function (v) {")
261 .append(" if (arguments.length == 1) this.fld_").
262 append(className).append('_').append(v.getName())
263 .append(" = v; return this.fld_").
264 append(className).append('_').append(v.getName())
268 declaredField(v, "c", "_" + v.getName());
270 for (MethodData m : jc.getMethods()) {
271 byte[] onlyArr = m.findAnnotationData(true);
272 if (javaScriptOnly(onlyArr)) continue;
278 mn = generateStaticMethod(destObject, m, toInitilize);
280 if (m.isConstructor()) {
282 mn = generateInstanceMethod(destObject, m);
285 mn = generateInstanceMethod(destObject, m);
288 declaredMethod(m, destObject, mn);
289 byte[] runAnno = m.findAnnotationData(false);
290 if (runAnno != null) {
291 append("\n m.anno = {");
292 AnnotationParser ap = new GenerateAnno(true, false);
293 ap.parse(runAnno, jc);
296 append("\n m.access = " + m.getAccess()).append(";");
297 append("\n m.cls = CLS;");
299 append(numbers.generate());
300 append("\n c.constructor = CLS;");
301 append("\n function ").append(className).append("fillInstOf(x) {");
302 String instOfName = "$instOf_" + className;
303 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
304 if (jc.isInterface()) {
305 for (MethodData m : jc.getMethods()) {
306 if ((m.getAccess() & ACC_ABSTRACT) == 0
307 && (m.getAccess() & ACC_STATIC) == 0
308 && (m.getAccess() & ACC_PRIVATE) == 0) {
309 final String mn = findMethodName(m, new StringBuilder());
310 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
314 for (String superInterface : jc.getSuperInterfaces()) {
315 String intrfc = mangleClassName(superInterface);
316 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
317 requireReference(superInterface);
320 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
321 append("\n ").append(className).append("fillInstOf(c);");
322 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
323 append("\n CLS.$class = 'temp';");
324 append("\n CLS.$class = ");
325 append(accessClass("java_lang_Class(true);"));
326 append("\n CLS.$class.jvmName = '").append(cn).append("';");
327 append("\n CLS.$class.superclass = sprcls;");
328 append("\n CLS.$class.interfaces = function() { return [");
330 boolean first = true;
331 for (String intrfc : jc.getSuperInterfaces()) {
335 requireReference(intrfc);
336 String mangledIface = mangleClassName(intrfc);
338 append(accessClass(mangledIface)).append("(false).constructor.$class");
343 int flags = jc.getAccessFlags();
344 if (jc.hasEnclosingMethod()) {
347 append("\n CLS.$class.access = ").append(flags+";");
348 append("\n CLS.$class.cnstr = CLS;");
349 byte[] classAnno = jc.findAnnotationData(false);
350 if (classAnno != null) {
351 append("\n CLS.$class.anno = {");
352 AnnotationParser ap = new GenerateAnno(true, false);
353 ap.parse(classAnno, jc);
356 for (String init : toInitilize.toArray()) {
357 append("\n ").append(init).append("();");
359 for (String ref : classRefs.toArray()) {
360 append("\n var refs_").append(ref).append(";");
364 if (jsResource != null) {
365 requireResource(jsResource);
369 append("\n if (arguments.length === 0) {");
370 append("\n if (!(this instanceof CLS)) {");
371 append("\n return new CLS();");
373 for (FieldData v : jc.getFields()) {
374 byte[] onlyArr = v.findAnnotationData(true);
375 if (javaScriptOnly(onlyArr)) continue;
377 append("\n this.fld_").
378 append(className).append('_').
379 append(v.getName()).append(initField(v));
382 append("\n return this;");
384 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
387 append("\n").append(assignClass(className));
388 declareClass(jc, className);
391 // StringBuilder sb = new StringBuilder();
392 // for (String init : toInitilize.toArray()) {
393 // sb.append("\n").append(init).append("();");
398 private boolean javaScriptOnly(byte[] anno) throws IOException {
399 String[] only = findAnnotation(anno, jc,
400 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
404 if (only[0] != null && only[1] != null) {
405 append("\n p.").append(only[0]).append(" = ")
406 .append(only[1]).append(";");
408 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
409 append("\n p['").append(only[0]).append("'] = p.")
410 .append(only[0]).append(";");
416 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
417 String jsb = javaScriptBody(destObject, m, true);
421 final String mn = findMethodName(m, new StringBuilder());
422 boolean defineProp = generateMethod(destObject, mn, m);
423 if (mn.equals("class__V")) {
425 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
427 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
433 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
434 String jsb = javaScriptBody(destObject, m, false);
438 final String mn = findMethodName(m, new StringBuilder());
439 generateMethod(destObject, mn, m);
443 private boolean generateMethod(String destObject, String name, MethodData m)
445 final StackMapIterator stackMapIterator = m.createStackMapIterator();
446 TrapDataIterator trap = m.getTrapDataIterator();
447 final LocalsMapper lmapper =
448 new LocalsMapper(stackMapIterator.getArguments());
451 "java/lang/Object".equals(jc.getClassName()) ||
452 "java/lang/reflect/Array".equals(jc.getClassName());
455 append("Object.defineProperty(").append(destObject).
456 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
458 append("m = ").append(destObject).append(".").append(name).append(" = function(");
460 lmapper.outputArguments(this, m.isStatic());
461 append(") {").append("\n");
463 final byte[] byteCodes = m.getCode();
464 if (byteCodes == null) {
465 byte[] defaultAttr = m.getDefaultAttribute();
466 if (defaultAttr != null) {
468 AnnotationParser ap = new GenerateAnno(true, false);
469 ap.parseDefault(defaultAttr, jc);
472 if (debug(" throw 'no code found for ")) {
474 .append(jc.getClassName()).append('.')
475 .append(m.getName()).append("';\n");
486 final StackMapper smapper = new StackMapper();
489 append(" var ").append(" lcA0 = this;\n");
493 TrapData[] previousTrap = null;
494 boolean wide = false;
496 if (stackMapIterator.isEmpty()) {
502 append("\n var gt = 0;\n");
506 int topMostLabel = 0;
507 for (int i = 0; i < byteCodes.length; i++) {
510 stackMapIterator.advanceTo(i);
511 boolean changeInCatch = trap.advanceTo(i);
512 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
513 if (previousTrap != null) {
514 generateCatch(previousTrap, i, topMostLabel);
518 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
523 if (openBraces > 64) {
524 for (int c = 0; c < 64; c++) {
531 lastStackFrame = stackMapIterator.getFrameIndex();
532 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
533 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
534 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
536 changeInCatch = true;
538 debug(" /* " + i + " */ ");
540 if (changeInCatch && trap.useTry()) {
542 previousTrap = trap.current();
544 final int c = readUByte(byteCodes, i);
547 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
550 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
553 smapper.assign(this, VarType.LONG, lmapper.getL(0));
556 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
559 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
562 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
565 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
568 smapper.assign(this, VarType.LONG, lmapper.getL(1));
571 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
574 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
577 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
580 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
583 smapper.assign(this, VarType.LONG, lmapper.getL(2));
586 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
589 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
592 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
595 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
598 smapper.assign(this, VarType.LONG, lmapper.getL(3));
601 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
604 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
608 final int indx = wide ? readUShort(byteCodes, i++)
609 : readUByte(byteCodes, i);
611 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
616 final int indx = wide ? readUShort(byteCodes, i++)
617 : readUByte(byteCodes, i);
619 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
624 final int indx = wide ? readUShort(byteCodes, i++)
625 : readUByte(byteCodes, i);
627 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
632 final int indx = wide ? readUShort(byteCodes, i++)
633 : readUByte(byteCodes, i);
635 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
640 final int indx = wide ? readUShort(byteCodes, i++)
641 : readUByte(byteCodes, i);
643 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
648 final int indx = wide ? readUShort(byteCodes, i++)
649 : readUByte(byteCodes, i);
651 emit(smapper, this, "var @1 = @2;",
652 lmapper.setI(indx), smapper.popI());
657 final int indx = wide ? readUShort(byteCodes, i++)
658 : readUByte(byteCodes, i);
660 emit(smapper, this, "var @1 = @2;",
661 lmapper.setL(indx), smapper.popL());
666 final int indx = wide ? readUShort(byteCodes, i++)
667 : readUByte(byteCodes, i);
669 emit(smapper, this, "var @1 = @2;",
670 lmapper.setF(indx), smapper.popF());
675 final int indx = wide ? readUShort(byteCodes, i++)
676 : readUByte(byteCodes, i);
678 emit(smapper, this, "var @1 = @2;",
679 lmapper.setD(indx), smapper.popD());
684 final int indx = wide ? readUShort(byteCodes, i++)
685 : readUByte(byteCodes, i);
687 emit(smapper, this, "var @1 = @2;",
688 lmapper.setA(indx), smapper.popA());
692 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
695 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
698 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
701 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
704 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
707 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
710 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
713 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
716 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
719 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
722 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
725 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
728 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
731 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
734 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
737 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
740 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
743 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
746 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
749 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
752 smapper.replace(this, VarType.INTEGER, "(((@1) + (@2)) | 0)", smapper.getI(1), smapper.popI());
755 smapper.replace(this, VarType.LONG, numbers.add64(), 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) - (@2)) | 0)", smapper.getI(1), smapper.popI());
767 smapper.replace(this, VarType.LONG, numbers.sub64(), smapper.getL(1), smapper.popL());
770 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
773 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
776 smapper.replace(this, VarType.INTEGER, numbers.mul32(), smapper.getI(1), smapper.popI());
779 smapper.replace(this, VarType.LONG, numbers.mul64(), smapper.getL(1), smapper.popL());
782 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
785 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
788 smapper.replace(this, VarType.INTEGER, numbers.div32(),
789 smapper.getI(1), smapper.popI());
792 smapper.replace(this, VarType.LONG, numbers.div64(),
793 smapper.getL(1), smapper.popL());
796 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
799 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
802 smapper.replace(this, VarType.INTEGER, numbers.mod32(),
803 smapper.getI(1), smapper.popI());
806 smapper.replace(this, VarType.LONG, numbers.mod64(),
807 smapper.getL(1), smapper.popL());
810 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
813 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
816 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
819 smapper.replace(this, VarType.LONG, numbers.and64(), smapper.getL(1), smapper.popL());
822 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
825 smapper.replace(this, VarType.LONG, numbers.or64(), smapper.getL(1), smapper.popL());
828 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
831 smapper.replace(this, VarType.LONG, numbers.xor64(), smapper.getL(1), smapper.popL());
834 smapper.replace(this, VarType.INTEGER, "(-(@1) | 0)", smapper.getI(0));
837 smapper.replace(this, VarType.LONG, numbers.neg64(), smapper.getL(0));
840 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
843 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
846 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
849 smapper.replace(this, VarType.LONG, numbers.shl64(), smapper.getL(1), smapper.popI());
852 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
855 smapper.replace(this, VarType.LONG, numbers.shr64(), smapper.getL(1), smapper.popI());
858 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
861 smapper.replace(this, VarType.LONG, numbers.ushr64(), smapper.getL(1), smapper.popI());
865 final int varIndx = wide ? readUShort(byteCodes, i++)
866 : readUByte(byteCodes, i);
868 final int incrBy = wide ? readShort(byteCodes, i++)
872 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
874 emit(smapper, this, "@1 += @2;",
875 lmapper.getI(varIndx),
876 Integer.toString(incrBy));
881 emit(smapper, this, "return;");
884 emit(smapper, this, "return @1;", smapper.popI());
887 emit(smapper, this, "return @1;", smapper.popL());
890 emit(smapper, this, "return @1;", smapper.popF());
893 emit(smapper, this, "return @1;", smapper.popD());
896 emit(smapper, this, "return @1;", smapper.popA());
899 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
902 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
905 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
908 smapper.replace(this, VarType.INTEGER, "((@1) | 0)", smapper.getL(0));
912 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
915 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
918 smapper.replace(this, VarType.DOUBLE, "@1",
922 smapper.replace(this, VarType.FLOAT, "@1",
926 smapper.replace(this, VarType.INTEGER, "((@1) | 0)",
930 smapper.replace(this, VarType.LONG, "(@1).toLong()",
934 smapper.replace(this, VarType.INTEGER, "((@1)| 0)",
938 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
941 smapper.replace(this, VarType.INTEGER, "(((@1) << 24) >> 24)", smapper.getI(0));
945 smapper.replace(this, VarType.INTEGER, "(((@1) << 16) >> 16)", smapper.getI(0));
947 case opc_aconst_null:
948 smapper.assign(this, VarType.REFERENCE, "null");
951 smapper.assign(this, VarType.INTEGER, "-1");
954 smapper.assign(this, VarType.INTEGER, "0");
957 smapper.assign(this, VarType.DOUBLE, "0");
960 smapper.assign(this, VarType.LONG, "0");
963 smapper.assign(this, VarType.FLOAT, "0");
966 smapper.assign(this, VarType.INTEGER, "1");
969 smapper.assign(this, VarType.LONG, "1");
972 smapper.assign(this, VarType.FLOAT, "1");
975 smapper.assign(this, VarType.DOUBLE, "1");
978 smapper.assign(this, VarType.INTEGER, "2");
981 smapper.assign(this, VarType.FLOAT, "2");
984 smapper.assign(this, VarType.INTEGER, "3");
987 smapper.assign(this, VarType.INTEGER, "4");
990 smapper.assign(this, VarType.INTEGER, "5");
993 int indx = readUByte(byteCodes, ++i);
994 String v = encodeConstant(indx);
995 int type = VarType.fromConstantType(jc.getTag(indx));
996 smapper.assign(this, type, v);
1001 int indx = readUShortArg(byteCodes, i);
1003 String v = encodeConstant(indx);
1004 int type = VarType.fromConstantType(jc.getTag(indx));
1005 if (type == VarType.LONG) {
1006 final Long lv = new Long(v);
1007 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
1008 final int hi = (int)(lv.longValue() >> 32);
1010 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
1012 smapper.assign(this, VarType.LONG,
1013 "0x" + Integer.toHexString(hi) + ".next32(0x" +
1014 Integer.toHexString(low) + ")"
1018 smapper.assign(this, type, v);
1023 smapper.replace(this, VarType.INTEGER, numbers.compare64(), smapper.popL(), smapper.getL(0));
1027 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1028 smapper.popF(), smapper.popF(), smapper.pushI());
1032 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1033 smapper.popD(), smapper.popD(), smapper.pushI());
1036 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1037 "===", topMostLabel);
1040 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1041 "!==", topMostLabel);
1044 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1045 "==", topMostLabel);
1048 int indx = i + readShortArg(byteCodes, i);
1049 emitIf(smapper, this, "if ((@1) == 0) ",
1050 smapper.popI(), i, indx, topMostLabel);
1055 int indx = i + readShortArg(byteCodes, i);
1056 emitIf(smapper, this, "if ((@1) != 0) ",
1057 smapper.popI(), i, indx, topMostLabel);
1062 int indx = i + readShortArg(byteCodes, i);
1063 emitIf(smapper, this, "if ((@1) < 0) ",
1064 smapper.popI(), i, indx, topMostLabel);
1069 int indx = i + readShortArg(byteCodes, i);
1070 emitIf(smapper, this, "if ((@1) <= 0) ",
1071 smapper.popI(), i, indx, topMostLabel);
1076 int indx = i + readShortArg(byteCodes, i);
1077 emitIf(smapper, this, "if ((@1) > 0) ",
1078 smapper.popI(), i, indx, topMostLabel);
1083 int indx = i + readShortArg(byteCodes, i);
1084 emitIf(smapper, this, "if ((@1) >= 0) ",
1085 smapper.popI(), i, indx, topMostLabel);
1089 case opc_ifnonnull: {
1090 int indx = i + readShortArg(byteCodes, i);
1091 emitIf(smapper, this, "if ((@1) !== null) ",
1092 smapper.popA(), i, indx, topMostLabel);
1097 int indx = i + readShortArg(byteCodes, i);
1098 emitIf(smapper, this, "if ((@1) === null) ",
1099 smapper.popA(), i, indx, topMostLabel);
1104 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1105 "!=", topMostLabel);
1108 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1112 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1113 "<=", topMostLabel);
1116 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1120 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1121 ">=", topMostLabel);
1124 smapper.flush(this);
1125 int indx = i + readShortArg(byteCodes, i);
1126 goTo(this, i, indx, topMostLabel);
1130 case opc_lookupswitch: {
1131 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1134 case opc_tableswitch: {
1135 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1138 case opc_invokeinterface: {
1139 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1142 case opc_invokevirtual:
1143 i = invokeVirtualMethod(byteCodes, i, smapper);
1145 case opc_invokespecial:
1146 i = invokeStaticMethod(byteCodes, i, smapper, false);
1148 case opc_invokestatic:
1149 i = invokeStaticMethod(byteCodes, i, smapper, true);
1151 case opc_invokedynamic: {
1152 int indx = readUShortArg(byteCodes, i);
1153 println("invoke dynamic: " + indx);
1154 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1155 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1156 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1157 println(" type: " + methodHandle.cpx1);
1158 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1159 String mcn = mangleClassName(mi[0]);
1160 char[] returnType = {'V'};
1161 StringBuilder cnt = new StringBuilder();
1162 String mn = findMethodName(mi, cnt, returnType);
1163 StringBuilder sb = new StringBuilder();
1164 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1165 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1166 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1167 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1168 sb.append(" mn : ").append(mn).append("\n");
1169 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1170 throw new IOException(sb.toString());
1172 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1173 String type = jc.StringValue(nameAndType.cpx2);
1174 String object = accessClass(mcn) + "(false)";
1175 if (mn.startsWith("cons_")) {
1176 object += ".constructor";
1178 append("var metHan = ");
1179 append(accessStaticMethod(object, mn, mi));
1181 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1183 append(", '").append(mi[1]).append("', ");
1184 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1185 append(methodType).append("'").append(type).append("', null)");
1186 // if (numArguments > 0) {
1188 // for (int j = 1; j < numArguments; ++j) {
1194 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1200 int indx = readUShortArg(byteCodes, i);
1201 String ci = jc.getClassName(indx);
1202 emit(smapper, this, "var @1 = new @2;",
1203 smapper.pushA(), accessClass(mangleClassName(ci)));
1209 int atype = readUByte(byteCodes, ++i);
1210 generateNewArray(atype, smapper);
1212 case opc_anewarray: {
1213 int type = readUShortArg(byteCodes, i);
1215 generateANewArray(type, smapper);
1218 case opc_multianewarray: {
1219 int type = readUShortArg(byteCodes, i);
1221 i = generateMultiANewArray(type, byteCodes, i, smapper);
1224 case opc_arraylength:
1225 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1228 emit(smapper, this, "Array.at(@3, @2, @1);",
1229 smapper.popL(), smapper.popI(), smapper.popA());
1232 emit(smapper, this, "Array.at(@3, @2, @1);",
1233 smapper.popF(), smapper.popI(), smapper.popA());
1236 emit(smapper, this, "Array.at(@3, @2, @1);",
1237 smapper.popD(), smapper.popI(), smapper.popA());
1240 emit(smapper, this, "Array.at(@3, @2, @1);",
1241 smapper.popA(), smapper.popI(), smapper.popA());
1247 emit(smapper, this, "Array.at(@3, @2, @1);",
1248 smapper.popI(), smapper.popI(), smapper.popA());
1251 smapper.replace(this, VarType.LONG, "(@2[@1] || Array.at(@2, @1))",
1252 smapper.popI(), smapper.getA(0));
1255 smapper.replace(this, VarType.FLOAT, "(@2[@1] || Array.at(@2, @1))",
1256 smapper.popI(), smapper.getA(0));
1259 smapper.replace(this, VarType.DOUBLE, "(@2[@1] || Array.at(@2, @1))",
1260 smapper.popI(), smapper.getA(0));
1263 smapper.replace(this, VarType.REFERENCE, "(@2[@1] || Array.at(@2, @1))",
1264 smapper.popI(), smapper.getA(0));
1270 smapper.replace(this, VarType.INTEGER, "(@2[@1] || Array.at(@2, @1))",
1271 smapper.popI(), smapper.getA(0));
1279 final Variable v = smapper.get(0);
1280 if (smapper.isDirty()) {
1281 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1283 smapper.assign(this, v.getType(), v);
1288 final Variable vi1 = smapper.get(0);
1290 if (vi1.isCategory2()) {
1291 emit(smapper, this, "var @1 = @2;",
1292 smapper.pushT(vi1.getType()), vi1);
1294 final Variable vi2 = smapper.get(1);
1295 emit(smapper, this, "var @1 = @2, @3 = @4;",
1296 smapper.pushT(vi2.getType()), vi2,
1297 smapper.pushT(vi1.getType()), vi1);
1302 final Variable vi1 = smapper.pop(this);
1303 final Variable vi2 = smapper.pop(this);
1304 final Variable vo3 = smapper.pushT(vi1.getType());
1305 final Variable vo2 = smapper.pushT(vi2.getType());
1306 final Variable vo1 = smapper.pushT(vi1.getType());
1308 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1309 vo1, vi1, vo2, vi2, vo3, vo1);
1313 final Variable vi1 = smapper.pop(this);
1314 final Variable vi2 = smapper.pop(this);
1316 if (vi1.isCategory2()) {
1317 final Variable vo3 = smapper.pushT(vi1.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;",
1322 vo1, vi1, vo2, vi2, vo3, vo1);
1324 final Variable vi3 = smapper.pop(this);
1325 final Variable vo5 = smapper.pushT(vi2.getType());
1326 final Variable vo4 = smapper.pushT(vi1.getType());
1327 final Variable vo3 = smapper.pushT(vi3.getType());
1328 final Variable vo2 = smapper.pushT(vi2.getType());
1329 final Variable vo1 = smapper.pushT(vi1.getType());
1331 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1332 vo1, vi1, vo2, vi2, vo3, vi3);
1333 emit(smapper, this, " @1 = @2, @3 = @4;",
1334 vo4, vo1, vo5, vo2);
1339 final Variable vi1 = smapper.pop(this);
1340 final Variable vi2 = smapper.pop(this);
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);
1362 final Variable vi1 = smapper.pop(this);
1363 final Variable vi2 = smapper.pop(this);
1365 if (vi1.isCategory2()) {
1366 if (vi2.isCategory2()) {
1367 final Variable vo3 = smapper.pushT(vi1.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;",
1372 vo1, vi1, vo2, vi2, vo3, vo1);
1374 final Variable vi3 = smapper.pop(this);
1375 final Variable vo4 = smapper.pushT(vi1.getType());
1376 final Variable vo3 = smapper.pushT(vi3.getType());
1377 final Variable vo2 = smapper.pushT(vi2.getType());
1378 final Variable vo1 = smapper.pushT(vi1.getType());
1380 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1381 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1384 final Variable vi3 = smapper.pop(this);
1386 if (vi3.isCategory2()) {
1387 final Variable vo5 = smapper.pushT(vi2.getType());
1388 final Variable vo4 = smapper.pushT(vi1.getType());
1389 final Variable vo3 = smapper.pushT(vi3.getType());
1390 final Variable vo2 = smapper.pushT(vi2.getType());
1391 final Variable vo1 = smapper.pushT(vi1.getType());
1393 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1394 vo1, vi1, vo2, vi2, vo3, vi3);
1395 emit(smapper, this, " @1 = @2, @3 = @4;",
1396 vo4, vo1, vo5, vo2);
1398 final Variable vi4 = smapper.pop(this);
1399 final Variable vo6 = smapper.pushT(vi2.getType());
1400 final Variable vo5 = smapper.pushT(vi1.getType());
1401 final Variable vo4 = smapper.pushT(vi4.getType());
1402 final Variable vo3 = smapper.pushT(vi3.getType());
1403 final Variable vo2 = smapper.pushT(vi2.getType());
1404 final Variable vo1 = smapper.pushT(vi1.getType());
1406 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1407 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1408 emit(smapper, this, " @1 = @2, @3 = @4;",
1409 vo5, vo1, vo6, vo2);
1415 final Variable vi1 = smapper.get(0);
1416 final Variable vi2 = smapper.get(1);
1418 if (vi1.getType() == vi2.getType()) {
1419 final Variable tmp = smapper.pushT(vi1.getType());
1421 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1426 smapper.pushT(vi1.getType());
1427 smapper.pushT(vi2.getType());
1432 smapper.assign(this, VarType.INTEGER,
1433 "(" + Integer.toString(byteCodes[++i]) + ")");
1436 smapper.assign(this, VarType.INTEGER,
1437 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1441 case opc_getfield: {
1442 int indx = readUShortArg(byteCodes, i);
1443 String[] fi = jc.getFieldInfoName(indx);
1444 final int type = VarType.fromFieldType(fi[2].charAt(0));
1445 FieldData field = findField(fi);
1446 if (field == null) {
1447 final String mangleClass = mangleClassName(fi[0]);
1448 final String mangleClassAccess = accessClassFalse(mangleClass);
1449 smapper.replace(this, type, "@2.call(@1)",
1451 accessField(mangleClassAccess, null, fi)
1454 final String fieldOwner = mangleClassName(field.cls.getClassName());
1455 smapper.replace(this, type, "@1.@2",
1457 accessField(fieldOwner, field, fi)
1461 addReference(fi[0]);
1464 case opc_putfield: {
1465 int indx = readUShortArg(byteCodes, i);
1466 String[] fi = jc.getFieldInfoName(indx);
1467 final int type = VarType.fromFieldType(fi[2].charAt(0));
1468 FieldData field = findField(fi);
1469 if (field == null) {
1470 final String mangleClass = mangleClassName(fi[0]);
1471 final String mangleClassAccess = accessClassFalse(mangleClass);
1472 emit(smapper, this, "@3.call(@2, @1);",
1475 accessField(mangleClassAccess, null, fi)
1478 final String fieldOwner = mangleClassName(field.cls.getClassName());
1479 emit(smapper, this, "@2.@3 = @1;",
1482 accessField(fieldOwner, field, fi)
1486 addReference(fi[0]);
1489 case opc_getstatic: {
1490 int indx = readUShortArg(byteCodes, i);
1491 String[] fi = jc.getFieldInfoName(indx);
1492 final int type = VarType.fromFieldType(fi[2].charAt(0));
1493 String ac = accessClassFalse(mangleClassName(fi[0]));
1494 FieldData field = findField(fi);
1495 String af = accessField(ac, field, fi);
1496 smapper.assign(this, type, af + "()");
1498 addReference(fi[0]);
1501 case opc_putstatic: {
1502 int indx = readUShortArg(byteCodes, i);
1503 String[] fi = jc.getFieldInfoName(indx);
1504 final int type = VarType.fromFieldType(fi[2].charAt(0));
1505 emit(smapper, this, "@1._@2(@3);",
1506 accessClassFalse(mangleClassName(fi[0])), fi[1],
1507 smapper.popT(type));
1509 addReference(fi[0]);
1512 case opc_checkcast: {
1513 int indx = readUShortArg(byteCodes, i);
1514 generateCheckcast(indx, smapper);
1518 case opc_instanceof: {
1519 int indx = readUShortArg(byteCodes, i);
1520 generateInstanceOf(indx, smapper);
1525 final CharSequence v = smapper.popA();
1528 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1529 smapper.pushA(), v);
1533 case opc_monitorenter: {
1534 debug("/* monitor enter */");
1539 case opc_monitorexit: {
1540 debug("/* monitor exit */");
1551 emit(smapper, this, "throw 'unknown bytecode @1';",
1552 Integer.toString(c));
1556 generateByteCodeComment(prev, i, byteCodes);
1562 if (previousTrap != null) {
1563 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1568 while (openBraces-- > 0) {
1579 private int generateIf(StackMapper mapper, byte[] byteCodes,
1580 int i, final CharSequence v2, final CharSequence v1,
1581 final String test, int topMostLabel
1582 ) throws IOException {
1584 int indx = i + readShortArg(byteCodes, i);
1585 append("if ((").append(v1)
1586 .append(") ").append(test).append(" (")
1587 .append(v2).append(")) ");
1588 goTo(this, i, indx, topMostLabel);
1592 private int readInt4(byte[] byteCodes, int offset) {
1593 final int d = byteCodes[offset + 0] << 24;
1594 final int c = byteCodes[offset + 1] << 16;
1595 final int b = byteCodes[offset + 2] << 8;
1596 final int a = byteCodes[offset + 3];
1597 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1599 private static int readUByte(byte[] byteCodes, int offset) {
1600 return byteCodes[offset] & 0xff;
1603 private static int readUShort(byte[] byteCodes, int offset) {
1604 return ((byteCodes[offset] & 0xff) << 8)
1605 | (byteCodes[offset + 1] & 0xff);
1607 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1608 return readUShort(byteCodes, offsetInstruction + 1);
1611 private static int readShort(byte[] byteCodes, int offset) {
1612 int signed = byteCodes[offset];
1613 byte b0 = (byte)signed;
1614 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1616 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1617 return readShort(byteCodes, offsetInstruction + 1);
1620 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1622 Boolean count = null;
1623 boolean array = false;
1625 int firstPos = sig.length();
1626 while (i < descriptor.length()) {
1627 char ch = descriptor.charAt(i++);
1648 if (ch == 'J' || ch == 'D') {
1654 sig.insert(firstPos, ch);
1656 returnType[0] = '[';
1657 sig.insert(firstPos, "_3");
1666 returnType[0] = 'V';
1667 sig.insert(firstPos, 'V');
1670 int next = descriptor.indexOf(';', i);
1671 String realSig = mangleSig(descriptor, i - 1, next + 1);
1676 sig.append(realSig);
1679 sig.insert(firstPos, realSig);
1681 sig.insert(firstPos, "_3");
1683 returnType[0] = 'L';
1692 throw new IllegalStateException("Invalid char: " + ch);
1697 static String mangleSig(String sig) {
1698 return mangleSig(sig, 0, sig.length());
1701 private static String mangleMethodName(String name) {
1702 StringBuilder sb = new StringBuilder(name.length() * 2);
1703 int last = name.length();
1704 for (int i = 0; i < last; i++) {
1705 final char ch = name.charAt(i);
1707 case '_': sb.append("_1"); break;
1708 default: sb.append(ch); break;
1711 return sb.toString();
1713 private static String mangleSig(String txt, int first, int last) {
1714 StringBuilder sb = new StringBuilder((last - first) * 2);
1715 for (int i = first; i < last; i++) {
1716 final char ch = txt.charAt(i);
1718 case '/': sb.append('_'); break;
1719 case '_': sb.append("_1"); break;
1720 case ';': sb.append("_2"); break;
1721 case '[': sb.append("_3"); break;
1723 if (Character.isJavaIdentifierPart(ch)) {
1727 String hex = Integer.toHexString(ch).toLowerCase();
1728 for (int m = hex.length(); m < 4; m++) {
1736 return sb.toString();
1739 private static String mangleClassName(String name) {
1740 return mangleSig(name);
1743 private static String findMethodName(MethodData m, StringBuilder cnt) {
1744 StringBuilder name = new StringBuilder();
1745 if ("<init>".equals(m.getName())) { // NOI18N
1746 name.append("cons"); // NOI18N
1747 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1748 name.append("class"); // NOI18N
1750 name.append(mangleMethodName(m.getName()));
1753 countArgs(m.getInternalSig(), new char[1], name, cnt);
1754 return name.toString();
1757 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1758 StringBuilder name = new StringBuilder();
1759 String descr = mi[2];//mi.getDescriptor();
1761 if ("<init>".equals(nm)) { // NOI18N
1762 name.append("cons"); // NOI18N
1764 name.append(mangleMethodName(nm));
1766 countArgs(descr, returnType, name, cnt);
1767 return name.toString();
1770 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1771 throws IOException {
1772 int methodIndex = readUShortArg(byteCodes, i);
1773 String[] mi = jc.getFieldInfoName(methodIndex);
1774 char[] returnType = { 'V' };
1775 StringBuilder cnt = new StringBuilder();
1776 String mn = findMethodName(mi, cnt, returnType);
1778 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1779 final CharSequence[] vars = new CharSequence[numArguments];
1781 for (int j = numArguments - 1; j >= 0; --j) {
1782 vars[j] = mapper.popValue();
1786 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1787 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1789 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1790 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1792 if (vars[1] instanceof String) {
1793 String field = vars[1].toString();
1794 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1795 vars[1] = "c._" + field.substring(1, field.length() - 1);
1800 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1801 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1803 if (vars[1] instanceof String) {
1804 String field = vars[2].toString();
1805 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1806 vars[2] = "c._" + field.substring(1, field.length() - 1);
1811 if (returnType[0] != 'V') {
1814 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1818 final String in = mi[0];
1821 in.equals("org/apidesign/html/boot/spi/Fn") ||
1822 in.equals("org/netbeans/html/boot/spi/Fn")
1824 mcn = "java_lang_Class";
1826 mcn = mangleClassName(in);
1828 String object = accessClassFalse(mcn);
1829 if (mn.startsWith("cons_")) {
1830 object += ".constructor";
1832 append(accessStaticMethod(object, mn, mi));
1838 if (numArguments > 0) {
1840 for (int j = 1; j < numArguments; ++j) {
1850 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1851 throws IOException {
1852 int methodIndex = readUShortArg(byteCodes, i);
1853 String[] mi = jc.getFieldInfoName(methodIndex);
1854 char[] returnType = { 'V' };
1855 StringBuilder cnt = new StringBuilder();
1856 String mn = findMethodName(mi, cnt, returnType);
1858 final int numArguments = cnt.length() + 1;
1859 final CharSequence[] vars = new CharSequence[numArguments];
1861 for (int j = numArguments - 1; j >= 0; --j) {
1862 vars[j] = mapper.popValue();
1865 if (returnType[0] != 'V') {
1868 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1872 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1874 for (int j = 1; j < numArguments; ++j) {
1884 private void addReference(String cn) throws IOException {
1885 if (requireReference(cn)) {
1886 debug(" /* needs " + cn + " */");
1890 private void outType(String d, StringBuilder out) {
1892 while (d.charAt(0) == '[') {
1896 if (d.charAt(0) == 'L') {
1897 assert d.charAt(d.length() - 1) == ';';
1898 out.append(mangleClassName(d).substring(0, d.length() - 1));
1904 private String encodeConstant(int entryIndex) throws IOException {
1905 String[] classRef = { null };
1906 String s = jc.stringValue(entryIndex, classRef);
1907 if (classRef[0] != null) {
1908 if (classRef[0].startsWith("[")) {
1909 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1911 addReference(classRef[0]);
1912 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1918 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1919 byte[] arr = m.findAnnotationData(true);
1923 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1924 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1925 class P extends AnnotationParser {
1931 String[] args = new String[30];
1937 protected void visitAttr(String type, String attr, String at, String value) {
1938 if (type.equals(jvmType)) {
1939 if ("body".equals(attr)) {
1941 } else if ("args".equals(attr)) {
1942 args[cnt++] = value;
1944 throw new IllegalArgumentException(attr);
1947 if (type.equals(htmlType)) {
1949 if ("body".equals(attr)) {
1951 } else if ("args".equals(attr)) {
1952 args[cnt++] = value;
1953 } else if ("javacall".equals(attr)) {
1954 javacall = "1".equals(value);
1955 } else if ("wait4js".equals(attr)) {
1956 // ignore, we always invoke synchronously
1958 throw new IllegalArgumentException(attr);
1965 if (p.body == null) {
1968 StringBuilder cnt = new StringBuilder();
1969 final String mn = findMethodName(m, cnt);
1970 append("m = ").append(destObject).append(".").append(mn);
1971 append(" = function(");
1974 StringBuilder toValue = new StringBuilder();
1975 for (int i = 0; i < cnt.length(); i++) {
1977 space = outputArg(this, p.args, index);
1978 if (p.html4j && space.length() > 0) {
1979 toValue.append("\n ").append(p.args[index]).append(" = ")
1980 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1981 append(p.args[index]).append(");");
1985 append(") {").append("\n");
1986 append(toValue.toString());
1988 int lastSlash = jc.getClassName().lastIndexOf('/');
1989 final String pkg = jc.getClassName().substring(0, lastSlash);
1990 append(mangleCallbacks(pkg, p.body));
1991 requireReference(pkg + "/$JsCallbacks$");
1999 private static CharSequence mangleCallbacks(String pkgName, String body) {
2000 StringBuilder sb = new StringBuilder();
2003 int next = body.indexOf(".@", pos);
2005 sb.append(body.substring(pos));
2006 body = sb.toString();
2011 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
2016 String refId = body.substring(ident, next);
2018 sb.append(body.substring(pos, ident));
2020 int sigBeg = body.indexOf('(', next);
2021 int sigEnd = body.indexOf(')', sigBeg);
2022 int colon4 = body.indexOf("::", next);
2023 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2024 throw new IllegalStateException("Malformed body " + body);
2026 String fqn = body.substring(next + 2, colon4);
2027 String method = body.substring(colon4 + 2, sigBeg);
2028 String params = body.substring(sigBeg, sigEnd + 1);
2030 int paramBeg = body.indexOf('(', sigEnd + 1);
2032 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2033 sb.append(mangleJsCallbacks(fqn, method, params, false));
2034 sb.append("(").append(refId);
2035 if (body.charAt(paramBeg + 1) != ')') {
2043 int next = body.indexOf("@", pos);
2048 sb.append(body.substring(pos));
2052 sb = new StringBuilder();
2055 sb.append(body.substring(pos, next));
2057 int sigBeg = body.indexOf('(', next);
2058 int sigEnd = body.indexOf(')', sigBeg);
2059 int colon4 = body.indexOf("::", next);
2060 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2061 throw new IllegalStateException("Malformed body " + body);
2063 String fqn = body.substring(next + 1, colon4);
2064 String method = body.substring(colon4 + 2, sigBeg);
2065 String params = body.substring(sigBeg, sigEnd + 1);
2067 int paramBeg = body.indexOf('(', sigEnd + 1);
2069 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2070 sb.append(mangleJsCallbacks(fqn, method, params, true));
2076 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2077 if (params.startsWith("(")) {
2078 params = params.substring(1);
2080 if (params.endsWith(")")) {
2081 params = params.substring(0, params.length() - 1);
2083 StringBuilder sb = new StringBuilder();
2084 final String fqnu = fqn.replace('.', '_');
2085 final String rfqn = mangleClassName(fqnu);
2086 final String rm = mangleMethodName(method);
2089 StringBuilder pb = new StringBuilder();
2090 int len = params.length();
2092 while (indx < len) {
2093 char ch = params.charAt(indx);
2094 if (ch == '[' || ch == 'L') {
2095 int column = params.indexOf(';', indx) + 1;
2096 if (column > indx) {
2097 String real = params.substring(indx, column);
2098 if ("Ljava/lang/String;".equals(real)) {
2099 pb.append("Ljava/lang/String;");
2104 pb.append("Ljava/lang/Object;");
2111 srp = mangleSig(pb.toString());
2113 final String rp = mangleSig(params);
2114 final String mrp = mangleMethodName(rp);
2115 sb.append(rfqn).append("$").append(rm).
2116 append('$').append(mrp).append("__Ljava_lang_Object_2");
2118 sb.append('L').append(fqnu).append("_2");
2121 return sb.toString();
2124 private static String className(ClassData jc) {
2125 //return jc.getName().getInternalName().replace('/', '_');
2126 return mangleClassName(jc.getClassName());
2129 private static String[] findAnnotation(
2130 byte[] arr, ClassData cd, final String className,
2131 final String... attrNames
2132 ) throws IOException {
2136 final String[] values = new String[attrNames.length];
2137 final boolean[] found = { false };
2138 final String jvmType = "L" + className.replace('.', '/') + ";";
2139 AnnotationParser ap = new AnnotationParser(false, true) {
2141 protected void visitAttr(String type, String attr, String at, String value) {
2142 if (type.equals(jvmType)) {
2144 for (int i = 0; i < attrNames.length; i++) {
2145 if (attrNames[i].equals(attr)) {
2154 return found[0] ? values : null;
2157 private CharSequence initField(FieldData v) {
2158 final String is = v.getInternalSig();
2159 if (is.length() == 1) {
2160 switch (is.charAt(0)) {
2166 case 'I': return " = 0;";
2168 case 'D': return " = 0.0;";
2170 throw new IllegalStateException(is);
2176 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2177 final String name = args[indx];
2181 if (name.contains(",")) {
2182 throw new IOException("Wrong parameter with ',': " + name);
2188 final void emitNoFlush(
2190 final String format, final CharSequence... params
2191 ) throws IOException {
2192 emitImpl(this, format, params);
2194 static final void emit(
2196 final Appendable out,
2197 final String format, final CharSequence... params
2198 ) throws IOException {
2200 emitImpl(out, format, params);
2202 static void emitImpl(final Appendable out,
2203 final String format,
2204 final CharSequence... params) throws IOException {
2205 final int length = format.length();
2208 int paramOffset = format.indexOf('@');
2209 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2210 final char paramChar = format.charAt(paramOffset + 1);
2211 if ((paramChar >= '1') && (paramChar <= '9')) {
2212 final int paramIndex = paramChar - '0' - 1;
2214 out.append(format, processed, paramOffset);
2215 out.append(params[paramIndex]);
2218 processed = paramOffset + 1;
2221 paramOffset = format.indexOf('@', paramOffset + 1);
2224 out.append(format, processed, length);
2227 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2228 append("} catch (e) {\n");
2230 for (TrapData e : traps) {
2234 if (e.catch_cpx != 0) { //not finally
2235 final String classInternalName = jc.getClassName(e.catch_cpx);
2236 addReference(classInternalName);
2237 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2238 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2239 append("var stA0 = e;");
2240 goTo(this, current, e.handler_pc, topMostLabel);
2243 finallyPC = e.handler_pc;
2246 if (finallyPC == -1) {
2249 append("var stA0 = e;");
2250 goTo(this, current, finallyPC, topMostLabel);
2255 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2258 out.append("{ gt = 0; continue X_" + to + "; }");
2260 out.append("{ gt = " + to + "; continue X_0; }");
2263 out.append("{ gt = " + to + "; break IF; }");
2267 private static void emitIf(
2269 Appendable out, String pattern,
2271 int current, int to, int canBack
2272 ) throws IOException {
2274 emitImpl(out, pattern, param);
2275 goTo(out, current, to, canBack);
2278 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2281 case 4: jvmType = "[Z"; break;
2282 case 5: jvmType = "[C"; break;
2283 case 6: jvmType = "[F"; break;
2284 case 7: jvmType = "[D"; break;
2285 case 8: jvmType = "[B"; break;
2286 case 9: jvmType = "[S"; break;
2287 case 10: jvmType = "[I"; break;
2288 case 11: jvmType = "[J"; break;
2289 default: throw new IllegalStateException("Array type: " + atype);
2292 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2293 smapper.popI(), smapper.pushA(), jvmType);
2296 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2297 String typeName = jc.getClassName(type);
2298 String ref = "null";
2299 if (typeName.startsWith("[")) {
2300 typeName = "'[" + typeName + "'";
2302 ref = "vm." + mangleClassName(typeName);
2303 typeName = "'[L" + typeName + ";'";
2306 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2307 smapper.popI(), smapper.pushA(), typeName, ref);
2310 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2311 String typeName = jc.getClassName(type);
2312 int dim = readUByte(byteCodes, ++i);
2313 StringBuilder dims = new StringBuilder();
2315 for (int d = 0; d < dim; d++) {
2317 dims.insert(1, ",");
2319 dims.insert(1, smapper.popI());
2323 if (typeName.charAt(dim) == 'L') {
2324 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2327 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2328 dims.toString(), smapper.pushA(), typeName, fn
2333 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2334 int table = i / 4 * 4 + 4;
2335 int dflt = i + readInt4(byteCodes, table);
2337 int low = readInt4(byteCodes, table);
2339 int high = readInt4(byteCodes, table);
2341 final CharSequence swVar = smapper.popValue();
2342 smapper.flush(this);
2343 append("switch (").append(swVar).append(") {\n");
2344 while (low <= high) {
2345 int offset = i + readInt4(byteCodes, table);
2347 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2350 append(" default: ");
2351 goTo(this, i, dflt, topMostLabel);
2357 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2358 int table = i / 4 * 4 + 4;
2359 int dflt = i + readInt4(byteCodes, table);
2361 int n = readInt4(byteCodes, table);
2363 final CharSequence swVar = smapper.popValue();
2364 smapper.flush(this);
2365 append("switch (").append(swVar).append(") {\n");
2367 int cnstnt = readInt4(byteCodes, table);
2369 int offset = i + readInt4(byteCodes, table);
2371 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2373 append(" default: ");
2374 goTo(this, i, dflt, topMostLabel);
2380 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2381 String type = jc.getClassName(indx);
2382 if (!type.startsWith("[")) {
2384 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2385 smapper.popA(), smapper.pushI(),
2386 mangleClassName(type));
2389 while (type.charAt(cnt) == '[') {
2392 if (type.charAt(cnt) == 'L') {
2393 String component = type.substring(cnt + 1, type.length() - 1);
2394 requireReference(component);
2395 type = "vm." + mangleClassName(component);
2397 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2398 smapper.popA(), smapper.pushI(),
2403 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2404 smapper.popA(), smapper.pushI(), type
2410 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2411 String type = jc.getClassName(indx);
2412 if (!type.startsWith("[")) {
2413 emitNoFlush(smapper,
2414 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2415 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2418 while (type.charAt(cnt) == '[') {
2421 if (type.charAt(cnt) == 'L') {
2422 String component = type.substring(cnt + 1, type.length() - 1);
2423 requireReference(component);
2424 type = "vm." + mangleClassName(component);
2425 emitNoFlush(smapper,
2426 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2427 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2430 emitNoFlush(smapper,
2431 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2432 smapper.getT(0, VarType.REFERENCE, false), type
2438 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2439 for (int j = prev; j <= i; j++) {
2441 final int cc = readUByte(byteCodes, j);
2442 append(Integer.toString(cc));
2446 @JavaScriptBody(args = "msg", body = "")
2447 private static void println(String msg) {
2448 System.err.println(msg);
2451 private class GenerateAnno extends AnnotationParser {
2452 public GenerateAnno(boolean textual, boolean iterateArray) {
2453 super(textual, iterateArray);
2455 int[] cnt = new int[32];
2459 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2460 final String slashType = attrType.substring(1, attrType.length() - 1);
2461 requireReference(slashType);
2463 if (cnt[depth]++ > 0) {
2467 append('"').append(attrType).append("\" : ");
2474 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2480 protected void visitValueStart(String attrName, char type) throws IOException {
2481 if (cnt[depth]++ > 0) {
2485 if (attrName != null) {
2486 append('"').append(attrName).append("\" : ");
2494 protected void visitValueEnd(String attrName, char type) throws IOException {
2502 protected void visitAttr(String type, String attr, String attrType, String value)
2503 throws IOException {
2504 if (attr == null && value == null) {
2511 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2512 throws IOException {
2513 final String slashType = attrType.substring(1, attrType.length() - 1);
2514 requireReference(slashType);
2516 final String cn = mangleClassName(slashType);
2517 append(accessClassFalse(cn))
2518 .append("['valueOf__L").
2520 append("_2Ljava_lang_String_2']('").
2526 protected void visitClassAttr(String annoType, String attr, String className) throws IOException {
2527 final String slashType = className.substring(1, className.length() - 1);
2528 requireReference(slashType);
2530 final String cn = mangleClassName(slashType);
2531 append(accessClassFalse(cn)).append(".constructor.$class");