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 org.apidesign.vm4brwsr.Bck2Brwsr.Flow;
24 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
26 /** Translator of the code inside class files to JavaScript.
28 * @author Jaroslav Tulach <jtulach@netbeans.org>
30 abstract class ByteCodeToJavaScript implements Appendable {
32 private final Appendable out;
33 private final StringArray classRefs = new StringArray();
34 private boolean outChanged;
35 private boolean callbacks;
37 protected ByteCodeToJavaScript(Appendable out) {
42 public final Appendable append(CharSequence csq) throws IOException {
49 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
50 out.append(csq, start, end);
56 public final Appendable append(char c) throws IOException {
62 /* Collects additional required resources.
64 * @param internalClassName classes that were referenced and should be loaded in order the
65 * generated JavaScript code works properly. The names are in internal
66 * JVM form so String is <code>java/lang/String</code>.
68 protected abstract boolean requireReference(String internalClassName);
71 * @param resourcePath name of resources to read
73 protected abstract void requireScript(String resourcePath) throws IOException;
75 protected abstract void requireResource(String resourcePath) throws IOException;
77 /** Allows subclasses to redefine what field a function representing a
78 * class gets assigned. By default it returns the suggested name followed
79 * by <code>" = "</code>;
81 * @param className suggested name of the class
83 /* protected */ String assignClass(String className) {
84 return className + " = ";
86 /* protected */ String accessClass(String classOperation) {
87 return classOperation;
90 final String accessClassFalse(String classOperation) {
91 if (jc.getClassName().replace('/', '_').equals(classOperation)) {
94 classRefs.addIfMissing(classOperation);
95 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
98 protected String accessField(String object, String mangledName,
99 String[] fieldInfoName) throws IOException {
100 return object + "." + mangledName;
103 protected String accessStaticMethod(
106 String[] fieldInfoName) throws IOException {
107 return object + "." + mangledName;
110 protected String accessVirtualMethod(
113 String[] fieldInfoName,
115 ) throws IOException {
116 return object + "." + mangledName + '(';
119 protected void declaredClass(ClassData classData, String mangledName)
123 protected void declaredField(FieldData fieldData,
125 String mangledName) throws IOException {
128 protected void declaredMethod(MethodData methodData,
130 String mangledName) throws IOException {
133 /** Prints out a debug message.
135 * @param msg the message
136 * @return true if the message has been printed
137 * @throws IOException
139 boolean debug(String msg) throws IOException {
145 * Converts a given class file to a JavaScript version.
147 * @param classFile input stream with code of the .class file
148 * @return the initialization code for this class, if any. Otherwise <code>null</code>
150 * @throws IOException if something goes wrong during read or write or translating
153 public String compile(InputStream classFile) throws IOException {
154 return compile(new ClassData(classFile));
157 protected String compile(ClassData classData) throws IOException {
159 final String cn = this.jc.getClassName();
161 return compileImpl(cn);
162 } catch (IOException ex) {
163 throw new IOException("Cannot compile " + cn + ":", ex);
167 private String compileImpl(final String cn) throws IOException {
168 this.callbacks = cn.endsWith("/$JsCallbacks$");
169 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
170 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
171 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
174 byte[] arrData = jc.findAnnotationData(true);
176 String[] arr = findAnnotation(arrData, jc,
177 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
178 "resource", "processByteCode"
181 if (!arr[0].isEmpty()) {
182 requireScript(arr[0]);
184 if ("0".equals(arr[1])) {
189 final String jsResource;
191 String[] arr = findAnnotation(arrData, jc,
192 "net.java.html.js.JavaScriptResource",
196 if (arr[0].startsWith("/")) {
199 int last = cn.lastIndexOf('/');
200 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
206 String[] proto = findAnnotation(arrData, jc,
207 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
208 "container", "prototype"
210 StringArray toInitilize = new StringArray();
211 final String className = className(jc);
212 append("\n\n").append(assignClass(className));
213 append("function ").append(className).append("() {");
215 append("\n var CLS = ").append(className).append(';');
216 append("\n if (!CLS.$class) {");
218 String sc = jc.getSuperClassName(); // with _
219 append("\n var pp = ").
220 append(accessClass(mangleClassName(sc))).append("(true);");
221 append("\n var p = CLS.prototype = pp;");
222 append("\n var c = p;");
223 append("\n var sprcls = pp.constructor.$class;");
225 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
226 if (proto[0] == null) {
229 append("\n var c = ").append(proto[0]).append(";");
230 append("\n var sprcls = null;");
232 for (FieldData v : jc.getFields()) {
234 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
235 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
239 append("\n CLS.fld_").append(v.getName()).append(initField(v));
240 append("\n m = c._").append(v.getName()).append(" = function (v) {")
241 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
242 .append(" = v; return CLS.fld_").
243 append(v.getName()).append("; };");
245 append("\n m = c._").append(v.getName()).append(" = function (v) {")
246 .append(" if (arguments.length == 1) this.fld_").
247 append(className).append('_').append(v.getName())
248 .append(" = v; return this.fld_").
249 append(className).append('_').append(v.getName())
253 declaredField(v, "c", "_" + v.getName());
255 for (MethodData m : jc.getMethods()) {
256 byte[] onlyArr = m.findAnnotationData(true);
257 if (javaScriptOnly(onlyArr)) continue;
263 mn = generateStaticMethod(destObject, m, toInitilize);
265 if (m.isConstructor()) {
267 mn = generateInstanceMethod(destObject, m);
270 mn = generateInstanceMethod(destObject, m);
273 declaredMethod(m, destObject, mn);
274 byte[] runAnno = m.findAnnotationData(false);
275 if (runAnno != null) {
276 append("\n m.anno = {");
277 generateAnno(jc, runAnno);
280 append("\n m.access = " + m.getAccess()).append(";");
281 append("\n m.cls = CLS;");
283 append("\n c.constructor = CLS;");
284 append("\n function ").append(className).append("fillInstOf(x) {");
285 String instOfName = "$instOf_" + className;
286 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
287 if (jc.isInterface()) {
288 for (MethodData m : jc.getMethods()) {
289 if ((m.getAccess() & ACC_ABSTRACT) == 0
290 && (m.getAccess() & ACC_STATIC) == 0
291 && (m.getAccess() & ACC_PRIVATE) == 0) {
292 final String mn = findMethodName(m, new StringBuilder());
293 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
297 for (String superInterface : jc.getSuperInterfaces()) {
298 String intrfc = superInterface.replace('/', '_');
299 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
300 requireReference(superInterface);
303 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
304 append("\n ").append(className).append("fillInstOf(c);");
305 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
306 append("\n CLS.$class = 'temp';");
307 append("\n CLS.$class = ");
308 append(accessClass("java_lang_Class(true);"));
309 append("\n CLS.$class.jvmName = '").append(cn).append("';");
310 append("\n CLS.$class.superclass = sprcls;");
311 append("\n CLS.$class.interfaces = function() { return [");
313 boolean first = true;
314 for (String intrfc : jc.getSuperInterfaces()) {
318 requireReference(intrfc);
319 String mangledIface = mangleClassName(intrfc);
321 append(accessClass(mangledIface)).append("(false).constructor.$class");
326 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
327 append("\n CLS.$class.cnstr = CLS;");
328 byte[] classAnno = jc.findAnnotationData(false);
329 if (classAnno != null) {
330 append("\n CLS.$class.anno = {");
331 generateAnno(jc, classAnno);
334 for (String init : toInitilize.toArray()) {
335 append("\n ").append(init).append("();");
337 for (String ref : classRefs.toArray()) {
338 append("\n var refs_").append(ref).append(";");
342 if (jsResource != null) {
343 requireResource(jsResource);
347 append("\n if (arguments.length === 0) {");
348 append("\n if (!(this instanceof CLS)) {");
349 append("\n return new CLS();");
351 for (FieldData v : jc.getFields()) {
352 byte[] onlyArr = v.findAnnotationData(true);
353 if (javaScriptOnly(onlyArr)) continue;
355 append("\n this.fld_").
356 append(className).append('_').
357 append(v.getName()).append(initField(v));
360 append("\n return this;");
362 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
365 declaredClass(jc, className);
367 // StringBuilder sb = new StringBuilder();
368 // for (String init : toInitilize.toArray()) {
369 // sb.append("\n").append(init).append("();");
374 private boolean javaScriptOnly(byte[] anno) throws IOException {
375 String[] only = findAnnotation(anno, jc,
376 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
380 if (only[0] != null && only[1] != null) {
381 append("\n p.").append(only[0]).append(" = ")
382 .append(only[1]).append(";");
384 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
385 append("\n p['").append(only[0]).append("'] = p.")
386 .append(only[0]).append(";");
392 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
393 String jsb = javaScriptBody(destObject, m, true);
397 final String mn = findMethodName(m, new StringBuilder());
398 boolean defineProp = generateMethod(destObject, mn, m);
399 if (mn.equals("class__V")) {
401 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
403 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
409 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
410 String jsb = javaScriptBody(destObject, m, false);
414 final String mn = findMethodName(m, new StringBuilder());
415 generateMethod(destObject, mn, m);
419 private boolean generateMethod(String destObject, String name, MethodData m)
421 final StackMapIterator stackMapIterator = m.createStackMapIterator();
422 TrapDataIterator trap = m.getTrapDataIterator();
423 final LocalsMapper lmapper =
424 new LocalsMapper(stackMapIterator.getArguments());
427 "java/lang/Object".equals(jc.getClassName()) ||
428 "java/lang/reflect/Array".equals(jc.getClassName());
431 append("Object.defineProperty(").append(destObject).
432 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
434 append("m = ").append(destObject).append(".").append(name).append(" = function(");
436 lmapper.outputArguments(this, m.isStatic());
437 append(") {").append("\n");
439 final byte[] byteCodes = m.getCode();
440 if (byteCodes == null) {
441 if (debug(" throw 'no code found for ")) {
443 .append(jc.getClassName()).append('.')
444 .append(m.getName()).append("';\n");
453 Flow flow = checkFlow(m);
455 final StackMapper smapper = new StackMapper();
458 append(" var ").append(" lcA0 = this;\n");
462 TrapData[] previousTrap = null;
463 boolean wide = false;
465 if (stackMapIterator.isEmpty()) {
471 append("\n var gt = 0;\n");
475 int topMostLabel = 0;
476 for (int i = 0; i < byteCodes.length; i++) {
479 stackMapIterator.advanceTo(i);
480 boolean changeInCatch = trap.advanceTo(i);
481 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
482 if (previousTrap != null) {
483 generateCatch(previousTrap, flow, i, topMostLabel);
487 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
492 if (openBraces > 64) {
493 for (int c = 0; c < 64; c++) {
500 lastStackFrame = stackMapIterator.getFrameIndex();
501 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
502 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
503 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
505 changeInCatch = true;
507 debug(" /* " + i + " */ ");
509 if (changeInCatch && trap.useTry()) {
511 previousTrap = trap.current();
513 final int c = readUByte(byteCodes, i);
516 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
519 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
522 smapper.assign(this, VarType.LONG, lmapper.getL(0));
525 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
528 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
531 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
534 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
537 smapper.assign(this, VarType.LONG, lmapper.getL(1));
540 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
543 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
546 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
549 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
552 smapper.assign(this, VarType.LONG, lmapper.getL(2));
555 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
558 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
561 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
564 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
567 smapper.assign(this, VarType.LONG, lmapper.getL(3));
570 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
573 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
577 final int indx = wide ? readUShort(byteCodes, i++)
578 : readUByte(byteCodes, i);
580 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
585 final int indx = wide ? readUShort(byteCodes, i++)
586 : readUByte(byteCodes, i);
588 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
593 final int indx = wide ? readUShort(byteCodes, i++)
594 : readUByte(byteCodes, i);
596 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
601 final int indx = wide ? readUShort(byteCodes, i++)
602 : readUByte(byteCodes, i);
604 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
609 final int indx = wide ? readUShort(byteCodes, i++)
610 : readUByte(byteCodes, i);
612 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
617 final int indx = wide ? readUShort(byteCodes, i++)
618 : readUByte(byteCodes, i);
620 emit(smapper, this, "var @1 = @2;",
621 lmapper.setI(indx), smapper.popI());
626 final int indx = wide ? readUShort(byteCodes, i++)
627 : readUByte(byteCodes, i);
629 emit(smapper, this, "var @1 = @2;",
630 lmapper.setL(indx), smapper.popL());
635 final int indx = wide ? readUShort(byteCodes, i++)
636 : readUByte(byteCodes, i);
638 emit(smapper, this, "var @1 = @2;",
639 lmapper.setF(indx), smapper.popF());
644 final int indx = wide ? readUShort(byteCodes, i++)
645 : readUByte(byteCodes, i);
647 emit(smapper, this, "var @1 = @2;",
648 lmapper.setD(indx), smapper.popD());
653 final int indx = wide ? readUShort(byteCodes, i++)
654 : readUByte(byteCodes, i);
656 emit(smapper, this, "var @1 = @2;",
657 lmapper.setA(indx), smapper.popA());
661 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
664 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
667 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
670 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
673 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
676 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
679 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
682 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
685 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
688 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
691 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
694 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
697 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
700 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
703 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
706 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
709 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
712 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
715 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
718 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
721 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
724 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
727 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
730 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
733 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
736 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
739 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
742 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
745 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
748 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
751 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
754 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
757 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
758 smapper.getI(1), smapper.popI());
761 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
762 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, "(@1).mod32(@2)",
772 smapper.getI(1), smapper.popI());
775 smapper.replace(this, VarType.LONG, "(@1).mod64(@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, "(@1 & @2)", smapper.getI(1), smapper.popI());
788 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
791 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
794 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
797 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
800 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
803 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
806 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
809 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
812 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
815 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
818 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
821 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
824 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
827 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
830 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
834 final int varIndx = wide ? readUShort(byteCodes, i++)
835 : readUByte(byteCodes, i);
837 final int incrBy = wide ? readShort(byteCodes, i++)
841 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
843 emit(smapper, this, "@1 += @2;",
844 lmapper.getI(varIndx),
845 Integer.toString(incrBy));
850 emit(smapper, this, "return;");
853 emit(smapper, this, "return @1;", smapper.popI());
856 emit(smapper, this, "return @1;", smapper.popL());
859 emit(smapper, this, "return @1;", smapper.popF());
862 emit(smapper, this, "return @1;", smapper.popD());
865 emit(smapper, this, "return @1;", smapper.popA());
868 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
871 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
874 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
877 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
881 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
884 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
887 smapper.replace(this, VarType.DOUBLE, "@1",
891 smapper.replace(this, VarType.FLOAT, "@1",
895 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
899 smapper.replace(this, VarType.LONG, "(@1).toLong()",
903 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
907 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
910 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
914 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
916 case opc_aconst_null:
917 smapper.assign(this, VarType.REFERENCE, "null");
920 smapper.assign(this, VarType.INTEGER, "-1");
923 smapper.assign(this, VarType.INTEGER, "0");
926 smapper.assign(this, VarType.DOUBLE, "0");
929 smapper.assign(this, VarType.LONG, "0");
932 smapper.assign(this, VarType.FLOAT, "0");
935 smapper.assign(this, VarType.INTEGER, "1");
938 smapper.assign(this, VarType.LONG, "1");
941 smapper.assign(this, VarType.FLOAT, "1");
944 smapper.assign(this, VarType.DOUBLE, "1");
947 smapper.assign(this, VarType.INTEGER, "2");
950 smapper.assign(this, VarType.FLOAT, "2");
953 smapper.assign(this, VarType.INTEGER, "3");
956 smapper.assign(this, VarType.INTEGER, "4");
959 smapper.assign(this, VarType.INTEGER, "5");
962 int indx = readUByte(byteCodes, ++i);
963 String v = encodeConstant(indx);
964 int type = VarType.fromConstantType(jc.getTag(indx));
965 smapper.assign(this, type, v);
970 int indx = readUShortArg(byteCodes, i);
972 String v = encodeConstant(indx);
973 int type = VarType.fromConstantType(jc.getTag(indx));
974 if (type == VarType.LONG) {
975 final Long lv = new Long(v);
976 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
977 final int hi = (int)(lv.longValue() >> 32);
979 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
981 smapper.assign(this, VarType.LONG,
982 "0x" + Integer.toHexString(hi) + ".next32(0x" +
983 Integer.toHexString(low) + ")"
987 smapper.assign(this, type, v);
992 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
996 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
997 smapper.popF(), smapper.popF(), smapper.pushI());
1001 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1002 smapper.popD(), smapper.popD(), smapper.pushI());
1005 i = generateIf(smapper, flow, byteCodes, i, smapper.popA(), smapper.popA(),
1006 "===", topMostLabel);
1009 i = generateIf(smapper, flow, byteCodes, i, smapper.popA(), smapper.popA(),
1010 "!==", topMostLabel);
1013 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1014 "==", topMostLabel);
1017 int indx = i + readShortArg(byteCodes, i);
1018 emitIf(smapper, flow, this, "if ((@1) == 0) ",
1019 smapper.popI(), i, indx, topMostLabel);
1024 int indx = i + readShortArg(byteCodes, i);
1025 emitIf(smapper, flow, this, "if ((@1) != 0) ",
1026 smapper.popI(), i, indx, topMostLabel);
1031 int indx = i + readShortArg(byteCodes, i);
1032 emitIf(smapper, flow, this, "if ((@1) < 0) ",
1033 smapper.popI(), i, indx, topMostLabel);
1038 int indx = i + readShortArg(byteCodes, i);
1039 emitIf(smapper, flow, this, "if ((@1) <= 0) ",
1040 smapper.popI(), i, indx, topMostLabel);
1045 int indx = i + readShortArg(byteCodes, i);
1046 emitIf(smapper, flow, this, "if ((@1) > 0) ",
1047 smapper.popI(), i, indx, topMostLabel);
1052 int indx = i + readShortArg(byteCodes, i);
1053 emitIf(smapper, flow, this, "if ((@1) >= 0) ",
1054 smapper.popI(), i, indx, topMostLabel);
1058 case opc_ifnonnull: {
1059 int indx = i + readShortArg(byteCodes, i);
1060 emitIf(smapper, flow, this, "if ((@1) !== null) ",
1061 smapper.popA(), i, indx, topMostLabel);
1066 int indx = i + readShortArg(byteCodes, i);
1067 emitIf(smapper, flow, this, "if ((@1) === null) ",
1068 smapper.popA(), i, indx, topMostLabel);
1073 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1074 "!=", topMostLabel);
1077 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1081 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1082 "<=", topMostLabel);
1085 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1089 i = generateIf(smapper, flow, byteCodes, i, smapper.popI(), smapper.popI(),
1090 ">=", topMostLabel);
1093 smapper.flush(this);
1094 int indx = i + readShortArg(byteCodes, i);
1095 goTo(this, flow, i, indx, topMostLabel);
1099 case opc_lookupswitch: {
1100 i = generateLookupSwitch(i, byteCodes, smapper, flow, topMostLabel);
1103 case opc_tableswitch: {
1104 i = generateTableSwitch(i, byteCodes, smapper, flow, topMostLabel);
1107 case opc_invokeinterface: {
1108 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1111 case opc_invokevirtual:
1112 i = invokeVirtualMethod(byteCodes, i, smapper);
1114 case opc_invokespecial:
1115 i = invokeStaticMethod(byteCodes, i, smapper, false);
1117 case opc_invokestatic:
1118 i = invokeStaticMethod(byteCodes, i, smapper, true);
1120 case opc_invokedynamic: {
1121 int indx = readUShortArg(byteCodes, i);
1122 println("invoke dynamic: " + indx);
1123 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1124 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1125 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1126 println(" type: " + methodHandle.cpx1);
1127 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1128 String mcn = mangleClassName(mi[0]);
1129 char[] returnType = {'V'};
1130 StringBuilder cnt = new StringBuilder();
1131 String mn = findMethodName(mi, cnt, returnType);
1132 StringBuilder sb = new StringBuilder();
1133 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1134 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1135 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1136 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1137 sb.append(" mn : ").append(mn).append("\n");
1138 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1139 throw new IOException(sb.toString());
1141 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1142 String type = jc.StringValue(nameAndType.cpx2);
1143 String object = accessClass(mcn) + "(false)";
1144 if (mn.startsWith("cons_")) {
1145 object += ".constructor";
1147 append("var metHan = ");
1148 append(accessStaticMethod(object, mn, mi));
1150 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1152 append(", '").append(mi[1]).append("', ");
1153 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1154 append(methodType).append("'").append(type).append("', null)");
1155 // if (numArguments > 0) {
1157 // for (int j = 1; j < numArguments; ++j) {
1163 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1169 int indx = readUShortArg(byteCodes, i);
1170 String ci = jc.getClassName(indx);
1171 emit(smapper, this, "var @1 = new @2;",
1172 smapper.pushA(), accessClass(mangleClassName(ci)));
1178 int atype = readUByte(byteCodes, ++i);
1179 generateNewArray(atype, smapper);
1181 case opc_anewarray: {
1182 int type = readUShortArg(byteCodes, i);
1184 generateANewArray(type, smapper);
1187 case opc_multianewarray: {
1188 int type = readUShortArg(byteCodes, i);
1190 i = generateMultiANewArray(type, byteCodes, i, smapper);
1193 case opc_arraylength:
1194 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1197 emit(smapper, this, "Array.at(@3, @2, @1);",
1198 smapper.popL(), smapper.popI(), smapper.popA());
1201 emit(smapper, this, "Array.at(@3, @2, @1);",
1202 smapper.popF(), smapper.popI(), smapper.popA());
1205 emit(smapper, this, "Array.at(@3, @2, @1);",
1206 smapper.popD(), smapper.popI(), smapper.popA());
1209 emit(smapper, this, "Array.at(@3, @2, @1);",
1210 smapper.popA(), smapper.popI(), smapper.popA());
1216 emit(smapper, this, "Array.at(@3, @2, @1);",
1217 smapper.popI(), smapper.popI(), smapper.popA());
1220 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1221 smapper.popI(), smapper.getA(0));
1224 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1225 smapper.popI(), smapper.getA(0));
1228 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1229 smapper.popI(), smapper.getA(0));
1232 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1233 smapper.popI(), smapper.getA(0));
1239 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1240 smapper.popI(), smapper.getA(0));
1248 final Variable v = smapper.get(0);
1249 if (smapper.isDirty()) {
1250 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1252 smapper.assign(this, v.getType(), v);
1257 final Variable vi1 = smapper.get(0);
1259 if (vi1.isCategory2()) {
1260 emit(smapper, this, "var @1 = @2;",
1261 smapper.pushT(vi1.getType()), vi1);
1263 final Variable vi2 = smapper.get(1);
1264 emit(smapper, this, "var @1 = @2, @3 = @4;",
1265 smapper.pushT(vi2.getType()), vi2,
1266 smapper.pushT(vi1.getType()), vi1);
1271 final Variable vi1 = smapper.pop(this);
1272 final Variable vi2 = smapper.pop(this);
1273 final Variable vo3 = smapper.pushT(vi1.getType());
1274 final Variable vo2 = smapper.pushT(vi2.getType());
1275 final Variable vo1 = smapper.pushT(vi1.getType());
1277 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1278 vo1, vi1, vo2, vi2, vo3, vo1);
1282 final Variable vi1 = smapper.pop(this);
1283 final Variable vi2 = smapper.pop(this);
1285 if (vi1.isCategory2()) {
1286 final Variable vo3 = smapper.pushT(vi1.getType());
1287 final Variable vo2 = smapper.pushT(vi2.getType());
1288 final Variable vo1 = smapper.pushT(vi1.getType());
1290 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1291 vo1, vi1, vo2, vi2, vo3, vo1);
1293 final Variable vi3 = smapper.pop(this);
1294 final Variable vo5 = smapper.pushT(vi2.getType());
1295 final Variable vo4 = smapper.pushT(vi1.getType());
1296 final Variable vo3 = smapper.pushT(vi3.getType());
1297 final Variable vo2 = smapper.pushT(vi2.getType());
1298 final Variable vo1 = smapper.pushT(vi1.getType());
1300 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1301 vo1, vi1, vo2, vi2, vo3, vi3);
1302 emit(smapper, this, " @1 = @2, @3 = @4;",
1303 vo4, vo1, vo5, vo2);
1308 final Variable vi1 = smapper.pop(this);
1309 final Variable vi2 = smapper.pop(this);
1311 if (vi2.isCategory2()) {
1312 final Variable vo3 = smapper.pushT(vi1.getType());
1313 final Variable vo2 = smapper.pushT(vi2.getType());
1314 final Variable vo1 = smapper.pushT(vi1.getType());
1316 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1317 vo1, vi1, vo2, vi2, vo3, vo1);
1319 final Variable vi3 = smapper.pop(this);
1320 final Variable vo4 = smapper.pushT(vi1.getType());
1321 final Variable vo3 = smapper.pushT(vi3.getType());
1322 final Variable vo2 = smapper.pushT(vi2.getType());
1323 final Variable vo1 = smapper.pushT(vi1.getType());
1325 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1326 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1331 final Variable vi1 = smapper.pop(this);
1332 final Variable vi2 = smapper.pop(this);
1334 if (vi1.isCategory2()) {
1335 if (vi2.isCategory2()) {
1336 final Variable vo3 = smapper.pushT(vi1.getType());
1337 final Variable vo2 = smapper.pushT(vi2.getType());
1338 final Variable vo1 = smapper.pushT(vi1.getType());
1340 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1341 vo1, vi1, vo2, vi2, vo3, vo1);
1343 final Variable vi3 = smapper.pop(this);
1344 final Variable vo4 = smapper.pushT(vi1.getType());
1345 final Variable vo3 = smapper.pushT(vi3.getType());
1346 final Variable vo2 = smapper.pushT(vi2.getType());
1347 final Variable vo1 = smapper.pushT(vi1.getType());
1349 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1350 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1353 final Variable vi3 = smapper.pop(this);
1355 if (vi3.isCategory2()) {
1356 final Variable vo5 = smapper.pushT(vi2.getType());
1357 final Variable vo4 = smapper.pushT(vi1.getType());
1358 final Variable vo3 = smapper.pushT(vi3.getType());
1359 final Variable vo2 = smapper.pushT(vi2.getType());
1360 final Variable vo1 = smapper.pushT(vi1.getType());
1362 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1363 vo1, vi1, vo2, vi2, vo3, vi3);
1364 emit(smapper, this, " @1 = @2, @3 = @4;",
1365 vo4, vo1, vo5, vo2);
1367 final Variable vi4 = smapper.pop(this);
1368 final Variable vo6 = smapper.pushT(vi2.getType());
1369 final Variable vo5 = smapper.pushT(vi1.getType());
1370 final Variable vo4 = smapper.pushT(vi4.getType());
1371 final Variable vo3 = smapper.pushT(vi3.getType());
1372 final Variable vo2 = smapper.pushT(vi2.getType());
1373 final Variable vo1 = smapper.pushT(vi1.getType());
1375 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1376 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1377 emit(smapper, this, " @1 = @2, @3 = @4;",
1378 vo5, vo1, vo6, vo2);
1384 final Variable vi1 = smapper.get(0);
1385 final Variable vi2 = smapper.get(1);
1387 if (vi1.getType() == vi2.getType()) {
1388 final Variable tmp = smapper.pushT(vi1.getType());
1390 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1395 smapper.pushT(vi1.getType());
1396 smapper.pushT(vi2.getType());
1401 smapper.assign(this, VarType.INTEGER,
1402 "(" + Integer.toString(byteCodes[++i]) + ")");
1405 smapper.assign(this, VarType.INTEGER,
1406 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1410 case opc_getfield: {
1411 int indx = readUShortArg(byteCodes, i);
1412 String[] fi = jc.getFieldInfoName(indx);
1413 final int type = VarType.fromFieldType(fi[2].charAt(0));
1414 final String mangleClass = mangleClassName(fi[0]);
1415 final String mangleClassAccess = accessClassFalse(mangleClass);
1416 smapper.replace(this, type, "@2.call(@1)",
1418 accessField(mangleClassAccess,
1422 addReference(fi[0]);
1425 case opc_putfield: {
1426 int indx = readUShortArg(byteCodes, i);
1427 String[] fi = jc.getFieldInfoName(indx);
1428 final int type = VarType.fromFieldType(fi[2].charAt(0));
1429 final String mangleClass = mangleClassName(fi[0]);
1430 final String mangleClassAccess = accessClassFalse(mangleClass);
1431 emit(smapper, this, "@3.call(@2, @1);",
1434 accessField(mangleClassAccess,
1437 addReference(fi[0]);
1440 case opc_getstatic: {
1441 int indx = readUShortArg(byteCodes, i);
1442 String[] fi = jc.getFieldInfoName(indx);
1443 final int type = VarType.fromFieldType(fi[2].charAt(0));
1444 String ac = accessClassFalse(mangleClassName(fi[0]));
1445 String af = accessField(ac, "_" + fi[1], fi);
1446 smapper.assign(this, type, af + "()");
1448 addReference(fi[0]);
1451 case opc_putstatic: {
1452 int indx = readUShortArg(byteCodes, i);
1453 String[] fi = jc.getFieldInfoName(indx);
1454 final int type = VarType.fromFieldType(fi[2].charAt(0));
1455 emit(smapper, this, "@1._@2(@3);",
1456 accessClassFalse(mangleClassName(fi[0])), fi[1],
1457 smapper.popT(type));
1459 addReference(fi[0]);
1462 case opc_checkcast: {
1463 int indx = readUShortArg(byteCodes, i);
1464 generateCheckcast(indx, smapper);
1468 case opc_instanceof: {
1469 int indx = readUShortArg(byteCodes, i);
1470 generateInstanceOf(indx, smapper);
1475 final CharSequence v = smapper.popA();
1478 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1479 smapper.pushA(), v);
1483 case opc_monitorenter: {
1484 debug("/* monitor enter */");
1489 case opc_monitorexit: {
1490 debug("/* monitor exit */");
1501 emit(smapper, this, "throw 'unknown bytecode @1';",
1502 Integer.toString(c));
1506 generateByteCodeComment(prev, i, byteCodes);
1512 if (previousTrap != null) {
1513 generateCatch(previousTrap, flow, byteCodes.length, topMostLabel);
1518 while (openBraces-- > 0) {
1529 private int generateIf(StackMapper mapper, Flow flow, byte[] byteCodes, int i, final CharSequence v2, final CharSequence v1, final String test, int topMostLabel) throws IOException {
1531 int indx = i + readShortArg(byteCodes, i);
1532 append("if ((").append(v1)
1533 .append(") ").append(test).append(" (")
1534 .append(v2).append(")) ");
1535 goTo(this, flow, i, indx, topMostLabel);
1539 private int readInt4(byte[] byteCodes, int offset) {
1540 final int d = byteCodes[offset + 0] << 24;
1541 final int c = byteCodes[offset + 1] << 16;
1542 final int b = byteCodes[offset + 2] << 8;
1543 final int a = byteCodes[offset + 3];
1544 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1546 private static int readUByte(byte[] byteCodes, int offset) {
1547 return byteCodes[offset] & 0xff;
1550 private static int readUShort(byte[] byteCodes, int offset) {
1551 return ((byteCodes[offset] & 0xff) << 8)
1552 | (byteCodes[offset + 1] & 0xff);
1554 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1555 return readUShort(byteCodes, offsetInstruction + 1);
1558 private static int readShort(byte[] byteCodes, int offset) {
1559 int signed = byteCodes[offset];
1560 byte b0 = (byte)signed;
1561 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1563 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1564 return readShort(byteCodes, offsetInstruction + 1);
1567 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1569 Boolean count = null;
1570 boolean array = false;
1572 int firstPos = sig.length();
1573 while (i < descriptor.length()) {
1574 char ch = descriptor.charAt(i++);
1595 if (ch == 'J' || ch == 'D') {
1601 sig.insert(firstPos, ch);
1603 returnType[0] = '[';
1604 sig.insert(firstPos, "_3");
1613 returnType[0] = 'V';
1614 sig.insert(firstPos, 'V');
1617 int next = descriptor.indexOf(';', i);
1618 String realSig = mangleSig(descriptor, i - 1, next + 1);
1623 sig.append(realSig);
1626 sig.insert(firstPos, realSig);
1628 sig.insert(firstPos, "_3");
1630 returnType[0] = 'L';
1639 throw new IllegalStateException("Invalid char: " + ch);
1644 static String mangleSig(String sig) {
1645 return mangleSig(sig, 0, sig.length());
1648 private static String mangleMethodName(String name) {
1649 StringBuilder sb = new StringBuilder(name.length() * 2);
1650 int last = name.length();
1651 for (int i = 0; i < last; i++) {
1652 final char ch = name.charAt(i);
1654 case '_': sb.append("_1"); break;
1655 default: sb.append(ch); break;
1658 return sb.toString();
1660 private static String mangleSig(String txt, int first, int last) {
1661 StringBuilder sb = new StringBuilder((last - first) * 2);
1662 for (int i = first; i < last; i++) {
1663 final char ch = txt.charAt(i);
1665 case '/': sb.append('_'); break;
1666 case '_': sb.append("_1"); break;
1667 case ';': sb.append("_2"); break;
1668 case '[': sb.append("_3"); break;
1670 if (Character.isJavaIdentifierPart(ch)) {
1674 String hex = Integer.toHexString(ch).toLowerCase();
1675 for (int m = hex.length(); m < 4; m++) {
1683 return sb.toString();
1686 private static String mangleClassName(String name) {
1687 return mangleSig(name);
1690 private static String findMethodName(MethodData m, StringBuilder cnt) {
1691 StringBuilder name = new StringBuilder();
1692 if ("<init>".equals(m.getName())) { // NOI18N
1693 name.append("cons"); // NOI18N
1694 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1695 name.append("class"); // NOI18N
1697 name.append(mangleMethodName(m.getName()));
1700 countArgs(m.getInternalSig(), new char[1], name, cnt);
1701 return name.toString();
1704 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1705 StringBuilder name = new StringBuilder();
1706 String descr = mi[2];//mi.getDescriptor();
1708 if ("<init>".equals(nm)) { // NOI18N
1709 name.append("cons"); // NOI18N
1711 name.append(mangleMethodName(nm));
1713 countArgs(descr, returnType, name, cnt);
1714 return name.toString();
1717 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1718 throws IOException {
1719 int methodIndex = readUShortArg(byteCodes, i);
1720 String[] mi = jc.getFieldInfoName(methodIndex);
1721 char[] returnType = { 'V' };
1722 StringBuilder cnt = new StringBuilder();
1723 String mn = findMethodName(mi, cnt, returnType);
1725 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1726 final CharSequence[] vars = new CharSequence[numArguments];
1728 for (int j = numArguments - 1; j >= 0; --j) {
1729 vars[j] = mapper.popValue();
1733 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1734 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1736 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1737 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1739 if (vars[1] instanceof String) {
1740 String field = vars[1].toString();
1741 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1742 vars[1] = "c._" + field.substring(1, field.length() - 1);
1747 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1748 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1750 if (vars[1] instanceof String) {
1751 String field = vars[2].toString();
1752 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1753 vars[2] = "c._" + field.substring(1, field.length() - 1);
1758 if (returnType[0] != 'V') {
1761 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1765 final String in = mi[0];
1768 in.equals("org/apidesign/html/boot/spi/Fn") ||
1769 in.equals("org/netbeans/html/boot/spi/Fn")
1771 mcn = "java_lang_Class";
1773 mcn = mangleClassName(in);
1775 String object = accessClassFalse(mcn);
1776 if (mn.startsWith("cons_")) {
1777 object += ".constructor";
1779 append(accessStaticMethod(object, mn, mi));
1785 if (numArguments > 0) {
1787 for (int j = 1; j < numArguments; ++j) {
1797 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1798 throws IOException {
1799 int methodIndex = readUShortArg(byteCodes, i);
1800 String[] mi = jc.getFieldInfoName(methodIndex);
1801 char[] returnType = { 'V' };
1802 StringBuilder cnt = new StringBuilder();
1803 String mn = findMethodName(mi, cnt, returnType);
1805 final int numArguments = cnt.length() + 1;
1806 final CharSequence[] vars = new CharSequence[numArguments];
1808 for (int j = numArguments - 1; j >= 0; --j) {
1809 vars[j] = mapper.popValue();
1812 if (returnType[0] != 'V') {
1815 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1819 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1821 for (int j = 1; j < numArguments; ++j) {
1831 private void addReference(String cn) throws IOException {
1832 if (requireReference(cn)) {
1833 debug(" /* needs " + cn + " */");
1837 private void outType(String d, StringBuilder out) {
1839 while (d.charAt(0) == '[') {
1843 if (d.charAt(0) == 'L') {
1844 assert d.charAt(d.length() - 1) == ';';
1845 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1851 private String encodeConstant(int entryIndex) throws IOException {
1852 String[] classRef = { null };
1853 String s = jc.stringValue(entryIndex, classRef);
1854 if (classRef[0] != null) {
1855 if (classRef[0].startsWith("[")) {
1856 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1858 addReference(classRef[0]);
1859 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1865 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1866 byte[] arr = m.findAnnotationData(true);
1870 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1871 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1872 class P extends AnnotationParser {
1878 String[] args = new String[30];
1884 protected void visitAttr(String type, String attr, String at, String value) {
1885 if (type.equals(jvmType)) {
1886 if ("body".equals(attr)) {
1888 } else if ("args".equals(attr)) {
1889 args[cnt++] = value;
1891 throw new IllegalArgumentException(attr);
1894 if (type.equals(htmlType)) {
1896 if ("body".equals(attr)) {
1898 } else if ("args".equals(attr)) {
1899 args[cnt++] = value;
1900 } else if ("javacall".equals(attr)) {
1901 javacall = "1".equals(value);
1902 } else if ("wait4js".equals(attr)) {
1903 // ignore, we always invoke synchronously
1905 throw new IllegalArgumentException(attr);
1912 if (p.body == null) {
1915 StringBuilder cnt = new StringBuilder();
1916 final String mn = findMethodName(m, cnt);
1917 append("m = ").append(destObject).append(".").append(mn);
1918 append(" = function(");
1921 StringBuilder toValue = new StringBuilder();
1922 for (int i = 0; i < cnt.length(); i++) {
1924 space = outputArg(this, p.args, index);
1925 if (p.html4j && space.length() > 0) {
1926 toValue.append("\n ").append(p.args[index]).append(" = ")
1927 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1928 append(p.args[index]).append(");");
1932 append(") {").append("\n");
1933 append(toValue.toString());
1935 int lastSlash = jc.getClassName().lastIndexOf('/');
1936 final String pkg = jc.getClassName().substring(0, lastSlash);
1937 append(mangleCallbacks(pkg, p.body));
1938 requireReference(pkg + "/$JsCallbacks$");
1946 private static CharSequence mangleCallbacks(String pkgName, String body) {
1947 StringBuilder sb = new StringBuilder();
1950 int next = body.indexOf(".@", pos);
1952 sb.append(body.substring(pos));
1953 body = sb.toString();
1958 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1963 String refId = body.substring(ident, next);
1965 sb.append(body.substring(pos, ident));
1967 int sigBeg = body.indexOf('(', next);
1968 int sigEnd = body.indexOf(')', sigBeg);
1969 int colon4 = body.indexOf("::", next);
1970 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1971 throw new IllegalStateException("Malformed body " + body);
1973 String fqn = body.substring(next + 2, colon4);
1974 String method = body.substring(colon4 + 2, sigBeg);
1975 String params = body.substring(sigBeg, sigEnd + 1);
1977 int paramBeg = body.indexOf('(', sigEnd + 1);
1979 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1980 sb.append(mangleJsCallbacks(fqn, method, params, false));
1981 sb.append("(").append(refId);
1982 if (body.charAt(paramBeg + 1) != ')') {
1990 int next = body.indexOf("@", pos);
1995 sb.append(body.substring(pos));
1999 sb = new StringBuilder();
2002 sb.append(body.substring(pos, next));
2004 int sigBeg = body.indexOf('(', next);
2005 int sigEnd = body.indexOf(')', sigBeg);
2006 int colon4 = body.indexOf("::", next);
2007 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2008 throw new IllegalStateException("Malformed body " + body);
2010 String fqn = body.substring(next + 1, colon4);
2011 String method = body.substring(colon4 + 2, sigBeg);
2012 String params = body.substring(sigBeg, sigEnd + 1);
2014 int paramBeg = body.indexOf('(', sigEnd + 1);
2016 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2017 sb.append(mangleJsCallbacks(fqn, method, params, true));
2023 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2024 if (params.startsWith("(")) {
2025 params = params.substring(1);
2027 if (params.endsWith(")")) {
2028 params = params.substring(0, params.length() - 1);
2030 StringBuilder sb = new StringBuilder();
2031 final String fqnu = fqn.replace('.', '_');
2032 final String rfqn = mangleClassName(fqnu);
2033 final String rm = mangleMethodName(method);
2036 StringBuilder pb = new StringBuilder();
2037 int len = params.length();
2039 while (indx < len) {
2040 char ch = params.charAt(indx);
2041 if (ch == '[' || ch == 'L') {
2042 int column = params.indexOf(';', indx) + 1;
2043 if (column > indx) {
2044 String real = params.substring(indx, column);
2045 if ("Ljava/lang/String;".equals(real)) {
2046 pb.append("Ljava/lang/String;");
2051 pb.append("Ljava/lang/Object;");
2058 srp = mangleSig(pb.toString());
2060 final String rp = mangleSig(params);
2061 final String mrp = mangleMethodName(rp);
2062 sb.append(rfqn).append("$").append(rm).
2063 append('$').append(mrp).append("__Ljava_lang_Object_2");
2065 sb.append('L').append(fqnu).append("_2");
2068 return sb.toString();
2071 private static String className(ClassData jc) {
2072 //return jc.getName().getInternalName().replace('/', '_');
2073 return mangleClassName(jc.getClassName());
2076 private static String[] findAnnotation(
2077 byte[] arr, ClassData cd, final String className,
2078 final String... attrNames
2079 ) throws IOException {
2083 final String[] values = new String[attrNames.length];
2084 final boolean[] found = { false };
2085 final String jvmType = "L" + className.replace('.', '/') + ";";
2086 AnnotationParser ap = new AnnotationParser(false, true) {
2088 protected void visitAttr(String type, String attr, String at, String value) {
2089 if (type.equals(jvmType)) {
2091 for (int i = 0; i < attrNames.length; i++) {
2092 if (attrNames[i].equals(attr)) {
2101 return found[0] ? values : null;
2104 private CharSequence initField(FieldData v) {
2105 final String is = v.getInternalSig();
2106 if (is.length() == 1) {
2107 switch (is.charAt(0)) {
2113 case 'I': return " = 0;";
2115 case 'D': return " = 0.0;";
2117 throw new IllegalStateException(is);
2123 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2124 AnnotationParser ap = new AnnotationParser(true, false) {
2125 int[] cnt = new int[32];
2129 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2130 final String slashType = attrType.substring(1, attrType.length() - 1);
2131 requireReference(slashType);
2133 if (cnt[depth]++ > 0) {
2137 append('"').append(attrType).append("\" : ");
2144 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2150 protected void visitValueStart(String attrName, char type) throws IOException {
2151 if (cnt[depth]++ > 0) {
2155 if (attrName != null) {
2156 append('"').append(attrName).append("\" : ");
2164 protected void visitValueEnd(String attrName, char type) throws IOException {
2172 protected void visitAttr(String type, String attr, String attrType, String value)
2173 throws IOException {
2174 if (attr == null && value == null) {
2181 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2182 throws IOException {
2183 final String slashType = attrType.substring(1, attrType.length() - 1);
2184 requireReference(slashType);
2186 final String cn = mangleClassName(slashType);
2187 append(accessClassFalse(cn))
2188 .append("['valueOf__L").
2190 append("_2Ljava_lang_String_2']('").
2198 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2199 final String name = args[indx];
2203 if (name.contains(",")) {
2204 throw new IOException("Wrong parameter with ',': " + name);
2210 final void emitNoFlush(
2212 final String format, final CharSequence... params
2213 ) throws IOException {
2214 emitImpl(this, format, params);
2216 static final void emit(
2218 final Appendable out,
2219 final String format, final CharSequence... params
2220 ) throws IOException {
2222 emitImpl(out, format, params);
2224 static void emitImpl(final Appendable out,
2225 final String format,
2226 final CharSequence... params) throws IOException {
2227 final int length = format.length();
2230 int paramOffset = format.indexOf('@');
2231 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2232 final char paramChar = format.charAt(paramOffset + 1);
2233 if ((paramChar >= '1') && (paramChar <= '9')) {
2234 final int paramIndex = paramChar - '0' - 1;
2236 out.append(format, processed, paramOffset);
2237 out.append(params[paramIndex]);
2240 processed = paramOffset + 1;
2243 paramOffset = format.indexOf('@', paramOffset + 1);
2246 out.append(format, processed, length);
2249 private void generateCatch(TrapData[] traps, Flow flow, int current, int topMostLabel) throws IOException {
2250 append("} catch (e) {\n");
2252 for (TrapData e : traps) {
2256 if (e.catch_cpx != 0) { //not finally
2257 final String classInternalName = jc.getClassName(e.catch_cpx);
2258 addReference(classInternalName);
2259 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2260 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2261 append("var stA0 = e;");
2262 goTo(this, flow, current, e.handler_pc, topMostLabel);
2265 finallyPC = e.handler_pc;
2268 if (finallyPC == -1) {
2271 append("var stA0 = e;");
2272 goTo(this, flow, current, finallyPC, topMostLabel);
2277 private static void goTo(Appendable out, Flow flow, int current, int to, int canBack) throws IOException {
2280 out.append("{ gt = 0; continue X_" + to + "; }");
2282 out.append("{ gt = " + to + "; continue X_0; }");
2285 out.append("{ gt = " + to + "; break IF; }");
2289 private static void emitIf(
2290 StackMapper sm, Flow flow, Appendable out, String pattern, CharSequence param, int current, int to, int canBack
2291 ) throws IOException {
2293 emitImpl(out, pattern, param);
2294 goTo(out, flow, current, to, canBack);
2297 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2300 case 4: jvmType = "[Z"; break;
2301 case 5: jvmType = "[C"; break;
2302 case 6: jvmType = "[F"; break;
2303 case 7: jvmType = "[D"; break;
2304 case 8: jvmType = "[B"; break;
2305 case 9: jvmType = "[S"; break;
2306 case 10: jvmType = "[I"; break;
2307 case 11: jvmType = "[J"; break;
2308 default: throw new IllegalStateException("Array type: " + atype);
2311 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2312 smapper.popI(), smapper.pushA(), jvmType);
2315 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2316 String typeName = jc.getClassName(type);
2317 String ref = "null";
2318 if (typeName.startsWith("[")) {
2319 typeName = "'[" + typeName + "'";
2321 ref = "vm." + mangleClassName(typeName);
2322 typeName = "'[L" + typeName + ";'";
2325 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2326 smapper.popI(), smapper.pushA(), typeName, ref);
2329 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2330 String typeName = jc.getClassName(type);
2331 int dim = readUByte(byteCodes, ++i);
2332 StringBuilder dims = new StringBuilder();
2334 for (int d = 0; d < dim; d++) {
2336 dims.insert(1, ",");
2338 dims.insert(1, smapper.popI());
2342 if (typeName.charAt(dim) == 'L') {
2343 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2346 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2347 dims.toString(), smapper.pushA(), typeName, fn
2352 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, Flow flow, int topMostLabel) throws IOException {
2353 int table = i / 4 * 4 + 4;
2354 int dflt = i + readInt4(byteCodes, table);
2356 int low = readInt4(byteCodes, table);
2358 int high = readInt4(byteCodes, table);
2360 final CharSequence swVar = smapper.popValue();
2361 smapper.flush(this);
2362 append("switch (").append(swVar).append(") {\n");
2363 while (low <= high) {
2364 int offset = i + readInt4(byteCodes, table);
2366 append(" case " + low).append(":"); goTo(this, flow, i, offset, topMostLabel); append('\n');
2369 append(" default: ");
2370 goTo(this, flow, i, dflt, topMostLabel);
2376 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, Flow flow, int topMostLabel) throws IOException {
2377 int table = i / 4 * 4 + 4;
2378 int dflt = i + readInt4(byteCodes, table);
2380 int n = readInt4(byteCodes, table);
2382 final CharSequence swVar = smapper.popValue();
2383 smapper.flush(this);
2384 append("switch (").append(swVar).append(") {\n");
2386 int cnstnt = readInt4(byteCodes, table);
2388 int offset = i + readInt4(byteCodes, table);
2390 append(" case " + cnstnt).append(": "); goTo(this, flow, i, offset, topMostLabel); append('\n');
2392 append(" default: ");
2393 goTo(this, flow, i, dflt, topMostLabel);
2399 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2400 String type = jc.getClassName(indx);
2401 if (!type.startsWith("[")) {
2403 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2404 smapper.popA(), smapper.pushI(),
2405 type.replace('/', '_'));
2408 while (type.charAt(cnt) == '[') {
2411 if (type.charAt(cnt) == 'L') {
2412 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2414 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2415 smapper.popA(), smapper.pushI(),
2420 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2421 smapper.popA(), smapper.pushI(), type
2427 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2428 String type = jc.getClassName(indx);
2429 if (!type.startsWith("[")) {
2430 emitNoFlush(smapper,
2431 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2432 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2435 while (type.charAt(cnt) == '[') {
2438 if (type.charAt(cnt) == 'L') {
2439 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2440 emitNoFlush(smapper,
2441 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2442 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2445 emitNoFlush(smapper,
2446 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2447 smapper.getT(0, VarType.REFERENCE, false), type
2453 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2454 for (int j = prev; j <= i; j++) {
2456 final int cc = readUByte(byteCodes, j);
2457 append(Integer.toString(cc));
2461 @JavaScriptBody(args = "msg", body = "")
2462 private static void println(String msg) {
2463 System.err.println(msg);
2466 protected Flow checkFlow(MethodData byteCodes) {