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, numbers.add64(), 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, numbers.sub64(), 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, numbers.mul64(), 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, numbers.div64(),
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, numbers.mod64(),
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, numbers.and64(), smapper.getL(1), smapper.popL());
805 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
808 smapper.replace(this, VarType.LONG, numbers.or64(), smapper.getL(1), smapper.popL());
811 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
814 smapper.replace(this, VarType.LONG, numbers.xor64(), smapper.getL(1), smapper.popL());
817 smapper.replace(this, VarType.INTEGER, "(-(@1))", smapper.getI(0));
820 smapper.replace(this, VarType.LONG, numbers.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, numbers.shl64(), smapper.getL(1), smapper.popI());
835 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
838 smapper.replace(this, VarType.LONG, numbers.shr64(), smapper.getL(1), smapper.popI());
841 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
844 smapper.replace(this, VarType.LONG, numbers.ushr64(), 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, numbers.compare64(), 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 FieldData field = findField(fi);
1478 String af = accessField(ac, field, fi);
1479 smapper.assign(this, type, af + "()");
1481 addReference(fi[0]);
1484 case opc_putstatic: {
1485 int indx = readUShortArg(byteCodes, i);
1486 String[] fi = jc.getFieldInfoName(indx);
1487 final int type = VarType.fromFieldType(fi[2].charAt(0));
1488 emit(smapper, this, "@1._@2(@3);",
1489 accessClassFalse(mangleClassName(fi[0])), fi[1],
1490 smapper.popT(type));
1492 addReference(fi[0]);
1495 case opc_checkcast: {
1496 int indx = readUShortArg(byteCodes, i);
1497 generateCheckcast(indx, smapper);
1501 case opc_instanceof: {
1502 int indx = readUShortArg(byteCodes, i);
1503 generateInstanceOf(indx, smapper);
1508 final CharSequence v = smapper.popA();
1511 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1512 smapper.pushA(), v);
1516 case opc_monitorenter: {
1517 debug("/* monitor enter */");
1522 case opc_monitorexit: {
1523 debug("/* monitor exit */");
1534 emit(smapper, this, "throw 'unknown bytecode @1';",
1535 Integer.toString(c));
1539 generateByteCodeComment(prev, i, byteCodes);
1545 if (previousTrap != null) {
1546 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1551 while (openBraces-- > 0) {
1562 private int generateIf(StackMapper mapper, byte[] byteCodes,
1563 int i, final CharSequence v2, final CharSequence v1,
1564 final String test, int topMostLabel
1565 ) throws IOException {
1567 int indx = i + readShortArg(byteCodes, i);
1568 append("if ((").append(v1)
1569 .append(") ").append(test).append(" (")
1570 .append(v2).append(")) ");
1571 goTo(this, i, indx, topMostLabel);
1575 private int readInt4(byte[] byteCodes, int offset) {
1576 final int d = byteCodes[offset + 0] << 24;
1577 final int c = byteCodes[offset + 1] << 16;
1578 final int b = byteCodes[offset + 2] << 8;
1579 final int a = byteCodes[offset + 3];
1580 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1582 private static int readUByte(byte[] byteCodes, int offset) {
1583 return byteCodes[offset] & 0xff;
1586 private static int readUShort(byte[] byteCodes, int offset) {
1587 return ((byteCodes[offset] & 0xff) << 8)
1588 | (byteCodes[offset + 1] & 0xff);
1590 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1591 return readUShort(byteCodes, offsetInstruction + 1);
1594 private static int readShort(byte[] byteCodes, int offset) {
1595 int signed = byteCodes[offset];
1596 byte b0 = (byte)signed;
1597 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1599 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1600 return readShort(byteCodes, offsetInstruction + 1);
1603 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1605 Boolean count = null;
1606 boolean array = false;
1608 int firstPos = sig.length();
1609 while (i < descriptor.length()) {
1610 char ch = descriptor.charAt(i++);
1631 if (ch == 'J' || ch == 'D') {
1637 sig.insert(firstPos, ch);
1639 returnType[0] = '[';
1640 sig.insert(firstPos, "_3");
1649 returnType[0] = 'V';
1650 sig.insert(firstPos, 'V');
1653 int next = descriptor.indexOf(';', i);
1654 String realSig = mangleSig(descriptor, i - 1, next + 1);
1659 sig.append(realSig);
1662 sig.insert(firstPos, realSig);
1664 sig.insert(firstPos, "_3");
1666 returnType[0] = 'L';
1675 throw new IllegalStateException("Invalid char: " + ch);
1680 static String mangleSig(String sig) {
1681 return mangleSig(sig, 0, sig.length());
1684 private static String mangleMethodName(String name) {
1685 StringBuilder sb = new StringBuilder(name.length() * 2);
1686 int last = name.length();
1687 for (int i = 0; i < last; i++) {
1688 final char ch = name.charAt(i);
1690 case '_': sb.append("_1"); break;
1691 default: sb.append(ch); break;
1694 return sb.toString();
1696 private static String mangleSig(String txt, int first, int last) {
1697 StringBuilder sb = new StringBuilder((last - first) * 2);
1698 for (int i = first; i < last; i++) {
1699 final char ch = txt.charAt(i);
1701 case '/': sb.append('_'); break;
1702 case '_': sb.append("_1"); break;
1703 case ';': sb.append("_2"); break;
1704 case '[': sb.append("_3"); break;
1706 if (Character.isJavaIdentifierPart(ch)) {
1710 String hex = Integer.toHexString(ch).toLowerCase();
1711 for (int m = hex.length(); m < 4; m++) {
1719 return sb.toString();
1722 private static String mangleClassName(String name) {
1723 return mangleSig(name);
1726 private static String findMethodName(MethodData m, StringBuilder cnt) {
1727 StringBuilder name = new StringBuilder();
1728 if ("<init>".equals(m.getName())) { // NOI18N
1729 name.append("cons"); // NOI18N
1730 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1731 name.append("class"); // NOI18N
1733 name.append(mangleMethodName(m.getName()));
1736 countArgs(m.getInternalSig(), new char[1], name, cnt);
1737 return name.toString();
1740 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1741 StringBuilder name = new StringBuilder();
1742 String descr = mi[2];//mi.getDescriptor();
1744 if ("<init>".equals(nm)) { // NOI18N
1745 name.append("cons"); // NOI18N
1747 name.append(mangleMethodName(nm));
1749 countArgs(descr, returnType, name, cnt);
1750 return name.toString();
1753 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1754 throws IOException {
1755 int methodIndex = readUShortArg(byteCodes, i);
1756 String[] mi = jc.getFieldInfoName(methodIndex);
1757 char[] returnType = { 'V' };
1758 StringBuilder cnt = new StringBuilder();
1759 String mn = findMethodName(mi, cnt, returnType);
1761 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1762 final CharSequence[] vars = new CharSequence[numArguments];
1764 for (int j = numArguments - 1; j >= 0; --j) {
1765 vars[j] = mapper.popValue();
1769 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1770 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1772 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1773 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1775 if (vars[1] instanceof String) {
1776 String field = vars[1].toString();
1777 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1778 vars[1] = "c._" + field.substring(1, field.length() - 1);
1783 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1784 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1786 if (vars[1] instanceof String) {
1787 String field = vars[2].toString();
1788 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1789 vars[2] = "c._" + field.substring(1, field.length() - 1);
1794 if (returnType[0] != 'V') {
1797 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1801 final String in = mi[0];
1804 in.equals("org/apidesign/html/boot/spi/Fn") ||
1805 in.equals("org/netbeans/html/boot/spi/Fn")
1807 mcn = "java_lang_Class";
1809 mcn = mangleClassName(in);
1811 String object = accessClassFalse(mcn);
1812 if (mn.startsWith("cons_")) {
1813 object += ".constructor";
1815 append(accessStaticMethod(object, mn, mi));
1821 if (numArguments > 0) {
1823 for (int j = 1; j < numArguments; ++j) {
1833 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1834 throws IOException {
1835 int methodIndex = readUShortArg(byteCodes, i);
1836 String[] mi = jc.getFieldInfoName(methodIndex);
1837 char[] returnType = { 'V' };
1838 StringBuilder cnt = new StringBuilder();
1839 String mn = findMethodName(mi, cnt, returnType);
1841 final int numArguments = cnt.length() + 1;
1842 final CharSequence[] vars = new CharSequence[numArguments];
1844 for (int j = numArguments - 1; j >= 0; --j) {
1845 vars[j] = mapper.popValue();
1848 if (returnType[0] != 'V') {
1851 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1855 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1857 for (int j = 1; j < numArguments; ++j) {
1867 private void addReference(String cn) throws IOException {
1868 if (requireReference(cn)) {
1869 debug(" /* needs " + cn + " */");
1873 private void outType(String d, StringBuilder out) {
1875 while (d.charAt(0) == '[') {
1879 if (d.charAt(0) == 'L') {
1880 assert d.charAt(d.length() - 1) == ';';
1881 out.append(mangleClassName(d).substring(0, d.length() - 1));
1887 private String encodeConstant(int entryIndex) throws IOException {
1888 String[] classRef = { null };
1889 String s = jc.stringValue(entryIndex, classRef);
1890 if (classRef[0] != null) {
1891 if (classRef[0].startsWith("[")) {
1892 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1894 addReference(classRef[0]);
1895 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1901 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1902 byte[] arr = m.findAnnotationData(true);
1906 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1907 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1908 class P extends AnnotationParser {
1914 String[] args = new String[30];
1920 protected void visitAttr(String type, String attr, String at, String value) {
1921 if (type.equals(jvmType)) {
1922 if ("body".equals(attr)) {
1924 } else if ("args".equals(attr)) {
1925 args[cnt++] = value;
1927 throw new IllegalArgumentException(attr);
1930 if (type.equals(htmlType)) {
1932 if ("body".equals(attr)) {
1934 } else if ("args".equals(attr)) {
1935 args[cnt++] = value;
1936 } else if ("javacall".equals(attr)) {
1937 javacall = "1".equals(value);
1938 } else if ("wait4js".equals(attr)) {
1939 // ignore, we always invoke synchronously
1941 throw new IllegalArgumentException(attr);
1948 if (p.body == null) {
1951 StringBuilder cnt = new StringBuilder();
1952 final String mn = findMethodName(m, cnt);
1953 append("m = ").append(destObject).append(".").append(mn);
1954 append(" = function(");
1957 StringBuilder toValue = new StringBuilder();
1958 for (int i = 0; i < cnt.length(); i++) {
1960 space = outputArg(this, p.args, index);
1961 if (p.html4j && space.length() > 0) {
1962 toValue.append("\n ").append(p.args[index]).append(" = ")
1963 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1964 append(p.args[index]).append(");");
1968 append(") {").append("\n");
1969 append(toValue.toString());
1971 int lastSlash = jc.getClassName().lastIndexOf('/');
1972 final String pkg = jc.getClassName().substring(0, lastSlash);
1973 append(mangleCallbacks(pkg, p.body));
1974 requireReference(pkg + "/$JsCallbacks$");
1982 private static CharSequence mangleCallbacks(String pkgName, String body) {
1983 StringBuilder sb = new StringBuilder();
1986 int next = body.indexOf(".@", pos);
1988 sb.append(body.substring(pos));
1989 body = sb.toString();
1994 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1999 String refId = body.substring(ident, next);
2001 sb.append(body.substring(pos, ident));
2003 int sigBeg = body.indexOf('(', next);
2004 int sigEnd = body.indexOf(')', sigBeg);
2005 int colon4 = body.indexOf("::", next);
2006 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2007 throw new IllegalStateException("Malformed body " + body);
2009 String fqn = body.substring(next + 2, colon4);
2010 String method = body.substring(colon4 + 2, sigBeg);
2011 String params = body.substring(sigBeg, sigEnd + 1);
2013 int paramBeg = body.indexOf('(', sigEnd + 1);
2015 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2016 sb.append(mangleJsCallbacks(fqn, method, params, false));
2017 sb.append("(").append(refId);
2018 if (body.charAt(paramBeg + 1) != ')') {
2026 int next = body.indexOf("@", pos);
2031 sb.append(body.substring(pos));
2035 sb = new StringBuilder();
2038 sb.append(body.substring(pos, next));
2040 int sigBeg = body.indexOf('(', next);
2041 int sigEnd = body.indexOf(')', sigBeg);
2042 int colon4 = body.indexOf("::", next);
2043 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2044 throw new IllegalStateException("Malformed body " + body);
2046 String fqn = body.substring(next + 1, colon4);
2047 String method = body.substring(colon4 + 2, sigBeg);
2048 String params = body.substring(sigBeg, sigEnd + 1);
2050 int paramBeg = body.indexOf('(', sigEnd + 1);
2052 sb.append("vm.").append(mangleClassName(pkgName)).append("_$JsCallbacks$(false)._VM().");
2053 sb.append(mangleJsCallbacks(fqn, method, params, true));
2059 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2060 if (params.startsWith("(")) {
2061 params = params.substring(1);
2063 if (params.endsWith(")")) {
2064 params = params.substring(0, params.length() - 1);
2066 StringBuilder sb = new StringBuilder();
2067 final String fqnu = fqn.replace('.', '_');
2068 final String rfqn = mangleClassName(fqnu);
2069 final String rm = mangleMethodName(method);
2072 StringBuilder pb = new StringBuilder();
2073 int len = params.length();
2075 while (indx < len) {
2076 char ch = params.charAt(indx);
2077 if (ch == '[' || ch == 'L') {
2078 int column = params.indexOf(';', indx) + 1;
2079 if (column > indx) {
2080 String real = params.substring(indx, column);
2081 if ("Ljava/lang/String;".equals(real)) {
2082 pb.append("Ljava/lang/String;");
2087 pb.append("Ljava/lang/Object;");
2094 srp = mangleSig(pb.toString());
2096 final String rp = mangleSig(params);
2097 final String mrp = mangleMethodName(rp);
2098 sb.append(rfqn).append("$").append(rm).
2099 append('$').append(mrp).append("__Ljava_lang_Object_2");
2101 sb.append('L').append(fqnu).append("_2");
2104 return sb.toString();
2107 private static String className(ClassData jc) {
2108 //return jc.getName().getInternalName().replace('/', '_');
2109 return mangleClassName(jc.getClassName());
2112 private static String[] findAnnotation(
2113 byte[] arr, ClassData cd, final String className,
2114 final String... attrNames
2115 ) throws IOException {
2119 final String[] values = new String[attrNames.length];
2120 final boolean[] found = { false };
2121 final String jvmType = "L" + className.replace('.', '/') + ";";
2122 AnnotationParser ap = new AnnotationParser(false, true) {
2124 protected void visitAttr(String type, String attr, String at, String value) {
2125 if (type.equals(jvmType)) {
2127 for (int i = 0; i < attrNames.length; i++) {
2128 if (attrNames[i].equals(attr)) {
2137 return found[0] ? values : null;
2140 private CharSequence initField(FieldData v) {
2141 final String is = v.getInternalSig();
2142 if (is.length() == 1) {
2143 switch (is.charAt(0)) {
2149 case 'I': return " = 0;";
2151 case 'D': return " = 0.0;";
2153 throw new IllegalStateException(is);
2159 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2160 AnnotationParser ap = new AnnotationParser(true, false) {
2161 int[] cnt = new int[32];
2165 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2166 final String slashType = attrType.substring(1, attrType.length() - 1);
2167 requireReference(slashType);
2169 if (cnt[depth]++ > 0) {
2173 append('"').append(attrType).append("\" : ");
2180 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2186 protected void visitValueStart(String attrName, char type) throws IOException {
2187 if (cnt[depth]++ > 0) {
2191 if (attrName != null) {
2192 append('"').append(attrName).append("\" : ");
2200 protected void visitValueEnd(String attrName, char type) throws IOException {
2208 protected void visitAttr(String type, String attr, String attrType, String value)
2209 throws IOException {
2210 if (attr == null && value == null) {
2217 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2218 throws IOException {
2219 final String slashType = attrType.substring(1, attrType.length() - 1);
2220 requireReference(slashType);
2222 final String cn = mangleClassName(slashType);
2223 append(accessClassFalse(cn))
2224 .append("['valueOf__L").
2226 append("_2Ljava_lang_String_2']('").
2234 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2235 final String name = args[indx];
2239 if (name.contains(",")) {
2240 throw new IOException("Wrong parameter with ',': " + name);
2246 final void emitNoFlush(
2248 final String format, final CharSequence... params
2249 ) throws IOException {
2250 emitImpl(this, format, params);
2252 static final void emit(
2254 final Appendable out,
2255 final String format, final CharSequence... params
2256 ) throws IOException {
2258 emitImpl(out, format, params);
2260 static void emitImpl(final Appendable out,
2261 final String format,
2262 final CharSequence... params) throws IOException {
2263 final int length = format.length();
2266 int paramOffset = format.indexOf('@');
2267 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2268 final char paramChar = format.charAt(paramOffset + 1);
2269 if ((paramChar >= '1') && (paramChar <= '9')) {
2270 final int paramIndex = paramChar - '0' - 1;
2272 out.append(format, processed, paramOffset);
2273 out.append(params[paramIndex]);
2276 processed = paramOffset + 1;
2279 paramOffset = format.indexOf('@', paramOffset + 1);
2282 out.append(format, processed, length);
2285 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2286 append("} catch (e) {\n");
2288 for (TrapData e : traps) {
2292 if (e.catch_cpx != 0) { //not finally
2293 final String classInternalName = jc.getClassName(e.catch_cpx);
2294 addReference(classInternalName);
2295 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2296 append("if (e['$instOf_" + mangleClassName(classInternalName) + "']) {");
2297 append("var stA0 = e;");
2298 goTo(this, current, e.handler_pc, topMostLabel);
2301 finallyPC = e.handler_pc;
2304 if (finallyPC == -1) {
2307 append("var stA0 = e;");
2308 goTo(this, current, finallyPC, topMostLabel);
2313 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2316 out.append("{ gt = 0; continue X_" + to + "; }");
2318 out.append("{ gt = " + to + "; continue X_0; }");
2321 out.append("{ gt = " + to + "; break IF; }");
2325 private static void emitIf(
2327 Appendable out, String pattern,
2329 int current, int to, int canBack
2330 ) throws IOException {
2332 emitImpl(out, pattern, param);
2333 goTo(out, current, to, canBack);
2336 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2339 case 4: jvmType = "[Z"; break;
2340 case 5: jvmType = "[C"; break;
2341 case 6: jvmType = "[F"; break;
2342 case 7: jvmType = "[D"; break;
2343 case 8: jvmType = "[B"; break;
2344 case 9: jvmType = "[S"; break;
2345 case 10: jvmType = "[I"; break;
2346 case 11: jvmType = "[J"; break;
2347 default: throw new IllegalStateException("Array type: " + atype);
2350 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2351 smapper.popI(), smapper.pushA(), jvmType);
2354 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2355 String typeName = jc.getClassName(type);
2356 String ref = "null";
2357 if (typeName.startsWith("[")) {
2358 typeName = "'[" + typeName + "'";
2360 ref = "vm." + mangleClassName(typeName);
2361 typeName = "'[L" + typeName + ";'";
2364 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2365 smapper.popI(), smapper.pushA(), typeName, ref);
2368 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2369 String typeName = jc.getClassName(type);
2370 int dim = readUByte(byteCodes, ++i);
2371 StringBuilder dims = new StringBuilder();
2373 for (int d = 0; d < dim; d++) {
2375 dims.insert(1, ",");
2377 dims.insert(1, smapper.popI());
2381 if (typeName.charAt(dim) == 'L') {
2382 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2385 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2386 dims.toString(), smapper.pushA(), typeName, fn
2391 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2392 int table = i / 4 * 4 + 4;
2393 int dflt = i + readInt4(byteCodes, table);
2395 int low = readInt4(byteCodes, table);
2397 int high = readInt4(byteCodes, table);
2399 final CharSequence swVar = smapper.popValue();
2400 smapper.flush(this);
2401 append("switch (").append(swVar).append(") {\n");
2402 while (low <= high) {
2403 int offset = i + readInt4(byteCodes, table);
2405 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2408 append(" default: ");
2409 goTo(this, i, dflt, topMostLabel);
2415 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2416 int table = i / 4 * 4 + 4;
2417 int dflt = i + readInt4(byteCodes, table);
2419 int n = readInt4(byteCodes, table);
2421 final CharSequence swVar = smapper.popValue();
2422 smapper.flush(this);
2423 append("switch (").append(swVar).append(") {\n");
2425 int cnstnt = readInt4(byteCodes, table);
2427 int offset = i + readInt4(byteCodes, table);
2429 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2431 append(" default: ");
2432 goTo(this, i, dflt, topMostLabel);
2438 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2439 String type = jc.getClassName(indx);
2440 if (!type.startsWith("[")) {
2442 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2443 smapper.popA(), smapper.pushI(),
2444 mangleClassName(type));
2447 while (type.charAt(cnt) == '[') {
2450 if (type.charAt(cnt) == 'L') {
2451 String component = type.substring(cnt + 1, type.length() - 1);
2452 requireReference(component);
2453 type = "vm." + mangleClassName(component);
2455 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2456 smapper.popA(), smapper.pushI(),
2461 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2462 smapper.popA(), smapper.pushI(), type
2468 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2469 String type = jc.getClassName(indx);
2470 if (!type.startsWith("[")) {
2471 emitNoFlush(smapper,
2472 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2473 smapper.getT(0, VarType.REFERENCE, false), mangleClassName(type));
2476 while (type.charAt(cnt) == '[') {
2479 if (type.charAt(cnt) == 'L') {
2480 String component = type.substring(cnt + 1, type.length() - 1);
2481 requireReference(component);
2482 type = "vm." + mangleClassName(component);
2483 emitNoFlush(smapper,
2484 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2485 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2488 emitNoFlush(smapper,
2489 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2490 smapper.getT(0, VarType.REFERENCE, false), type
2496 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2497 for (int j = prev; j <= i; j++) {
2499 final int cc = readUByte(byteCodes, j);
2500 append(Integer.toString(cc));
2504 @JavaScriptBody(args = "msg", body = "")
2505 private static void println(String msg) {
2506 System.err.println(msg);