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 generateAnno(jc, runAnno);
294 append("\n m.access = " + m.getAccess()).append(";");
295 append("\n m.cls = CLS;");
297 append(numbers.generate());
298 append("\n c.constructor = CLS;");
299 append("\n function ").append(className).append("fillInstOf(x) {");
300 String instOfName = "$instOf_" + className;
301 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
302 if (jc.isInterface()) {
303 for (MethodData m : jc.getMethods()) {
304 if ((m.getAccess() & ACC_ABSTRACT) == 0
305 && (m.getAccess() & ACC_STATIC) == 0
306 && (m.getAccess() & ACC_PRIVATE) == 0) {
307 final String mn = findMethodName(m, new StringBuilder());
308 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
312 for (String superInterface : jc.getSuperInterfaces()) {
313 String intrfc = mangleClassName(superInterface);
314 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
315 requireReference(superInterface);
318 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
319 append("\n ").append(className).append("fillInstOf(c);");
320 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
321 append("\n CLS.$class = 'temp';");
322 append("\n CLS.$class = ");
323 append(accessClass("java_lang_Class(true);"));
324 append("\n CLS.$class.jvmName = '").append(cn).append("';");
325 append("\n CLS.$class.superclass = sprcls;");
326 append("\n CLS.$class.interfaces = function() { return [");
328 boolean first = true;
329 for (String intrfc : jc.getSuperInterfaces()) {
333 requireReference(intrfc);
334 String mangledIface = mangleClassName(intrfc);
336 append(accessClass(mangledIface)).append("(false).constructor.$class");
341 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
342 append("\n CLS.$class.cnstr = CLS;");
343 byte[] classAnno = jc.findAnnotationData(false);
344 if (classAnno != null) {
345 append("\n CLS.$class.anno = {");
346 generateAnno(jc, classAnno);
349 for (String init : toInitilize.toArray()) {
350 append("\n ").append(init).append("();");
352 for (String ref : classRefs.toArray()) {
353 append("\n var refs_").append(ref).append(";");
357 if (jsResource != null) {
358 requireResource(jsResource);
362 append("\n if (arguments.length === 0) {");
363 append("\n if (!(this instanceof CLS)) {");
364 append("\n return new CLS();");
366 for (FieldData v : jc.getFields()) {
367 byte[] onlyArr = v.findAnnotationData(true);
368 if (javaScriptOnly(onlyArr)) continue;
370 append("\n this.fld_").
371 append(className).append('_').
372 append(v.getName()).append(initField(v));
375 append("\n return this;");
377 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
380 declaredClass(jc, className);
382 // StringBuilder sb = new StringBuilder();
383 // for (String init : toInitilize.toArray()) {
384 // sb.append("\n").append(init).append("();");
389 private boolean javaScriptOnly(byte[] anno) throws IOException {
390 String[] only = findAnnotation(anno, jc,
391 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
395 if (only[0] != null && only[1] != null) {
396 append("\n p.").append(only[0]).append(" = ")
397 .append(only[1]).append(";");
399 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
400 append("\n p['").append(only[0]).append("'] = p.")
401 .append(only[0]).append(";");
407 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
408 String jsb = javaScriptBody(destObject, m, true);
412 final String mn = findMethodName(m, new StringBuilder());
413 boolean defineProp = generateMethod(destObject, mn, m);
414 if (mn.equals("class__V")) {
416 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
418 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
424 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
425 String jsb = javaScriptBody(destObject, m, false);
429 final String mn = findMethodName(m, new StringBuilder());
430 generateMethod(destObject, mn, m);
434 private boolean generateMethod(String destObject, String name, MethodData m)
436 final StackMapIterator stackMapIterator = m.createStackMapIterator();
437 TrapDataIterator trap = m.getTrapDataIterator();
438 final LocalsMapper lmapper =
439 new LocalsMapper(stackMapIterator.getArguments());
442 "java/lang/Object".equals(jc.getClassName()) ||
443 "java/lang/reflect/Array".equals(jc.getClassName());
446 append("Object.defineProperty(").append(destObject).
447 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
449 append("m = ").append(destObject).append(".").append(name).append(" = function(");
451 lmapper.outputArguments(this, m.isStatic());
452 append(") {").append("\n");
454 final byte[] byteCodes = m.getCode();
455 if (byteCodes == null) {
456 if (debug(" throw 'no code found for ")) {
458 .append(jc.getClassName()).append('.')
459 .append(m.getName()).append("';\n");
469 final StackMapper smapper = new StackMapper();
472 append(" var ").append(" lcA0 = this;\n");
476 TrapData[] previousTrap = null;
477 boolean wide = false;
479 if (stackMapIterator.isEmpty()) {
485 append("\n var gt = 0;\n");
489 int topMostLabel = 0;
490 for (int i = 0; i < byteCodes.length; i++) {
493 stackMapIterator.advanceTo(i);
494 boolean changeInCatch = trap.advanceTo(i);
495 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
496 if (previousTrap != null) {
497 generateCatch(previousTrap, i, topMostLabel);
501 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
506 if (openBraces > 64) {
507 for (int c = 0; c < 64; c++) {
514 lastStackFrame = stackMapIterator.getFrameIndex();
515 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
516 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
517 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
519 changeInCatch = true;
521 debug(" /* " + i + " */ ");
523 if (changeInCatch && trap.useTry()) {
525 previousTrap = trap.current();
527 final int c = readUByte(byteCodes, i);
530 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
533 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
536 smapper.assign(this, VarType.LONG, lmapper.getL(0));
539 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
542 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
545 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
548 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
551 smapper.assign(this, VarType.LONG, lmapper.getL(1));
554 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
557 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
560 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
563 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
566 smapper.assign(this, VarType.LONG, lmapper.getL(2));
569 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
572 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
575 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
578 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
581 smapper.assign(this, VarType.LONG, lmapper.getL(3));
584 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
587 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
591 final int indx = wide ? readUShort(byteCodes, i++)
592 : readUByte(byteCodes, i);
594 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
599 final int indx = wide ? readUShort(byteCodes, i++)
600 : readUByte(byteCodes, i);
602 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
607 final int indx = wide ? readUShort(byteCodes, i++)
608 : readUByte(byteCodes, i);
610 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
615 final int indx = wide ? readUShort(byteCodes, i++)
616 : readUByte(byteCodes, i);
618 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
623 final int indx = wide ? readUShort(byteCodes, i++)
624 : readUByte(byteCodes, i);
626 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
631 final int indx = wide ? readUShort(byteCodes, i++)
632 : readUByte(byteCodes, i);
634 emit(smapper, this, "var @1 = @2;",
635 lmapper.setI(indx), smapper.popI());
640 final int indx = wide ? readUShort(byteCodes, i++)
641 : readUByte(byteCodes, i);
643 emit(smapper, this, "var @1 = @2;",
644 lmapper.setL(indx), smapper.popL());
649 final int indx = wide ? readUShort(byteCodes, i++)
650 : readUByte(byteCodes, i);
652 emit(smapper, this, "var @1 = @2;",
653 lmapper.setF(indx), smapper.popF());
658 final int indx = wide ? readUShort(byteCodes, i++)
659 : readUByte(byteCodes, i);
661 emit(smapper, this, "var @1 = @2;",
662 lmapper.setD(indx), smapper.popD());
667 final int indx = wide ? readUShort(byteCodes, i++)
668 : readUByte(byteCodes, i);
670 emit(smapper, this, "var @1 = @2;",
671 lmapper.setA(indx), smapper.popA());
675 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
678 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
681 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
684 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
687 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
690 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
693 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
696 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
699 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
702 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
705 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
708 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
711 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
714 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
717 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
720 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
723 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
726 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
729 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
732 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
735 smapper.replace(this, VarType.INTEGER, "(((@1) + (@2)) | 0)", smapper.getI(1), smapper.popI());
738 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
741 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
744 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
747 smapper.replace(this, VarType.INTEGER, "(((@1) - (@2)) | 0)", smapper.getI(1), smapper.popI());
750 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
753 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
756 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
759 smapper.replace(this, VarType.INTEGER, numbers.mul32(), smapper.getI(1), smapper.popI());
762 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
765 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
768 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
771 smapper.replace(this, VarType.INTEGER, numbers.div32(),
772 smapper.getI(1), smapper.popI());
775 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
776 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.mod32(),
786 smapper.getI(1), smapper.popI());
789 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
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, "(@1 & @2)", smapper.getI(1), smapper.popI());
802 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
805 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
808 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
811 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
814 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
817 smapper.replace(this, VarType.INTEGER, "(-(@1))", smapper.getI(0));
820 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
823 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
826 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
829 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
832 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
835 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
838 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
841 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
844 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
848 final int varIndx = wide ? readUShort(byteCodes, i++)
849 : readUByte(byteCodes, i);
851 final int incrBy = wide ? readShort(byteCodes, i++)
855 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
857 emit(smapper, this, "@1 += @2;",
858 lmapper.getI(varIndx),
859 Integer.toString(incrBy));
864 emit(smapper, this, "return;");
867 emit(smapper, this, "return @1;", smapper.popI());
870 emit(smapper, this, "return @1;", smapper.popL());
873 emit(smapper, this, "return @1;", smapper.popF());
876 emit(smapper, this, "return @1;", smapper.popD());
879 emit(smapper, this, "return @1;", smapper.popA());
882 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
885 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
888 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
891 smapper.replace(this, VarType.INTEGER, "((@1) | 0)", smapper.getL(0));
895 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
898 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
901 smapper.replace(this, VarType.DOUBLE, "@1",
905 smapper.replace(this, VarType.FLOAT, "@1",
909 smapper.replace(this, VarType.INTEGER, "((@1) | 0)",
913 smapper.replace(this, VarType.LONG, "(@1).toLong()",
917 smapper.replace(this, VarType.INTEGER, "((@1)| 0)",
921 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
924 smapper.replace(this, VarType.INTEGER, "(((@1) << 24) >> 24)", smapper.getI(0));
928 smapper.replace(this, VarType.INTEGER, "(((@1) << 16) >> 16)", smapper.getI(0));
930 case opc_aconst_null:
931 smapper.assign(this, VarType.REFERENCE, "null");
934 smapper.assign(this, VarType.INTEGER, "-1");
937 smapper.assign(this, VarType.INTEGER, "0");
940 smapper.assign(this, VarType.DOUBLE, "0");
943 smapper.assign(this, VarType.LONG, "0");
946 smapper.assign(this, VarType.FLOAT, "0");
949 smapper.assign(this, VarType.INTEGER, "1");
952 smapper.assign(this, VarType.LONG, "1");
955 smapper.assign(this, VarType.FLOAT, "1");
958 smapper.assign(this, VarType.DOUBLE, "1");
961 smapper.assign(this, VarType.INTEGER, "2");
964 smapper.assign(this, VarType.FLOAT, "2");
967 smapper.assign(this, VarType.INTEGER, "3");
970 smapper.assign(this, VarType.INTEGER, "4");
973 smapper.assign(this, VarType.INTEGER, "5");
976 int indx = readUByte(byteCodes, ++i);
977 String v = encodeConstant(indx);
978 int type = VarType.fromConstantType(jc.getTag(indx));
979 smapper.assign(this, type, v);
984 int indx = readUShortArg(byteCodes, i);
986 String v = encodeConstant(indx);
987 int type = VarType.fromConstantType(jc.getTag(indx));
988 if (type == VarType.LONG) {
989 final Long lv = new Long(v);
990 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
991 final int hi = (int)(lv.longValue() >> 32);
993 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
995 smapper.assign(this, VarType.LONG,
996 "0x" + Integer.toHexString(hi) + ".next32(0x" +
997 Integer.toHexString(low) + ")"
1001 smapper.assign(this, type, v);
1006 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
1010 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1011 smapper.popF(), smapper.popF(), smapper.pushI());
1015 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1016 smapper.popD(), smapper.popD(), smapper.pushI());
1019 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1020 "===", topMostLabel);
1023 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1024 "!==", topMostLabel);
1027 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1028 "==", topMostLabel);
1031 int indx = i + readShortArg(byteCodes, i);
1032 emitIf(smapper, this, "if ((@1) == 0) ",
1033 smapper.popI(), i, indx, topMostLabel);
1038 int indx = i + readShortArg(byteCodes, i);
1039 emitIf(smapper, this, "if ((@1) != 0) ",
1040 smapper.popI(), i, indx, topMostLabel);
1045 int indx = i + readShortArg(byteCodes, i);
1046 emitIf(smapper, this, "if ((@1) < 0) ",
1047 smapper.popI(), i, indx, topMostLabel);
1052 int indx = i + readShortArg(byteCodes, i);
1053 emitIf(smapper, this, "if ((@1) <= 0) ",
1054 smapper.popI(), i, indx, topMostLabel);
1059 int indx = i + readShortArg(byteCodes, i);
1060 emitIf(smapper, this, "if ((@1) > 0) ",
1061 smapper.popI(), i, indx, topMostLabel);
1066 int indx = i + readShortArg(byteCodes, i);
1067 emitIf(smapper, this, "if ((@1) >= 0) ",
1068 smapper.popI(), i, indx, topMostLabel);
1072 case opc_ifnonnull: {
1073 int indx = i + readShortArg(byteCodes, i);
1074 emitIf(smapper, this, "if ((@1) !== null) ",
1075 smapper.popA(), i, indx, topMostLabel);
1080 int indx = i + readShortArg(byteCodes, i);
1081 emitIf(smapper, this, "if ((@1) === null) ",
1082 smapper.popA(), i, indx, topMostLabel);
1087 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1088 "!=", topMostLabel);
1091 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1095 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1096 "<=", topMostLabel);
1099 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1103 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1104 ">=", topMostLabel);
1107 smapper.flush(this);
1108 int indx = i + readShortArg(byteCodes, i);
1109 goTo(this, i, indx, topMostLabel);
1113 case opc_lookupswitch: {
1114 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1117 case opc_tableswitch: {
1118 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1121 case opc_invokeinterface: {
1122 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1125 case opc_invokevirtual:
1126 i = invokeVirtualMethod(byteCodes, i, smapper);
1128 case opc_invokespecial:
1129 i = invokeStaticMethod(byteCodes, i, smapper, false);
1131 case opc_invokestatic:
1132 i = invokeStaticMethod(byteCodes, i, smapper, true);
1134 case opc_invokedynamic: {
1135 int indx = readUShortArg(byteCodes, i);
1136 println("invoke dynamic: " + indx);
1137 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1138 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1139 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1140 println(" type: " + methodHandle.cpx1);
1141 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1142 String mcn = mangleClassName(mi[0]);
1143 char[] returnType = {'V'};
1144 StringBuilder cnt = new StringBuilder();
1145 String mn = findMethodName(mi, cnt, returnType);
1146 StringBuilder sb = new StringBuilder();
1147 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1148 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1149 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1150 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1151 sb.append(" mn : ").append(mn).append("\n");
1152 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1153 throw new IOException(sb.toString());
1155 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1156 String type = jc.StringValue(nameAndType.cpx2);
1157 String object = accessClass(mcn) + "(false)";
1158 if (mn.startsWith("cons_")) {
1159 object += ".constructor";
1161 append("var metHan = ");
1162 append(accessStaticMethod(object, mn, mi));
1164 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1166 append(", '").append(mi[1]).append("', ");
1167 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1168 append(methodType).append("'").append(type).append("', null)");
1169 // if (numArguments > 0) {
1171 // for (int j = 1; j < numArguments; ++j) {
1177 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1183 int indx = readUShortArg(byteCodes, i);
1184 String ci = jc.getClassName(indx);
1185 emit(smapper, this, "var @1 = new @2;",
1186 smapper.pushA(), accessClass(mangleClassName(ci)));
1192 int atype = readUByte(byteCodes, ++i);
1193 generateNewArray(atype, smapper);
1195 case opc_anewarray: {
1196 int type = readUShortArg(byteCodes, i);
1198 generateANewArray(type, smapper);
1201 case opc_multianewarray: {
1202 int type = readUShortArg(byteCodes, i);
1204 i = generateMultiANewArray(type, byteCodes, i, smapper);
1207 case opc_arraylength:
1208 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1211 emit(smapper, this, "Array.at(@3, @2, @1);",
1212 smapper.popL(), smapper.popI(), smapper.popA());
1215 emit(smapper, this, "Array.at(@3, @2, @1);",
1216 smapper.popF(), smapper.popI(), smapper.popA());
1219 emit(smapper, this, "Array.at(@3, @2, @1);",
1220 smapper.popD(), smapper.popI(), smapper.popA());
1223 emit(smapper, this, "Array.at(@3, @2, @1);",
1224 smapper.popA(), smapper.popI(), smapper.popA());
1230 emit(smapper, this, "Array.at(@3, @2, @1);",
1231 smapper.popI(), smapper.popI(), smapper.popA());
1234 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1235 smapper.popI(), smapper.getA(0));
1238 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1239 smapper.popI(), smapper.getA(0));
1242 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1243 smapper.popI(), smapper.getA(0));
1246 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1247 smapper.popI(), smapper.getA(0));
1253 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1254 smapper.popI(), smapper.getA(0));
1262 final Variable v = smapper.get(0);
1263 if (smapper.isDirty()) {
1264 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1266 smapper.assign(this, v.getType(), v);
1271 final Variable vi1 = smapper.get(0);
1273 if (vi1.isCategory2()) {
1274 emit(smapper, this, "var @1 = @2;",
1275 smapper.pushT(vi1.getType()), vi1);
1277 final Variable vi2 = smapper.get(1);
1278 emit(smapper, this, "var @1 = @2, @3 = @4;",
1279 smapper.pushT(vi2.getType()), vi2,
1280 smapper.pushT(vi1.getType()), vi1);
1285 final Variable vi1 = smapper.pop(this);
1286 final Variable vi2 = smapper.pop(this);
1287 final Variable vo3 = smapper.pushT(vi1.getType());
1288 final Variable vo2 = smapper.pushT(vi2.getType());
1289 final Variable vo1 = smapper.pushT(vi1.getType());
1291 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1292 vo1, vi1, vo2, vi2, vo3, vo1);
1296 final Variable vi1 = smapper.pop(this);
1297 final Variable vi2 = smapper.pop(this);
1299 if (vi1.isCategory2()) {
1300 final Variable vo3 = smapper.pushT(vi1.getType());
1301 final Variable vo2 = smapper.pushT(vi2.getType());
1302 final Variable vo1 = smapper.pushT(vi1.getType());
1304 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1305 vo1, vi1, vo2, vi2, vo3, vo1);
1307 final Variable vi3 = smapper.pop(this);
1308 final Variable vo5 = smapper.pushT(vi2.getType());
1309 final Variable vo4 = smapper.pushT(vi1.getType());
1310 final Variable vo3 = smapper.pushT(vi3.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, vi3);
1316 emit(smapper, this, " @1 = @2, @3 = @4;",
1317 vo4, vo1, vo5, vo2);
1322 final Variable vi1 = smapper.pop(this);
1323 final Variable vi2 = smapper.pop(this);
1325 if (vi2.isCategory2()) {
1326 final Variable vo3 = smapper.pushT(vi1.getType());
1327 final Variable vo2 = smapper.pushT(vi2.getType());
1328 final Variable vo1 = smapper.pushT(vi1.getType());
1330 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1331 vo1, vi1, vo2, vi2, vo3, vo1);
1333 final Variable vi3 = smapper.pop(this);
1334 final Variable vo4 = smapper.pushT(vi1.getType());
1335 final Variable vo3 = smapper.pushT(vi3.getType());
1336 final Variable vo2 = smapper.pushT(vi2.getType());
1337 final Variable vo1 = smapper.pushT(vi1.getType());
1339 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1340 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1345 final Variable vi1 = smapper.pop(this);
1346 final Variable vi2 = smapper.pop(this);
1348 if (vi1.isCategory2()) {
1349 if (vi2.isCategory2()) {
1350 final Variable vo3 = smapper.pushT(vi1.getType());
1351 final Variable vo2 = smapper.pushT(vi2.getType());
1352 final Variable vo1 = smapper.pushT(vi1.getType());
1354 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1355 vo1, vi1, vo2, vi2, vo3, vo1);
1357 final Variable vi3 = smapper.pop(this);
1358 final Variable vo4 = smapper.pushT(vi1.getType());
1359 final Variable vo3 = smapper.pushT(vi3.getType());
1360 final Variable vo2 = smapper.pushT(vi2.getType());
1361 final Variable vo1 = smapper.pushT(vi1.getType());
1363 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1364 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1367 final Variable vi3 = smapper.pop(this);
1369 if (vi3.isCategory2()) {
1370 final Variable vo5 = smapper.pushT(vi2.getType());
1371 final Variable vo4 = smapper.pushT(vi1.getType());
1372 final Variable vo3 = smapper.pushT(vi3.getType());
1373 final Variable vo2 = smapper.pushT(vi2.getType());
1374 final Variable vo1 = smapper.pushT(vi1.getType());
1376 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1377 vo1, vi1, vo2, vi2, vo3, vi3);
1378 emit(smapper, this, " @1 = @2, @3 = @4;",
1379 vo4, vo1, vo5, vo2);
1381 final Variable vi4 = smapper.pop(this);
1382 final Variable vo6 = smapper.pushT(vi2.getType());
1383 final Variable vo5 = smapper.pushT(vi1.getType());
1384 final Variable vo4 = smapper.pushT(vi4.getType());
1385 final Variable vo3 = smapper.pushT(vi3.getType());
1386 final Variable vo2 = smapper.pushT(vi2.getType());
1387 final Variable vo1 = smapper.pushT(vi1.getType());
1389 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1390 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1391 emit(smapper, this, " @1 = @2, @3 = @4;",
1392 vo5, vo1, vo6, vo2);
1398 final Variable vi1 = smapper.get(0);
1399 final Variable vi2 = smapper.get(1);
1401 if (vi1.getType() == vi2.getType()) {
1402 final Variable tmp = smapper.pushT(vi1.getType());
1404 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1409 smapper.pushT(vi1.getType());
1410 smapper.pushT(vi2.getType());
1415 smapper.assign(this, VarType.INTEGER,
1416 "(" + Integer.toString(byteCodes[++i]) + ")");
1419 smapper.assign(this, VarType.INTEGER,
1420 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1424 case opc_getfield: {
1425 int indx = readUShortArg(byteCodes, i);
1426 String[] fi = jc.getFieldInfoName(indx);
1427 final int type = VarType.fromFieldType(fi[2].charAt(0));
1428 FieldData field = findField(fi);
1429 if (field == null) {
1430 final String mangleClass = mangleClassName(fi[0]);
1431 final String mangleClassAccess = accessClassFalse(mangleClass);
1432 smapper.replace(this, type, "@2.call(@1)",
1434 accessField(mangleClassAccess, null, fi)
1437 final String fieldOwner = mangleClassName(field.cls.getClassName());
1438 smapper.replace(this, type, "@1.@2",
1440 accessField(fieldOwner, field, fi)
1444 addReference(fi[0]);
1447 case opc_putfield: {
1448 int indx = readUShortArg(byteCodes, i);
1449 String[] fi = jc.getFieldInfoName(indx);
1450 final int type = VarType.fromFieldType(fi[2].charAt(0));
1451 FieldData field = findField(fi);
1452 if (field == null) {
1453 final String mangleClass = mangleClassName(fi[0]);
1454 final String mangleClassAccess = accessClassFalse(mangleClass);
1455 emit(smapper, this, "@3.call(@2, @1);",
1458 accessField(mangleClassAccess, null, fi)
1461 final String fieldOwner = mangleClassName(field.cls.getClassName());
1462 emit(smapper, this, "@2.@3 = @1;",
1465 accessField(fieldOwner, field, fi)
1469 addReference(fi[0]);
1472 case opc_getstatic: {
1473 int indx = readUShortArg(byteCodes, i);
1474 String[] fi = jc.getFieldInfoName(indx);
1475 final int type = VarType.fromFieldType(fi[2].charAt(0));
1476 String ac = accessClassFalse(mangleClassName(fi[0]));
1477 String af = accessField(ac, null, fi);
1478 smapper.assign(this, type, af + "()");
1480 addReference(fi[0]);
1483 case opc_putstatic: {
1484 int indx = readUShortArg(byteCodes, i);
1485 String[] fi = jc.getFieldInfoName(indx);
1486 final int type = VarType.fromFieldType(fi[2].charAt(0));
1487 emit(smapper, this, "@1._@2(@3);",
1488 accessClassFalse(mangleClassName(fi[0])), fi[1],
1489 smapper.popT(type));
1491 addReference(fi[0]);
1494 case opc_checkcast: {
1495 int indx = readUShortArg(byteCodes, i);
1496 generateCheckcast(indx, smapper);
1500 case opc_instanceof: {
1501 int indx = readUShortArg(byteCodes, i);
1502 generateInstanceOf(indx, smapper);
1507 final CharSequence v = smapper.popA();
1510 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1511 smapper.pushA(), v);
1515 case opc_monitorenter: {
1516 debug("/* monitor enter */");
1521 case opc_monitorexit: {
1522 debug("/* monitor exit */");
1533 emit(smapper, this, "throw 'unknown bytecode @1';",
1534 Integer.toString(c));
1538 generateByteCodeComment(prev, i, byteCodes);
1544 if (previousTrap != null) {
1545 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1550 while (openBraces-- > 0) {
1561 private int generateIf(StackMapper mapper, byte[] byteCodes,
1562 int i, final CharSequence v2, final CharSequence v1,
1563 final String test, int topMostLabel
1564 ) throws IOException {
1566 int indx = i + readShortArg(byteCodes, i);
1567 append("if ((").append(v1)
1568 .append(") ").append(test).append(" (")
1569 .append(v2).append(")) ");
1570 goTo(this, i, indx, topMostLabel);
1574 private int readInt4(byte[] byteCodes, int offset) {
1575 final int d = byteCodes[offset + 0] << 24;
1576 final int c = byteCodes[offset + 1] << 16;
1577 final int b = byteCodes[offset + 2] << 8;
1578 final int a = byteCodes[offset + 3];
1579 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1581 private static int readUByte(byte[] byteCodes, int offset) {
1582 return byteCodes[offset] & 0xff;
1585 private static int readUShort(byte[] byteCodes, int offset) {
1586 return ((byteCodes[offset] & 0xff) << 8)
1587 | (byteCodes[offset + 1] & 0xff);
1589 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1590 return readUShort(byteCodes, offsetInstruction + 1);
1593 private static int readShort(byte[] byteCodes, int offset) {
1594 int signed = byteCodes[offset];
1595 byte b0 = (byte)signed;
1596 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1598 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1599 return readShort(byteCodes, offsetInstruction + 1);
1602 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1604 Boolean count = null;
1605 boolean array = false;
1607 int firstPos = sig.length();
1608 while (i < descriptor.length()) {
1609 char ch = descriptor.charAt(i++);
1630 if (ch == 'J' || ch == 'D') {
1636 sig.insert(firstPos, ch);
1638 returnType[0] = '[';
1639 sig.insert(firstPos, "_3");
1648 returnType[0] = 'V';
1649 sig.insert(firstPos, 'V');
1652 int next = descriptor.indexOf(';', i);
1653 String realSig = mangleSig(descriptor, i - 1, next + 1);
1658 sig.append(realSig);
1661 sig.insert(firstPos, realSig);
1663 sig.insert(firstPos, "_3");
1665 returnType[0] = 'L';
1674 throw new IllegalStateException("Invalid char: " + ch);
1679 static String mangleSig(String sig) {
1680 return mangleSig(sig, 0, sig.length());
1683 private static String mangleMethodName(String name) {
1684 StringBuilder sb = new StringBuilder(name.length() * 2);
1685 int last = name.length();
1686 for (int i = 0; i < last; i++) {
1687 final char ch = name.charAt(i);
1689 case '_': sb.append("_1"); break;
1690 default: sb.append(ch); break;
1693 return sb.toString();
1695 private static String mangleSig(String txt, int first, int last) {
1696 StringBuilder sb = new StringBuilder((last - first) * 2);
1697 for (int i = first; i < last; i++) {
1698 final char ch = txt.charAt(i);
1700 case '/': sb.append('_'); break;
1701 case '_': sb.append("_1"); break;
1702 case ';': sb.append("_2"); break;
1703 case '[': sb.append("_3"); break;
1705 if (Character.isJavaIdentifierPart(ch)) {
1709 String hex = Integer.toHexString(ch).toLowerCase();
1710 for (int m = hex.length(); m < 4; m++) {
1718 return sb.toString();
1721 private static String mangleClassName(String name) {
1722 return mangleSig(name);
1725 private static String findMethodName(MethodData m, StringBuilder cnt) {
1726 StringBuilder name = new StringBuilder();
1727 if ("<init>".equals(m.getName())) { // NOI18N
1728 name.append("cons"); // NOI18N
1729 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1730 name.append("class"); // NOI18N
1732 name.append(mangleMethodName(m.getName()));
1735 countArgs(m.getInternalSig(), new char[1], name, cnt);
1736 return name.toString();
1739 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1740 StringBuilder name = new StringBuilder();
1741 String descr = mi[2];//mi.getDescriptor();
1743 if ("<init>".equals(nm)) { // NOI18N
1744 name.append("cons"); // NOI18N
1746 name.append(mangleMethodName(nm));
1748 countArgs(descr, returnType, name, cnt);
1749 return name.toString();
1752 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1753 throws IOException {
1754 int methodIndex = readUShortArg(byteCodes, i);
1755 String[] mi = jc.getFieldInfoName(methodIndex);
1756 char[] returnType = { 'V' };
1757 StringBuilder cnt = new StringBuilder();
1758 String mn = findMethodName(mi, cnt, returnType);
1760 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1761 final CharSequence[] vars = new CharSequence[numArguments];
1763 for (int j = numArguments - 1; j >= 0; --j) {
1764 vars[j] = mapper.popValue();
1768 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1769 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1771 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1772 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1774 if (vars[1] instanceof String) {
1775 String field = vars[1].toString();
1776 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1777 vars[1] = "c._" + field.substring(1, field.length() - 1);
1782 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1783 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1785 if (vars[1] instanceof String) {
1786 String field = vars[2].toString();
1787 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1788 vars[2] = "c._" + field.substring(1, field.length() - 1);
1793 if (returnType[0] != 'V') {
1796 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1800 final String in = mi[0];
1803 in.equals("org/apidesign/html/boot/spi/Fn") ||
1804 in.equals("org/netbeans/html/boot/spi/Fn")
1806 mcn = "java_lang_Class";
1808 mcn = mangleClassName(in);
1810 String object = accessClassFalse(mcn);
1811 if (mn.startsWith("cons_")) {
1812 object += ".constructor";
1814 append(accessStaticMethod(object, mn, mi));
1820 if (numArguments > 0) {
1822 for (int j = 1; j < numArguments; ++j) {
1832 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1833 throws IOException {
1834 int methodIndex = readUShortArg(byteCodes, i);
1835 String[] mi = jc.getFieldInfoName(methodIndex);
1836 char[] returnType = { 'V' };
1837 StringBuilder cnt = new StringBuilder();
1838 String mn = findMethodName(mi, cnt, returnType);
1840 final int numArguments = cnt.length() + 1;
1841 final CharSequence[] vars = new CharSequence[numArguments];
1843 for (int j = numArguments - 1; j >= 0; --j) {
1844 vars[j] = mapper.popValue();
1847 if (returnType[0] != 'V') {
1850 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1854 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1856 for (int j = 1; j < numArguments; ++j) {
1866 private void addReference(String cn) throws IOException {
1867 if (requireReference(cn)) {
1868 debug(" /* needs " + cn + " */");
1872 private void outType(String d, StringBuilder out) {
1874 while (d.charAt(0) == '[') {
1878 if (d.charAt(0) == 'L') {
1879 assert d.charAt(d.length() - 1) == ';';
1880 out.append(mangleClassName(d).substring(0, d.length() - 1));
1886 private String encodeConstant(int entryIndex) throws IOException {
1887 String[] classRef = { null };
1888 String s = jc.stringValue(entryIndex, classRef);
1889 if (classRef[0] != null) {
1890 if (classRef[0].startsWith("[")) {
1891 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1893 addReference(classRef[0]);
1894 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1900 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1901 byte[] arr = m.findAnnotationData(true);
1905 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1906 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1907 class P extends AnnotationParser {
1913 String[] args = new String[30];
1919 protected void visitAttr(String type, String attr, String at, String value) {
1920 if (type.equals(jvmType)) {
1921 if ("body".equals(attr)) {
1923 } else if ("args".equals(attr)) {
1924 args[cnt++] = value;
1926 throw new IllegalArgumentException(attr);
1929 if (type.equals(htmlType)) {
1931 if ("body".equals(attr)) {
1933 } else if ("args".equals(attr)) {
1934 args[cnt++] = value;
1935 } else if ("javacall".equals(attr)) {
1936 javacall = "1".equals(value);
1937 } else if ("wait4js".equals(attr)) {
1938 // ignore, we always invoke synchronously
1940 throw new IllegalArgumentException(attr);
1947 if (p.body == null) {
1950 StringBuilder cnt = new StringBuilder();
1951 final String mn = findMethodName(m, cnt);
1952 append("m = ").append(destObject).append(".").append(mn);
1953 append(" = function(");
1956 StringBuilder toValue = new StringBuilder();
1957 for (int i = 0; i < cnt.length(); i++) {
1959 space = outputArg(this, p.args, index);
1960 if (p.html4j && space.length() > 0) {
1961 toValue.append("\n ").append(p.args[index]).append(" = ")
1962 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1963 append(p.args[index]).append(");");
1967 append(") {").append("\n");
1968 append(toValue.toString());
1970 int lastSlash = jc.getClassName().lastIndexOf('/');
1971 final String pkg = jc.getClassName().substring(0, lastSlash);
1972 append(mangleCallbacks(pkg, p.body));
1973 requireReference(pkg + "/$JsCallbacks$");
1981 private static CharSequence mangleCallbacks(String pkgName, String body) {
1982 StringBuilder sb = new StringBuilder();
1985 int next = body.indexOf(".@", pos);
1987 sb.append(body.substring(pos));
1988 body = sb.toString();
1993 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1998 String refId = body.substring(ident, next);
2000 sb.append(body.substring(pos, ident));
2002 int sigBeg = body.indexOf('(', next);
2003 int sigEnd = body.indexOf(')', sigBeg);
2004 int colon4 = body.indexOf("::", next);
2005 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2006 throw new IllegalStateException("Malformed body " + body);
2008 String fqn = body.substring(next + 2, colon4);
2009 String method = body.substring(colon4 + 2, sigBeg);
2010 String params = body.substring(sigBeg, sigEnd + 1);
2012 int paramBeg = body.indexOf('(', sigEnd + 1);
2014 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2015 sb.append(mangleJsCallbacks(fqn, method, params, false));
2016 sb.append("(").append(refId);
2017 if (body.charAt(paramBeg + 1) != ')') {
2025 int next = body.indexOf("@", pos);
2030 sb.append(body.substring(pos));
2034 sb = new StringBuilder();
2037 sb.append(body.substring(pos, next));
2039 int sigBeg = body.indexOf('(', next);
2040 int sigEnd = body.indexOf(')', sigBeg);
2041 int colon4 = body.indexOf("::", next);
2042 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2043 throw new IllegalStateException("Malformed body " + body);
2045 String fqn = body.substring(next + 1, colon4);
2046 String method = body.substring(colon4 + 2, sigBeg);
2047 String params = body.substring(sigBeg, sigEnd + 1);
2049 int paramBeg = body.indexOf('(', sigEnd + 1);
2051 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2052 sb.append(mangleJsCallbacks(fqn, method, params, true));
2058 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2059 if (params.startsWith("(")) {
2060 params = params.substring(1);
2062 if (params.endsWith(")")) {
2063 params = params.substring(0, params.length() - 1);
2065 StringBuilder sb = new StringBuilder();
2066 final String fqnu = fqn.replace('.', '_');
2067 final String rfqn = mangleClassName(fqnu);
2068 final String rm = mangleMethodName(method);
2071 StringBuilder pb = new StringBuilder();
2072 int len = params.length();
2074 while (indx < len) {
2075 char ch = params.charAt(indx);
2076 if (ch == '[' || ch == 'L') {
2077 int column = params.indexOf(';', indx) + 1;
2078 if (column > indx) {
2079 String real = params.substring(indx, column);
2080 if ("Ljava/lang/String;".equals(real)) {
2081 pb.append("Ljava/lang/String;");
2086 pb.append("Ljava/lang/Object;");
2093 srp = mangleSig(pb.toString());
2095 final String rp = mangleSig(params);
2096 final String mrp = mangleMethodName(rp);
2097 sb.append(rfqn).append("$").append(rm).
2098 append('$').append(mrp).append("__Ljava_lang_Object_2");
2100 sb.append('L').append(fqnu).append("_2");
2103 return sb.toString();
2106 private static String className(ClassData jc) {
2107 //return jc.getName().getInternalName().replace('/', '_');
2108 return mangleClassName(jc.getClassName());
2111 private static String[] findAnnotation(
2112 byte[] arr, ClassData cd, final String className,
2113 final String... attrNames
2114 ) throws IOException {
2118 final String[] values = new String[attrNames.length];
2119 final boolean[] found = { false };
2120 final String jvmType = "L" + className.replace('.', '/') + ";";
2121 AnnotationParser ap = new AnnotationParser(false, true) {
2123 protected void visitAttr(String type, String attr, String at, String value) {
2124 if (type.equals(jvmType)) {
2126 for (int i = 0; i < attrNames.length; i++) {
2127 if (attrNames[i].equals(attr)) {
2136 return found[0] ? values : null;
2139 private CharSequence initField(FieldData v) {
2140 final String is = v.getInternalSig();
2141 if (is.length() == 1) {
2142 switch (is.charAt(0)) {
2148 case 'I': return " = 0;";
2150 case 'D': return " = 0.0;";
2152 throw new IllegalStateException(is);
2158 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2159 AnnotationParser ap = new AnnotationParser(true, false) {
2160 int[] cnt = new int[32];
2164 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2165 final String slashType = attrType.substring(1, attrType.length() - 1);
2166 requireReference(slashType);
2168 if (cnt[depth]++ > 0) {
2172 append('"').append(attrType).append("\" : ");
2179 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2185 protected void visitValueStart(String attrName, char type) throws IOException {
2186 if (cnt[depth]++ > 0) {
2190 if (attrName != null) {
2191 append('"').append(attrName).append("\" : ");
2199 protected void visitValueEnd(String attrName, char type) throws IOException {
2207 protected void visitAttr(String type, String attr, String attrType, String value)
2208 throws IOException {
2209 if (attr == null && value == null) {
2216 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2217 throws IOException {
2218 final String slashType = attrType.substring(1, attrType.length() - 1);
2219 requireReference(slashType);
2221 final String cn = mangleClassName(slashType);
2222 append(accessClassFalse(cn))
2223 .append("['valueOf__L").
2225 append("_2Ljava_lang_String_2']('").
2233 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2234 final String name = args[indx];
2238 if (name.contains(",")) {
2239 throw new IOException("Wrong parameter with ',': " + name);
2245 final void emitNoFlush(
2247 final String format, final CharSequence... params
2248 ) throws IOException {
2249 emitImpl(this, format, params);
2251 static final void emit(
2253 final Appendable out,
2254 final String format, final CharSequence... params
2255 ) throws IOException {
2257 emitImpl(out, format, params);
2259 static void emitImpl(final Appendable out,
2260 final String format,
2261 final CharSequence... params) throws IOException {
2262 final int length = format.length();
2265 int paramOffset = format.indexOf('@');
2266 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2267 final char paramChar = format.charAt(paramOffset + 1);
2268 if ((paramChar >= '1') && (paramChar <= '9')) {
2269 final int paramIndex = paramChar - '0' - 1;
2271 out.append(format, processed, paramOffset);
2272 out.append(params[paramIndex]);
2275 processed = paramOffset + 1;
2278 paramOffset = format.indexOf('@', paramOffset + 1);
2281 out.append(format, processed, length);
2284 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2285 append("} catch (e) {\n");
2287 for (TrapData e : traps) {
2291 if (e.catch_cpx != 0) { //not finally
2292 final String classInternalName = jc.getClassName(e.catch_cpx);
2293 addReference(classInternalName);
2294 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2295 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2296 append("var stA0 = e;");
2297 goTo(this, current, e.handler_pc, topMostLabel);
2300 finallyPC = e.handler_pc;
2303 if (finallyPC == -1) {
2306 append("var stA0 = e;");
2307 goTo(this, current, finallyPC, topMostLabel);
2312 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2315 out.append("{ gt = 0; continue X_" + to + "; }");
2317 out.append("{ gt = " + to + "; continue X_0; }");
2320 out.append("{ gt = " + to + "; break IF; }");
2324 private static void emitIf(
2326 Appendable out, String pattern,
2328 int current, int to, int canBack
2329 ) throws IOException {
2331 emitImpl(out, pattern, param);
2332 goTo(out, current, to, canBack);
2335 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2338 case 4: jvmType = "[Z"; break;
2339 case 5: jvmType = "[C"; break;
2340 case 6: jvmType = "[F"; break;
2341 case 7: jvmType = "[D"; break;
2342 case 8: jvmType = "[B"; break;
2343 case 9: jvmType = "[S"; break;
2344 case 10: jvmType = "[I"; break;
2345 case 11: jvmType = "[J"; break;
2346 default: throw new IllegalStateException("Array type: " + atype);
2349 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2350 smapper.popI(), smapper.pushA(), jvmType);
2353 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2354 String typeName = jc.getClassName(type);
2355 String ref = "null";
2356 if (typeName.startsWith("[")) {
2357 typeName = "'[" + typeName + "'";
2359 ref = "vm." + mangleClassName(typeName);
2360 typeName = "'[L" + typeName + ";'";
2363 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2364 smapper.popI(), smapper.pushA(), typeName, ref);
2367 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2368 String typeName = jc.getClassName(type);
2369 int dim = readUByte(byteCodes, ++i);
2370 StringBuilder dims = new StringBuilder();
2372 for (int d = 0; d < dim; d++) {
2374 dims.insert(1, ",");
2376 dims.insert(1, smapper.popI());
2380 if (typeName.charAt(dim) == 'L') {
2381 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2384 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2385 dims.toString(), smapper.pushA(), typeName, fn
2390 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2391 int table = i / 4 * 4 + 4;
2392 int dflt = i + readInt4(byteCodes, table);
2394 int low = readInt4(byteCodes, table);
2396 int high = readInt4(byteCodes, table);
2398 final CharSequence swVar = smapper.popValue();
2399 smapper.flush(this);
2400 append("switch (").append(swVar).append(") {\n");
2401 while (low <= high) {
2402 int offset = i + readInt4(byteCodes, table);
2404 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2407 append(" default: ");
2408 goTo(this, i, dflt, topMostLabel);
2414 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2415 int table = i / 4 * 4 + 4;
2416 int dflt = i + readInt4(byteCodes, table);
2418 int n = readInt4(byteCodes, table);
2420 final CharSequence swVar = smapper.popValue();
2421 smapper.flush(this);
2422 append("switch (").append(swVar).append(") {\n");
2424 int cnstnt = readInt4(byteCodes, table);
2426 int offset = i + readInt4(byteCodes, table);
2428 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2430 append(" default: ");
2431 goTo(this, i, dflt, topMostLabel);
2437 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2438 String type = jc.getClassName(indx);
2439 if (!type.startsWith("[")) {
2441 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2442 smapper.popA(), smapper.pushI(),
2443 mangleClassName(type));
2446 while (type.charAt(cnt) == '[') {
2449 if (type.charAt(cnt) == 'L') {
2450 String component = type.substring(cnt + 1, type.length() - 1);
2451 requireReference(component);
2452 type = "vm." + mangleClassName(component);
2454 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2455 smapper.popA(), smapper.pushI(),
2460 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2461 smapper.popA(), smapper.pushI(), type
2467 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2468 String type = jc.getClassName(indx);
2469 if (!type.startsWith("[")) {
2470 emitNoFlush(smapper,
2471 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2472 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2475 while (type.charAt(cnt) == '[') {
2478 if (type.charAt(cnt) == 'L') {
2479 String component = type.substring(cnt + 1, type.length() - 1);
2480 requireReference(component);
2481 type = "vm." + mangleClassName(component);
2482 emitNoFlush(smapper,
2483 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2484 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2487 emitNoFlush(smapper,
2488 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2489 smapper.getT(0, VarType.REFERENCE, false), type
2495 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2496 for (int j = prev; j <= i; j++) {
2498 final int cc = readUByte(byteCodes, j);
2499 append(Integer.toString(cc));
2503 @JavaScriptBody(args = "msg", body = "")
2504 private static void println(String msg) {
2505 System.err.println(msg);