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 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
343 append("\n CLS.$class.cnstr = CLS;");
344 byte[] classAnno = jc.findAnnotationData(false);
345 if (classAnno != null) {
346 append("\n CLS.$class.anno = {");
347 AnnotationParser ap = new GenerateAnno(true, false);
348 ap.parse(classAnno, jc);
351 for (String init : toInitilize.toArray()) {
352 append("\n ").append(init).append("();");
354 for (String ref : classRefs.toArray()) {
355 append("\n var refs_").append(ref).append(";");
359 if (jsResource != null) {
360 requireResource(jsResource);
364 append("\n if (arguments.length === 0) {");
365 append("\n if (!(this instanceof CLS)) {");
366 append("\n return new CLS();");
368 for (FieldData v : jc.getFields()) {
369 byte[] onlyArr = v.findAnnotationData(true);
370 if (javaScriptOnly(onlyArr)) continue;
372 append("\n this.fld_").
373 append(className).append('_').
374 append(v.getName()).append(initField(v));
377 append("\n return this;");
379 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
382 declaredClass(jc, className);
384 // StringBuilder sb = new StringBuilder();
385 // for (String init : toInitilize.toArray()) {
386 // sb.append("\n").append(init).append("();");
391 private boolean javaScriptOnly(byte[] anno) throws IOException {
392 String[] only = findAnnotation(anno, jc,
393 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
397 if (only[0] != null && only[1] != null) {
398 append("\n p.").append(only[0]).append(" = ")
399 .append(only[1]).append(";");
401 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
402 append("\n p['").append(only[0]).append("'] = p.")
403 .append(only[0]).append(";");
409 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
410 String jsb = javaScriptBody(destObject, m, true);
414 final String mn = findMethodName(m, new StringBuilder());
415 boolean defineProp = generateMethod(destObject, mn, m);
416 if (mn.equals("class__V")) {
418 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
420 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
426 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
427 String jsb = javaScriptBody(destObject, m, false);
431 final String mn = findMethodName(m, new StringBuilder());
432 generateMethod(destObject, mn, m);
436 private boolean generateMethod(String destObject, String name, MethodData m)
438 final StackMapIterator stackMapIterator = m.createStackMapIterator();
439 TrapDataIterator trap = m.getTrapDataIterator();
440 final LocalsMapper lmapper =
441 new LocalsMapper(stackMapIterator.getArguments());
444 "java/lang/Object".equals(jc.getClassName()) ||
445 "java/lang/reflect/Array".equals(jc.getClassName());
448 append("Object.defineProperty(").append(destObject).
449 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
451 append("m = ").append(destObject).append(".").append(name).append(" = function(");
453 lmapper.outputArguments(this, m.isStatic());
454 append(") {").append("\n");
456 final byte[] byteCodes = m.getCode();
457 if (byteCodes == null) {
458 byte[] defaultAttr = m.getDefaultAttribute();
459 if (defaultAttr != null) {
461 AnnotationParser ap = new GenerateAnno(true, false);
462 ap.parseDefault(defaultAttr, jc);
465 if (debug(" throw 'no code found for ")) {
467 .append(jc.getClassName()).append('.')
468 .append(m.getName()).append("';\n");
479 final StackMapper smapper = new StackMapper();
482 append(" var ").append(" lcA0 = this;\n");
486 TrapData[] previousTrap = null;
487 boolean wide = false;
489 if (stackMapIterator.isEmpty()) {
495 append("\n var gt = 0;\n");
499 int topMostLabel = 0;
500 for (int i = 0; i < byteCodes.length; i++) {
503 stackMapIterator.advanceTo(i);
504 boolean changeInCatch = trap.advanceTo(i);
505 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
506 if (previousTrap != null) {
507 generateCatch(previousTrap, i, topMostLabel);
511 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
516 if (openBraces > 64) {
517 for (int c = 0; c < 64; c++) {
524 lastStackFrame = stackMapIterator.getFrameIndex();
525 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
526 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
527 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
529 changeInCatch = true;
531 debug(" /* " + i + " */ ");
533 if (changeInCatch && trap.useTry()) {
535 previousTrap = trap.current();
537 final int c = readUByte(byteCodes, i);
540 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
543 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
546 smapper.assign(this, VarType.LONG, lmapper.getL(0));
549 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
552 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
555 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
558 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
561 smapper.assign(this, VarType.LONG, lmapper.getL(1));
564 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
567 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
570 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
573 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
576 smapper.assign(this, VarType.LONG, lmapper.getL(2));
579 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
582 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
585 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
588 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
591 smapper.assign(this, VarType.LONG, lmapper.getL(3));
594 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
597 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
601 final int indx = wide ? readUShort(byteCodes, i++)
602 : readUByte(byteCodes, i);
604 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
609 final int indx = wide ? readUShort(byteCodes, i++)
610 : readUByte(byteCodes, i);
612 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
617 final int indx = wide ? readUShort(byteCodes, i++)
618 : readUByte(byteCodes, i);
620 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
625 final int indx = wide ? readUShort(byteCodes, i++)
626 : readUByte(byteCodes, i);
628 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
633 final int indx = wide ? readUShort(byteCodes, i++)
634 : readUByte(byteCodes, i);
636 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
641 final int indx = wide ? readUShort(byteCodes, i++)
642 : readUByte(byteCodes, i);
644 emit(smapper, this, "var @1 = @2;",
645 lmapper.setI(indx), smapper.popI());
650 final int indx = wide ? readUShort(byteCodes, i++)
651 : readUByte(byteCodes, i);
653 emit(smapper, this, "var @1 = @2;",
654 lmapper.setL(indx), smapper.popL());
659 final int indx = wide ? readUShort(byteCodes, i++)
660 : readUByte(byteCodes, i);
662 emit(smapper, this, "var @1 = @2;",
663 lmapper.setF(indx), smapper.popF());
668 final int indx = wide ? readUShort(byteCodes, i++)
669 : readUByte(byteCodes, i);
671 emit(smapper, this, "var @1 = @2;",
672 lmapper.setD(indx), smapper.popD());
677 final int indx = wide ? readUShort(byteCodes, i++)
678 : readUByte(byteCodes, i);
680 emit(smapper, this, "var @1 = @2;",
681 lmapper.setA(indx), smapper.popA());
685 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
688 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
691 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
694 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
697 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
700 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
703 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
706 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
709 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
712 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
715 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
718 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
721 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
724 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
727 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
730 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
733 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
736 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
739 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
742 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
745 smapper.replace(this, VarType.INTEGER, "(((@1) + (@2)) | 0)", smapper.getI(1), smapper.popI());
748 smapper.replace(this, VarType.LONG, numbers.add64(), 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) - (@2)) | 0)", smapper.getI(1), smapper.popI());
760 smapper.replace(this, VarType.LONG, numbers.sub64(), 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, numbers.mul32(), smapper.getI(1), smapper.popI());
772 smapper.replace(this, VarType.LONG, numbers.mul64(), smapper.getL(1), smapper.popL());
775 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
778 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
781 smapper.replace(this, VarType.INTEGER, numbers.div32(),
782 smapper.getI(1), smapper.popI());
785 smapper.replace(this, VarType.LONG, numbers.div64(),
786 smapper.getL(1), smapper.popL());
789 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
792 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
795 smapper.replace(this, VarType.INTEGER, numbers.mod32(),
796 smapper.getI(1), smapper.popI());
799 smapper.replace(this, VarType.LONG, numbers.mod64(),
800 smapper.getL(1), smapper.popL());
803 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
806 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
809 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
812 smapper.replace(this, VarType.LONG, numbers.and64(), smapper.getL(1), smapper.popL());
815 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
818 smapper.replace(this, VarType.LONG, numbers.or64(), smapper.getL(1), smapper.popL());
821 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
824 smapper.replace(this, VarType.LONG, numbers.xor64(), smapper.getL(1), smapper.popL());
827 smapper.replace(this, VarType.INTEGER, "(-(@1) | 0)", smapper.getI(0));
830 smapper.replace(this, VarType.LONG, numbers.neg64(), smapper.getL(0));
833 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
836 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
839 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
842 smapper.replace(this, VarType.LONG, numbers.shl64(), smapper.getL(1), smapper.popI());
845 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
848 smapper.replace(this, VarType.LONG, numbers.shr64(), smapper.getL(1), smapper.popI());
851 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
854 smapper.replace(this, VarType.LONG, numbers.ushr64(), smapper.getL(1), smapper.popI());
858 final int varIndx = wide ? readUShort(byteCodes, i++)
859 : readUByte(byteCodes, i);
861 final int incrBy = wide ? readShort(byteCodes, i++)
865 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
867 emit(smapper, this, "@1 += @2;",
868 lmapper.getI(varIndx),
869 Integer.toString(incrBy));
874 emit(smapper, this, "return;");
877 emit(smapper, this, "return @1;", smapper.popI());
880 emit(smapper, this, "return @1;", smapper.popL());
883 emit(smapper, this, "return @1;", smapper.popF());
886 emit(smapper, this, "return @1;", smapper.popD());
889 emit(smapper, this, "return @1;", smapper.popA());
892 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
895 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
898 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
901 smapper.replace(this, VarType.INTEGER, "((@1) | 0)", smapper.getL(0));
905 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
908 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
911 smapper.replace(this, VarType.DOUBLE, "@1",
915 smapper.replace(this, VarType.FLOAT, "@1",
919 smapper.replace(this, VarType.INTEGER, "((@1) | 0)",
923 smapper.replace(this, VarType.LONG, "(@1).toLong()",
927 smapper.replace(this, VarType.INTEGER, "((@1)| 0)",
931 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
934 smapper.replace(this, VarType.INTEGER, "(((@1) << 24) >> 24)", smapper.getI(0));
938 smapper.replace(this, VarType.INTEGER, "(((@1) << 16) >> 16)", smapper.getI(0));
940 case opc_aconst_null:
941 smapper.assign(this, VarType.REFERENCE, "null");
944 smapper.assign(this, VarType.INTEGER, "-1");
947 smapper.assign(this, VarType.INTEGER, "0");
950 smapper.assign(this, VarType.DOUBLE, "0");
953 smapper.assign(this, VarType.LONG, "0");
956 smapper.assign(this, VarType.FLOAT, "0");
959 smapper.assign(this, VarType.INTEGER, "1");
962 smapper.assign(this, VarType.LONG, "1");
965 smapper.assign(this, VarType.FLOAT, "1");
968 smapper.assign(this, VarType.DOUBLE, "1");
971 smapper.assign(this, VarType.INTEGER, "2");
974 smapper.assign(this, VarType.FLOAT, "2");
977 smapper.assign(this, VarType.INTEGER, "3");
980 smapper.assign(this, VarType.INTEGER, "4");
983 smapper.assign(this, VarType.INTEGER, "5");
986 int indx = readUByte(byteCodes, ++i);
987 String v = encodeConstant(indx);
988 int type = VarType.fromConstantType(jc.getTag(indx));
989 smapper.assign(this, type, v);
994 int indx = readUShortArg(byteCodes, i);
996 String v = encodeConstant(indx);
997 int type = VarType.fromConstantType(jc.getTag(indx));
998 if (type == VarType.LONG) {
999 final Long lv = new Long(v);
1000 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
1001 final int hi = (int)(lv.longValue() >> 32);
1003 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
1005 smapper.assign(this, VarType.LONG,
1006 "0x" + Integer.toHexString(hi) + ".next32(0x" +
1007 Integer.toHexString(low) + ")"
1011 smapper.assign(this, type, v);
1016 smapper.replace(this, VarType.INTEGER, numbers.compare64(), smapper.popL(), smapper.getL(0));
1020 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1021 smapper.popF(), smapper.popF(), smapper.pushI());
1025 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1026 smapper.popD(), smapper.popD(), smapper.pushI());
1029 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1030 "===", topMostLabel);
1033 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1034 "!==", topMostLabel);
1037 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1038 "==", topMostLabel);
1041 int indx = i + readShortArg(byteCodes, i);
1042 emitIf(smapper, this, "if ((@1) == 0) ",
1043 smapper.popI(), i, indx, topMostLabel);
1048 int indx = i + readShortArg(byteCodes, i);
1049 emitIf(smapper, this, "if ((@1) != 0) ",
1050 smapper.popI(), i, indx, topMostLabel);
1055 int indx = i + readShortArg(byteCodes, i);
1056 emitIf(smapper, this, "if ((@1) < 0) ",
1057 smapper.popI(), i, indx, topMostLabel);
1062 int indx = i + readShortArg(byteCodes, i);
1063 emitIf(smapper, this, "if ((@1) <= 0) ",
1064 smapper.popI(), i, indx, topMostLabel);
1069 int indx = i + readShortArg(byteCodes, i);
1070 emitIf(smapper, this, "if ((@1) > 0) ",
1071 smapper.popI(), i, indx, topMostLabel);
1076 int indx = i + readShortArg(byteCodes, i);
1077 emitIf(smapper, this, "if ((@1) >= 0) ",
1078 smapper.popI(), i, indx, topMostLabel);
1082 case opc_ifnonnull: {
1083 int indx = i + readShortArg(byteCodes, i);
1084 emitIf(smapper, this, "if ((@1) !== null) ",
1085 smapper.popA(), i, indx, topMostLabel);
1090 int indx = i + readShortArg(byteCodes, i);
1091 emitIf(smapper, this, "if ((@1) === null) ",
1092 smapper.popA(), i, indx, topMostLabel);
1097 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1098 "!=", topMostLabel);
1101 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1105 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1106 "<=", topMostLabel);
1109 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1113 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1114 ">=", topMostLabel);
1117 smapper.flush(this);
1118 int indx = i + readShortArg(byteCodes, i);
1119 goTo(this, i, indx, topMostLabel);
1123 case opc_lookupswitch: {
1124 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1127 case opc_tableswitch: {
1128 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1131 case opc_invokeinterface: {
1132 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1135 case opc_invokevirtual:
1136 i = invokeVirtualMethod(byteCodes, i, smapper);
1138 case opc_invokespecial:
1139 i = invokeStaticMethod(byteCodes, i, smapper, false);
1141 case opc_invokestatic:
1142 i = invokeStaticMethod(byteCodes, i, smapper, true);
1144 case opc_invokedynamic: {
1145 int indx = readUShortArg(byteCodes, i);
1146 println("invoke dynamic: " + indx);
1147 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1148 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1149 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1150 println(" type: " + methodHandle.cpx1);
1151 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1152 String mcn = mangleClassName(mi[0]);
1153 char[] returnType = {'V'};
1154 StringBuilder cnt = new StringBuilder();
1155 String mn = findMethodName(mi, cnt, returnType);
1156 StringBuilder sb = new StringBuilder();
1157 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1158 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1159 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1160 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1161 sb.append(" mn : ").append(mn).append("\n");
1162 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1163 throw new IOException(sb.toString());
1165 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1166 String type = jc.StringValue(nameAndType.cpx2);
1167 String object = accessClass(mcn) + "(false)";
1168 if (mn.startsWith("cons_")) {
1169 object += ".constructor";
1171 append("var metHan = ");
1172 append(accessStaticMethod(object, mn, mi));
1174 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1176 append(", '").append(mi[1]).append("', ");
1177 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1178 append(methodType).append("'").append(type).append("', null)");
1179 // if (numArguments > 0) {
1181 // for (int j = 1; j < numArguments; ++j) {
1187 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1193 int indx = readUShortArg(byteCodes, i);
1194 String ci = jc.getClassName(indx);
1195 emit(smapper, this, "var @1 = new @2;",
1196 smapper.pushA(), accessClass(mangleClassName(ci)));
1202 int atype = readUByte(byteCodes, ++i);
1203 generateNewArray(atype, smapper);
1205 case opc_anewarray: {
1206 int type = readUShortArg(byteCodes, i);
1208 generateANewArray(type, smapper);
1211 case opc_multianewarray: {
1212 int type = readUShortArg(byteCodes, i);
1214 i = generateMultiANewArray(type, byteCodes, i, smapper);
1217 case opc_arraylength:
1218 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1221 emit(smapper, this, "Array.at(@3, @2, @1);",
1222 smapper.popL(), smapper.popI(), smapper.popA());
1225 emit(smapper, this, "Array.at(@3, @2, @1);",
1226 smapper.popF(), smapper.popI(), smapper.popA());
1229 emit(smapper, this, "Array.at(@3, @2, @1);",
1230 smapper.popD(), smapper.popI(), smapper.popA());
1233 emit(smapper, this, "Array.at(@3, @2, @1);",
1234 smapper.popA(), smapper.popI(), smapper.popA());
1240 emit(smapper, this, "Array.at(@3, @2, @1);",
1241 smapper.popI(), smapper.popI(), smapper.popA());
1244 smapper.replace(this, VarType.LONG, "(@2[@1] || Array.at(@2, @1))",
1245 smapper.popI(), smapper.getA(0));
1248 smapper.replace(this, VarType.FLOAT, "(@2[@1] || Array.at(@2, @1))",
1249 smapper.popI(), smapper.getA(0));
1252 smapper.replace(this, VarType.DOUBLE, "(@2[@1] || Array.at(@2, @1))",
1253 smapper.popI(), smapper.getA(0));
1256 smapper.replace(this, VarType.REFERENCE, "(@2[@1] || Array.at(@2, @1))",
1257 smapper.popI(), smapper.getA(0));
1263 smapper.replace(this, VarType.INTEGER, "(@2[@1] || Array.at(@2, @1))",
1264 smapper.popI(), smapper.getA(0));
1272 final Variable v = smapper.get(0);
1273 if (smapper.isDirty()) {
1274 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1276 smapper.assign(this, v.getType(), v);
1281 final Variable vi1 = smapper.get(0);
1283 if (vi1.isCategory2()) {
1284 emit(smapper, this, "var @1 = @2;",
1285 smapper.pushT(vi1.getType()), vi1);
1287 final Variable vi2 = smapper.get(1);
1288 emit(smapper, this, "var @1 = @2, @3 = @4;",
1289 smapper.pushT(vi2.getType()), vi2,
1290 smapper.pushT(vi1.getType()), vi1);
1295 final Variable vi1 = smapper.pop(this);
1296 final Variable vi2 = smapper.pop(this);
1297 final Variable vo3 = smapper.pushT(vi1.getType());
1298 final Variable vo2 = smapper.pushT(vi2.getType());
1299 final Variable vo1 = smapper.pushT(vi1.getType());
1301 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1302 vo1, vi1, vo2, vi2, vo3, vo1);
1306 final Variable vi1 = smapper.pop(this);
1307 final Variable vi2 = smapper.pop(this);
1309 if (vi1.isCategory2()) {
1310 final Variable vo3 = smapper.pushT(vi1.getType());
1311 final Variable vo2 = smapper.pushT(vi2.getType());
1312 final Variable vo1 = smapper.pushT(vi1.getType());
1314 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1315 vo1, vi1, vo2, vi2, vo3, vo1);
1317 final Variable vi3 = smapper.pop(this);
1318 final Variable vo5 = smapper.pushT(vi2.getType());
1319 final Variable vo4 = smapper.pushT(vi1.getType());
1320 final Variable vo3 = smapper.pushT(vi3.getType());
1321 final Variable vo2 = smapper.pushT(vi2.getType());
1322 final Variable vo1 = smapper.pushT(vi1.getType());
1324 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1325 vo1, vi1, vo2, vi2, vo3, vi3);
1326 emit(smapper, this, " @1 = @2, @3 = @4;",
1327 vo4, vo1, vo5, vo2);
1332 final Variable vi1 = smapper.pop(this);
1333 final Variable vi2 = smapper.pop(this);
1335 if (vi2.isCategory2()) {
1336 final Variable vo3 = smapper.pushT(vi1.getType());
1337 final Variable vo2 = smapper.pushT(vi2.getType());
1338 final Variable vo1 = smapper.pushT(vi1.getType());
1340 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1341 vo1, vi1, vo2, vi2, vo3, vo1);
1343 final Variable vi3 = smapper.pop(this);
1344 final Variable vo4 = smapper.pushT(vi1.getType());
1345 final Variable vo3 = smapper.pushT(vi3.getType());
1346 final Variable vo2 = smapper.pushT(vi2.getType());
1347 final Variable vo1 = smapper.pushT(vi1.getType());
1349 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1350 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1355 final Variable vi1 = smapper.pop(this);
1356 final Variable vi2 = smapper.pop(this);
1358 if (vi1.isCategory2()) {
1359 if (vi2.isCategory2()) {
1360 final Variable vo3 = smapper.pushT(vi1.getType());
1361 final Variable vo2 = smapper.pushT(vi2.getType());
1362 final Variable vo1 = smapper.pushT(vi1.getType());
1364 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1365 vo1, vi1, vo2, vi2, vo3, vo1);
1367 final Variable vi3 = smapper.pop(this);
1368 final Variable vo4 = smapper.pushT(vi1.getType());
1369 final Variable vo3 = smapper.pushT(vi3.getType());
1370 final Variable vo2 = smapper.pushT(vi2.getType());
1371 final Variable vo1 = smapper.pushT(vi1.getType());
1373 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1374 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1377 final Variable vi3 = smapper.pop(this);
1379 if (vi3.isCategory2()) {
1380 final Variable vo5 = smapper.pushT(vi2.getType());
1381 final Variable vo4 = smapper.pushT(vi1.getType());
1382 final Variable vo3 = smapper.pushT(vi3.getType());
1383 final Variable vo2 = smapper.pushT(vi2.getType());
1384 final Variable vo1 = smapper.pushT(vi1.getType());
1386 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1387 vo1, vi1, vo2, vi2, vo3, vi3);
1388 emit(smapper, this, " @1 = @2, @3 = @4;",
1389 vo4, vo1, vo5, vo2);
1391 final Variable vi4 = smapper.pop(this);
1392 final Variable vo6 = smapper.pushT(vi2.getType());
1393 final Variable vo5 = smapper.pushT(vi1.getType());
1394 final Variable vo4 = smapper.pushT(vi4.getType());
1395 final Variable vo3 = smapper.pushT(vi3.getType());
1396 final Variable vo2 = smapper.pushT(vi2.getType());
1397 final Variable vo1 = smapper.pushT(vi1.getType());
1399 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1400 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1401 emit(smapper, this, " @1 = @2, @3 = @4;",
1402 vo5, vo1, vo6, vo2);
1408 final Variable vi1 = smapper.get(0);
1409 final Variable vi2 = smapper.get(1);
1411 if (vi1.getType() == vi2.getType()) {
1412 final Variable tmp = smapper.pushT(vi1.getType());
1414 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1419 smapper.pushT(vi1.getType());
1420 smapper.pushT(vi2.getType());
1425 smapper.assign(this, VarType.INTEGER,
1426 "(" + Integer.toString(byteCodes[++i]) + ")");
1429 smapper.assign(this, VarType.INTEGER,
1430 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1434 case opc_getfield: {
1435 int indx = readUShortArg(byteCodes, i);
1436 String[] fi = jc.getFieldInfoName(indx);
1437 final int type = VarType.fromFieldType(fi[2].charAt(0));
1438 FieldData field = findField(fi);
1439 if (field == null) {
1440 final String mangleClass = mangleClassName(fi[0]);
1441 final String mangleClassAccess = accessClassFalse(mangleClass);
1442 smapper.replace(this, type, "@2.call(@1)",
1444 accessField(mangleClassAccess, null, fi)
1447 final String fieldOwner = mangleClassName(field.cls.getClassName());
1448 smapper.replace(this, type, "@1.@2",
1450 accessField(fieldOwner, field, fi)
1454 addReference(fi[0]);
1457 case opc_putfield: {
1458 int indx = readUShortArg(byteCodes, i);
1459 String[] fi = jc.getFieldInfoName(indx);
1460 final int type = VarType.fromFieldType(fi[2].charAt(0));
1461 FieldData field = findField(fi);
1462 if (field == null) {
1463 final String mangleClass = mangleClassName(fi[0]);
1464 final String mangleClassAccess = accessClassFalse(mangleClass);
1465 emit(smapper, this, "@3.call(@2, @1);",
1468 accessField(mangleClassAccess, null, fi)
1471 final String fieldOwner = mangleClassName(field.cls.getClassName());
1472 emit(smapper, this, "@2.@3 = @1;",
1475 accessField(fieldOwner, field, fi)
1479 addReference(fi[0]);
1482 case opc_getstatic: {
1483 int indx = readUShortArg(byteCodes, i);
1484 String[] fi = jc.getFieldInfoName(indx);
1485 final int type = VarType.fromFieldType(fi[2].charAt(0));
1486 String ac = accessClassFalse(mangleClassName(fi[0]));
1487 FieldData field = findField(fi);
1488 String af = accessField(ac, field, fi);
1489 smapper.assign(this, type, af + "()");
1491 addReference(fi[0]);
1494 case opc_putstatic: {
1495 int indx = readUShortArg(byteCodes, i);
1496 String[] fi = jc.getFieldInfoName(indx);
1497 final int type = VarType.fromFieldType(fi[2].charAt(0));
1498 emit(smapper, this, "@1._@2(@3);",
1499 accessClassFalse(mangleClassName(fi[0])), fi[1],
1500 smapper.popT(type));
1502 addReference(fi[0]);
1505 case opc_checkcast: {
1506 int indx = readUShortArg(byteCodes, i);
1507 generateCheckcast(indx, smapper);
1511 case opc_instanceof: {
1512 int indx = readUShortArg(byteCodes, i);
1513 generateInstanceOf(indx, smapper);
1518 final CharSequence v = smapper.popA();
1521 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1522 smapper.pushA(), v);
1526 case opc_monitorenter: {
1527 debug("/* monitor enter */");
1532 case opc_monitorexit: {
1533 debug("/* monitor exit */");
1544 emit(smapper, this, "throw 'unknown bytecode @1';",
1545 Integer.toString(c));
1549 generateByteCodeComment(prev, i, byteCodes);
1555 if (previousTrap != null) {
1556 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1561 while (openBraces-- > 0) {
1572 private int generateIf(StackMapper mapper, byte[] byteCodes,
1573 int i, final CharSequence v2, final CharSequence v1,
1574 final String test, int topMostLabel
1575 ) throws IOException {
1577 int indx = i + readShortArg(byteCodes, i);
1578 append("if ((").append(v1)
1579 .append(") ").append(test).append(" (")
1580 .append(v2).append(")) ");
1581 goTo(this, i, indx, topMostLabel);
1585 private int readInt4(byte[] byteCodes, int offset) {
1586 final int d = byteCodes[offset + 0] << 24;
1587 final int c = byteCodes[offset + 1] << 16;
1588 final int b = byteCodes[offset + 2] << 8;
1589 final int a = byteCodes[offset + 3];
1590 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1592 private static int readUByte(byte[] byteCodes, int offset) {
1593 return byteCodes[offset] & 0xff;
1596 private static int readUShort(byte[] byteCodes, int offset) {
1597 return ((byteCodes[offset] & 0xff) << 8)
1598 | (byteCodes[offset + 1] & 0xff);
1600 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1601 return readUShort(byteCodes, offsetInstruction + 1);
1604 private static int readShort(byte[] byteCodes, int offset) {
1605 int signed = byteCodes[offset];
1606 byte b0 = (byte)signed;
1607 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1609 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1610 return readShort(byteCodes, offsetInstruction + 1);
1613 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1615 Boolean count = null;
1616 boolean array = false;
1618 int firstPos = sig.length();
1619 while (i < descriptor.length()) {
1620 char ch = descriptor.charAt(i++);
1641 if (ch == 'J' || ch == 'D') {
1647 sig.insert(firstPos, ch);
1649 returnType[0] = '[';
1650 sig.insert(firstPos, "_3");
1659 returnType[0] = 'V';
1660 sig.insert(firstPos, 'V');
1663 int next = descriptor.indexOf(';', i);
1664 String realSig = mangleSig(descriptor, i - 1, next + 1);
1669 sig.append(realSig);
1672 sig.insert(firstPos, realSig);
1674 sig.insert(firstPos, "_3");
1676 returnType[0] = 'L';
1685 throw new IllegalStateException("Invalid char: " + ch);
1690 static String mangleSig(String sig) {
1691 return mangleSig(sig, 0, sig.length());
1694 private static String mangleMethodName(String name) {
1695 StringBuilder sb = new StringBuilder(name.length() * 2);
1696 int last = name.length();
1697 for (int i = 0; i < last; i++) {
1698 final char ch = name.charAt(i);
1700 case '_': sb.append("_1"); break;
1701 default: sb.append(ch); break;
1704 return sb.toString();
1706 private static String mangleSig(String txt, int first, int last) {
1707 StringBuilder sb = new StringBuilder((last - first) * 2);
1708 for (int i = first; i < last; i++) {
1709 final char ch = txt.charAt(i);
1711 case '/': sb.append('_'); break;
1712 case '_': sb.append("_1"); break;
1713 case ';': sb.append("_2"); break;
1714 case '[': sb.append("_3"); break;
1716 if (Character.isJavaIdentifierPart(ch)) {
1720 String hex = Integer.toHexString(ch).toLowerCase();
1721 for (int m = hex.length(); m < 4; m++) {
1729 return sb.toString();
1732 private static String mangleClassName(String name) {
1733 return mangleSig(name);
1736 private static String findMethodName(MethodData m, StringBuilder cnt) {
1737 StringBuilder name = new StringBuilder();
1738 if ("<init>".equals(m.getName())) { // NOI18N
1739 name.append("cons"); // NOI18N
1740 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1741 name.append("class"); // NOI18N
1743 name.append(mangleMethodName(m.getName()));
1746 countArgs(m.getInternalSig(), new char[1], name, cnt);
1747 return name.toString();
1750 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1751 StringBuilder name = new StringBuilder();
1752 String descr = mi[2];//mi.getDescriptor();
1754 if ("<init>".equals(nm)) { // NOI18N
1755 name.append("cons"); // NOI18N
1757 name.append(mangleMethodName(nm));
1759 countArgs(descr, returnType, name, cnt);
1760 return name.toString();
1763 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1764 throws IOException {
1765 int methodIndex = readUShortArg(byteCodes, i);
1766 String[] mi = jc.getFieldInfoName(methodIndex);
1767 char[] returnType = { 'V' };
1768 StringBuilder cnt = new StringBuilder();
1769 String mn = findMethodName(mi, cnt, returnType);
1771 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1772 final CharSequence[] vars = new CharSequence[numArguments];
1774 for (int j = numArguments - 1; j >= 0; --j) {
1775 vars[j] = mapper.popValue();
1779 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1780 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1782 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1783 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1785 if (vars[1] instanceof String) {
1786 String field = vars[1].toString();
1787 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1788 vars[1] = "c._" + field.substring(1, field.length() - 1);
1793 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1794 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1796 if (vars[1] instanceof String) {
1797 String field = vars[2].toString();
1798 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1799 vars[2] = "c._" + field.substring(1, field.length() - 1);
1804 if (returnType[0] != 'V') {
1807 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1811 final String in = mi[0];
1814 in.equals("org/apidesign/html/boot/spi/Fn") ||
1815 in.equals("org/netbeans/html/boot/spi/Fn")
1817 mcn = "java_lang_Class";
1819 mcn = mangleClassName(in);
1821 String object = accessClassFalse(mcn);
1822 if (mn.startsWith("cons_")) {
1823 object += ".constructor";
1825 append(accessStaticMethod(object, mn, mi));
1831 if (numArguments > 0) {
1833 for (int j = 1; j < numArguments; ++j) {
1843 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1844 throws IOException {
1845 int methodIndex = readUShortArg(byteCodes, i);
1846 String[] mi = jc.getFieldInfoName(methodIndex);
1847 char[] returnType = { 'V' };
1848 StringBuilder cnt = new StringBuilder();
1849 String mn = findMethodName(mi, cnt, returnType);
1851 final int numArguments = cnt.length() + 1;
1852 final CharSequence[] vars = new CharSequence[numArguments];
1854 for (int j = numArguments - 1; j >= 0; --j) {
1855 vars[j] = mapper.popValue();
1858 if (returnType[0] != 'V') {
1861 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1865 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1867 for (int j = 1; j < numArguments; ++j) {
1877 private void addReference(String cn) throws IOException {
1878 if (requireReference(cn)) {
1879 debug(" /* needs " + cn + " */");
1883 private void outType(String d, StringBuilder out) {
1885 while (d.charAt(0) == '[') {
1889 if (d.charAt(0) == 'L') {
1890 assert d.charAt(d.length() - 1) == ';';
1891 out.append(mangleClassName(d).substring(0, d.length() - 1));
1897 private String encodeConstant(int entryIndex) throws IOException {
1898 String[] classRef = { null };
1899 String s = jc.stringValue(entryIndex, classRef);
1900 if (classRef[0] != null) {
1901 if (classRef[0].startsWith("[")) {
1902 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1904 addReference(classRef[0]);
1905 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1911 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1912 byte[] arr = m.findAnnotationData(true);
1916 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1917 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1918 class P extends AnnotationParser {
1924 String[] args = new String[30];
1930 protected void visitAttr(String type, String attr, String at, String value) {
1931 if (type.equals(jvmType)) {
1932 if ("body".equals(attr)) {
1934 } else if ("args".equals(attr)) {
1935 args[cnt++] = value;
1937 throw new IllegalArgumentException(attr);
1940 if (type.equals(htmlType)) {
1942 if ("body".equals(attr)) {
1944 } else if ("args".equals(attr)) {
1945 args[cnt++] = value;
1946 } else if ("javacall".equals(attr)) {
1947 javacall = "1".equals(value);
1948 } else if ("wait4js".equals(attr)) {
1949 // ignore, we always invoke synchronously
1951 throw new IllegalArgumentException(attr);
1958 if (p.body == null) {
1961 StringBuilder cnt = new StringBuilder();
1962 final String mn = findMethodName(m, cnt);
1963 append("m = ").append(destObject).append(".").append(mn);
1964 append(" = function(");
1967 StringBuilder toValue = new StringBuilder();
1968 for (int i = 0; i < cnt.length(); i++) {
1970 space = outputArg(this, p.args, index);
1971 if (p.html4j && space.length() > 0) {
1972 toValue.append("\n ").append(p.args[index]).append(" = ")
1973 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1974 append(p.args[index]).append(");");
1978 append(") {").append("\n");
1979 append(toValue.toString());
1981 int lastSlash = jc.getClassName().lastIndexOf('/');
1982 final String pkg = jc.getClassName().substring(0, lastSlash);
1983 append(mangleCallbacks(pkg, p.body));
1984 requireReference(pkg + "/$JsCallbacks$");
1992 private static CharSequence mangleCallbacks(String pkgName, String body) {
1993 StringBuilder sb = new StringBuilder();
1996 int next = body.indexOf(".@", pos);
1998 sb.append(body.substring(pos));
1999 body = sb.toString();
2004 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
2009 String refId = body.substring(ident, next);
2011 sb.append(body.substring(pos, ident));
2013 int sigBeg = body.indexOf('(', next);
2014 int sigEnd = body.indexOf(')', sigBeg);
2015 int colon4 = body.indexOf("::", next);
2016 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2017 throw new IllegalStateException("Malformed body " + body);
2019 String fqn = body.substring(next + 2, colon4);
2020 String method = body.substring(colon4 + 2, sigBeg);
2021 String params = body.substring(sigBeg, sigEnd + 1);
2023 int paramBeg = body.indexOf('(', sigEnd + 1);
2025 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2026 sb.append(mangleJsCallbacks(fqn, method, params, false));
2027 sb.append("(").append(refId);
2028 if (body.charAt(paramBeg + 1) != ')') {
2036 int next = body.indexOf("@", pos);
2041 sb.append(body.substring(pos));
2045 sb = new StringBuilder();
2048 sb.append(body.substring(pos, next));
2050 int sigBeg = body.indexOf('(', next);
2051 int sigEnd = body.indexOf(')', sigBeg);
2052 int colon4 = body.indexOf("::", next);
2053 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2054 throw new IllegalStateException("Malformed body " + body);
2056 String fqn = body.substring(next + 1, colon4);
2057 String method = body.substring(colon4 + 2, sigBeg);
2058 String params = body.substring(sigBeg, sigEnd + 1);
2060 int paramBeg = body.indexOf('(', sigEnd + 1);
2062 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2063 sb.append(mangleJsCallbacks(fqn, method, params, true));
2069 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2070 if (params.startsWith("(")) {
2071 params = params.substring(1);
2073 if (params.endsWith(")")) {
2074 params = params.substring(0, params.length() - 1);
2076 StringBuilder sb = new StringBuilder();
2077 final String fqnu = fqn.replace('.', '_');
2078 final String rfqn = mangleClassName(fqnu);
2079 final String rm = mangleMethodName(method);
2082 StringBuilder pb = new StringBuilder();
2083 int len = params.length();
2085 while (indx < len) {
2086 char ch = params.charAt(indx);
2087 if (ch == '[' || ch == 'L') {
2088 int column = params.indexOf(';', indx) + 1;
2089 if (column > indx) {
2090 String real = params.substring(indx, column);
2091 if ("Ljava/lang/String;".equals(real)) {
2092 pb.append("Ljava/lang/String;");
2097 pb.append("Ljava/lang/Object;");
2104 srp = mangleSig(pb.toString());
2106 final String rp = mangleSig(params);
2107 final String mrp = mangleMethodName(rp);
2108 sb.append(rfqn).append("$").append(rm).
2109 append('$').append(mrp).append("__Ljava_lang_Object_2");
2111 sb.append('L').append(fqnu).append("_2");
2114 return sb.toString();
2117 private static String className(ClassData jc) {
2118 //return jc.getName().getInternalName().replace('/', '_');
2119 return mangleClassName(jc.getClassName());
2122 private static String[] findAnnotation(
2123 byte[] arr, ClassData cd, final String className,
2124 final String... attrNames
2125 ) throws IOException {
2129 final String[] values = new String[attrNames.length];
2130 final boolean[] found = { false };
2131 final String jvmType = "L" + className.replace('.', '/') + ";";
2132 AnnotationParser ap = new AnnotationParser(false, true) {
2134 protected void visitAttr(String type, String attr, String at, String value) {
2135 if (type.equals(jvmType)) {
2137 for (int i = 0; i < attrNames.length; i++) {
2138 if (attrNames[i].equals(attr)) {
2147 return found[0] ? values : null;
2150 private CharSequence initField(FieldData v) {
2151 final String is = v.getInternalSig();
2152 if (is.length() == 1) {
2153 switch (is.charAt(0)) {
2159 case 'I': return " = 0;";
2161 case 'D': return " = 0.0;";
2163 throw new IllegalStateException(is);
2169 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2170 final String name = args[indx];
2174 if (name.contains(",")) {
2175 throw new IOException("Wrong parameter with ',': " + name);
2181 final void emitNoFlush(
2183 final String format, final CharSequence... params
2184 ) throws IOException {
2185 emitImpl(this, format, params);
2187 static final void emit(
2189 final Appendable out,
2190 final String format, final CharSequence... params
2191 ) throws IOException {
2193 emitImpl(out, format, params);
2195 static void emitImpl(final Appendable out,
2196 final String format,
2197 final CharSequence... params) throws IOException {
2198 final int length = format.length();
2201 int paramOffset = format.indexOf('@');
2202 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2203 final char paramChar = format.charAt(paramOffset + 1);
2204 if ((paramChar >= '1') && (paramChar <= '9')) {
2205 final int paramIndex = paramChar - '0' - 1;
2207 out.append(format, processed, paramOffset);
2208 out.append(params[paramIndex]);
2211 processed = paramOffset + 1;
2214 paramOffset = format.indexOf('@', paramOffset + 1);
2217 out.append(format, processed, length);
2220 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2221 append("} catch (e) {\n");
2223 for (TrapData e : traps) {
2227 if (e.catch_cpx != 0) { //not finally
2228 final String classInternalName = jc.getClassName(e.catch_cpx);
2229 addReference(classInternalName);
2230 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2231 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2232 append("var stA0 = e;");
2233 goTo(this, current, e.handler_pc, topMostLabel);
2236 finallyPC = e.handler_pc;
2239 if (finallyPC == -1) {
2242 append("var stA0 = e;");
2243 goTo(this, current, finallyPC, topMostLabel);
2248 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2251 out.append("{ gt = 0; continue X_" + to + "; }");
2253 out.append("{ gt = " + to + "; continue X_0; }");
2256 out.append("{ gt = " + to + "; break IF; }");
2260 private static void emitIf(
2262 Appendable out, String pattern,
2264 int current, int to, int canBack
2265 ) throws IOException {
2267 emitImpl(out, pattern, param);
2268 goTo(out, current, to, canBack);
2271 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2274 case 4: jvmType = "[Z"; break;
2275 case 5: jvmType = "[C"; break;
2276 case 6: jvmType = "[F"; break;
2277 case 7: jvmType = "[D"; break;
2278 case 8: jvmType = "[B"; break;
2279 case 9: jvmType = "[S"; break;
2280 case 10: jvmType = "[I"; break;
2281 case 11: jvmType = "[J"; break;
2282 default: throw new IllegalStateException("Array type: " + atype);
2285 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2286 smapper.popI(), smapper.pushA(), jvmType);
2289 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2290 String typeName = jc.getClassName(type);
2291 String ref = "null";
2292 if (typeName.startsWith("[")) {
2293 typeName = "'[" + typeName + "'";
2295 ref = "vm." + mangleClassName(typeName);
2296 typeName = "'[L" + typeName + ";'";
2299 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2300 smapper.popI(), smapper.pushA(), typeName, ref);
2303 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2304 String typeName = jc.getClassName(type);
2305 int dim = readUByte(byteCodes, ++i);
2306 StringBuilder dims = new StringBuilder();
2308 for (int d = 0; d < dim; d++) {
2310 dims.insert(1, ",");
2312 dims.insert(1, smapper.popI());
2316 if (typeName.charAt(dim) == 'L') {
2317 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2320 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2321 dims.toString(), smapper.pushA(), typeName, fn
2326 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2327 int table = i / 4 * 4 + 4;
2328 int dflt = i + readInt4(byteCodes, table);
2330 int low = readInt4(byteCodes, table);
2332 int high = readInt4(byteCodes, table);
2334 final CharSequence swVar = smapper.popValue();
2335 smapper.flush(this);
2336 append("switch (").append(swVar).append(") {\n");
2337 while (low <= high) {
2338 int offset = i + readInt4(byteCodes, table);
2340 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2343 append(" default: ");
2344 goTo(this, i, dflt, topMostLabel);
2350 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2351 int table = i / 4 * 4 + 4;
2352 int dflt = i + readInt4(byteCodes, table);
2354 int n = readInt4(byteCodes, table);
2356 final CharSequence swVar = smapper.popValue();
2357 smapper.flush(this);
2358 append("switch (").append(swVar).append(") {\n");
2360 int cnstnt = readInt4(byteCodes, table);
2362 int offset = i + readInt4(byteCodes, table);
2364 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2366 append(" default: ");
2367 goTo(this, i, dflt, topMostLabel);
2373 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2374 String type = jc.getClassName(indx);
2375 if (!type.startsWith("[")) {
2377 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2378 smapper.popA(), smapper.pushI(),
2379 mangleClassName(type));
2382 while (type.charAt(cnt) == '[') {
2385 if (type.charAt(cnt) == 'L') {
2386 String component = type.substring(cnt + 1, type.length() - 1);
2387 requireReference(component);
2388 type = "vm." + mangleClassName(component);
2390 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2391 smapper.popA(), smapper.pushI(),
2396 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2397 smapper.popA(), smapper.pushI(), type
2403 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2404 String type = jc.getClassName(indx);
2405 if (!type.startsWith("[")) {
2406 emitNoFlush(smapper,
2407 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2408 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2411 while (type.charAt(cnt) == '[') {
2414 if (type.charAt(cnt) == 'L') {
2415 String component = type.substring(cnt + 1, type.length() - 1);
2416 requireReference(component);
2417 type = "vm." + mangleClassName(component);
2418 emitNoFlush(smapper,
2419 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2420 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2423 emitNoFlush(smapper,
2424 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2425 smapper.getT(0, VarType.REFERENCE, false), type
2431 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2432 for (int j = prev; j <= i; j++) {
2434 final int cc = readUByte(byteCodes, j);
2435 append(Integer.toString(cc));
2439 @JavaScriptBody(args = "msg", body = "")
2440 private static void println(String msg) {
2441 System.err.println(msg);
2444 private class GenerateAnno extends AnnotationParser {
2445 public GenerateAnno(boolean textual, boolean iterateArray) {
2446 super(textual, iterateArray);
2448 int[] cnt = new int[32];
2452 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2453 final String slashType = attrType.substring(1, attrType.length() - 1);
2454 requireReference(slashType);
2456 if (cnt[depth]++ > 0) {
2460 append('"').append(attrType).append("\" : ");
2467 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2473 protected void visitValueStart(String attrName, char type) throws IOException {
2474 if (cnt[depth]++ > 0) {
2478 if (attrName != null) {
2479 append('"').append(attrName).append("\" : ");
2487 protected void visitValueEnd(String attrName, char type) throws IOException {
2495 protected void visitAttr(String type, String attr, String attrType, String value)
2496 throws IOException {
2497 if (attr == null && value == null) {
2504 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2505 throws IOException {
2506 final String slashType = attrType.substring(1, attrType.length() - 1);
2507 requireReference(slashType);
2509 final String cn = mangleClassName(slashType);
2510 append(accessClassFalse(cn))
2511 .append("['valueOf__L").
2513 append("_2Ljava_lang_String_2']('").
2519 protected void visitClassAttr(String annoType, String attr, String className) throws IOException {
2520 final String slashType = className.substring(1, className.length() - 1);
2521 requireReference(slashType);
2523 final String cn = mangleClassName(slashType);
2524 append(accessClassFalse(cn)).append(".constructor.$class");