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 FieldData findField(String[] fieldInfoName) throws IOException {
110 protected String accessField(String object, FieldData data, String[] fieldInfoName)
112 String mangledName = "_" + fieldInfoName[1];
113 return object + "." + mangledName;
116 protected String accessStaticMethod(
119 String[] fieldInfoName) throws IOException {
120 return object + "." + mangledName;
123 protected String accessVirtualMethod(
126 String[] fieldInfoName,
128 ) throws IOException {
129 return object + "." + mangledName + '(';
132 protected void declaredClass(ClassData classData, String mangledName)
136 protected void declaredField(FieldData fieldData,
138 String mangledName) throws IOException {
141 protected void declaredMethod(MethodData methodData,
143 String mangledName) throws IOException {
146 /** Prints out a debug message.
148 * @param msg the message
149 * @return true if the message has been printed
150 * @throws IOException
152 boolean debug(String msg) throws IOException {
158 * Converts a given class file to a JavaScript version.
160 * @param classFile input stream with code of the .class file
161 * @return the initialization code for this class, if any. Otherwise <code>null</code>
163 * @throws IOException if something goes wrong during read or write or translating
166 public String compile(InputStream classFile) throws IOException {
167 return compile(new ClassData(classFile));
170 protected String compile(ClassData classData) throws IOException {
172 final String cn = this.jc.getClassName();
174 return compileImpl(cn);
175 } catch (IOException ex) {
176 throw new IOException("Cannot compile " + cn + ":", ex);
180 private String compileImpl(final String cn) throws IOException {
181 this.callbacks = cn.endsWith("/$JsCallbacks$");
182 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
183 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
184 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
187 byte[] arrData = jc.findAnnotationData(true);
189 String[] arr = findAnnotation(arrData, jc,
190 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
191 "resource", "processByteCode"
194 if (!arr[0].isEmpty()) {
195 requireScript(arr[0]);
197 if ("0".equals(arr[1])) {
202 final String jsResource;
204 String[] arr = findAnnotation(arrData, jc,
205 "net.java.html.js.JavaScriptResource",
209 if (arr[0].startsWith("/")) {
212 int last = cn.lastIndexOf('/');
213 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
219 String[] proto = findAnnotation(arrData, jc,
220 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
221 "container", "prototype"
223 StringArray toInitilize = new StringArray();
224 final String className = className(jc);
225 append("\n\n").append(assignClass(className));
226 append("function ").append(className).append("() {");
228 append("\n var CLS = ").append(className).append(';');
229 append("\n if (!CLS.$class) {");
231 String sc = jc.getSuperClassName(); // with _
232 append("\n var pp = ").
233 append(accessClass(mangleClassName(sc))).append("(true);");
234 append("\n var p = CLS.prototype = pp;");
235 append("\n var c = p;");
236 append("\n var sprcls = pp.constructor.$class;");
238 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
239 if (proto[0] == null) {
242 append("\n var c = ").append(proto[0]).append(";");
243 append("\n var sprcls = null;");
245 for (FieldData v : jc.getFields()) {
247 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
248 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
252 append("\n CLS.fld_").append(v.getName()).append(initField(v));
253 append("\n m = c._").append(v.getName()).append(" = function (v) {")
254 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
255 .append(" = v; return CLS.fld_").
256 append(v.getName()).append("; };");
258 append("\n m = c._").append(v.getName()).append(" = function (v) {")
259 .append(" if (arguments.length == 1) this.fld_").
260 append(className).append('_').append(v.getName())
261 .append(" = v; return this.fld_").
262 append(className).append('_').append(v.getName())
266 declaredField(v, "c", "_" + v.getName());
268 for (MethodData m : jc.getMethods()) {
269 byte[] onlyArr = m.findAnnotationData(true);
270 if (javaScriptOnly(onlyArr)) continue;
276 mn = generateStaticMethod(destObject, m, toInitilize);
278 if (m.isConstructor()) {
280 mn = generateInstanceMethod(destObject, m);
283 mn = generateInstanceMethod(destObject, m);
286 declaredMethod(m, destObject, mn);
287 byte[] runAnno = m.findAnnotationData(false);
288 if (runAnno != null) {
289 append("\n m.anno = {");
290 generateAnno(jc, runAnno);
293 append("\n m.access = " + m.getAccess()).append(";");
294 append("\n m.cls = CLS;");
296 append("\n c.constructor = CLS;");
297 append("\n function ").append(className).append("fillInstOf(x) {");
298 String instOfName = "$instOf_" + className;
299 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
300 if (jc.isInterface()) {
301 for (MethodData m : jc.getMethods()) {
302 if ((m.getAccess() & ACC_ABSTRACT) == 0
303 && (m.getAccess() & ACC_STATIC) == 0
304 && (m.getAccess() & ACC_PRIVATE) == 0) {
305 final String mn = findMethodName(m, new StringBuilder());
306 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
310 for (String superInterface : jc.getSuperInterfaces()) {
311 String intrfc = mangleClassName(superInterface);
312 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
313 requireReference(superInterface);
316 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
317 append("\n ").append(className).append("fillInstOf(c);");
318 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
319 append("\n CLS.$class = 'temp';");
320 append("\n CLS.$class = ");
321 append(accessClass("java_lang_Class(true);"));
322 append("\n CLS.$class.jvmName = '").append(cn).append("';");
323 append("\n CLS.$class.superclass = sprcls;");
324 append("\n CLS.$class.interfaces = function() { return [");
326 boolean first = true;
327 for (String intrfc : jc.getSuperInterfaces()) {
331 requireReference(intrfc);
332 String mangledIface = mangleClassName(intrfc);
334 append(accessClass(mangledIface)).append("(false).constructor.$class");
339 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
340 append("\n CLS.$class.cnstr = CLS;");
341 byte[] classAnno = jc.findAnnotationData(false);
342 if (classAnno != null) {
343 append("\n CLS.$class.anno = {");
344 generateAnno(jc, classAnno);
347 for (String init : toInitilize.toArray()) {
348 append("\n ").append(init).append("();");
350 for (String ref : classRefs.toArray()) {
351 append("\n var refs_").append(ref).append(";");
355 if (jsResource != null) {
356 requireResource(jsResource);
360 append("\n if (arguments.length === 0) {");
361 append("\n if (!(this instanceof CLS)) {");
362 append("\n return new CLS();");
364 for (FieldData v : jc.getFields()) {
365 byte[] onlyArr = v.findAnnotationData(true);
366 if (javaScriptOnly(onlyArr)) continue;
368 append("\n this.fld_").
369 append(className).append('_').
370 append(v.getName()).append(initField(v));
373 append("\n return this;");
375 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
378 declaredClass(jc, className);
380 // StringBuilder sb = new StringBuilder();
381 // for (String init : toInitilize.toArray()) {
382 // sb.append("\n").append(init).append("();");
387 private boolean javaScriptOnly(byte[] anno) throws IOException {
388 String[] only = findAnnotation(anno, jc,
389 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
393 if (only[0] != null && only[1] != null) {
394 append("\n p.").append(only[0]).append(" = ")
395 .append(only[1]).append(";");
397 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
398 append("\n p['").append(only[0]).append("'] = p.")
399 .append(only[0]).append(";");
405 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
406 String jsb = javaScriptBody(destObject, m, true);
410 final String mn = findMethodName(m, new StringBuilder());
411 boolean defineProp = generateMethod(destObject, mn, m);
412 if (mn.equals("class__V")) {
414 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
416 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
422 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
423 String jsb = javaScriptBody(destObject, m, false);
427 final String mn = findMethodName(m, new StringBuilder());
428 generateMethod(destObject, mn, m);
432 private boolean generateMethod(String destObject, String name, MethodData m)
434 final StackMapIterator stackMapIterator = m.createStackMapIterator();
435 TrapDataIterator trap = m.getTrapDataIterator();
436 final LocalsMapper lmapper =
437 new LocalsMapper(stackMapIterator.getArguments());
440 "java/lang/Object".equals(jc.getClassName()) ||
441 "java/lang/reflect/Array".equals(jc.getClassName());
444 append("Object.defineProperty(").append(destObject).
445 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
447 append("m = ").append(destObject).append(".").append(name).append(" = function(");
449 lmapper.outputArguments(this, m.isStatic());
450 append(") {").append("\n");
452 final byte[] byteCodes = m.getCode();
453 if (byteCodes == null) {
454 if (debug(" throw 'no code found for ")) {
456 .append(jc.getClassName()).append('.')
457 .append(m.getName()).append("';\n");
467 final StackMapper smapper = new StackMapper();
470 append(" var ").append(" lcA0 = this;\n");
474 TrapData[] previousTrap = null;
475 boolean wide = false;
477 if (stackMapIterator.isEmpty()) {
483 append("\n var gt = 0;\n");
487 int topMostLabel = 0;
488 for (int i = 0; i < byteCodes.length; i++) {
491 stackMapIterator.advanceTo(i);
492 boolean changeInCatch = trap.advanceTo(i);
493 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
494 if (previousTrap != null) {
495 generateCatch(previousTrap, i, topMostLabel);
499 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
504 if (openBraces > 64) {
505 for (int c = 0; c < 64; c++) {
512 lastStackFrame = stackMapIterator.getFrameIndex();
513 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
514 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
515 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
517 changeInCatch = true;
519 debug(" /* " + i + " */ ");
521 if (changeInCatch && trap.useTry()) {
523 previousTrap = trap.current();
525 final int c = readUByte(byteCodes, i);
528 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
531 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
534 smapper.assign(this, VarType.LONG, lmapper.getL(0));
537 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
540 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
543 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
546 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
549 smapper.assign(this, VarType.LONG, lmapper.getL(1));
552 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
555 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
558 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
561 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
564 smapper.assign(this, VarType.LONG, lmapper.getL(2));
567 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
570 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
573 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
576 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
579 smapper.assign(this, VarType.LONG, lmapper.getL(3));
582 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
585 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
589 final int indx = wide ? readUShort(byteCodes, i++)
590 : readUByte(byteCodes, i);
592 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
597 final int indx = wide ? readUShort(byteCodes, i++)
598 : readUByte(byteCodes, i);
600 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
605 final int indx = wide ? readUShort(byteCodes, i++)
606 : readUByte(byteCodes, i);
608 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
613 final int indx = wide ? readUShort(byteCodes, i++)
614 : readUByte(byteCodes, i);
616 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
621 final int indx = wide ? readUShort(byteCodes, i++)
622 : readUByte(byteCodes, i);
624 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
629 final int indx = wide ? readUShort(byteCodes, i++)
630 : readUByte(byteCodes, i);
632 emit(smapper, this, "var @1 = @2;",
633 lmapper.setI(indx), smapper.popI());
638 final int indx = wide ? readUShort(byteCodes, i++)
639 : readUByte(byteCodes, i);
641 emit(smapper, this, "var @1 = @2;",
642 lmapper.setL(indx), smapper.popL());
647 final int indx = wide ? readUShort(byteCodes, i++)
648 : readUByte(byteCodes, i);
650 emit(smapper, this, "var @1 = @2;",
651 lmapper.setF(indx), smapper.popF());
656 final int indx = wide ? readUShort(byteCodes, i++)
657 : readUByte(byteCodes, i);
659 emit(smapper, this, "var @1 = @2;",
660 lmapper.setD(indx), smapper.popD());
665 final int indx = wide ? readUShort(byteCodes, i++)
666 : readUByte(byteCodes, i);
668 emit(smapper, this, "var @1 = @2;",
669 lmapper.setA(indx), smapper.popA());
673 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
676 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
679 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
682 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
685 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
688 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
691 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
694 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
697 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
700 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
703 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
706 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
709 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
712 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
715 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
718 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
721 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
724 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
727 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
730 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
733 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
736 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
739 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
742 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
745 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
748 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
751 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
754 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
757 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
760 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
763 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
766 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
769 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
770 smapper.getI(1), smapper.popI());
773 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
774 smapper.getL(1), smapper.popL());
777 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
780 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
783 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
784 smapper.getI(1), smapper.popI());
787 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
788 smapper.getL(1), smapper.popL());
791 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
794 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
797 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
800 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
803 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
806 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
809 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
812 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
815 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
818 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
821 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
824 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
827 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
830 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
833 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
836 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
839 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
842 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
846 final int varIndx = wide ? readUShort(byteCodes, i++)
847 : readUByte(byteCodes, i);
849 final int incrBy = wide ? readShort(byteCodes, i++)
853 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
855 emit(smapper, this, "@1 += @2;",
856 lmapper.getI(varIndx),
857 Integer.toString(incrBy));
862 emit(smapper, this, "return;");
865 emit(smapper, this, "return @1;", smapper.popI());
868 emit(smapper, this, "return @1;", smapper.popL());
871 emit(smapper, this, "return @1;", smapper.popF());
874 emit(smapper, this, "return @1;", smapper.popD());
877 emit(smapper, this, "return @1;", smapper.popA());
880 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
883 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
886 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
889 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
893 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
896 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
899 smapper.replace(this, VarType.DOUBLE, "@1",
903 smapper.replace(this, VarType.FLOAT, "@1",
907 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
911 smapper.replace(this, VarType.LONG, "(@1).toLong()",
915 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
919 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
922 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
926 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
928 case opc_aconst_null:
929 smapper.assign(this, VarType.REFERENCE, "null");
932 smapper.assign(this, VarType.INTEGER, "-1");
935 smapper.assign(this, VarType.INTEGER, "0");
938 smapper.assign(this, VarType.DOUBLE, "0");
941 smapper.assign(this, VarType.LONG, "0");
944 smapper.assign(this, VarType.FLOAT, "0");
947 smapper.assign(this, VarType.INTEGER, "1");
950 smapper.assign(this, VarType.LONG, "1");
953 smapper.assign(this, VarType.FLOAT, "1");
956 smapper.assign(this, VarType.DOUBLE, "1");
959 smapper.assign(this, VarType.INTEGER, "2");
962 smapper.assign(this, VarType.FLOAT, "2");
965 smapper.assign(this, VarType.INTEGER, "3");
968 smapper.assign(this, VarType.INTEGER, "4");
971 smapper.assign(this, VarType.INTEGER, "5");
974 int indx = readUByte(byteCodes, ++i);
975 String v = encodeConstant(indx);
976 int type = VarType.fromConstantType(jc.getTag(indx));
977 smapper.assign(this, type, v);
982 int indx = readUShortArg(byteCodes, i);
984 String v = encodeConstant(indx);
985 int type = VarType.fromConstantType(jc.getTag(indx));
986 if (type == VarType.LONG) {
987 final Long lv = new Long(v);
988 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
989 final int hi = (int)(lv.longValue() >> 32);
991 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
993 smapper.assign(this, VarType.LONG,
994 "0x" + Integer.toHexString(hi) + ".next32(0x" +
995 Integer.toHexString(low) + ")"
999 smapper.assign(this, type, v);
1004 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
1008 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1009 smapper.popF(), smapper.popF(), smapper.pushI());
1013 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1014 smapper.popD(), smapper.popD(), smapper.pushI());
1017 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1018 "===", topMostLabel);
1021 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1022 "!==", topMostLabel);
1025 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1026 "==", topMostLabel);
1029 int indx = i + readShortArg(byteCodes, i);
1030 emitIf(smapper, this, "if ((@1) == 0) ",
1031 smapper.popI(), i, indx, topMostLabel);
1036 int indx = i + readShortArg(byteCodes, i);
1037 emitIf(smapper, this, "if ((@1) != 0) ",
1038 smapper.popI(), i, indx, topMostLabel);
1043 int indx = i + readShortArg(byteCodes, i);
1044 emitIf(smapper, this, "if ((@1) < 0) ",
1045 smapper.popI(), i, indx, topMostLabel);
1050 int indx = i + readShortArg(byteCodes, i);
1051 emitIf(smapper, this, "if ((@1) <= 0) ",
1052 smapper.popI(), i, indx, topMostLabel);
1057 int indx = i + readShortArg(byteCodes, i);
1058 emitIf(smapper, this, "if ((@1) > 0) ",
1059 smapper.popI(), i, indx, topMostLabel);
1064 int indx = i + readShortArg(byteCodes, i);
1065 emitIf(smapper, this, "if ((@1) >= 0) ",
1066 smapper.popI(), i, indx, topMostLabel);
1070 case opc_ifnonnull: {
1071 int indx = i + readShortArg(byteCodes, i);
1072 emitIf(smapper, this, "if ((@1) !== null) ",
1073 smapper.popA(), i, indx, topMostLabel);
1078 int indx = i + readShortArg(byteCodes, i);
1079 emitIf(smapper, this, "if ((@1) === null) ",
1080 smapper.popA(), i, indx, topMostLabel);
1085 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1086 "!=", topMostLabel);
1089 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1093 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1094 "<=", topMostLabel);
1097 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1101 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1102 ">=", topMostLabel);
1105 smapper.flush(this);
1106 int indx = i + readShortArg(byteCodes, i);
1107 goTo(this, i, indx, topMostLabel);
1111 case opc_lookupswitch: {
1112 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1115 case opc_tableswitch: {
1116 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1119 case opc_invokeinterface: {
1120 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1123 case opc_invokevirtual:
1124 i = invokeVirtualMethod(byteCodes, i, smapper);
1126 case opc_invokespecial:
1127 i = invokeStaticMethod(byteCodes, i, smapper, false);
1129 case opc_invokestatic:
1130 i = invokeStaticMethod(byteCodes, i, smapper, true);
1132 case opc_invokedynamic: {
1133 int indx = readUShortArg(byteCodes, i);
1134 println("invoke dynamic: " + indx);
1135 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1136 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1137 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1138 println(" type: " + methodHandle.cpx1);
1139 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1140 String mcn = mangleClassName(mi[0]);
1141 char[] returnType = {'V'};
1142 StringBuilder cnt = new StringBuilder();
1143 String mn = findMethodName(mi, cnt, returnType);
1144 StringBuilder sb = new StringBuilder();
1145 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1146 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1147 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1148 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1149 sb.append(" mn : ").append(mn).append("\n");
1150 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1151 throw new IOException(sb.toString());
1153 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1154 String type = jc.StringValue(nameAndType.cpx2);
1155 String object = accessClass(mcn) + "(false)";
1156 if (mn.startsWith("cons_")) {
1157 object += ".constructor";
1159 append("var metHan = ");
1160 append(accessStaticMethod(object, mn, mi));
1162 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1164 append(", '").append(mi[1]).append("', ");
1165 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1166 append(methodType).append("'").append(type).append("', null)");
1167 // if (numArguments > 0) {
1169 // for (int j = 1; j < numArguments; ++j) {
1175 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1181 int indx = readUShortArg(byteCodes, i);
1182 String ci = jc.getClassName(indx);
1183 emit(smapper, this, "var @1 = new @2;",
1184 smapper.pushA(), accessClass(mangleClassName(ci)));
1190 int atype = readUByte(byteCodes, ++i);
1191 generateNewArray(atype, smapper);
1193 case opc_anewarray: {
1194 int type = readUShortArg(byteCodes, i);
1196 generateANewArray(type, smapper);
1199 case opc_multianewarray: {
1200 int type = readUShortArg(byteCodes, i);
1202 i = generateMultiANewArray(type, byteCodes, i, smapper);
1205 case opc_arraylength:
1206 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1209 emit(smapper, this, "Array.at(@3, @2, @1);",
1210 smapper.popL(), smapper.popI(), smapper.popA());
1213 emit(smapper, this, "Array.at(@3, @2, @1);",
1214 smapper.popF(), smapper.popI(), smapper.popA());
1217 emit(smapper, this, "Array.at(@3, @2, @1);",
1218 smapper.popD(), smapper.popI(), smapper.popA());
1221 emit(smapper, this, "Array.at(@3, @2, @1);",
1222 smapper.popA(), smapper.popI(), smapper.popA());
1228 emit(smapper, this, "Array.at(@3, @2, @1);",
1229 smapper.popI(), smapper.popI(), smapper.popA());
1232 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1233 smapper.popI(), smapper.getA(0));
1236 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1237 smapper.popI(), smapper.getA(0));
1240 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1241 smapper.popI(), smapper.getA(0));
1244 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1245 smapper.popI(), smapper.getA(0));
1251 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1252 smapper.popI(), smapper.getA(0));
1260 final Variable v = smapper.get(0);
1261 if (smapper.isDirty()) {
1262 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1264 smapper.assign(this, v.getType(), v);
1269 final Variable vi1 = smapper.get(0);
1271 if (vi1.isCategory2()) {
1272 emit(smapper, this, "var @1 = @2;",
1273 smapper.pushT(vi1.getType()), vi1);
1275 final Variable vi2 = smapper.get(1);
1276 emit(smapper, this, "var @1 = @2, @3 = @4;",
1277 smapper.pushT(vi2.getType()), vi2,
1278 smapper.pushT(vi1.getType()), vi1);
1283 final Variable vi1 = smapper.pop(this);
1284 final Variable vi2 = smapper.pop(this);
1285 final Variable vo3 = smapper.pushT(vi1.getType());
1286 final Variable vo2 = smapper.pushT(vi2.getType());
1287 final Variable vo1 = smapper.pushT(vi1.getType());
1289 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1290 vo1, vi1, vo2, vi2, vo3, vo1);
1294 final Variable vi1 = smapper.pop(this);
1295 final Variable vi2 = smapper.pop(this);
1297 if (vi1.isCategory2()) {
1298 final Variable vo3 = smapper.pushT(vi1.getType());
1299 final Variable vo2 = smapper.pushT(vi2.getType());
1300 final Variable vo1 = smapper.pushT(vi1.getType());
1302 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1303 vo1, vi1, vo2, vi2, vo3, vo1);
1305 final Variable vi3 = smapper.pop(this);
1306 final Variable vo5 = smapper.pushT(vi2.getType());
1307 final Variable vo4 = smapper.pushT(vi1.getType());
1308 final Variable vo3 = smapper.pushT(vi3.getType());
1309 final Variable vo2 = smapper.pushT(vi2.getType());
1310 final Variable vo1 = smapper.pushT(vi1.getType());
1312 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1313 vo1, vi1, vo2, vi2, vo3, vi3);
1314 emit(smapper, this, " @1 = @2, @3 = @4;",
1315 vo4, vo1, vo5, vo2);
1320 final Variable vi1 = smapper.pop(this);
1321 final Variable vi2 = smapper.pop(this);
1323 if (vi2.isCategory2()) {
1324 final Variable vo3 = smapper.pushT(vi1.getType());
1325 final Variable vo2 = smapper.pushT(vi2.getType());
1326 final Variable vo1 = smapper.pushT(vi1.getType());
1328 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1329 vo1, vi1, vo2, vi2, vo3, vo1);
1331 final Variable vi3 = smapper.pop(this);
1332 final Variable vo4 = smapper.pushT(vi1.getType());
1333 final Variable vo3 = smapper.pushT(vi3.getType());
1334 final Variable vo2 = smapper.pushT(vi2.getType());
1335 final Variable vo1 = smapper.pushT(vi1.getType());
1337 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1338 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1343 final Variable vi1 = smapper.pop(this);
1344 final Variable vi2 = smapper.pop(this);
1346 if (vi1.isCategory2()) {
1347 if (vi2.isCategory2()) {
1348 final Variable vo3 = smapper.pushT(vi1.getType());
1349 final Variable vo2 = smapper.pushT(vi2.getType());
1350 final Variable vo1 = smapper.pushT(vi1.getType());
1352 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1353 vo1, vi1, vo2, vi2, vo3, vo1);
1355 final Variable vi3 = smapper.pop(this);
1356 final Variable vo4 = smapper.pushT(vi1.getType());
1357 final Variable vo3 = smapper.pushT(vi3.getType());
1358 final Variable vo2 = smapper.pushT(vi2.getType());
1359 final Variable vo1 = smapper.pushT(vi1.getType());
1361 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1362 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1365 final Variable vi3 = smapper.pop(this);
1367 if (vi3.isCategory2()) {
1368 final Variable vo5 = smapper.pushT(vi2.getType());
1369 final Variable vo4 = smapper.pushT(vi1.getType());
1370 final Variable vo3 = smapper.pushT(vi3.getType());
1371 final Variable vo2 = smapper.pushT(vi2.getType());
1372 final Variable vo1 = smapper.pushT(vi1.getType());
1374 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1375 vo1, vi1, vo2, vi2, vo3, vi3);
1376 emit(smapper, this, " @1 = @2, @3 = @4;",
1377 vo4, vo1, vo5, vo2);
1379 final Variable vi4 = smapper.pop(this);
1380 final Variable vo6 = smapper.pushT(vi2.getType());
1381 final Variable vo5 = smapper.pushT(vi1.getType());
1382 final Variable vo4 = smapper.pushT(vi4.getType());
1383 final Variable vo3 = smapper.pushT(vi3.getType());
1384 final Variable vo2 = smapper.pushT(vi2.getType());
1385 final Variable vo1 = smapper.pushT(vi1.getType());
1387 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1388 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1389 emit(smapper, this, " @1 = @2, @3 = @4;",
1390 vo5, vo1, vo6, vo2);
1396 final Variable vi1 = smapper.get(0);
1397 final Variable vi2 = smapper.get(1);
1399 if (vi1.getType() == vi2.getType()) {
1400 final Variable tmp = smapper.pushT(vi1.getType());
1402 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1407 smapper.pushT(vi1.getType());
1408 smapper.pushT(vi2.getType());
1413 smapper.assign(this, VarType.INTEGER,
1414 "(" + Integer.toString(byteCodes[++i]) + ")");
1417 smapper.assign(this, VarType.INTEGER,
1418 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1422 case opc_getfield: {
1423 int indx = readUShortArg(byteCodes, i);
1424 String[] fi = jc.getFieldInfoName(indx);
1425 final int type = VarType.fromFieldType(fi[2].charAt(0));
1426 FieldData field = findField(fi);
1427 if (field == null) {
1428 final String mangleClass = mangleClassName(fi[0]);
1429 final String mangleClassAccess = accessClassFalse(mangleClass);
1430 smapper.replace(this, type, "@2.call(@1)",
1432 accessField(mangleClassAccess, null, fi)
1435 final String fieldOwner = mangleClassName(field.cls.getClassName());
1436 smapper.replace(this, type, "@1.@2",
1438 accessField(fieldOwner, field, fi)
1442 addReference(fi[0]);
1445 case opc_putfield: {
1446 int indx = readUShortArg(byteCodes, i);
1447 String[] fi = jc.getFieldInfoName(indx);
1448 final int type = VarType.fromFieldType(fi[2].charAt(0));
1449 FieldData field = findField(fi);
1450 if (field == null) {
1451 final String mangleClass = mangleClassName(fi[0]);
1452 final String mangleClassAccess = accessClassFalse(mangleClass);
1453 emit(smapper, this, "@3.call(@2, @1);",
1456 accessField(mangleClassAccess, null, fi)
1459 final String fieldOwner = mangleClassName(field.cls.getClassName());
1460 emit(smapper, this, "@2.@3 = @1;",
1463 accessField(fieldOwner, field, fi)
1467 addReference(fi[0]);
1470 case opc_getstatic: {
1471 int indx = readUShortArg(byteCodes, i);
1472 String[] fi = jc.getFieldInfoName(indx);
1473 final int type = VarType.fromFieldType(fi[2].charAt(0));
1474 String ac = accessClassFalse(mangleClassName(fi[0]));
1475 String af = accessField(ac, null, fi);
1476 smapper.assign(this, type, af + "()");
1478 addReference(fi[0]);
1481 case opc_putstatic: {
1482 int indx = readUShortArg(byteCodes, i);
1483 String[] fi = jc.getFieldInfoName(indx);
1484 final int type = VarType.fromFieldType(fi[2].charAt(0));
1485 emit(smapper, this, "@1._@2(@3);",
1486 accessClassFalse(mangleClassName(fi[0])), fi[1],
1487 smapper.popT(type));
1489 addReference(fi[0]);
1492 case opc_checkcast: {
1493 int indx = readUShortArg(byteCodes, i);
1494 generateCheckcast(indx, smapper);
1498 case opc_instanceof: {
1499 int indx = readUShortArg(byteCodes, i);
1500 generateInstanceOf(indx, smapper);
1505 final CharSequence v = smapper.popA();
1508 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1509 smapper.pushA(), v);
1513 case opc_monitorenter: {
1514 debug("/* monitor enter */");
1519 case opc_monitorexit: {
1520 debug("/* monitor exit */");
1531 emit(smapper, this, "throw 'unknown bytecode @1';",
1532 Integer.toString(c));
1536 generateByteCodeComment(prev, i, byteCodes);
1542 if (previousTrap != null) {
1543 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1548 while (openBraces-- > 0) {
1559 private int generateIf(StackMapper mapper, byte[] byteCodes,
1560 int i, final CharSequence v2, final CharSequence v1,
1561 final String test, int topMostLabel
1562 ) throws IOException {
1564 int indx = i + readShortArg(byteCodes, i);
1565 append("if ((").append(v1)
1566 .append(") ").append(test).append(" (")
1567 .append(v2).append(")) ");
1568 goTo(this, i, indx, topMostLabel);
1572 private int readInt4(byte[] byteCodes, int offset) {
1573 final int d = byteCodes[offset + 0] << 24;
1574 final int c = byteCodes[offset + 1] << 16;
1575 final int b = byteCodes[offset + 2] << 8;
1576 final int a = byteCodes[offset + 3];
1577 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1579 private static int readUByte(byte[] byteCodes, int offset) {
1580 return byteCodes[offset] & 0xff;
1583 private static int readUShort(byte[] byteCodes, int offset) {
1584 return ((byteCodes[offset] & 0xff) << 8)
1585 | (byteCodes[offset + 1] & 0xff);
1587 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1588 return readUShort(byteCodes, offsetInstruction + 1);
1591 private static int readShort(byte[] byteCodes, int offset) {
1592 int signed = byteCodes[offset];
1593 byte b0 = (byte)signed;
1594 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1596 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1597 return readShort(byteCodes, offsetInstruction + 1);
1600 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1602 Boolean count = null;
1603 boolean array = false;
1605 int firstPos = sig.length();
1606 while (i < descriptor.length()) {
1607 char ch = descriptor.charAt(i++);
1628 if (ch == 'J' || ch == 'D') {
1634 sig.insert(firstPos, ch);
1636 returnType[0] = '[';
1637 sig.insert(firstPos, "_3");
1646 returnType[0] = 'V';
1647 sig.insert(firstPos, 'V');
1650 int next = descriptor.indexOf(';', i);
1651 String realSig = mangleSig(descriptor, i - 1, next + 1);
1656 sig.append(realSig);
1659 sig.insert(firstPos, realSig);
1661 sig.insert(firstPos, "_3");
1663 returnType[0] = 'L';
1672 throw new IllegalStateException("Invalid char: " + ch);
1677 static String mangleSig(String sig) {
1678 return mangleSig(sig, 0, sig.length());
1681 private static String mangleMethodName(String name) {
1682 StringBuilder sb = new StringBuilder(name.length() * 2);
1683 int last = name.length();
1684 for (int i = 0; i < last; i++) {
1685 final char ch = name.charAt(i);
1687 case '_': sb.append("_1"); break;
1688 default: sb.append(ch); break;
1691 return sb.toString();
1693 private static String mangleSig(String txt, int first, int last) {
1694 StringBuilder sb = new StringBuilder((last - first) * 2);
1695 for (int i = first; i < last; i++) {
1696 final char ch = txt.charAt(i);
1698 case '/': sb.append('_'); break;
1699 case '_': sb.append("_1"); break;
1700 case ';': sb.append("_2"); break;
1701 case '[': sb.append("_3"); break;
1703 if (Character.isJavaIdentifierPart(ch)) {
1707 String hex = Integer.toHexString(ch).toLowerCase();
1708 for (int m = hex.length(); m < 4; m++) {
1716 return sb.toString();
1719 private static String mangleClassName(String name) {
1720 return mangleSig(name);
1723 private static String findMethodName(MethodData m, StringBuilder cnt) {
1724 StringBuilder name = new StringBuilder();
1725 if ("<init>".equals(m.getName())) { // NOI18N
1726 name.append("cons"); // NOI18N
1727 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1728 name.append("class"); // NOI18N
1730 name.append(mangleMethodName(m.getName()));
1733 countArgs(m.getInternalSig(), new char[1], name, cnt);
1734 return name.toString();
1737 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1738 StringBuilder name = new StringBuilder();
1739 String descr = mi[2];//mi.getDescriptor();
1741 if ("<init>".equals(nm)) { // NOI18N
1742 name.append("cons"); // NOI18N
1744 name.append(mangleMethodName(nm));
1746 countArgs(descr, returnType, name, cnt);
1747 return name.toString();
1750 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1751 throws IOException {
1752 int methodIndex = readUShortArg(byteCodes, i);
1753 String[] mi = jc.getFieldInfoName(methodIndex);
1754 char[] returnType = { 'V' };
1755 StringBuilder cnt = new StringBuilder();
1756 String mn = findMethodName(mi, cnt, returnType);
1758 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1759 final CharSequence[] vars = new CharSequence[numArguments];
1761 for (int j = numArguments - 1; j >= 0; --j) {
1762 vars[j] = mapper.popValue();
1766 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1767 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1769 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1770 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1772 if (vars[1] instanceof String) {
1773 String field = vars[1].toString();
1774 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1775 vars[1] = "c._" + field.substring(1, field.length() - 1);
1780 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1781 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1783 if (vars[1] instanceof String) {
1784 String field = vars[2].toString();
1785 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1786 vars[2] = "c._" + field.substring(1, field.length() - 1);
1791 if (returnType[0] != 'V') {
1794 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1798 final String in = mi[0];
1801 in.equals("org/apidesign/html/boot/spi/Fn") ||
1802 in.equals("org/netbeans/html/boot/spi/Fn")
1804 mcn = "java_lang_Class";
1806 mcn = mangleClassName(in);
1808 String object = accessClassFalse(mcn);
1809 if (mn.startsWith("cons_")) {
1810 object += ".constructor";
1812 append(accessStaticMethod(object, mn, mi));
1818 if (numArguments > 0) {
1820 for (int j = 1; j < numArguments; ++j) {
1830 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1831 throws IOException {
1832 int methodIndex = readUShortArg(byteCodes, i);
1833 String[] mi = jc.getFieldInfoName(methodIndex);
1834 char[] returnType = { 'V' };
1835 StringBuilder cnt = new StringBuilder();
1836 String mn = findMethodName(mi, cnt, returnType);
1838 final int numArguments = cnt.length() + 1;
1839 final CharSequence[] vars = new CharSequence[numArguments];
1841 for (int j = numArguments - 1; j >= 0; --j) {
1842 vars[j] = mapper.popValue();
1845 if (returnType[0] != 'V') {
1848 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1852 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1854 for (int j = 1; j < numArguments; ++j) {
1864 private void addReference(String cn) throws IOException {
1865 if (requireReference(cn)) {
1866 debug(" /* needs " + cn + " */");
1870 private void outType(String d, StringBuilder out) {
1872 while (d.charAt(0) == '[') {
1876 if (d.charAt(0) == 'L') {
1877 assert d.charAt(d.length() - 1) == ';';
1878 out.append(mangleClassName(d).substring(0, d.length() - 1));
1884 private String encodeConstant(int entryIndex) throws IOException {
1885 String[] classRef = { null };
1886 String s = jc.stringValue(entryIndex, classRef);
1887 if (classRef[0] != null) {
1888 if (classRef[0].startsWith("[")) {
1889 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1891 addReference(classRef[0]);
1892 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1898 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1899 byte[] arr = m.findAnnotationData(true);
1903 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1904 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1905 class P extends AnnotationParser {
1911 String[] args = new String[30];
1917 protected void visitAttr(String type, String attr, String at, String value) {
1918 if (type.equals(jvmType)) {
1919 if ("body".equals(attr)) {
1921 } else if ("args".equals(attr)) {
1922 args[cnt++] = value;
1924 throw new IllegalArgumentException(attr);
1927 if (type.equals(htmlType)) {
1929 if ("body".equals(attr)) {
1931 } else if ("args".equals(attr)) {
1932 args[cnt++] = value;
1933 } else if ("javacall".equals(attr)) {
1934 javacall = "1".equals(value);
1935 } else if ("wait4js".equals(attr)) {
1936 // ignore, we always invoke synchronously
1938 throw new IllegalArgumentException(attr);
1945 if (p.body == null) {
1948 StringBuilder cnt = new StringBuilder();
1949 final String mn = findMethodName(m, cnt);
1950 append("m = ").append(destObject).append(".").append(mn);
1951 append(" = function(");
1954 StringBuilder toValue = new StringBuilder();
1955 for (int i = 0; i < cnt.length(); i++) {
1957 space = outputArg(this, p.args, index);
1958 if (p.html4j && space.length() > 0) {
1959 toValue.append("\n ").append(p.args[index]).append(" = ")
1960 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1961 append(p.args[index]).append(");");
1965 append(") {").append("\n");
1966 append(toValue.toString());
1968 int lastSlash = jc.getClassName().lastIndexOf('/');
1969 final String pkg = jc.getClassName().substring(0, lastSlash);
1970 append(mangleCallbacks(pkg, p.body));
1971 requireReference(pkg + "/$JsCallbacks$");
1979 private static CharSequence mangleCallbacks(String pkgName, String body) {
1980 StringBuilder sb = new StringBuilder();
1983 int next = body.indexOf(".@", pos);
1985 sb.append(body.substring(pos));
1986 body = sb.toString();
1991 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1996 String refId = body.substring(ident, next);
1998 sb.append(body.substring(pos, ident));
2000 int sigBeg = body.indexOf('(', next);
2001 int sigEnd = body.indexOf(')', sigBeg);
2002 int colon4 = body.indexOf("::", next);
2003 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2004 throw new IllegalStateException("Malformed body " + body);
2006 String fqn = body.substring(next + 2, colon4);
2007 String method = body.substring(colon4 + 2, sigBeg);
2008 String params = body.substring(sigBeg, sigEnd + 1);
2010 int paramBeg = body.indexOf('(', sigEnd + 1);
2012 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2013 sb.append(mangleJsCallbacks(fqn, method, params, false));
2014 sb.append("(").append(refId);
2015 if (body.charAt(paramBeg + 1) != ')') {
2023 int next = body.indexOf("@", pos);
2028 sb.append(body.substring(pos));
2032 sb = new StringBuilder();
2035 sb.append(body.substring(pos, next));
2037 int sigBeg = body.indexOf('(', next);
2038 int sigEnd = body.indexOf(')', sigBeg);
2039 int colon4 = body.indexOf("::", next);
2040 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2041 throw new IllegalStateException("Malformed body " + body);
2043 String fqn = body.substring(next + 1, colon4);
2044 String method = body.substring(colon4 + 2, sigBeg);
2045 String params = body.substring(sigBeg, sigEnd + 1);
2047 int paramBeg = body.indexOf('(', sigEnd + 1);
2049 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2050 sb.append(mangleJsCallbacks(fqn, method, params, true));
2056 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2057 if (params.startsWith("(")) {
2058 params = params.substring(1);
2060 if (params.endsWith(")")) {
2061 params = params.substring(0, params.length() - 1);
2063 StringBuilder sb = new StringBuilder();
2064 final String fqnu = fqn.replace('.', '_');
2065 final String rfqn = mangleClassName(fqnu);
2066 final String rm = mangleMethodName(method);
2069 StringBuilder pb = new StringBuilder();
2070 int len = params.length();
2072 while (indx < len) {
2073 char ch = params.charAt(indx);
2074 if (ch == '[' || ch == 'L') {
2075 int column = params.indexOf(';', indx) + 1;
2076 if (column > indx) {
2077 String real = params.substring(indx, column);
2078 if ("Ljava/lang/String;".equals(real)) {
2079 pb.append("Ljava/lang/String;");
2084 pb.append("Ljava/lang/Object;");
2091 srp = mangleSig(pb.toString());
2093 final String rp = mangleSig(params);
2094 final String mrp = mangleMethodName(rp);
2095 sb.append(rfqn).append("$").append(rm).
2096 append('$').append(mrp).append("__Ljava_lang_Object_2");
2098 sb.append('L').append(fqnu).append("_2");
2101 return sb.toString();
2104 private static String className(ClassData jc) {
2105 //return jc.getName().getInternalName().replace('/', '_');
2106 return mangleClassName(jc.getClassName());
2109 private static String[] findAnnotation(
2110 byte[] arr, ClassData cd, final String className,
2111 final String... attrNames
2112 ) throws IOException {
2116 final String[] values = new String[attrNames.length];
2117 final boolean[] found = { false };
2118 final String jvmType = "L" + className.replace('.', '/') + ";";
2119 AnnotationParser ap = new AnnotationParser(false, true) {
2121 protected void visitAttr(String type, String attr, String at, String value) {
2122 if (type.equals(jvmType)) {
2124 for (int i = 0; i < attrNames.length; i++) {
2125 if (attrNames[i].equals(attr)) {
2134 return found[0] ? values : null;
2137 private CharSequence initField(FieldData v) {
2138 final String is = v.getInternalSig();
2139 if (is.length() == 1) {
2140 switch (is.charAt(0)) {
2146 case 'I': return " = 0;";
2148 case 'D': return " = 0.0;";
2150 throw new IllegalStateException(is);
2156 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2157 AnnotationParser ap = new AnnotationParser(true, false) {
2158 int[] cnt = new int[32];
2162 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2163 final String slashType = attrType.substring(1, attrType.length() - 1);
2164 requireReference(slashType);
2166 if (cnt[depth]++ > 0) {
2170 append('"').append(attrType).append("\" : ");
2177 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2183 protected void visitValueStart(String attrName, char type) throws IOException {
2184 if (cnt[depth]++ > 0) {
2188 if (attrName != null) {
2189 append('"').append(attrName).append("\" : ");
2197 protected void visitValueEnd(String attrName, char type) throws IOException {
2205 protected void visitAttr(String type, String attr, String attrType, String value)
2206 throws IOException {
2207 if (attr == null && value == null) {
2214 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2215 throws IOException {
2216 final String slashType = attrType.substring(1, attrType.length() - 1);
2217 requireReference(slashType);
2219 final String cn = mangleClassName(slashType);
2220 append(accessClassFalse(cn))
2221 .append("['valueOf__L").
2223 append("_2Ljava_lang_String_2']('").
2231 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2232 final String name = args[indx];
2236 if (name.contains(",")) {
2237 throw new IOException("Wrong parameter with ',': " + name);
2243 final void emitNoFlush(
2245 final String format, final CharSequence... params
2246 ) throws IOException {
2247 emitImpl(this, format, params);
2249 static final void emit(
2251 final Appendable out,
2252 final String format, final CharSequence... params
2253 ) throws IOException {
2255 emitImpl(out, format, params);
2257 static void emitImpl(final Appendable out,
2258 final String format,
2259 final CharSequence... params) throws IOException {
2260 final int length = format.length();
2263 int paramOffset = format.indexOf('@');
2264 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2265 final char paramChar = format.charAt(paramOffset + 1);
2266 if ((paramChar >= '1') && (paramChar <= '9')) {
2267 final int paramIndex = paramChar - '0' - 1;
2269 out.append(format, processed, paramOffset);
2270 out.append(params[paramIndex]);
2273 processed = paramOffset + 1;
2276 paramOffset = format.indexOf('@', paramOffset + 1);
2279 out.append(format, processed, length);
2282 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2283 append("} catch (e) {\n");
2285 for (TrapData e : traps) {
2289 if (e.catch_cpx != 0) { //not finally
2290 final String classInternalName = jc.getClassName(e.catch_cpx);
2291 addReference(classInternalName);
2292 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2293 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2294 append("var stA0 = e;");
2295 goTo(this, current, e.handler_pc, topMostLabel);
2298 finallyPC = e.handler_pc;
2301 if (finallyPC == -1) {
2304 append("var stA0 = e;");
2305 goTo(this, current, finallyPC, topMostLabel);
2310 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2313 out.append("{ gt = 0; continue X_" + to + "; }");
2315 out.append("{ gt = " + to + "; continue X_0; }");
2318 out.append("{ gt = " + to + "; break IF; }");
2322 private static void emitIf(
2324 Appendable out, String pattern,
2326 int current, int to, int canBack
2327 ) throws IOException {
2329 emitImpl(out, pattern, param);
2330 goTo(out, current, to, canBack);
2333 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2336 case 4: jvmType = "[Z"; break;
2337 case 5: jvmType = "[C"; break;
2338 case 6: jvmType = "[F"; break;
2339 case 7: jvmType = "[D"; break;
2340 case 8: jvmType = "[B"; break;
2341 case 9: jvmType = "[S"; break;
2342 case 10: jvmType = "[I"; break;
2343 case 11: jvmType = "[J"; break;
2344 default: throw new IllegalStateException("Array type: " + atype);
2347 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2348 smapper.popI(), smapper.pushA(), jvmType);
2351 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2352 String typeName = jc.getClassName(type);
2353 String ref = "null";
2354 if (typeName.startsWith("[")) {
2355 typeName = "'[" + typeName + "'";
2357 ref = "vm." + mangleClassName(typeName);
2358 typeName = "'[L" + typeName + ";'";
2361 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2362 smapper.popI(), smapper.pushA(), typeName, ref);
2365 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2366 String typeName = jc.getClassName(type);
2367 int dim = readUByte(byteCodes, ++i);
2368 StringBuilder dims = new StringBuilder();
2370 for (int d = 0; d < dim; d++) {
2372 dims.insert(1, ",");
2374 dims.insert(1, smapper.popI());
2378 if (typeName.charAt(dim) == 'L') {
2379 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2382 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2383 dims.toString(), smapper.pushA(), typeName, fn
2388 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2389 int table = i / 4 * 4 + 4;
2390 int dflt = i + readInt4(byteCodes, table);
2392 int low = readInt4(byteCodes, table);
2394 int high = readInt4(byteCodes, table);
2396 final CharSequence swVar = smapper.popValue();
2397 smapper.flush(this);
2398 append("switch (").append(swVar).append(") {\n");
2399 while (low <= high) {
2400 int offset = i + readInt4(byteCodes, table);
2402 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2405 append(" default: ");
2406 goTo(this, i, dflt, topMostLabel);
2412 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2413 int table = i / 4 * 4 + 4;
2414 int dflt = i + readInt4(byteCodes, table);
2416 int n = readInt4(byteCodes, table);
2418 final CharSequence swVar = smapper.popValue();
2419 smapper.flush(this);
2420 append("switch (").append(swVar).append(") {\n");
2422 int cnstnt = readInt4(byteCodes, table);
2424 int offset = i + readInt4(byteCodes, table);
2426 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2428 append(" default: ");
2429 goTo(this, i, dflt, topMostLabel);
2435 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2436 String type = jc.getClassName(indx);
2437 if (!type.startsWith("[")) {
2439 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2440 smapper.popA(), smapper.pushI(),
2441 mangleClassName(type));
2444 while (type.charAt(cnt) == '[') {
2447 if (type.charAt(cnt) == 'L') {
2448 String component = type.substring(cnt + 1, type.length() - 1);
2449 requireReference(component);
2450 type = "vm." + mangleClassName(component);
2452 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2453 smapper.popA(), smapper.pushI(),
2458 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2459 smapper.popA(), smapper.pushI(), type
2465 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2466 String type = jc.getClassName(indx);
2467 if (!type.startsWith("[")) {
2468 emitNoFlush(smapper,
2469 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2470 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2473 while (type.charAt(cnt) == '[') {
2476 if (type.charAt(cnt) == 'L') {
2477 String component = type.substring(cnt + 1, type.length() - 1);
2478 requireReference(component);
2479 type = "vm." + mangleClassName(component);
2480 emitNoFlush(smapper,
2481 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2482 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2485 emitNoFlush(smapper,
2486 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2487 smapper.getT(0, VarType.REFERENCE, false), type
2493 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2494 for (int j = prev; j <= i; j++) {
2496 final int cc = readUByte(byteCodes, j);
2497 append(Integer.toString(cc));
2501 @JavaScriptBody(args = "msg", body = "")
2502 private static void println(String msg) {
2503 System.err.println(msg);