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 declaredClass(ClassData classData, String mangledName)
137 protected void declaredField(FieldData fieldData,
139 String mangledName) throws IOException {
142 protected void declaredMethod(MethodData methodData,
144 String mangledName) throws IOException {
147 /** Prints out a debug message.
149 * @param msg the message
150 * @return true if the message has been printed
151 * @throws IOException
153 boolean debug(String msg) throws IOException {
159 * Converts a given class file to a JavaScript version.
161 * @param classFile input stream with code of the .class file
162 * @return the initialization code for this class, if any. Otherwise <code>null</code>
164 * @throws IOException if something goes wrong during read or write or translating
167 public String compile(InputStream classFile) throws IOException {
168 return compile(new ClassData(classFile));
171 protected String compile(ClassData classData) throws IOException {
173 final String cn = this.jc.getClassName();
175 return compileImpl(cn);
176 } catch (IOException ex) {
177 throw new IOException("Cannot compile " + cn + ":", ex);
181 private String compileImpl(final String cn) throws IOException {
182 this.callbacks = cn.endsWith("/$JsCallbacks$");
183 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
184 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
185 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
188 byte[] arrData = jc.findAnnotationData(true);
190 String[] arr = findAnnotation(arrData, jc,
191 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
192 "resource", "processByteCode"
195 if (!arr[0].isEmpty()) {
196 requireScript(arr[0]);
198 if ("0".equals(arr[1])) {
203 final String jsResource;
205 String[] arr = findAnnotation(arrData, jc,
206 "net.java.html.js.JavaScriptResource",
210 if (arr[0].startsWith("/")) {
213 int last = cn.lastIndexOf('/');
214 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
220 String[] proto = findAnnotation(arrData, jc,
221 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
222 "container", "prototype"
224 StringArray toInitilize = new StringArray();
225 final String className = className(jc);
226 append("\n\n").append(assignClass(className));
227 append("function ").append(className).append("() {");
229 append("\n var CLS = ").append(className).append(';');
230 append("\n if (!CLS.$class) {");
232 String sc = jc.getSuperClassName(); // with _
233 append("\n var pp = ").
234 append(accessClass(mangleClassName(sc))).append("(true);");
235 append("\n var p = CLS.prototype = pp;");
236 append("\n var c = p;");
237 append("\n var sprcls = pp.constructor.$class;");
239 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
240 if (proto[0] == null) {
243 append("\n var c = ").append(proto[0]).append(";");
244 append("\n var sprcls = null;");
246 for (FieldData v : jc.getFields()) {
248 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
249 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
253 append("\n CLS.fld_").append(v.getName()).append(initField(v));
254 append("\n m = c._").append(v.getName()).append(" = function (v) {")
255 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
256 .append(" = v; return CLS.fld_").
257 append(v.getName()).append("; };");
259 append("\n m = c._").append(v.getName()).append(" = function (v) {")
260 .append(" if (arguments.length == 1) this.fld_").
261 append(className).append('_').append(v.getName())
262 .append(" = v; return this.fld_").
263 append(className).append('_').append(v.getName())
267 declaredField(v, "c", "_" + v.getName());
269 for (MethodData m : jc.getMethods()) {
270 byte[] onlyArr = m.findAnnotationData(true);
271 if (javaScriptOnly(onlyArr)) continue;
277 mn = generateStaticMethod(destObject, m, toInitilize);
279 if (m.isConstructor()) {
281 mn = generateInstanceMethod(destObject, m);
284 mn = generateInstanceMethod(destObject, m);
287 declaredMethod(m, destObject, mn);
288 byte[] runAnno = m.findAnnotationData(false);
289 if (runAnno != null) {
290 append("\n m.anno = {");
291 AnnotationParser ap = new GenerateAnno(true, false);
292 ap.parse(runAnno, jc);
295 append("\n m.access = " + m.getAccess()).append(";");
296 append("\n m.cls = CLS;");
298 append(numbers.generate());
299 append("\n c.constructor = CLS;");
300 append("\n function ").append(className).append("fillInstOf(x) {");
301 String instOfName = "$instOf_" + className;
302 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
303 if (jc.isInterface()) {
304 for (MethodData m : jc.getMethods()) {
305 if ((m.getAccess() & ACC_ABSTRACT) == 0
306 && (m.getAccess() & ACC_STATIC) == 0
307 && (m.getAccess() & ACC_PRIVATE) == 0) {
308 final String mn = findMethodName(m, new StringBuilder());
309 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
313 for (String superInterface : jc.getSuperInterfaces()) {
314 String intrfc = mangleClassName(superInterface);
315 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
316 requireReference(superInterface);
319 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
320 append("\n ").append(className).append("fillInstOf(c);");
321 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
322 append("\n CLS.$class = 'temp';");
323 append("\n CLS.$class = ");
324 append(accessClass("java_lang_Class(true);"));
325 append("\n CLS.$class.jvmName = '").append(cn).append("';");
326 append("\n CLS.$class.superclass = sprcls;");
327 append("\n CLS.$class.interfaces = function() { return [");
329 boolean first = true;
330 for (String intrfc : jc.getSuperInterfaces()) {
334 requireReference(intrfc);
335 String mangledIface = mangleClassName(intrfc);
337 append(accessClass(mangledIface)).append("(false).constructor.$class");
342 int flags = jc.getAccessFlags();
343 if (jc.hasEnclosingMethod()) {
346 append("\n CLS.$class.access = ").append(flags+";");
347 append("\n CLS.$class.cnstr = CLS;");
348 byte[] classAnno = jc.findAnnotationData(false);
349 if (classAnno != null) {
350 append("\n CLS.$class.anno = {");
351 AnnotationParser ap = new GenerateAnno(true, false);
352 ap.parse(classAnno, jc);
355 for (String init : toInitilize.toArray()) {
356 append("\n ").append(init).append("();");
358 for (String ref : classRefs.toArray()) {
359 append("\n var refs_").append(ref).append(";");
363 if (jsResource != null) {
364 requireResource(jsResource);
368 append("\n if (arguments.length === 0) {");
369 append("\n if (!(this instanceof CLS)) {");
370 append("\n return new CLS();");
372 for (FieldData v : jc.getFields()) {
373 byte[] onlyArr = v.findAnnotationData(true);
374 if (javaScriptOnly(onlyArr)) continue;
376 append("\n this.fld_").
377 append(className).append('_').
378 append(v.getName()).append(initField(v));
381 append("\n return this;");
383 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
386 declaredClass(jc, className);
388 // StringBuilder sb = new StringBuilder();
389 // for (String init : toInitilize.toArray()) {
390 // sb.append("\n").append(init).append("();");
395 private boolean javaScriptOnly(byte[] anno) throws IOException {
396 String[] only = findAnnotation(anno, jc,
397 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
401 if (only[0] != null && only[1] != null) {
402 append("\n p.").append(only[0]).append(" = ")
403 .append(only[1]).append(";");
405 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
406 append("\n p['").append(only[0]).append("'] = p.")
407 .append(only[0]).append(";");
413 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
414 String jsb = javaScriptBody(destObject, m, true);
418 final String mn = findMethodName(m, new StringBuilder());
419 boolean defineProp = generateMethod(destObject, mn, m);
420 if (mn.equals("class__V")) {
422 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
424 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
430 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
431 String jsb = javaScriptBody(destObject, m, false);
435 final String mn = findMethodName(m, new StringBuilder());
436 generateMethod(destObject, mn, m);
440 private boolean generateMethod(String destObject, String name, MethodData m)
442 final StackMapIterator stackMapIterator = m.createStackMapIterator();
443 TrapDataIterator trap = m.getTrapDataIterator();
444 final LocalsMapper lmapper =
445 new LocalsMapper(stackMapIterator.getArguments());
448 "java/lang/Object".equals(jc.getClassName()) ||
449 "java/lang/reflect/Array".equals(jc.getClassName());
452 append("Object.defineProperty(").append(destObject).
453 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
455 append("m = ").append(destObject).append(".").append(name).append(" = function(");
457 lmapper.outputArguments(this, m.isStatic());
458 append(") {").append("\n");
460 final byte[] byteCodes = m.getCode();
461 if (byteCodes == null) {
462 byte[] defaultAttr = m.getDefaultAttribute();
463 if (defaultAttr != null) {
465 AnnotationParser ap = new GenerateAnno(true, false);
466 ap.parseDefault(defaultAttr, jc);
469 if (debug(" throw 'no code found for ")) {
471 .append(jc.getClassName()).append('.')
472 .append(m.getName()).append("';\n");
483 final StackMapper smapper = new StackMapper();
486 append(" var ").append(" lcA0 = this;\n");
490 TrapData[] previousTrap = null;
491 boolean wide = false;
493 if (stackMapIterator.isEmpty()) {
499 append("\n var gt = 0;\n");
503 int topMostLabel = 0;
504 for (int i = 0; i < byteCodes.length; i++) {
507 stackMapIterator.advanceTo(i);
508 boolean changeInCatch = trap.advanceTo(i);
509 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
510 if (previousTrap != null) {
511 generateCatch(previousTrap, i, topMostLabel);
515 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
520 if (openBraces > 64) {
521 for (int c = 0; c < 64; c++) {
528 lastStackFrame = stackMapIterator.getFrameIndex();
529 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
530 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
531 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
533 changeInCatch = true;
535 debug(" /* " + i + " */ ");
537 if (changeInCatch && trap.useTry()) {
539 previousTrap = trap.current();
541 final int c = readUByte(byteCodes, i);
544 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
547 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
550 smapper.assign(this, VarType.LONG, lmapper.getL(0));
553 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
556 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
559 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
562 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
565 smapper.assign(this, VarType.LONG, lmapper.getL(1));
568 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
571 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
574 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
577 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
580 smapper.assign(this, VarType.LONG, lmapper.getL(2));
583 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
586 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
589 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
592 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
595 smapper.assign(this, VarType.LONG, lmapper.getL(3));
598 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
601 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
605 final int indx = wide ? readUShort(byteCodes, i++)
606 : readUByte(byteCodes, i);
608 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
613 final int indx = wide ? readUShort(byteCodes, i++)
614 : readUByte(byteCodes, i);
616 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
621 final int indx = wide ? readUShort(byteCodes, i++)
622 : readUByte(byteCodes, i);
624 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
629 final int indx = wide ? readUShort(byteCodes, i++)
630 : readUByte(byteCodes, i);
632 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
637 final int indx = wide ? readUShort(byteCodes, i++)
638 : readUByte(byteCodes, i);
640 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
645 final int indx = wide ? readUShort(byteCodes, i++)
646 : readUByte(byteCodes, i);
648 emit(smapper, this, "var @1 = @2;",
649 lmapper.setI(indx), smapper.popI());
654 final int indx = wide ? readUShort(byteCodes, i++)
655 : readUByte(byteCodes, i);
657 emit(smapper, this, "var @1 = @2;",
658 lmapper.setL(indx), smapper.popL());
663 final int indx = wide ? readUShort(byteCodes, i++)
664 : readUByte(byteCodes, i);
666 emit(smapper, this, "var @1 = @2;",
667 lmapper.setF(indx), smapper.popF());
672 final int indx = wide ? readUShort(byteCodes, i++)
673 : readUByte(byteCodes, i);
675 emit(smapper, this, "var @1 = @2;",
676 lmapper.setD(indx), smapper.popD());
681 final int indx = wide ? readUShort(byteCodes, i++)
682 : readUByte(byteCodes, i);
684 emit(smapper, this, "var @1 = @2;",
685 lmapper.setA(indx), smapper.popA());
689 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
692 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
695 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
698 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
701 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
704 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
707 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
710 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
713 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
716 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
719 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
722 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
725 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
728 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
731 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
734 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
737 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
740 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
743 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
746 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
749 smapper.replace(this, VarType.INTEGER, "(((@1) + (@2)) | 0)", smapper.getI(1), smapper.popI());
752 smapper.replace(this, VarType.LONG, numbers.add64(), smapper.getL(1), smapper.popL());
755 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
758 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
761 smapper.replace(this, VarType.INTEGER, "(((@1) - (@2)) | 0)", smapper.getI(1), smapper.popI());
764 smapper.replace(this, VarType.LONG, numbers.sub64(), smapper.getL(1), smapper.popL());
767 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
770 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
773 smapper.replace(this, VarType.INTEGER, numbers.mul32(), smapper.getI(1), smapper.popI());
776 smapper.replace(this, VarType.LONG, numbers.mul64(), smapper.getL(1), smapper.popL());
779 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
782 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
785 smapper.replace(this, VarType.INTEGER, numbers.div32(),
786 smapper.getI(1), smapper.popI());
789 smapper.replace(this, VarType.LONG, numbers.div64(),
790 smapper.getL(1), smapper.popL());
793 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
796 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
799 smapper.replace(this, VarType.INTEGER, numbers.mod32(),
800 smapper.getI(1), smapper.popI());
803 smapper.replace(this, VarType.LONG, numbers.mod64(),
804 smapper.getL(1), smapper.popL());
807 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
810 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
813 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
816 smapper.replace(this, VarType.LONG, numbers.and64(), smapper.getL(1), smapper.popL());
819 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
822 smapper.replace(this, VarType.LONG, numbers.or64(), smapper.getL(1), smapper.popL());
825 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
828 smapper.replace(this, VarType.LONG, numbers.xor64(), smapper.getL(1), smapper.popL());
831 smapper.replace(this, VarType.INTEGER, "(-(@1) | 0)", smapper.getI(0));
834 smapper.replace(this, VarType.LONG, numbers.neg64(), smapper.getL(0));
837 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
840 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
843 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
846 smapper.replace(this, VarType.LONG, numbers.shl64(), smapper.getL(1), smapper.popI());
849 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
852 smapper.replace(this, VarType.LONG, numbers.shr64(), smapper.getL(1), smapper.popI());
855 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
858 smapper.replace(this, VarType.LONG, numbers.ushr64(), smapper.getL(1), smapper.popI());
862 final int varIndx = wide ? readUShort(byteCodes, i++)
863 : readUByte(byteCodes, i);
865 final int incrBy = wide ? readShort(byteCodes, i++)
869 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
871 emit(smapper, this, "@1 += @2;",
872 lmapper.getI(varIndx),
873 Integer.toString(incrBy));
878 emit(smapper, this, "return;");
881 emit(smapper, this, "return @1;", smapper.popI());
884 emit(smapper, this, "return @1;", smapper.popL());
887 emit(smapper, this, "return @1;", smapper.popF());
890 emit(smapper, this, "return @1;", smapper.popD());
893 emit(smapper, this, "return @1;", smapper.popA());
896 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
899 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
902 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
905 smapper.replace(this, VarType.INTEGER, "((@1) | 0)", smapper.getL(0));
909 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
912 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
915 smapper.replace(this, VarType.DOUBLE, "@1",
919 smapper.replace(this, VarType.FLOAT, "@1",
923 smapper.replace(this, VarType.INTEGER, "((@1) | 0)",
927 smapper.replace(this, VarType.LONG, "(@1).toLong()",
931 smapper.replace(this, VarType.INTEGER, "((@1)| 0)",
935 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
938 smapper.replace(this, VarType.INTEGER, "(((@1) << 24) >> 24)", smapper.getI(0));
942 smapper.replace(this, VarType.INTEGER, "(((@1) << 16) >> 16)", smapper.getI(0));
944 case opc_aconst_null:
945 smapper.assign(this, VarType.REFERENCE, "null");
948 smapper.assign(this, VarType.INTEGER, "-1");
951 smapper.assign(this, VarType.INTEGER, "0");
954 smapper.assign(this, VarType.DOUBLE, "0");
957 smapper.assign(this, VarType.LONG, "0");
960 smapper.assign(this, VarType.FLOAT, "0");
963 smapper.assign(this, VarType.INTEGER, "1");
966 smapper.assign(this, VarType.LONG, "1");
969 smapper.assign(this, VarType.FLOAT, "1");
972 smapper.assign(this, VarType.DOUBLE, "1");
975 smapper.assign(this, VarType.INTEGER, "2");
978 smapper.assign(this, VarType.FLOAT, "2");
981 smapper.assign(this, VarType.INTEGER, "3");
984 smapper.assign(this, VarType.INTEGER, "4");
987 smapper.assign(this, VarType.INTEGER, "5");
990 int indx = readUByte(byteCodes, ++i);
991 String v = encodeConstant(indx);
992 int type = VarType.fromConstantType(jc.getTag(indx));
993 smapper.assign(this, type, v);
998 int indx = readUShortArg(byteCodes, i);
1000 String v = encodeConstant(indx);
1001 int type = VarType.fromConstantType(jc.getTag(indx));
1002 if (type == VarType.LONG) {
1003 final Long lv = new Long(v);
1004 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
1005 final int hi = (int)(lv.longValue() >> 32);
1007 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
1009 smapper.assign(this, VarType.LONG,
1010 "0x" + Integer.toHexString(hi) + ".next32(0x" +
1011 Integer.toHexString(low) + ")"
1015 smapper.assign(this, type, v);
1020 smapper.replace(this, VarType.INTEGER, numbers.compare64(), smapper.popL(), smapper.getL(0));
1024 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1025 smapper.popF(), smapper.popF(), smapper.pushI());
1029 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1030 smapper.popD(), smapper.popD(), smapper.pushI());
1033 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1034 "===", topMostLabel);
1037 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1038 "!==", topMostLabel);
1041 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1042 "==", topMostLabel);
1045 int indx = i + readShortArg(byteCodes, i);
1046 emitIf(smapper, this, "if ((@1) == 0) ",
1047 smapper.popI(), i, indx, topMostLabel);
1052 int indx = i + readShortArg(byteCodes, i);
1053 emitIf(smapper, this, "if ((@1) != 0) ",
1054 smapper.popI(), i, indx, topMostLabel);
1059 int indx = i + readShortArg(byteCodes, i);
1060 emitIf(smapper, this, "if ((@1) < 0) ",
1061 smapper.popI(), i, indx, topMostLabel);
1066 int indx = i + readShortArg(byteCodes, i);
1067 emitIf(smapper, this, "if ((@1) <= 0) ",
1068 smapper.popI(), i, indx, topMostLabel);
1073 int indx = i + readShortArg(byteCodes, i);
1074 emitIf(smapper, this, "if ((@1) > 0) ",
1075 smapper.popI(), i, indx, topMostLabel);
1080 int indx = i + readShortArg(byteCodes, i);
1081 emitIf(smapper, this, "if ((@1) >= 0) ",
1082 smapper.popI(), i, indx, topMostLabel);
1086 case opc_ifnonnull: {
1087 int indx = i + readShortArg(byteCodes, i);
1088 emitIf(smapper, this, "if ((@1) !== null) ",
1089 smapper.popA(), i, indx, topMostLabel);
1094 int indx = i + readShortArg(byteCodes, i);
1095 emitIf(smapper, this, "if ((@1) === null) ",
1096 smapper.popA(), i, indx, topMostLabel);
1101 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1102 "!=", topMostLabel);
1105 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1109 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1110 "<=", topMostLabel);
1113 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1117 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1118 ">=", topMostLabel);
1121 smapper.flush(this);
1122 int indx = i + readShortArg(byteCodes, i);
1123 goTo(this, i, indx, topMostLabel);
1127 case opc_lookupswitch: {
1128 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1131 case opc_tableswitch: {
1132 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1135 case opc_invokeinterface: {
1136 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1139 case opc_invokevirtual:
1140 i = invokeVirtualMethod(byteCodes, i, smapper);
1142 case opc_invokespecial:
1143 i = invokeStaticMethod(byteCodes, i, smapper, false);
1145 case opc_invokestatic:
1146 i = invokeStaticMethod(byteCodes, i, smapper, true);
1148 case opc_invokedynamic: {
1149 int indx = readUShortArg(byteCodes, i);
1150 println("invoke dynamic: " + indx);
1151 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1152 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1153 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1154 println(" type: " + methodHandle.cpx1);
1155 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1156 String mcn = mangleClassName(mi[0]);
1157 char[] returnType = {'V'};
1158 StringBuilder cnt = new StringBuilder();
1159 String mn = findMethodName(mi, cnt, returnType);
1160 StringBuilder sb = new StringBuilder();
1161 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1162 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1163 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1164 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1165 sb.append(" mn : ").append(mn).append("\n");
1166 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1167 throw new IOException(sb.toString());
1169 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1170 String type = jc.StringValue(nameAndType.cpx2);
1171 String object = accessClass(mcn) + "(false)";
1172 if (mn.startsWith("cons_")) {
1173 object += ".constructor";
1175 append("var metHan = ");
1176 append(accessStaticMethod(object, mn, mi));
1178 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1180 append(", '").append(mi[1]).append("', ");
1181 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1182 append(methodType).append("'").append(type).append("', null)");
1183 // if (numArguments > 0) {
1185 // for (int j = 1; j < numArguments; ++j) {
1191 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1197 int indx = readUShortArg(byteCodes, i);
1198 String ci = jc.getClassName(indx);
1199 emit(smapper, this, "var @1 = new @2;",
1200 smapper.pushA(), accessClass(mangleClassName(ci)));
1206 int atype = readUByte(byteCodes, ++i);
1207 generateNewArray(atype, smapper);
1209 case opc_anewarray: {
1210 int type = readUShortArg(byteCodes, i);
1212 generateANewArray(type, smapper);
1215 case opc_multianewarray: {
1216 int type = readUShortArg(byteCodes, i);
1218 i = generateMultiANewArray(type, byteCodes, i, smapper);
1221 case opc_arraylength:
1222 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1225 emit(smapper, this, "Array.at(@3, @2, @1);",
1226 smapper.popL(), smapper.popI(), smapper.popA());
1229 emit(smapper, this, "Array.at(@3, @2, @1);",
1230 smapper.popF(), smapper.popI(), smapper.popA());
1233 emit(smapper, this, "Array.at(@3, @2, @1);",
1234 smapper.popD(), smapper.popI(), smapper.popA());
1237 emit(smapper, this, "Array.at(@3, @2, @1);",
1238 smapper.popA(), smapper.popI(), smapper.popA());
1244 emit(smapper, this, "Array.at(@3, @2, @1);",
1245 smapper.popI(), smapper.popI(), smapper.popA());
1248 smapper.replace(this, VarType.LONG, "(@2[@1] || Array.at(@2, @1))",
1249 smapper.popI(), smapper.getA(0));
1252 smapper.replace(this, VarType.FLOAT, "(@2[@1] || Array.at(@2, @1))",
1253 smapper.popI(), smapper.getA(0));
1256 smapper.replace(this, VarType.DOUBLE, "(@2[@1] || Array.at(@2, @1))",
1257 smapper.popI(), smapper.getA(0));
1260 smapper.replace(this, VarType.REFERENCE, "(@2[@1] || Array.at(@2, @1))",
1261 smapper.popI(), smapper.getA(0));
1267 smapper.replace(this, VarType.INTEGER, "(@2[@1] || Array.at(@2, @1))",
1268 smapper.popI(), smapper.getA(0));
1276 final Variable v = smapper.get(0);
1277 if (smapper.isDirty()) {
1278 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1280 smapper.assign(this, v.getType(), v);
1285 final Variable vi1 = smapper.get(0);
1287 if (vi1.isCategory2()) {
1288 emit(smapper, this, "var @1 = @2;",
1289 smapper.pushT(vi1.getType()), vi1);
1291 final Variable vi2 = smapper.get(1);
1292 emit(smapper, this, "var @1 = @2, @3 = @4;",
1293 smapper.pushT(vi2.getType()), vi2,
1294 smapper.pushT(vi1.getType()), vi1);
1299 final Variable vi1 = smapper.pop(this);
1300 final Variable vi2 = smapper.pop(this);
1301 final Variable vo3 = smapper.pushT(vi1.getType());
1302 final Variable vo2 = smapper.pushT(vi2.getType());
1303 final Variable vo1 = smapper.pushT(vi1.getType());
1305 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1306 vo1, vi1, vo2, vi2, vo3, vo1);
1310 final Variable vi1 = smapper.pop(this);
1311 final Variable vi2 = smapper.pop(this);
1313 if (vi1.isCategory2()) {
1314 final Variable vo3 = smapper.pushT(vi1.getType());
1315 final Variable vo2 = smapper.pushT(vi2.getType());
1316 final Variable vo1 = smapper.pushT(vi1.getType());
1318 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1319 vo1, vi1, vo2, vi2, vo3, vo1);
1321 final Variable vi3 = smapper.pop(this);
1322 final Variable vo5 = smapper.pushT(vi2.getType());
1323 final Variable vo4 = smapper.pushT(vi1.getType());
1324 final Variable vo3 = smapper.pushT(vi3.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, vi3);
1330 emit(smapper, this, " @1 = @2, @3 = @4;",
1331 vo4, vo1, vo5, vo2);
1336 final Variable vi1 = smapper.pop(this);
1337 final Variable vi2 = smapper.pop(this);
1339 if (vi2.isCategory2()) {
1340 final Variable vo3 = smapper.pushT(vi1.getType());
1341 final Variable vo2 = smapper.pushT(vi2.getType());
1342 final Variable vo1 = smapper.pushT(vi1.getType());
1344 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1345 vo1, vi1, vo2, vi2, vo3, vo1);
1347 final Variable vi3 = smapper.pop(this);
1348 final Variable vo4 = smapper.pushT(vi1.getType());
1349 final Variable vo3 = smapper.pushT(vi3.getType());
1350 final Variable vo2 = smapper.pushT(vi2.getType());
1351 final Variable vo1 = smapper.pushT(vi1.getType());
1353 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1354 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1359 final Variable vi1 = smapper.pop(this);
1360 final Variable vi2 = smapper.pop(this);
1362 if (vi1.isCategory2()) {
1363 if (vi2.isCategory2()) {
1364 final Variable vo3 = smapper.pushT(vi1.getType());
1365 final Variable vo2 = smapper.pushT(vi2.getType());
1366 final Variable vo1 = smapper.pushT(vi1.getType());
1368 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1369 vo1, vi1, vo2, vi2, vo3, vo1);
1371 final Variable vi3 = smapper.pop(this);
1372 final Variable vo4 = smapper.pushT(vi1.getType());
1373 final Variable vo3 = smapper.pushT(vi3.getType());
1374 final Variable vo2 = smapper.pushT(vi2.getType());
1375 final Variable vo1 = smapper.pushT(vi1.getType());
1377 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1378 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1381 final Variable vi3 = smapper.pop(this);
1383 if (vi3.isCategory2()) {
1384 final Variable vo5 = smapper.pushT(vi2.getType());
1385 final Variable vo4 = smapper.pushT(vi1.getType());
1386 final Variable vo3 = smapper.pushT(vi3.getType());
1387 final Variable vo2 = smapper.pushT(vi2.getType());
1388 final Variable vo1 = smapper.pushT(vi1.getType());
1390 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1391 vo1, vi1, vo2, vi2, vo3, vi3);
1392 emit(smapper, this, " @1 = @2, @3 = @4;",
1393 vo4, vo1, vo5, vo2);
1395 final Variable vi4 = smapper.pop(this);
1396 final Variable vo6 = smapper.pushT(vi2.getType());
1397 final Variable vo5 = smapper.pushT(vi1.getType());
1398 final Variable vo4 = smapper.pushT(vi4.getType());
1399 final Variable vo3 = smapper.pushT(vi3.getType());
1400 final Variable vo2 = smapper.pushT(vi2.getType());
1401 final Variable vo1 = smapper.pushT(vi1.getType());
1403 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1404 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1405 emit(smapper, this, " @1 = @2, @3 = @4;",
1406 vo5, vo1, vo6, vo2);
1412 final Variable vi1 = smapper.get(0);
1413 final Variable vi2 = smapper.get(1);
1415 if (vi1.getType() == vi2.getType()) {
1416 final Variable tmp = smapper.pushT(vi1.getType());
1418 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1423 smapper.pushT(vi1.getType());
1424 smapper.pushT(vi2.getType());
1429 smapper.assign(this, VarType.INTEGER,
1430 "(" + Integer.toString(byteCodes[++i]) + ")");
1433 smapper.assign(this, VarType.INTEGER,
1434 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1438 case opc_getfield: {
1439 int indx = readUShortArg(byteCodes, i);
1440 String[] fi = jc.getFieldInfoName(indx);
1441 final int type = VarType.fromFieldType(fi[2].charAt(0));
1442 FieldData field = findField(fi);
1443 if (field == null) {
1444 final String mangleClass = mangleClassName(fi[0]);
1445 final String mangleClassAccess = accessClassFalse(mangleClass);
1446 smapper.replace(this, type, "@2.call(@1)",
1448 accessField(mangleClassAccess, null, fi)
1451 final String fieldOwner = mangleClassName(field.cls.getClassName());
1452 smapper.replace(this, type, "@1.@2",
1454 accessField(fieldOwner, field, fi)
1458 addReference(fi[0]);
1461 case opc_putfield: {
1462 int indx = readUShortArg(byteCodes, i);
1463 String[] fi = jc.getFieldInfoName(indx);
1464 final int type = VarType.fromFieldType(fi[2].charAt(0));
1465 FieldData field = findField(fi);
1466 if (field == null) {
1467 final String mangleClass = mangleClassName(fi[0]);
1468 final String mangleClassAccess = accessClassFalse(mangleClass);
1469 emit(smapper, this, "@3.call(@2, @1);",
1472 accessField(mangleClassAccess, null, fi)
1475 final String fieldOwner = mangleClassName(field.cls.getClassName());
1476 emit(smapper, this, "@2.@3 = @1;",
1479 accessField(fieldOwner, field, fi)
1483 addReference(fi[0]);
1486 case opc_getstatic: {
1487 int indx = readUShortArg(byteCodes, i);
1488 String[] fi = jc.getFieldInfoName(indx);
1489 final int type = VarType.fromFieldType(fi[2].charAt(0));
1490 String ac = accessClassFalse(mangleClassName(fi[0]));
1491 FieldData field = findField(fi);
1492 String af = accessField(ac, field, fi);
1493 smapper.assign(this, type, af + "()");
1495 addReference(fi[0]);
1498 case opc_putstatic: {
1499 int indx = readUShortArg(byteCodes, i);
1500 String[] fi = jc.getFieldInfoName(indx);
1501 final int type = VarType.fromFieldType(fi[2].charAt(0));
1502 emit(smapper, this, "@1._@2(@3);",
1503 accessClassFalse(mangleClassName(fi[0])), fi[1],
1504 smapper.popT(type));
1506 addReference(fi[0]);
1509 case opc_checkcast: {
1510 int indx = readUShortArg(byteCodes, i);
1511 generateCheckcast(indx, smapper);
1515 case opc_instanceof: {
1516 int indx = readUShortArg(byteCodes, i);
1517 generateInstanceOf(indx, smapper);
1522 final CharSequence v = smapper.popA();
1525 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1526 smapper.pushA(), v);
1530 case opc_monitorenter: {
1531 debug("/* monitor enter */");
1536 case opc_monitorexit: {
1537 debug("/* monitor exit */");
1548 emit(smapper, this, "throw 'unknown bytecode @1';",
1549 Integer.toString(c));
1553 generateByteCodeComment(prev, i, byteCodes);
1559 if (previousTrap != null) {
1560 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1565 while (openBraces-- > 0) {
1576 private int generateIf(StackMapper mapper, byte[] byteCodes,
1577 int i, final CharSequence v2, final CharSequence v1,
1578 final String test, int topMostLabel
1579 ) throws IOException {
1581 int indx = i + readShortArg(byteCodes, i);
1582 append("if ((").append(v1)
1583 .append(") ").append(test).append(" (")
1584 .append(v2).append(")) ");
1585 goTo(this, i, indx, topMostLabel);
1589 private int readInt4(byte[] byteCodes, int offset) {
1590 final int d = byteCodes[offset + 0] << 24;
1591 final int c = byteCodes[offset + 1] << 16;
1592 final int b = byteCodes[offset + 2] << 8;
1593 final int a = byteCodes[offset + 3];
1594 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1596 private static int readUByte(byte[] byteCodes, int offset) {
1597 return byteCodes[offset] & 0xff;
1600 private static int readUShort(byte[] byteCodes, int offset) {
1601 return ((byteCodes[offset] & 0xff) << 8)
1602 | (byteCodes[offset + 1] & 0xff);
1604 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1605 return readUShort(byteCodes, offsetInstruction + 1);
1608 private static int readShort(byte[] byteCodes, int offset) {
1609 int signed = byteCodes[offset];
1610 byte b0 = (byte)signed;
1611 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1613 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1614 return readShort(byteCodes, offsetInstruction + 1);
1617 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1619 Boolean count = null;
1620 boolean array = false;
1622 int firstPos = sig.length();
1623 while (i < descriptor.length()) {
1624 char ch = descriptor.charAt(i++);
1645 if (ch == 'J' || ch == 'D') {
1651 sig.insert(firstPos, ch);
1653 returnType[0] = '[';
1654 sig.insert(firstPos, "_3");
1663 returnType[0] = 'V';
1664 sig.insert(firstPos, 'V');
1667 int next = descriptor.indexOf(';', i);
1668 String realSig = mangleSig(descriptor, i - 1, next + 1);
1673 sig.append(realSig);
1676 sig.insert(firstPos, realSig);
1678 sig.insert(firstPos, "_3");
1680 returnType[0] = 'L';
1689 throw new IllegalStateException("Invalid char: " + ch);
1694 static String mangleSig(String sig) {
1695 return mangleSig(sig, 0, sig.length());
1698 private static String mangleMethodName(String name) {
1699 StringBuilder sb = new StringBuilder(name.length() * 2);
1700 int last = name.length();
1701 for (int i = 0; i < last; i++) {
1702 final char ch = name.charAt(i);
1704 case '_': sb.append("_1"); break;
1705 default: sb.append(ch); break;
1708 return sb.toString();
1710 private static String mangleSig(String txt, int first, int last) {
1711 StringBuilder sb = new StringBuilder((last - first) * 2);
1712 for (int i = first; i < last; i++) {
1713 final char ch = txt.charAt(i);
1715 case '/': sb.append('_'); break;
1716 case '_': sb.append("_1"); break;
1717 case ';': sb.append("_2"); break;
1718 case '[': sb.append("_3"); break;
1720 if (Character.isJavaIdentifierPart(ch)) {
1724 String hex = Integer.toHexString(ch).toLowerCase();
1725 for (int m = hex.length(); m < 4; m++) {
1733 return sb.toString();
1736 private static String mangleClassName(String name) {
1737 return mangleSig(name);
1740 private static String findMethodName(MethodData m, StringBuilder cnt) {
1741 StringBuilder name = new StringBuilder();
1742 if ("<init>".equals(m.getName())) { // NOI18N
1743 name.append("cons"); // NOI18N
1744 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1745 name.append("class"); // NOI18N
1747 name.append(mangleMethodName(m.getName()));
1750 countArgs(m.getInternalSig(), new char[1], name, cnt);
1751 return name.toString();
1754 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1755 StringBuilder name = new StringBuilder();
1756 String descr = mi[2];//mi.getDescriptor();
1758 if ("<init>".equals(nm)) { // NOI18N
1759 name.append("cons"); // NOI18N
1761 name.append(mangleMethodName(nm));
1763 countArgs(descr, returnType, name, cnt);
1764 return name.toString();
1767 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1768 throws IOException {
1769 int methodIndex = readUShortArg(byteCodes, i);
1770 String[] mi = jc.getFieldInfoName(methodIndex);
1771 char[] returnType = { 'V' };
1772 StringBuilder cnt = new StringBuilder();
1773 String mn = findMethodName(mi, cnt, returnType);
1775 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1776 final CharSequence[] vars = new CharSequence[numArguments];
1778 for (int j = numArguments - 1; j >= 0; --j) {
1779 vars[j] = mapper.popValue();
1783 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1784 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1786 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1787 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1789 if (vars[1] instanceof String) {
1790 String field = vars[1].toString();
1791 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1792 vars[1] = "c._" + field.substring(1, field.length() - 1);
1797 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1798 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1800 if (vars[1] instanceof String) {
1801 String field = vars[2].toString();
1802 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1803 vars[2] = "c._" + field.substring(1, field.length() - 1);
1808 if (returnType[0] != 'V') {
1811 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1815 final String in = mi[0];
1818 in.equals("org/apidesign/html/boot/spi/Fn") ||
1819 in.equals("org/netbeans/html/boot/spi/Fn")
1821 mcn = "java_lang_Class";
1823 mcn = mangleClassName(in);
1825 String object = accessClassFalse(mcn);
1826 if (mn.startsWith("cons_")) {
1827 object += ".constructor";
1829 append(accessStaticMethod(object, mn, mi));
1835 if (numArguments > 0) {
1837 for (int j = 1; j < numArguments; ++j) {
1847 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1848 throws IOException {
1849 int methodIndex = readUShortArg(byteCodes, i);
1850 String[] mi = jc.getFieldInfoName(methodIndex);
1851 char[] returnType = { 'V' };
1852 StringBuilder cnt = new StringBuilder();
1853 String mn = findMethodName(mi, cnt, returnType);
1855 final int numArguments = cnt.length() + 1;
1856 final CharSequence[] vars = new CharSequence[numArguments];
1858 for (int j = numArguments - 1; j >= 0; --j) {
1859 vars[j] = mapper.popValue();
1862 if (returnType[0] != 'V') {
1865 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1869 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1871 for (int j = 1; j < numArguments; ++j) {
1881 private void addReference(String cn) throws IOException {
1882 if (requireReference(cn)) {
1883 debug(" /* needs " + cn + " */");
1887 private void outType(String d, StringBuilder out) {
1889 while (d.charAt(0) == '[') {
1893 if (d.charAt(0) == 'L') {
1894 assert d.charAt(d.length() - 1) == ';';
1895 out.append(mangleClassName(d).substring(0, d.length() - 1));
1901 private String encodeConstant(int entryIndex) throws IOException {
1902 String[] classRef = { null };
1903 String s = jc.stringValue(entryIndex, classRef);
1904 if (classRef[0] != null) {
1905 if (classRef[0].startsWith("[")) {
1906 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1908 addReference(classRef[0]);
1909 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1915 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1916 byte[] arr = m.findAnnotationData(true);
1920 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1921 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1922 class P extends AnnotationParser {
1928 String[] args = new String[30];
1934 protected void visitAttr(String type, String attr, String at, String value) {
1935 if (type.equals(jvmType)) {
1936 if ("body".equals(attr)) {
1938 } else if ("args".equals(attr)) {
1939 args[cnt++] = value;
1941 throw new IllegalArgumentException(attr);
1944 if (type.equals(htmlType)) {
1946 if ("body".equals(attr)) {
1948 } else if ("args".equals(attr)) {
1949 args[cnt++] = value;
1950 } else if ("javacall".equals(attr)) {
1951 javacall = "1".equals(value);
1952 } else if ("wait4js".equals(attr)) {
1953 // ignore, we always invoke synchronously
1955 throw new IllegalArgumentException(attr);
1962 if (p.body == null) {
1965 StringBuilder cnt = new StringBuilder();
1966 final String mn = findMethodName(m, cnt);
1967 append("m = ").append(destObject).append(".").append(mn);
1968 append(" = function(");
1971 StringBuilder toValue = new StringBuilder();
1972 for (int i = 0; i < cnt.length(); i++) {
1974 space = outputArg(this, p.args, index);
1975 if (p.html4j && space.length() > 0) {
1976 toValue.append("\n ").append(p.args[index]).append(" = ")
1977 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1978 append(p.args[index]).append(");");
1982 append(") {").append("\n");
1983 append(toValue.toString());
1985 int lastSlash = jc.getClassName().lastIndexOf('/');
1986 final String pkg = jc.getClassName().substring(0, lastSlash);
1987 append(mangleCallbacks(pkg, p.body));
1988 requireReference(pkg + "/$JsCallbacks$");
1996 private static CharSequence mangleCallbacks(String pkgName, String body) {
1997 StringBuilder sb = new StringBuilder();
2000 int next = body.indexOf(".@", pos);
2002 sb.append(body.substring(pos));
2003 body = sb.toString();
2008 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
2013 String refId = body.substring(ident, next);
2015 sb.append(body.substring(pos, ident));
2017 int sigBeg = body.indexOf('(', next);
2018 int sigEnd = body.indexOf(')', sigBeg);
2019 int colon4 = body.indexOf("::", next);
2020 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2021 throw new IllegalStateException("Malformed body " + body);
2023 String fqn = body.substring(next + 2, colon4);
2024 String method = body.substring(colon4 + 2, sigBeg);
2025 String params = body.substring(sigBeg, sigEnd + 1);
2027 int paramBeg = body.indexOf('(', sigEnd + 1);
2029 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2030 sb.append(mangleJsCallbacks(fqn, method, params, false));
2031 sb.append("(").append(refId);
2032 if (body.charAt(paramBeg + 1) != ')') {
2040 int next = body.indexOf("@", pos);
2045 sb.append(body.substring(pos));
2049 sb = new StringBuilder();
2052 sb.append(body.substring(pos, next));
2054 int sigBeg = body.indexOf('(', next);
2055 int sigEnd = body.indexOf(')', sigBeg);
2056 int colon4 = body.indexOf("::", next);
2057 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2058 throw new IllegalStateException("Malformed body " + body);
2060 String fqn = body.substring(next + 1, colon4);
2061 String method = body.substring(colon4 + 2, sigBeg);
2062 String params = body.substring(sigBeg, sigEnd + 1);
2064 int paramBeg = body.indexOf('(', sigEnd + 1);
2066 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2067 sb.append(mangleJsCallbacks(fqn, method, params, true));
2073 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2074 if (params.startsWith("(")) {
2075 params = params.substring(1);
2077 if (params.endsWith(")")) {
2078 params = params.substring(0, params.length() - 1);
2080 StringBuilder sb = new StringBuilder();
2081 final String fqnu = fqn.replace('.', '_');
2082 final String rfqn = mangleClassName(fqnu);
2083 final String rm = mangleMethodName(method);
2086 StringBuilder pb = new StringBuilder();
2087 int len = params.length();
2089 while (indx < len) {
2090 char ch = params.charAt(indx);
2091 if (ch == '[' || ch == 'L') {
2092 int column = params.indexOf(';', indx) + 1;
2093 if (column > indx) {
2094 String real = params.substring(indx, column);
2095 if ("Ljava/lang/String;".equals(real)) {
2096 pb.append("Ljava/lang/String;");
2101 pb.append("Ljava/lang/Object;");
2108 srp = mangleSig(pb.toString());
2110 final String rp = mangleSig(params);
2111 final String mrp = mangleMethodName(rp);
2112 sb.append(rfqn).append("$").append(rm).
2113 append('$').append(mrp).append("__Ljava_lang_Object_2");
2115 sb.append('L').append(fqnu).append("_2");
2118 return sb.toString();
2121 private static String className(ClassData jc) {
2122 //return jc.getName().getInternalName().replace('/', '_');
2123 return mangleClassName(jc.getClassName());
2126 private static String[] findAnnotation(
2127 byte[] arr, ClassData cd, final String className,
2128 final String... attrNames
2129 ) throws IOException {
2133 final String[] values = new String[attrNames.length];
2134 final boolean[] found = { false };
2135 final String jvmType = "L" + className.replace('.', '/') + ";";
2136 AnnotationParser ap = new AnnotationParser(false, true) {
2138 protected void visitAttr(String type, String attr, String at, String value) {
2139 if (type.equals(jvmType)) {
2141 for (int i = 0; i < attrNames.length; i++) {
2142 if (attrNames[i].equals(attr)) {
2151 return found[0] ? values : null;
2154 private CharSequence initField(FieldData v) {
2155 final String is = v.getInternalSig();
2156 if (is.length() == 1) {
2157 switch (is.charAt(0)) {
2163 case 'I': return " = 0;";
2165 case 'D': return " = 0.0;";
2167 throw new IllegalStateException(is);
2173 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2174 final String name = args[indx];
2178 if (name.contains(",")) {
2179 throw new IOException("Wrong parameter with ',': " + name);
2185 final void emitNoFlush(
2187 final String format, final CharSequence... params
2188 ) throws IOException {
2189 emitImpl(this, format, params);
2191 static final void emit(
2193 final Appendable out,
2194 final String format, final CharSequence... params
2195 ) throws IOException {
2197 emitImpl(out, format, params);
2199 static void emitImpl(final Appendable out,
2200 final String format,
2201 final CharSequence... params) throws IOException {
2202 final int length = format.length();
2205 int paramOffset = format.indexOf('@');
2206 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2207 final char paramChar = format.charAt(paramOffset + 1);
2208 if ((paramChar >= '1') && (paramChar <= '9')) {
2209 final int paramIndex = paramChar - '0' - 1;
2211 out.append(format, processed, paramOffset);
2212 out.append(params[paramIndex]);
2215 processed = paramOffset + 1;
2218 paramOffset = format.indexOf('@', paramOffset + 1);
2221 out.append(format, processed, length);
2224 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2225 append("} catch (e) {\n");
2227 for (TrapData e : traps) {
2231 if (e.catch_cpx != 0) { //not finally
2232 final String classInternalName = jc.getClassName(e.catch_cpx);
2233 addReference(classInternalName);
2234 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2235 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2236 append("var stA0 = e;");
2237 goTo(this, current, e.handler_pc, topMostLabel);
2240 finallyPC = e.handler_pc;
2243 if (finallyPC == -1) {
2246 append("var stA0 = e;");
2247 goTo(this, current, finallyPC, topMostLabel);
2252 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2255 out.append("{ gt = 0; continue X_" + to + "; }");
2257 out.append("{ gt = " + to + "; continue X_0; }");
2260 out.append("{ gt = " + to + "; break IF; }");
2264 private static void emitIf(
2266 Appendable out, String pattern,
2268 int current, int to, int canBack
2269 ) throws IOException {
2271 emitImpl(out, pattern, param);
2272 goTo(out, current, to, canBack);
2275 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2278 case 4: jvmType = "[Z"; break;
2279 case 5: jvmType = "[C"; break;
2280 case 6: jvmType = "[F"; break;
2281 case 7: jvmType = "[D"; break;
2282 case 8: jvmType = "[B"; break;
2283 case 9: jvmType = "[S"; break;
2284 case 10: jvmType = "[I"; break;
2285 case 11: jvmType = "[J"; break;
2286 default: throw new IllegalStateException("Array type: " + atype);
2289 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2290 smapper.popI(), smapper.pushA(), jvmType);
2293 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2294 String typeName = jc.getClassName(type);
2295 String ref = "null";
2296 if (typeName.startsWith("[")) {
2297 typeName = "'[" + typeName + "'";
2299 ref = "vm." + mangleClassName(typeName);
2300 typeName = "'[L" + typeName + ";'";
2303 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2304 smapper.popI(), smapper.pushA(), typeName, ref);
2307 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2308 String typeName = jc.getClassName(type);
2309 int dim = readUByte(byteCodes, ++i);
2310 StringBuilder dims = new StringBuilder();
2312 for (int d = 0; d < dim; d++) {
2314 dims.insert(1, ",");
2316 dims.insert(1, smapper.popI());
2320 if (typeName.charAt(dim) == 'L') {
2321 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2324 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2325 dims.toString(), smapper.pushA(), typeName, fn
2330 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2331 int table = i / 4 * 4 + 4;
2332 int dflt = i + readInt4(byteCodes, table);
2334 int low = readInt4(byteCodes, table);
2336 int high = readInt4(byteCodes, table);
2338 final CharSequence swVar = smapper.popValue();
2339 smapper.flush(this);
2340 append("switch (").append(swVar).append(") {\n");
2341 while (low <= high) {
2342 int offset = i + readInt4(byteCodes, table);
2344 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2347 append(" default: ");
2348 goTo(this, i, dflt, topMostLabel);
2354 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2355 int table = i / 4 * 4 + 4;
2356 int dflt = i + readInt4(byteCodes, table);
2358 int n = readInt4(byteCodes, table);
2360 final CharSequence swVar = smapper.popValue();
2361 smapper.flush(this);
2362 append("switch (").append(swVar).append(") {\n");
2364 int cnstnt = readInt4(byteCodes, table);
2366 int offset = i + readInt4(byteCodes, table);
2368 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2370 append(" default: ");
2371 goTo(this, i, dflt, topMostLabel);
2377 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2378 String type = jc.getClassName(indx);
2379 if (!type.startsWith("[")) {
2381 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2382 smapper.popA(), smapper.pushI(),
2383 mangleClassName(type));
2386 while (type.charAt(cnt) == '[') {
2389 if (type.charAt(cnt) == 'L') {
2390 String component = type.substring(cnt + 1, type.length() - 1);
2391 requireReference(component);
2392 type = "vm." + mangleClassName(component);
2394 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2395 smapper.popA(), smapper.pushI(),
2400 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2401 smapper.popA(), smapper.pushI(), type
2407 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2408 String type = jc.getClassName(indx);
2409 if (!type.startsWith("[")) {
2410 emitNoFlush(smapper,
2411 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2412 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2415 while (type.charAt(cnt) == '[') {
2418 if (type.charAt(cnt) == 'L') {
2419 String component = type.substring(cnt + 1, type.length() - 1);
2420 requireReference(component);
2421 type = "vm." + mangleClassName(component);
2422 emitNoFlush(smapper,
2423 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2424 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2427 emitNoFlush(smapper,
2428 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2429 smapper.getT(0, VarType.REFERENCE, false), type
2435 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2436 for (int j = prev; j <= i; j++) {
2438 final int cc = readUByte(byteCodes, j);
2439 append(Integer.toString(cc));
2443 @JavaScriptBody(args = "msg", body = "")
2444 private static void println(String msg) {
2445 System.err.println(msg);
2448 private class GenerateAnno extends AnnotationParser {
2449 public GenerateAnno(boolean textual, boolean iterateArray) {
2450 super(textual, iterateArray);
2452 int[] cnt = new int[32];
2456 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2457 final String slashType = attrType.substring(1, attrType.length() - 1);
2458 requireReference(slashType);
2460 if (cnt[depth]++ > 0) {
2464 append('"').append(attrType).append("\" : ");
2471 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2477 protected void visitValueStart(String attrName, char type) throws IOException {
2478 if (cnt[depth]++ > 0) {
2482 if (attrName != null) {
2483 append('"').append(attrName).append("\" : ");
2491 protected void visitValueEnd(String attrName, char type) throws IOException {
2499 protected void visitAttr(String type, String attr, String attrType, String value)
2500 throws IOException {
2501 if (attr == null && value == null) {
2508 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2509 throws IOException {
2510 final String slashType = attrType.substring(1, attrType.length() - 1);
2511 requireReference(slashType);
2513 final String cn = mangleClassName(slashType);
2514 append(accessClassFalse(cn))
2515 .append("['valueOf__L").
2517 append("_2Ljava_lang_String_2']('").
2523 protected void visitClassAttr(String annoType, String attr, String className) throws IOException {
2524 final String slashType = className.substring(1, className.length() - 1);
2525 requireReference(slashType);
2527 final String cn = mangleClassName(slashType);
2528 append(accessClassFalse(cn)).append(".constructor.$class");