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, 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, byteCodes, i, smapper.popA(), smapper.popA(),
1006 "===", topMostLabel);
1009 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1010 "!==", topMostLabel);
1013 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1014 "==", topMostLabel);
1017 int indx = i + readShortArg(byteCodes, i);
1018 emitIf(smapper, this, "if ((@1) == 0) ",
1019 smapper.popI(), i, indx, topMostLabel);
1024 int indx = i + readShortArg(byteCodes, i);
1025 emitIf(smapper, this, "if ((@1) != 0) ",
1026 smapper.popI(), i, indx, 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);
1058 case opc_ifnonnull: {
1059 int indx = i + readShortArg(byteCodes, i);
1060 emitIf(smapper, this, "if ((@1) !== null) ",
1061 smapper.popA(), i, indx, topMostLabel);
1066 int indx = i + readShortArg(byteCodes, i);
1067 emitIf(smapper, this, "if ((@1) === null) ",
1068 smapper.popA(), i, indx, topMostLabel);
1073 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1074 "!=", topMostLabel);
1077 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1081 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1082 "<=", topMostLabel);
1085 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1089 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1090 ">=", topMostLabel);
1093 smapper.flush(this);
1094 int indx = i + readShortArg(byteCodes, i);
1095 goTo(this, i, indx, topMostLabel);
1099 case opc_lookupswitch: {
1100 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1103 case opc_tableswitch: {
1104 i = generateTableSwitch(i, byteCodes, smapper, 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, byteCodes.length, topMostLabel);
1518 while (openBraces-- > 0) {
1529 private int generateIf(StackMapper mapper, byte[] byteCodes,
1530 int i, final CharSequence v2, final CharSequence v1,
1531 final String test, int topMostLabel
1532 ) throws IOException {
1534 int indx = i + readShortArg(byteCodes, i);
1535 append("if ((").append(v1)
1536 .append(") ").append(test).append(" (")
1537 .append(v2).append(")) ");
1538 goTo(this, i, indx, topMostLabel);
1542 private int readInt4(byte[] byteCodes, int offset) {
1543 final int d = byteCodes[offset + 0] << 24;
1544 final int c = byteCodes[offset + 1] << 16;
1545 final int b = byteCodes[offset + 2] << 8;
1546 final int a = byteCodes[offset + 3];
1547 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1549 private static int readUByte(byte[] byteCodes, int offset) {
1550 return byteCodes[offset] & 0xff;
1553 private static int readUShort(byte[] byteCodes, int offset) {
1554 return ((byteCodes[offset] & 0xff) << 8)
1555 | (byteCodes[offset + 1] & 0xff);
1557 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1558 return readUShort(byteCodes, offsetInstruction + 1);
1561 private static int readShort(byte[] byteCodes, int offset) {
1562 int signed = byteCodes[offset];
1563 byte b0 = (byte)signed;
1564 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1566 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1567 return readShort(byteCodes, offsetInstruction + 1);
1570 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1572 Boolean count = null;
1573 boolean array = false;
1575 int firstPos = sig.length();
1576 while (i < descriptor.length()) {
1577 char ch = descriptor.charAt(i++);
1598 if (ch == 'J' || ch == 'D') {
1604 sig.insert(firstPos, ch);
1606 returnType[0] = '[';
1607 sig.insert(firstPos, "_3");
1616 returnType[0] = 'V';
1617 sig.insert(firstPos, 'V');
1620 int next = descriptor.indexOf(';', i);
1621 String realSig = mangleSig(descriptor, i - 1, next + 1);
1626 sig.append(realSig);
1629 sig.insert(firstPos, realSig);
1631 sig.insert(firstPos, "_3");
1633 returnType[0] = 'L';
1642 throw new IllegalStateException("Invalid char: " + ch);
1647 static String mangleSig(String sig) {
1648 return mangleSig(sig, 0, sig.length());
1651 private static String mangleMethodName(String name) {
1652 StringBuilder sb = new StringBuilder(name.length() * 2);
1653 int last = name.length();
1654 for (int i = 0; i < last; i++) {
1655 final char ch = name.charAt(i);
1657 case '_': sb.append("_1"); break;
1658 default: sb.append(ch); break;
1661 return sb.toString();
1663 private static String mangleSig(String txt, int first, int last) {
1664 StringBuilder sb = new StringBuilder((last - first) * 2);
1665 for (int i = first; i < last; i++) {
1666 final char ch = txt.charAt(i);
1668 case '/': sb.append('_'); break;
1669 case '_': sb.append("_1"); break;
1670 case ';': sb.append("_2"); break;
1671 case '[': sb.append("_3"); break;
1673 if (Character.isJavaIdentifierPart(ch)) {
1677 String hex = Integer.toHexString(ch).toLowerCase();
1678 for (int m = hex.length(); m < 4; m++) {
1686 return sb.toString();
1689 private static String mangleClassName(String name) {
1690 return mangleSig(name);
1693 private static String findMethodName(MethodData m, StringBuilder cnt) {
1694 StringBuilder name = new StringBuilder();
1695 if ("<init>".equals(m.getName())) { // NOI18N
1696 name.append("cons"); // NOI18N
1697 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1698 name.append("class"); // NOI18N
1700 name.append(mangleMethodName(m.getName()));
1703 countArgs(m.getInternalSig(), new char[1], name, cnt);
1704 return name.toString();
1707 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1708 StringBuilder name = new StringBuilder();
1709 String descr = mi[2];//mi.getDescriptor();
1711 if ("<init>".equals(nm)) { // NOI18N
1712 name.append("cons"); // NOI18N
1714 name.append(mangleMethodName(nm));
1716 countArgs(descr, returnType, name, cnt);
1717 return name.toString();
1720 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1721 throws IOException {
1722 int methodIndex = readUShortArg(byteCodes, i);
1723 String[] mi = jc.getFieldInfoName(methodIndex);
1724 char[] returnType = { 'V' };
1725 StringBuilder cnt = new StringBuilder();
1726 String mn = findMethodName(mi, cnt, returnType);
1728 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1729 final CharSequence[] vars = new CharSequence[numArguments];
1731 for (int j = numArguments - 1; j >= 0; --j) {
1732 vars[j] = mapper.popValue();
1736 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1737 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1739 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1740 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1742 if (vars[1] instanceof String) {
1743 String field = vars[1].toString();
1744 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1745 vars[1] = "c._" + field.substring(1, field.length() - 1);
1750 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1751 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1753 if (vars[1] instanceof String) {
1754 String field = vars[2].toString();
1755 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1756 vars[2] = "c._" + field.substring(1, field.length() - 1);
1761 if (returnType[0] != 'V') {
1764 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1768 final String in = mi[0];
1771 in.equals("org/apidesign/html/boot/spi/Fn") ||
1772 in.equals("org/netbeans/html/boot/spi/Fn")
1774 mcn = "java_lang_Class";
1776 mcn = mangleClassName(in);
1778 String object = accessClassFalse(mcn);
1779 if (mn.startsWith("cons_")) {
1780 object += ".constructor";
1782 append(accessStaticMethod(object, mn, mi));
1788 if (numArguments > 0) {
1790 for (int j = 1; j < numArguments; ++j) {
1800 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1801 throws IOException {
1802 int methodIndex = readUShortArg(byteCodes, i);
1803 String[] mi = jc.getFieldInfoName(methodIndex);
1804 char[] returnType = { 'V' };
1805 StringBuilder cnt = new StringBuilder();
1806 String mn = findMethodName(mi, cnt, returnType);
1808 final int numArguments = cnt.length() + 1;
1809 final CharSequence[] vars = new CharSequence[numArguments];
1811 for (int j = numArguments - 1; j >= 0; --j) {
1812 vars[j] = mapper.popValue();
1815 if (returnType[0] != 'V') {
1818 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1822 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1824 for (int j = 1; j < numArguments; ++j) {
1834 private void addReference(String cn) throws IOException {
1835 if (requireReference(cn)) {
1836 debug(" /* needs " + cn + " */");
1840 private void outType(String d, StringBuilder out) {
1842 while (d.charAt(0) == '[') {
1846 if (d.charAt(0) == 'L') {
1847 assert d.charAt(d.length() - 1) == ';';
1848 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1854 private String encodeConstant(int entryIndex) throws IOException {
1855 String[] classRef = { null };
1856 String s = jc.stringValue(entryIndex, classRef);
1857 if (classRef[0] != null) {
1858 if (classRef[0].startsWith("[")) {
1859 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1861 addReference(classRef[0]);
1862 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1868 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1869 byte[] arr = m.findAnnotationData(true);
1873 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1874 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1875 class P extends AnnotationParser {
1881 String[] args = new String[30];
1887 protected void visitAttr(String type, String attr, String at, String value) {
1888 if (type.equals(jvmType)) {
1889 if ("body".equals(attr)) {
1891 } else if ("args".equals(attr)) {
1892 args[cnt++] = value;
1894 throw new IllegalArgumentException(attr);
1897 if (type.equals(htmlType)) {
1899 if ("body".equals(attr)) {
1901 } else if ("args".equals(attr)) {
1902 args[cnt++] = value;
1903 } else if ("javacall".equals(attr)) {
1904 javacall = "1".equals(value);
1905 } else if ("wait4js".equals(attr)) {
1906 // ignore, we always invoke synchronously
1908 throw new IllegalArgumentException(attr);
1915 if (p.body == null) {
1918 StringBuilder cnt = new StringBuilder();
1919 final String mn = findMethodName(m, cnt);
1920 append("m = ").append(destObject).append(".").append(mn);
1921 append(" = function(");
1924 StringBuilder toValue = new StringBuilder();
1925 for (int i = 0; i < cnt.length(); i++) {
1927 space = outputArg(this, p.args, index);
1928 if (p.html4j && space.length() > 0) {
1929 toValue.append("\n ").append(p.args[index]).append(" = ")
1930 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1931 append(p.args[index]).append(");");
1935 append(") {").append("\n");
1936 append(toValue.toString());
1938 int lastSlash = jc.getClassName().lastIndexOf('/');
1939 final String pkg = jc.getClassName().substring(0, lastSlash);
1940 append(mangleCallbacks(pkg, p.body));
1941 requireReference(pkg + "/$JsCallbacks$");
1949 private static CharSequence mangleCallbacks(String pkgName, String body) {
1950 StringBuilder sb = new StringBuilder();
1953 int next = body.indexOf(".@", pos);
1955 sb.append(body.substring(pos));
1956 body = sb.toString();
1961 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1966 String refId = body.substring(ident, next);
1968 sb.append(body.substring(pos, ident));
1970 int sigBeg = body.indexOf('(', next);
1971 int sigEnd = body.indexOf(')', sigBeg);
1972 int colon4 = body.indexOf("::", next);
1973 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1974 throw new IllegalStateException("Malformed body " + body);
1976 String fqn = body.substring(next + 2, colon4);
1977 String method = body.substring(colon4 + 2, sigBeg);
1978 String params = body.substring(sigBeg, sigEnd + 1);
1980 int paramBeg = body.indexOf('(', sigEnd + 1);
1982 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1983 sb.append(mangleJsCallbacks(fqn, method, params, false));
1984 sb.append("(").append(refId);
1985 if (body.charAt(paramBeg + 1) != ')') {
1993 int next = body.indexOf("@", pos);
1998 sb.append(body.substring(pos));
2002 sb = new StringBuilder();
2005 sb.append(body.substring(pos, next));
2007 int sigBeg = body.indexOf('(', next);
2008 int sigEnd = body.indexOf(')', sigBeg);
2009 int colon4 = body.indexOf("::", next);
2010 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2011 throw new IllegalStateException("Malformed body " + body);
2013 String fqn = body.substring(next + 1, colon4);
2014 String method = body.substring(colon4 + 2, sigBeg);
2015 String params = body.substring(sigBeg, sigEnd + 1);
2017 int paramBeg = body.indexOf('(', sigEnd + 1);
2019 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2020 sb.append(mangleJsCallbacks(fqn, method, params, true));
2026 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2027 if (params.startsWith("(")) {
2028 params = params.substring(1);
2030 if (params.endsWith(")")) {
2031 params = params.substring(0, params.length() - 1);
2033 StringBuilder sb = new StringBuilder();
2034 final String fqnu = fqn.replace('.', '_');
2035 final String rfqn = mangleClassName(fqnu);
2036 final String rm = mangleMethodName(method);
2039 StringBuilder pb = new StringBuilder();
2040 int len = params.length();
2042 while (indx < len) {
2043 char ch = params.charAt(indx);
2044 if (ch == '[' || ch == 'L') {
2045 int column = params.indexOf(';', indx) + 1;
2046 if (column > indx) {
2047 String real = params.substring(indx, column);
2048 if ("Ljava/lang/String;".equals(real)) {
2049 pb.append("Ljava/lang/String;");
2054 pb.append("Ljava/lang/Object;");
2061 srp = mangleSig(pb.toString());
2063 final String rp = mangleSig(params);
2064 final String mrp = mangleMethodName(rp);
2065 sb.append(rfqn).append("$").append(rm).
2066 append('$').append(mrp).append("__Ljava_lang_Object_2");
2068 sb.append('L').append(fqnu).append("_2");
2071 return sb.toString();
2074 private static String className(ClassData jc) {
2075 //return jc.getName().getInternalName().replace('/', '_');
2076 return mangleClassName(jc.getClassName());
2079 private static String[] findAnnotation(
2080 byte[] arr, ClassData cd, final String className,
2081 final String... attrNames
2082 ) throws IOException {
2086 final String[] values = new String[attrNames.length];
2087 final boolean[] found = { false };
2088 final String jvmType = "L" + className.replace('.', '/') + ";";
2089 AnnotationParser ap = new AnnotationParser(false, true) {
2091 protected void visitAttr(String type, String attr, String at, String value) {
2092 if (type.equals(jvmType)) {
2094 for (int i = 0; i < attrNames.length; i++) {
2095 if (attrNames[i].equals(attr)) {
2104 return found[0] ? values : null;
2107 private CharSequence initField(FieldData v) {
2108 final String is = v.getInternalSig();
2109 if (is.length() == 1) {
2110 switch (is.charAt(0)) {
2116 case 'I': return " = 0;";
2118 case 'D': return " = 0.0;";
2120 throw new IllegalStateException(is);
2126 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2127 AnnotationParser ap = new AnnotationParser(true, false) {
2128 int[] cnt = new int[32];
2132 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2133 final String slashType = attrType.substring(1, attrType.length() - 1);
2134 requireReference(slashType);
2136 if (cnt[depth]++ > 0) {
2140 append('"').append(attrType).append("\" : ");
2147 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2153 protected void visitValueStart(String attrName, char type) throws IOException {
2154 if (cnt[depth]++ > 0) {
2158 if (attrName != null) {
2159 append('"').append(attrName).append("\" : ");
2167 protected void visitValueEnd(String attrName, char type) throws IOException {
2175 protected void visitAttr(String type, String attr, String attrType, String value)
2176 throws IOException {
2177 if (attr == null && value == null) {
2184 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2185 throws IOException {
2186 final String slashType = attrType.substring(1, attrType.length() - 1);
2187 requireReference(slashType);
2189 final String cn = mangleClassName(slashType);
2190 append(accessClassFalse(cn))
2191 .append("['valueOf__L").
2193 append("_2Ljava_lang_String_2']('").
2201 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2202 final String name = args[indx];
2206 if (name.contains(",")) {
2207 throw new IOException("Wrong parameter with ',': " + name);
2213 final void emitNoFlush(
2215 final String format, final CharSequence... params
2216 ) throws IOException {
2217 emitImpl(this, format, params);
2219 static final void emit(
2221 final Appendable out,
2222 final String format, final CharSequence... params
2223 ) throws IOException {
2225 emitImpl(out, format, params);
2227 static void emitImpl(final Appendable out,
2228 final String format,
2229 final CharSequence... params) throws IOException {
2230 final int length = format.length();
2233 int paramOffset = format.indexOf('@');
2234 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2235 final char paramChar = format.charAt(paramOffset + 1);
2236 if ((paramChar >= '1') && (paramChar <= '9')) {
2237 final int paramIndex = paramChar - '0' - 1;
2239 out.append(format, processed, paramOffset);
2240 out.append(params[paramIndex]);
2243 processed = paramOffset + 1;
2246 paramOffset = format.indexOf('@', paramOffset + 1);
2249 out.append(format, processed, length);
2252 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2253 append("} catch (e) {\n");
2255 for (TrapData e : traps) {
2259 if (e.catch_cpx != 0) { //not finally
2260 final String classInternalName = jc.getClassName(e.catch_cpx);
2261 addReference(classInternalName);
2262 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2263 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2264 append("var stA0 = e;");
2265 goTo(this, current, e.handler_pc, topMostLabel);
2268 finallyPC = e.handler_pc;
2271 if (finallyPC == -1) {
2274 append("var stA0 = e;");
2275 goTo(this, current, finallyPC, topMostLabel);
2280 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2283 out.append("{ gt = 0; continue X_" + to + "; }");
2285 out.append("{ gt = " + to + "; continue X_0; }");
2288 out.append("{ gt = " + to + "; break IF; }");
2292 private static void emitIf(
2294 Appendable out, String pattern,
2296 int current, int to, int canBack
2297 ) throws IOException {
2299 emitImpl(out, pattern, param);
2300 goTo(out, current, to, canBack);
2303 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2306 case 4: jvmType = "[Z"; break;
2307 case 5: jvmType = "[C"; break;
2308 case 6: jvmType = "[F"; break;
2309 case 7: jvmType = "[D"; break;
2310 case 8: jvmType = "[B"; break;
2311 case 9: jvmType = "[S"; break;
2312 case 10: jvmType = "[I"; break;
2313 case 11: jvmType = "[J"; break;
2314 default: throw new IllegalStateException("Array type: " + atype);
2317 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2318 smapper.popI(), smapper.pushA(), jvmType);
2321 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2322 String typeName = jc.getClassName(type);
2323 String ref = "null";
2324 if (typeName.startsWith("[")) {
2325 typeName = "'[" + typeName + "'";
2327 ref = "vm." + mangleClassName(typeName);
2328 typeName = "'[L" + typeName + ";'";
2331 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2332 smapper.popI(), smapper.pushA(), typeName, ref);
2335 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2336 String typeName = jc.getClassName(type);
2337 int dim = readUByte(byteCodes, ++i);
2338 StringBuilder dims = new StringBuilder();
2340 for (int d = 0; d < dim; d++) {
2342 dims.insert(1, ",");
2344 dims.insert(1, smapper.popI());
2348 if (typeName.charAt(dim) == 'L') {
2349 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2352 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2353 dims.toString(), smapper.pushA(), typeName, fn
2358 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2359 int table = i / 4 * 4 + 4;
2360 int dflt = i + readInt4(byteCodes, table);
2362 int low = readInt4(byteCodes, table);
2364 int high = readInt4(byteCodes, table);
2366 final CharSequence swVar = smapper.popValue();
2367 smapper.flush(this);
2368 append("switch (").append(swVar).append(") {\n");
2369 while (low <= high) {
2370 int offset = i + readInt4(byteCodes, table);
2372 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2375 append(" default: ");
2376 goTo(this, i, dflt, topMostLabel);
2382 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2383 int table = i / 4 * 4 + 4;
2384 int dflt = i + readInt4(byteCodes, table);
2386 int n = readInt4(byteCodes, table);
2388 final CharSequence swVar = smapper.popValue();
2389 smapper.flush(this);
2390 append("switch (").append(swVar).append(") {\n");
2392 int cnstnt = readInt4(byteCodes, table);
2394 int offset = i + readInt4(byteCodes, table);
2396 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2398 append(" default: ");
2399 goTo(this, i, dflt, topMostLabel);
2405 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2406 String type = jc.getClassName(indx);
2407 if (!type.startsWith("[")) {
2409 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2410 smapper.popA(), smapper.pushI(),
2411 type.replace('/', '_'));
2414 while (type.charAt(cnt) == '[') {
2417 if (type.charAt(cnt) == 'L') {
2418 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2420 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2421 smapper.popA(), smapper.pushI(),
2426 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2427 smapper.popA(), smapper.pushI(), type
2433 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2434 String type = jc.getClassName(indx);
2435 if (!type.startsWith("[")) {
2436 emitNoFlush(smapper,
2437 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2438 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2441 while (type.charAt(cnt) == '[') {
2444 if (type.charAt(cnt) == 'L') {
2445 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2446 emitNoFlush(smapper,
2447 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2448 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2451 emitNoFlush(smapper,
2452 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2453 smapper.getT(0, VarType.REFERENCE, false), type
2459 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2460 for (int j = prev; j <= i; j++) {
2462 final int cc = readUByte(byteCodes, j);
2463 append(Integer.toString(cc));
2467 @JavaScriptBody(args = "msg", body = "")
2468 private static void println(String msg) {
2469 System.err.println(msg);
2472 protected Flow checkFlow(MethodData byteCodes) {