Make sure the array component we check is properly referenced from the generated file
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import org.apidesign.bck2brwsr.core.JavaScriptBody;
23 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
25 /** Translator of the code inside class files to JavaScript.
27 * @author Jaroslav Tulach <jtulach@netbeans.org>
29 abstract class ByteCodeToJavaScript implements Appendable {
31 private final Appendable out;
32 private final StringArray classRefs = new StringArray();
33 private boolean outChanged;
34 private boolean callbacks;
36 protected ByteCodeToJavaScript(Appendable out) {
41 public final Appendable append(CharSequence csq) throws IOException {
48 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
49 out.append(csq, start, end);
55 public final Appendable append(char c) throws IOException {
61 /* Collects additional required resources.
63 * @param internalClassName classes that were referenced and should be loaded in order the
64 * generated JavaScript code works properly. The names are in internal
65 * JVM form so String is <code>java/lang/String</code>.
67 protected abstract boolean requireReference(String internalClassName);
70 * @param resourcePath name of resources to read
72 protected abstract void requireScript(String resourcePath) throws IOException;
74 protected abstract void requireResource(String resourcePath) throws IOException;
76 /** Allows subclasses to redefine what field a function representing a
77 * class gets assigned. By default it returns the suggested name followed
78 * by <code>" = "</code>;
80 * @param className suggested name of the class
82 /* protected */ String assignClass(String className) {
83 return className + " = ";
85 /* protected */ String accessClass(String classOperation) {
86 return classOperation;
89 final String accessClassFalse(String classOperation) {
90 if (jc.getClassName().replace('/', '_').equals(classOperation)) {
93 classRefs.addIfMissing(classOperation);
94 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
97 protected String accessField(String object, String mangledName,
98 String[] fieldInfoName) throws IOException {
99 return object + "." + mangledName;
102 protected String accessStaticMethod(
105 String[] fieldInfoName) throws IOException {
106 return object + "." + mangledName;
109 protected String accessVirtualMethod(
112 String[] fieldInfoName,
114 ) throws IOException {
115 return object + "." + mangledName + '(';
118 protected void declaredClass(ClassData classData, String mangledName)
122 protected void declaredField(FieldData fieldData,
124 String mangledName) throws IOException {
127 protected void declaredMethod(MethodData methodData,
129 String mangledName) throws IOException {
132 /** Prints out a debug message.
134 * @param msg the message
135 * @return true if the message has been printed
136 * @throws IOException
138 boolean debug(String msg) throws IOException {
144 * Converts a given class file to a JavaScript version.
146 * @param classFile input stream with code of the .class file
147 * @return the initialization code for this class, if any. Otherwise <code>null</code>
149 * @throws IOException if something goes wrong during read or write or translating
152 public String compile(InputStream classFile) throws IOException {
153 return compile(new ClassData(classFile));
156 protected String compile(ClassData classData) throws IOException {
158 final String cn = this.jc.getClassName();
160 return compileImpl(cn);
161 } catch (IOException ex) {
162 throw new IOException("Cannot compile " + cn + ":", ex);
166 private String compileImpl(final String cn) throws IOException {
167 this.callbacks = cn.endsWith("/$JsCallbacks$");
168 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
169 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
170 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
173 byte[] arrData = jc.findAnnotationData(true);
175 String[] arr = findAnnotation(arrData, jc,
176 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
177 "resource", "processByteCode"
180 if (!arr[0].isEmpty()) {
181 requireScript(arr[0]);
183 if ("0".equals(arr[1])) {
188 final String jsResource;
190 String[] arr = findAnnotation(arrData, jc,
191 "net.java.html.js.JavaScriptResource",
195 if (arr[0].startsWith("/")) {
198 int last = cn.lastIndexOf('/');
199 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
205 String[] proto = findAnnotation(arrData, jc,
206 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
207 "container", "prototype"
209 StringArray toInitilize = new StringArray();
210 final String className = className(jc);
211 append("\n\n").append(assignClass(className));
212 append("function ").append(className).append("() {");
214 append("\n var CLS = ").append(className).append(';');
215 append("\n if (!CLS.$class) {");
217 String sc = jc.getSuperClassName(); // with _
218 append("\n var pp = ").
219 append(accessClass(mangleClassName(sc))).append("(true);");
220 append("\n var p = CLS.prototype = pp;");
221 append("\n var c = p;");
222 append("\n var sprcls = pp.constructor.$class;");
224 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
225 if (proto[0] == null) {
228 append("\n var c = ").append(proto[0]).append(";");
229 append("\n var sprcls = null;");
231 for (FieldData v : jc.getFields()) {
233 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
234 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
238 append("\n CLS.fld_").append(v.getName()).append(initField(v));
239 append("\n m = c._").append(v.getName()).append(" = function (v) {")
240 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
241 .append(" = v; return CLS.fld_").
242 append(v.getName()).append("; };");
244 append("\n m = c._").append(v.getName()).append(" = function (v) {")
245 .append(" if (arguments.length == 1) this.fld_").
246 append(className).append('_').append(v.getName())
247 .append(" = v; return this.fld_").
248 append(className).append('_').append(v.getName())
252 declaredField(v, "c", "_" + v.getName());
254 for (MethodData m : jc.getMethods()) {
255 byte[] onlyArr = m.findAnnotationData(true);
256 if (javaScriptOnly(onlyArr)) continue;
262 mn = generateStaticMethod(destObject, m, toInitilize);
264 if (m.isConstructor()) {
266 mn = generateInstanceMethod(destObject, m);
269 mn = generateInstanceMethod(destObject, m);
272 declaredMethod(m, destObject, mn);
273 byte[] runAnno = m.findAnnotationData(false);
274 if (runAnno != null) {
275 append("\n m.anno = {");
276 generateAnno(jc, runAnno);
279 append("\n m.access = " + m.getAccess()).append(";");
280 append("\n m.cls = CLS;");
282 append("\n c.constructor = CLS;");
283 append("\n function ").append(className).append("fillInstOf(x) {");
284 String instOfName = "$instOf_" + className;
285 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
286 if (jc.isInterface()) {
287 for (MethodData m : jc.getMethods()) {
288 if ((m.getAccess() & ACC_ABSTRACT) == 0
289 && (m.getAccess() & ACC_STATIC) == 0
290 && (m.getAccess() & ACC_PRIVATE) == 0) {
291 final String mn = findMethodName(m, new StringBuilder());
292 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
296 for (String superInterface : jc.getSuperInterfaces()) {
297 String intrfc = superInterface.replace('/', '_');
298 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
299 requireReference(superInterface);
302 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
303 append("\n ").append(className).append("fillInstOf(c);");
304 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
305 append("\n CLS.$class = 'temp';");
306 append("\n CLS.$class = ");
307 append(accessClass("java_lang_Class(true);"));
308 append("\n CLS.$class.jvmName = '").append(cn).append("';");
309 append("\n CLS.$class.superclass = sprcls;");
310 append("\n CLS.$class.interfaces = function() { return [");
312 boolean first = true;
313 for (String intrfc : jc.getSuperInterfaces()) {
317 requireReference(intrfc);
318 String mangledIface = mangleClassName(intrfc);
320 append(accessClass(mangledIface)).append("(false).constructor.$class");
325 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
326 append("\n CLS.$class.cnstr = CLS;");
327 byte[] classAnno = jc.findAnnotationData(false);
328 if (classAnno != null) {
329 append("\n CLS.$class.anno = {");
330 generateAnno(jc, classAnno);
333 for (String init : toInitilize.toArray()) {
334 append("\n ").append(init).append("();");
336 for (String ref : classRefs.toArray()) {
337 append("\n var refs_").append(ref).append(";");
341 if (jsResource != null) {
342 requireResource(jsResource);
346 append("\n if (arguments.length === 0) {");
347 append("\n if (!(this instanceof CLS)) {");
348 append("\n return new CLS();");
350 for (FieldData v : jc.getFields()) {
351 byte[] onlyArr = v.findAnnotationData(true);
352 if (javaScriptOnly(onlyArr)) continue;
354 append("\n this.fld_").
355 append(className).append('_').
356 append(v.getName()).append(initField(v));
359 append("\n return this;");
361 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
364 declaredClass(jc, className);
366 // StringBuilder sb = new StringBuilder();
367 // for (String init : toInitilize.toArray()) {
368 // sb.append("\n").append(init).append("();");
373 private boolean javaScriptOnly(byte[] anno) throws IOException {
374 String[] only = findAnnotation(anno, jc,
375 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
379 if (only[0] != null && only[1] != null) {
380 append("\n p.").append(only[0]).append(" = ")
381 .append(only[1]).append(";");
383 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
384 append("\n p['").append(only[0]).append("'] = p.")
385 .append(only[0]).append(";");
391 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
392 String jsb = javaScriptBody(destObject, m, true);
396 final String mn = findMethodName(m, new StringBuilder());
397 boolean defineProp = generateMethod(destObject, mn, m);
398 if (mn.equals("class__V")) {
400 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
402 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
408 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
409 String jsb = javaScriptBody(destObject, m, false);
413 final String mn = findMethodName(m, new StringBuilder());
414 generateMethod(destObject, mn, m);
418 private boolean generateMethod(String destObject, String name, MethodData m)
420 final StackMapIterator stackMapIterator = m.createStackMapIterator();
421 TrapDataIterator trap = m.getTrapDataIterator();
422 final LocalsMapper lmapper =
423 new LocalsMapper(stackMapIterator.getArguments());
426 "java/lang/Object".equals(jc.getClassName()) ||
427 "java/lang/reflect/Array".equals(jc.getClassName());
430 append("Object.defineProperty(").append(destObject).
431 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
433 append("m = ").append(destObject).append(".").append(name).append(" = function(");
435 lmapper.outputArguments(this, m.isStatic());
436 append(") {").append("\n");
438 final byte[] byteCodes = m.getCode();
439 if (byteCodes == null) {
440 if (debug(" throw 'no code found for ")) {
442 .append(jc.getClassName()).append('.')
443 .append(m.getName()).append("';\n");
453 final StackMapper smapper = new StackMapper();
456 append(" var ").append(" lcA0 = this;\n");
460 TrapData[] previousTrap = null;
461 boolean wide = false;
463 if (stackMapIterator.isEmpty()) {
469 append("\n var gt = 0;\n");
473 int topMostLabel = 0;
474 for (int i = 0; i < byteCodes.length; i++) {
477 stackMapIterator.advanceTo(i);
478 boolean changeInCatch = trap.advanceTo(i);
479 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
480 if (previousTrap != null) {
481 generateCatch(previousTrap, i, topMostLabel);
485 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
490 if (openBraces > 64) {
491 for (int c = 0; c < 64; c++) {
498 lastStackFrame = stackMapIterator.getFrameIndex();
499 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
500 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
501 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
503 changeInCatch = true;
505 debug(" /* " + i + " */ ");
507 if (changeInCatch && trap.useTry()) {
509 previousTrap = trap.current();
511 final int c = readUByte(byteCodes, i);
514 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
517 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
520 smapper.assign(this, VarType.LONG, lmapper.getL(0));
523 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
526 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
529 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
532 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
535 smapper.assign(this, VarType.LONG, lmapper.getL(1));
538 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
541 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
544 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
547 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
550 smapper.assign(this, VarType.LONG, lmapper.getL(2));
553 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
556 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
559 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
562 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
565 smapper.assign(this, VarType.LONG, lmapper.getL(3));
568 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
571 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
575 final int indx = wide ? readUShort(byteCodes, i++)
576 : readUByte(byteCodes, i);
578 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
583 final int indx = wide ? readUShort(byteCodes, i++)
584 : readUByte(byteCodes, i);
586 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
591 final int indx = wide ? readUShort(byteCodes, i++)
592 : readUByte(byteCodes, i);
594 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
599 final int indx = wide ? readUShort(byteCodes, i++)
600 : readUByte(byteCodes, i);
602 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
607 final int indx = wide ? readUShort(byteCodes, i++)
608 : readUByte(byteCodes, i);
610 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
615 final int indx = wide ? readUShort(byteCodes, i++)
616 : readUByte(byteCodes, i);
618 emit(smapper, this, "var @1 = @2;",
619 lmapper.setI(indx), smapper.popI());
624 final int indx = wide ? readUShort(byteCodes, i++)
625 : readUByte(byteCodes, i);
627 emit(smapper, this, "var @1 = @2;",
628 lmapper.setL(indx), smapper.popL());
633 final int indx = wide ? readUShort(byteCodes, i++)
634 : readUByte(byteCodes, i);
636 emit(smapper, this, "var @1 = @2;",
637 lmapper.setF(indx), smapper.popF());
642 final int indx = wide ? readUShort(byteCodes, i++)
643 : readUByte(byteCodes, i);
645 emit(smapper, this, "var @1 = @2;",
646 lmapper.setD(indx), smapper.popD());
651 final int indx = wide ? readUShort(byteCodes, i++)
652 : readUByte(byteCodes, i);
654 emit(smapper, this, "var @1 = @2;",
655 lmapper.setA(indx), smapper.popA());
659 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
662 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
665 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
668 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
671 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
674 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
677 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
680 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
683 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
686 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
689 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
692 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
695 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
698 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
701 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
704 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
707 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
710 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
713 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
716 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
719 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
722 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
725 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
728 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
731 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
734 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
737 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
740 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
743 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
746 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
749 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
752 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
755 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
756 smapper.getI(1), smapper.popI());
759 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
760 smapper.getL(1), smapper.popL());
763 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
766 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
769 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
770 smapper.getI(1), smapper.popI());
773 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
774 smapper.getL(1), smapper.popL());
777 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
780 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
783 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
786 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
789 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
792 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
795 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
798 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
801 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
804 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
807 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
810 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
813 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
816 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
819 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
822 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
825 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
828 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
832 final int varIndx = wide ? readUShort(byteCodes, i++)
833 : readUByte(byteCodes, i);
835 final int incrBy = wide ? readShort(byteCodes, i++)
839 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
841 emit(smapper, this, "@1 += @2;",
842 lmapper.getI(varIndx),
843 Integer.toString(incrBy));
848 emit(smapper, this, "return;");
851 emit(smapper, this, "return @1;", smapper.popI());
854 emit(smapper, this, "return @1;", smapper.popL());
857 emit(smapper, this, "return @1;", smapper.popF());
860 emit(smapper, this, "return @1;", smapper.popD());
863 emit(smapper, this, "return @1;", smapper.popA());
866 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
869 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
872 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
875 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
879 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
882 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
885 smapper.replace(this, VarType.DOUBLE, "@1",
889 smapper.replace(this, VarType.FLOAT, "@1",
893 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
897 smapper.replace(this, VarType.LONG, "(@1).toLong()",
901 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
905 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
908 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
912 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
914 case opc_aconst_null:
915 smapper.assign(this, VarType.REFERENCE, "null");
918 smapper.assign(this, VarType.INTEGER, "-1");
921 smapper.assign(this, VarType.INTEGER, "0");
924 smapper.assign(this, VarType.DOUBLE, "0");
927 smapper.assign(this, VarType.LONG, "0");
930 smapper.assign(this, VarType.FLOAT, "0");
933 smapper.assign(this, VarType.INTEGER, "1");
936 smapper.assign(this, VarType.LONG, "1");
939 smapper.assign(this, VarType.FLOAT, "1");
942 smapper.assign(this, VarType.DOUBLE, "1");
945 smapper.assign(this, VarType.INTEGER, "2");
948 smapper.assign(this, VarType.FLOAT, "2");
951 smapper.assign(this, VarType.INTEGER, "3");
954 smapper.assign(this, VarType.INTEGER, "4");
957 smapper.assign(this, VarType.INTEGER, "5");
960 int indx = readUByte(byteCodes, ++i);
961 String v = encodeConstant(indx);
962 int type = VarType.fromConstantType(jc.getTag(indx));
963 smapper.assign(this, type, v);
968 int indx = readUShortArg(byteCodes, i);
970 String v = encodeConstant(indx);
971 int type = VarType.fromConstantType(jc.getTag(indx));
972 if (type == VarType.LONG) {
973 final Long lv = new Long(v);
974 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
975 final int hi = (int)(lv.longValue() >> 32);
977 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
979 smapper.assign(this, VarType.LONG,
980 "0x" + Integer.toHexString(hi) + ".next32(0x" +
981 Integer.toHexString(low) + ")"
985 smapper.assign(this, type, v);
990 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
994 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
995 smapper.popF(), smapper.popF(), smapper.pushI());
999 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
1000 smapper.popD(), smapper.popD(), smapper.pushI());
1003 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1004 "===", topMostLabel);
1007 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
1008 "!==", topMostLabel);
1011 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1012 "==", topMostLabel);
1015 int indx = i + readShortArg(byteCodes, i);
1016 emitIf(smapper, this, "if ((@1) == 0) ",
1017 smapper.popI(), i, indx, topMostLabel);
1022 int indx = i + readShortArg(byteCodes, i);
1023 emitIf(smapper, this, "if ((@1) != 0) ",
1024 smapper.popI(), i, indx, topMostLabel);
1029 int indx = i + readShortArg(byteCodes, i);
1030 emitIf(smapper, this, "if ((@1) < 0) ",
1031 smapper.popI(), i, indx, topMostLabel);
1036 int indx = i + readShortArg(byteCodes, i);
1037 emitIf(smapper, this, "if ((@1) <= 0) ",
1038 smapper.popI(), i, indx, topMostLabel);
1043 int indx = i + readShortArg(byteCodes, i);
1044 emitIf(smapper, this, "if ((@1) > 0) ",
1045 smapper.popI(), i, indx, topMostLabel);
1050 int indx = i + readShortArg(byteCodes, i);
1051 emitIf(smapper, this, "if ((@1) >= 0) ",
1052 smapper.popI(), i, indx, topMostLabel);
1056 case opc_ifnonnull: {
1057 int indx = i + readShortArg(byteCodes, i);
1058 emitIf(smapper, this, "if ((@1) !== null) ",
1059 smapper.popA(), i, indx, topMostLabel);
1064 int indx = i + readShortArg(byteCodes, i);
1065 emitIf(smapper, this, "if ((@1) === null) ",
1066 smapper.popA(), i, indx, topMostLabel);
1071 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1072 "!=", topMostLabel);
1075 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1079 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1080 "<=", topMostLabel);
1083 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1087 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1088 ">=", topMostLabel);
1091 smapper.flush(this);
1092 int indx = i + readShortArg(byteCodes, i);
1093 goTo(this, i, indx, topMostLabel);
1097 case opc_lookupswitch: {
1098 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1101 case opc_tableswitch: {
1102 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1105 case opc_invokeinterface: {
1106 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1109 case opc_invokevirtual:
1110 i = invokeVirtualMethod(byteCodes, i, smapper);
1112 case opc_invokespecial:
1113 i = invokeStaticMethod(byteCodes, i, smapper, false);
1115 case opc_invokestatic:
1116 i = invokeStaticMethod(byteCodes, i, smapper, true);
1118 case opc_invokedynamic: {
1119 int indx = readUShortArg(byteCodes, i);
1120 println("invoke dynamic: " + indx);
1121 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1122 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1123 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1124 println(" type: " + methodHandle.cpx1);
1125 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1126 String mcn = mangleClassName(mi[0]);
1127 char[] returnType = {'V'};
1128 StringBuilder cnt = new StringBuilder();
1129 String mn = findMethodName(mi, cnt, returnType);
1130 StringBuilder sb = new StringBuilder();
1131 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1132 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1133 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1134 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1135 sb.append(" mn : ").append(mn).append("\n");
1136 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1137 throw new IOException(sb.toString());
1139 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1140 String type = jc.StringValue(nameAndType.cpx2);
1141 String object = accessClass(mcn) + "(false)";
1142 if (mn.startsWith("cons_")) {
1143 object += ".constructor";
1145 append("var metHan = ");
1146 append(accessStaticMethod(object, mn, mi));
1148 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1150 append(", '").append(mi[1]).append("', ");
1151 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1152 append(methodType).append("'").append(type).append("', null)");
1153 // if (numArguments > 0) {
1155 // for (int j = 1; j < numArguments; ++j) {
1161 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1167 int indx = readUShortArg(byteCodes, i);
1168 String ci = jc.getClassName(indx);
1169 emit(smapper, this, "var @1 = new @2;",
1170 smapper.pushA(), accessClass(mangleClassName(ci)));
1176 int atype = readUByte(byteCodes, ++i);
1177 generateNewArray(atype, smapper);
1179 case opc_anewarray: {
1180 int type = readUShortArg(byteCodes, i);
1182 generateANewArray(type, smapper);
1185 case opc_multianewarray: {
1186 int type = readUShortArg(byteCodes, i);
1188 i = generateMultiANewArray(type, byteCodes, i, smapper);
1191 case opc_arraylength:
1192 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1195 emit(smapper, this, "Array.at(@3, @2, @1);",
1196 smapper.popL(), smapper.popI(), smapper.popA());
1199 emit(smapper, this, "Array.at(@3, @2, @1);",
1200 smapper.popF(), smapper.popI(), smapper.popA());
1203 emit(smapper, this, "Array.at(@3, @2, @1);",
1204 smapper.popD(), smapper.popI(), smapper.popA());
1207 emit(smapper, this, "Array.at(@3, @2, @1);",
1208 smapper.popA(), smapper.popI(), smapper.popA());
1214 emit(smapper, this, "Array.at(@3, @2, @1);",
1215 smapper.popI(), smapper.popI(), smapper.popA());
1218 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1219 smapper.popI(), smapper.getA(0));
1222 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1223 smapper.popI(), smapper.getA(0));
1226 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1227 smapper.popI(), smapper.getA(0));
1230 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1231 smapper.popI(), smapper.getA(0));
1237 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1238 smapper.popI(), smapper.getA(0));
1246 final Variable v = smapper.get(0);
1247 if (smapper.isDirty()) {
1248 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1250 smapper.assign(this, v.getType(), v);
1255 final Variable vi1 = smapper.get(0);
1257 if (vi1.isCategory2()) {
1258 emit(smapper, this, "var @1 = @2;",
1259 smapper.pushT(vi1.getType()), vi1);
1261 final Variable vi2 = smapper.get(1);
1262 emit(smapper, this, "var @1 = @2, @3 = @4;",
1263 smapper.pushT(vi2.getType()), vi2,
1264 smapper.pushT(vi1.getType()), vi1);
1269 final Variable vi1 = smapper.pop(this);
1270 final Variable vi2 = smapper.pop(this);
1271 final Variable vo3 = smapper.pushT(vi1.getType());
1272 final Variable vo2 = smapper.pushT(vi2.getType());
1273 final Variable vo1 = smapper.pushT(vi1.getType());
1275 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1276 vo1, vi1, vo2, vi2, vo3, vo1);
1280 final Variable vi1 = smapper.pop(this);
1281 final Variable vi2 = smapper.pop(this);
1283 if (vi1.isCategory2()) {
1284 final Variable vo3 = smapper.pushT(vi1.getType());
1285 final Variable vo2 = smapper.pushT(vi2.getType());
1286 final Variable vo1 = smapper.pushT(vi1.getType());
1288 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1289 vo1, vi1, vo2, vi2, vo3, vo1);
1291 final Variable vi3 = smapper.pop(this);
1292 final Variable vo5 = smapper.pushT(vi2.getType());
1293 final Variable vo4 = smapper.pushT(vi1.getType());
1294 final Variable vo3 = smapper.pushT(vi3.getType());
1295 final Variable vo2 = smapper.pushT(vi2.getType());
1296 final Variable vo1 = smapper.pushT(vi1.getType());
1298 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1299 vo1, vi1, vo2, vi2, vo3, vi3);
1300 emit(smapper, this, " @1 = @2, @3 = @4;",
1301 vo4, vo1, vo5, vo2);
1306 final Variable vi1 = smapper.pop(this);
1307 final Variable vi2 = smapper.pop(this);
1309 if (vi2.isCategory2()) {
1310 final Variable vo3 = smapper.pushT(vi1.getType());
1311 final Variable vo2 = smapper.pushT(vi2.getType());
1312 final Variable vo1 = smapper.pushT(vi1.getType());
1314 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1315 vo1, vi1, vo2, vi2, vo3, vo1);
1317 final Variable vi3 = smapper.pop(this);
1318 final Variable vo4 = smapper.pushT(vi1.getType());
1319 final Variable vo3 = smapper.pushT(vi3.getType());
1320 final Variable vo2 = smapper.pushT(vi2.getType());
1321 final Variable vo1 = smapper.pushT(vi1.getType());
1323 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1324 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1329 final Variable vi1 = smapper.pop(this);
1330 final Variable vi2 = smapper.pop(this);
1332 if (vi1.isCategory2()) {
1333 if (vi2.isCategory2()) {
1334 final Variable vo3 = smapper.pushT(vi1.getType());
1335 final Variable vo2 = smapper.pushT(vi2.getType());
1336 final Variable vo1 = smapper.pushT(vi1.getType());
1338 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1339 vo1, vi1, vo2, vi2, vo3, vo1);
1341 final Variable vi3 = smapper.pop(this);
1342 final Variable vo4 = smapper.pushT(vi1.getType());
1343 final Variable vo3 = smapper.pushT(vi3.getType());
1344 final Variable vo2 = smapper.pushT(vi2.getType());
1345 final Variable vo1 = smapper.pushT(vi1.getType());
1347 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1348 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1351 final Variable vi3 = smapper.pop(this);
1353 if (vi3.isCategory2()) {
1354 final Variable vo5 = smapper.pushT(vi2.getType());
1355 final Variable vo4 = smapper.pushT(vi1.getType());
1356 final Variable vo3 = smapper.pushT(vi3.getType());
1357 final Variable vo2 = smapper.pushT(vi2.getType());
1358 final Variable vo1 = smapper.pushT(vi1.getType());
1360 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1361 vo1, vi1, vo2, vi2, vo3, vi3);
1362 emit(smapper, this, " @1 = @2, @3 = @4;",
1363 vo4, vo1, vo5, vo2);
1365 final Variable vi4 = smapper.pop(this);
1366 final Variable vo6 = smapper.pushT(vi2.getType());
1367 final Variable vo5 = smapper.pushT(vi1.getType());
1368 final Variable vo4 = smapper.pushT(vi4.getType());
1369 final Variable vo3 = smapper.pushT(vi3.getType());
1370 final Variable vo2 = smapper.pushT(vi2.getType());
1371 final Variable vo1 = smapper.pushT(vi1.getType());
1373 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1374 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1375 emit(smapper, this, " @1 = @2, @3 = @4;",
1376 vo5, vo1, vo6, vo2);
1382 final Variable vi1 = smapper.get(0);
1383 final Variable vi2 = smapper.get(1);
1385 if (vi1.getType() == vi2.getType()) {
1386 final Variable tmp = smapper.pushT(vi1.getType());
1388 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1393 smapper.pushT(vi1.getType());
1394 smapper.pushT(vi2.getType());
1399 smapper.assign(this, VarType.INTEGER,
1400 "(" + Integer.toString(byteCodes[++i]) + ")");
1403 smapper.assign(this, VarType.INTEGER,
1404 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1408 case opc_getfield: {
1409 int indx = readUShortArg(byteCodes, i);
1410 String[] fi = jc.getFieldInfoName(indx);
1411 final int type = VarType.fromFieldType(fi[2].charAt(0));
1412 final String mangleClass = mangleClassName(fi[0]);
1413 final String mangleClassAccess = accessClassFalse(mangleClass);
1414 smapper.replace(this, type, "@2.call(@1)",
1416 accessField(mangleClassAccess,
1420 addReference(fi[0]);
1423 case opc_putfield: {
1424 int indx = readUShortArg(byteCodes, i);
1425 String[] fi = jc.getFieldInfoName(indx);
1426 final int type = VarType.fromFieldType(fi[2].charAt(0));
1427 final String mangleClass = mangleClassName(fi[0]);
1428 final String mangleClassAccess = accessClassFalse(mangleClass);
1429 emit(smapper, this, "@3.call(@2, @1);",
1432 accessField(mangleClassAccess,
1435 addReference(fi[0]);
1438 case opc_getstatic: {
1439 int indx = readUShortArg(byteCodes, i);
1440 String[] fi = jc.getFieldInfoName(indx);
1441 final int type = VarType.fromFieldType(fi[2].charAt(0));
1442 String ac = accessClassFalse(mangleClassName(fi[0]));
1443 String af = accessField(ac, "_" + fi[1], fi);
1444 smapper.assign(this, type, af + "()");
1446 addReference(fi[0]);
1449 case opc_putstatic: {
1450 int indx = readUShortArg(byteCodes, i);
1451 String[] fi = jc.getFieldInfoName(indx);
1452 final int type = VarType.fromFieldType(fi[2].charAt(0));
1453 emit(smapper, this, "@1._@2(@3);",
1454 accessClassFalse(mangleClassName(fi[0])), fi[1],
1455 smapper.popT(type));
1457 addReference(fi[0]);
1460 case opc_checkcast: {
1461 int indx = readUShortArg(byteCodes, i);
1462 generateCheckcast(indx, smapper);
1466 case opc_instanceof: {
1467 int indx = readUShortArg(byteCodes, i);
1468 generateInstanceOf(indx, smapper);
1473 final CharSequence v = smapper.popA();
1476 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1477 smapper.pushA(), v);
1481 case opc_monitorenter: {
1482 debug("/* monitor enter */");
1487 case opc_monitorexit: {
1488 debug("/* monitor exit */");
1499 emit(smapper, this, "throw 'unknown bytecode @1';",
1500 Integer.toString(c));
1504 generateByteCodeComment(prev, i, byteCodes);
1510 if (previousTrap != null) {
1511 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1516 while (openBraces-- > 0) {
1527 private int generateIf(StackMapper mapper, byte[] byteCodes,
1528 int i, final CharSequence v2, final CharSequence v1,
1529 final String test, int topMostLabel
1530 ) throws IOException {
1532 int indx = i + readShortArg(byteCodes, i);
1533 append("if ((").append(v1)
1534 .append(") ").append(test).append(" (")
1535 .append(v2).append(")) ");
1536 goTo(this, i, indx, topMostLabel);
1540 private int readInt4(byte[] byteCodes, int offset) {
1541 final int d = byteCodes[offset + 0] << 24;
1542 final int c = byteCodes[offset + 1] << 16;
1543 final int b = byteCodes[offset + 2] << 8;
1544 final int a = byteCodes[offset + 3];
1545 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1547 private static int readUByte(byte[] byteCodes, int offset) {
1548 return byteCodes[offset] & 0xff;
1551 private static int readUShort(byte[] byteCodes, int offset) {
1552 return ((byteCodes[offset] & 0xff) << 8)
1553 | (byteCodes[offset + 1] & 0xff);
1555 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1556 return readUShort(byteCodes, offsetInstruction + 1);
1559 private static int readShort(byte[] byteCodes, int offset) {
1560 int signed = byteCodes[offset];
1561 byte b0 = (byte)signed;
1562 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1564 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1565 return readShort(byteCodes, offsetInstruction + 1);
1568 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1570 Boolean count = null;
1571 boolean array = false;
1573 int firstPos = sig.length();
1574 while (i < descriptor.length()) {
1575 char ch = descriptor.charAt(i++);
1596 if (ch == 'J' || ch == 'D') {
1602 sig.insert(firstPos, ch);
1604 returnType[0] = '[';
1605 sig.insert(firstPos, "_3");
1614 returnType[0] = 'V';
1615 sig.insert(firstPos, 'V');
1618 int next = descriptor.indexOf(';', i);
1619 String realSig = mangleSig(descriptor, i - 1, next + 1);
1624 sig.append(realSig);
1627 sig.insert(firstPos, realSig);
1629 sig.insert(firstPos, "_3");
1631 returnType[0] = 'L';
1640 throw new IllegalStateException("Invalid char: " + ch);
1645 static String mangleSig(String sig) {
1646 return mangleSig(sig, 0, sig.length());
1649 private static String mangleMethodName(String name) {
1650 StringBuilder sb = new StringBuilder(name.length() * 2);
1651 int last = name.length();
1652 for (int i = 0; i < last; i++) {
1653 final char ch = name.charAt(i);
1655 case '_': sb.append("_1"); break;
1656 default: sb.append(ch); break;
1659 return sb.toString();
1661 private static String mangleSig(String txt, int first, int last) {
1662 StringBuilder sb = new StringBuilder((last - first) * 2);
1663 for (int i = first; i < last; i++) {
1664 final char ch = txt.charAt(i);
1666 case '/': sb.append('_'); break;
1667 case '_': sb.append("_1"); break;
1668 case ';': sb.append("_2"); break;
1669 case '[': sb.append("_3"); break;
1671 if (Character.isJavaIdentifierPart(ch)) {
1675 String hex = Integer.toHexString(ch).toLowerCase();
1676 for (int m = hex.length(); m < 4; m++) {
1684 return sb.toString();
1687 private static String mangleClassName(String name) {
1688 return mangleSig(name);
1691 private static String findMethodName(MethodData m, StringBuilder cnt) {
1692 StringBuilder name = new StringBuilder();
1693 if ("<init>".equals(m.getName())) { // NOI18N
1694 name.append("cons"); // NOI18N
1695 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1696 name.append("class"); // NOI18N
1698 name.append(mangleMethodName(m.getName()));
1701 countArgs(m.getInternalSig(), new char[1], name, cnt);
1702 return name.toString();
1705 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1706 StringBuilder name = new StringBuilder();
1707 String descr = mi[2];//mi.getDescriptor();
1709 if ("<init>".equals(nm)) { // NOI18N
1710 name.append("cons"); // NOI18N
1712 name.append(mangleMethodName(nm));
1714 countArgs(descr, returnType, name, cnt);
1715 return name.toString();
1718 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1719 throws IOException {
1720 int methodIndex = readUShortArg(byteCodes, i);
1721 String[] mi = jc.getFieldInfoName(methodIndex);
1722 char[] returnType = { 'V' };
1723 StringBuilder cnt = new StringBuilder();
1724 String mn = findMethodName(mi, cnt, returnType);
1726 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1727 final CharSequence[] vars = new CharSequence[numArguments];
1729 for (int j = numArguments - 1; j >= 0; --j) {
1730 vars[j] = mapper.popValue();
1734 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1735 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1737 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1738 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1740 if (vars[1] instanceof String) {
1741 String field = vars[1].toString();
1742 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1743 vars[1] = "c._" + field.substring(1, field.length() - 1);
1748 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1749 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1751 if (vars[1] instanceof String) {
1752 String field = vars[2].toString();
1753 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1754 vars[2] = "c._" + field.substring(1, field.length() - 1);
1759 if (returnType[0] != 'V') {
1762 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1766 final String in = mi[0];
1769 in.equals("org/apidesign/html/boot/spi/Fn") ||
1770 in.equals("org/netbeans/html/boot/spi/Fn")
1772 mcn = "java_lang_Class";
1774 mcn = mangleClassName(in);
1776 String object = accessClassFalse(mcn);
1777 if (mn.startsWith("cons_")) {
1778 object += ".constructor";
1780 append(accessStaticMethod(object, mn, mi));
1786 if (numArguments > 0) {
1788 for (int j = 1; j < numArguments; ++j) {
1798 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1799 throws IOException {
1800 int methodIndex = readUShortArg(byteCodes, i);
1801 String[] mi = jc.getFieldInfoName(methodIndex);
1802 char[] returnType = { 'V' };
1803 StringBuilder cnt = new StringBuilder();
1804 String mn = findMethodName(mi, cnt, returnType);
1806 final int numArguments = cnt.length() + 1;
1807 final CharSequence[] vars = new CharSequence[numArguments];
1809 for (int j = numArguments - 1; j >= 0; --j) {
1810 vars[j] = mapper.popValue();
1813 if (returnType[0] != 'V') {
1816 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1820 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1822 for (int j = 1; j < numArguments; ++j) {
1832 private void addReference(String cn) throws IOException {
1833 if (requireReference(cn)) {
1834 debug(" /* needs " + cn + " */");
1838 private void outType(String d, StringBuilder out) {
1840 while (d.charAt(0) == '[') {
1844 if (d.charAt(0) == 'L') {
1845 assert d.charAt(d.length() - 1) == ';';
1846 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1852 private String encodeConstant(int entryIndex) throws IOException {
1853 String[] classRef = { null };
1854 String s = jc.stringValue(entryIndex, classRef);
1855 if (classRef[0] != null) {
1856 if (classRef[0].startsWith("[")) {
1857 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1859 addReference(classRef[0]);
1860 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1866 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1867 byte[] arr = m.findAnnotationData(true);
1871 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1872 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1873 class P extends AnnotationParser {
1879 String[] args = new String[30];
1885 protected void visitAttr(String type, String attr, String at, String value) {
1886 if (type.equals(jvmType)) {
1887 if ("body".equals(attr)) {
1889 } else if ("args".equals(attr)) {
1890 args[cnt++] = value;
1892 throw new IllegalArgumentException(attr);
1895 if (type.equals(htmlType)) {
1897 if ("body".equals(attr)) {
1899 } else if ("args".equals(attr)) {
1900 args[cnt++] = value;
1901 } else if ("javacall".equals(attr)) {
1902 javacall = "1".equals(value);
1903 } else if ("wait4js".equals(attr)) {
1904 // ignore, we always invoke synchronously
1906 throw new IllegalArgumentException(attr);
1913 if (p.body == null) {
1916 StringBuilder cnt = new StringBuilder();
1917 final String mn = findMethodName(m, cnt);
1918 append("m = ").append(destObject).append(".").append(mn);
1919 append(" = function(");
1922 StringBuilder toValue = new StringBuilder();
1923 for (int i = 0; i < cnt.length(); i++) {
1925 space = outputArg(this, p.args, index);
1926 if (p.html4j && space.length() > 0) {
1927 toValue.append("\n ").append(p.args[index]).append(" = ")
1928 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1929 append(p.args[index]).append(");");
1933 append(") {").append("\n");
1934 append(toValue.toString());
1936 int lastSlash = jc.getClassName().lastIndexOf('/');
1937 final String pkg = jc.getClassName().substring(0, lastSlash);
1938 append(mangleCallbacks(pkg, p.body));
1939 requireReference(pkg + "/$JsCallbacks$");
1947 private static CharSequence mangleCallbacks(String pkgName, String body) {
1948 StringBuilder sb = new StringBuilder();
1951 int next = body.indexOf(".@", pos);
1953 sb.append(body.substring(pos));
1954 body = sb.toString();
1959 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1964 String refId = body.substring(ident, next);
1966 sb.append(body.substring(pos, ident));
1968 int sigBeg = body.indexOf('(', next);
1969 int sigEnd = body.indexOf(')', sigBeg);
1970 int colon4 = body.indexOf("::", next);
1971 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1972 throw new IllegalStateException("Malformed body " + body);
1974 String fqn = body.substring(next + 2, colon4);
1975 String method = body.substring(colon4 + 2, sigBeg);
1976 String params = body.substring(sigBeg, sigEnd + 1);
1978 int paramBeg = body.indexOf('(', sigEnd + 1);
1980 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1981 sb.append(mangleJsCallbacks(fqn, method, params, false));
1982 sb.append("(").append(refId);
1983 if (body.charAt(paramBeg + 1) != ')') {
1991 int next = body.indexOf("@", pos);
1996 sb.append(body.substring(pos));
2000 sb = new StringBuilder();
2003 sb.append(body.substring(pos, next));
2005 int sigBeg = body.indexOf('(', next);
2006 int sigEnd = body.indexOf(')', sigBeg);
2007 int colon4 = body.indexOf("::", next);
2008 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
2009 throw new IllegalStateException("Malformed body " + body);
2011 String fqn = body.substring(next + 1, colon4);
2012 String method = body.substring(colon4 + 2, sigBeg);
2013 String params = body.substring(sigBeg, sigEnd + 1);
2015 int paramBeg = body.indexOf('(', sigEnd + 1);
2017 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2018 sb.append(mangleJsCallbacks(fqn, method, params, true));
2024 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2025 if (params.startsWith("(")) {
2026 params = params.substring(1);
2028 if (params.endsWith(")")) {
2029 params = params.substring(0, params.length() - 1);
2031 StringBuilder sb = new StringBuilder();
2032 final String fqnu = fqn.replace('.', '_');
2033 final String rfqn = mangleClassName(fqnu);
2034 final String rm = mangleMethodName(method);
2037 StringBuilder pb = new StringBuilder();
2038 int len = params.length();
2040 while (indx < len) {
2041 char ch = params.charAt(indx);
2042 if (ch == '[' || ch == 'L') {
2043 int column = params.indexOf(';', indx) + 1;
2044 if (column > indx) {
2045 String real = params.substring(indx, column);
2046 if ("Ljava/lang/String;".equals(real)) {
2047 pb.append("Ljava/lang/String;");
2052 pb.append("Ljava/lang/Object;");
2059 srp = mangleSig(pb.toString());
2061 final String rp = mangleSig(params);
2062 final String mrp = mangleMethodName(rp);
2063 sb.append(rfqn).append("$").append(rm).
2064 append('$').append(mrp).append("__Ljava_lang_Object_2");
2066 sb.append('L').append(fqnu).append("_2");
2069 return sb.toString();
2072 private static String className(ClassData jc) {
2073 //return jc.getName().getInternalName().replace('/', '_');
2074 return mangleClassName(jc.getClassName());
2077 private static String[] findAnnotation(
2078 byte[] arr, ClassData cd, final String className,
2079 final String... attrNames
2080 ) throws IOException {
2084 final String[] values = new String[attrNames.length];
2085 final boolean[] found = { false };
2086 final String jvmType = "L" + className.replace('.', '/') + ";";
2087 AnnotationParser ap = new AnnotationParser(false, true) {
2089 protected void visitAttr(String type, String attr, String at, String value) {
2090 if (type.equals(jvmType)) {
2092 for (int i = 0; i < attrNames.length; i++) {
2093 if (attrNames[i].equals(attr)) {
2102 return found[0] ? values : null;
2105 private CharSequence initField(FieldData v) {
2106 final String is = v.getInternalSig();
2107 if (is.length() == 1) {
2108 switch (is.charAt(0)) {
2114 case 'I': return " = 0;";
2116 case 'D': return " = 0.0;";
2118 throw new IllegalStateException(is);
2124 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2125 AnnotationParser ap = new AnnotationParser(true, false) {
2126 int[] cnt = new int[32];
2130 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2131 final String slashType = attrType.substring(1, attrType.length() - 1);
2132 requireReference(slashType);
2134 if (cnt[depth]++ > 0) {
2138 append('"').append(attrType).append("\" : ");
2145 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2151 protected void visitValueStart(String attrName, char type) throws IOException {
2152 if (cnt[depth]++ > 0) {
2156 if (attrName != null) {
2157 append('"').append(attrName).append("\" : ");
2165 protected void visitValueEnd(String attrName, char type) throws IOException {
2173 protected void visitAttr(String type, String attr, String attrType, String value)
2174 throws IOException {
2175 if (attr == null && value == null) {
2182 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2183 throws IOException {
2184 final String slashType = attrType.substring(1, attrType.length() - 1);
2185 requireReference(slashType);
2187 final String cn = mangleClassName(slashType);
2188 append(accessClassFalse(cn))
2189 .append("['valueOf__L").
2191 append("_2Ljava_lang_String_2']('").
2199 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2200 final String name = args[indx];
2204 if (name.contains(",")) {
2205 throw new IOException("Wrong parameter with ',': " + name);
2211 final void emitNoFlush(
2213 final String format, final CharSequence... params
2214 ) throws IOException {
2215 emitImpl(this, format, params);
2217 static final void emit(
2219 final Appendable out,
2220 final String format, final CharSequence... params
2221 ) throws IOException {
2223 emitImpl(out, format, params);
2225 static void emitImpl(final Appendable out,
2226 final String format,
2227 final CharSequence... params) throws IOException {
2228 final int length = format.length();
2231 int paramOffset = format.indexOf('@');
2232 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2233 final char paramChar = format.charAt(paramOffset + 1);
2234 if ((paramChar >= '1') && (paramChar <= '9')) {
2235 final int paramIndex = paramChar - '0' - 1;
2237 out.append(format, processed, paramOffset);
2238 out.append(params[paramIndex]);
2241 processed = paramOffset + 1;
2244 paramOffset = format.indexOf('@', paramOffset + 1);
2247 out.append(format, processed, length);
2250 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2251 append("} catch (e) {\n");
2253 for (TrapData e : traps) {
2257 if (e.catch_cpx != 0) { //not finally
2258 final String classInternalName = jc.getClassName(e.catch_cpx);
2259 addReference(classInternalName);
2260 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2261 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2262 append("var stA0 = e;");
2263 goTo(this, current, e.handler_pc, topMostLabel);
2266 finallyPC = e.handler_pc;
2269 if (finallyPC == -1) {
2272 append("var stA0 = e;");
2273 goTo(this, current, finallyPC, topMostLabel);
2278 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2281 out.append("{ gt = 0; continue X_" + to + "; }");
2283 out.append("{ gt = " + to + "; continue X_0; }");
2286 out.append("{ gt = " + to + "; break IF; }");
2290 private static void emitIf(
2292 Appendable out, String pattern,
2294 int current, int to, int canBack
2295 ) throws IOException {
2297 emitImpl(out, pattern, param);
2298 goTo(out, current, to, canBack);
2301 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2304 case 4: jvmType = "[Z"; break;
2305 case 5: jvmType = "[C"; break;
2306 case 6: jvmType = "[F"; break;
2307 case 7: jvmType = "[D"; break;
2308 case 8: jvmType = "[B"; break;
2309 case 9: jvmType = "[S"; break;
2310 case 10: jvmType = "[I"; break;
2311 case 11: jvmType = "[J"; break;
2312 default: throw new IllegalStateException("Array type: " + atype);
2315 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2316 smapper.popI(), smapper.pushA(), jvmType);
2319 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2320 String typeName = jc.getClassName(type);
2321 String ref = "null";
2322 if (typeName.startsWith("[")) {
2323 typeName = "'[" + typeName + "'";
2325 ref = "vm." + mangleClassName(typeName);
2326 typeName = "'[L" + typeName + ";'";
2329 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2330 smapper.popI(), smapper.pushA(), typeName, ref);
2333 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2334 String typeName = jc.getClassName(type);
2335 int dim = readUByte(byteCodes, ++i);
2336 StringBuilder dims = new StringBuilder();
2338 for (int d = 0; d < dim; d++) {
2340 dims.insert(1, ",");
2342 dims.insert(1, smapper.popI());
2346 if (typeName.charAt(dim) == 'L') {
2347 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2350 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2351 dims.toString(), smapper.pushA(), typeName, fn
2356 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2357 int table = i / 4 * 4 + 4;
2358 int dflt = i + readInt4(byteCodes, table);
2360 int low = readInt4(byteCodes, table);
2362 int high = readInt4(byteCodes, table);
2364 final CharSequence swVar = smapper.popValue();
2365 smapper.flush(this);
2366 append("switch (").append(swVar).append(") {\n");
2367 while (low <= high) {
2368 int offset = i + readInt4(byteCodes, table);
2370 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2373 append(" default: ");
2374 goTo(this, i, dflt, topMostLabel);
2380 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2381 int table = i / 4 * 4 + 4;
2382 int dflt = i + readInt4(byteCodes, table);
2384 int n = readInt4(byteCodes, table);
2386 final CharSequence swVar = smapper.popValue();
2387 smapper.flush(this);
2388 append("switch (").append(swVar).append(") {\n");
2390 int cnstnt = readInt4(byteCodes, table);
2392 int offset = i + readInt4(byteCodes, table);
2394 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2396 append(" default: ");
2397 goTo(this, i, dflt, topMostLabel);
2403 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2404 String type = jc.getClassName(indx);
2405 if (!type.startsWith("[")) {
2407 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2408 smapper.popA(), smapper.pushI(),
2409 type.replace('/', '_'));
2412 while (type.charAt(cnt) == '[') {
2415 if (type.charAt(cnt) == 'L') {
2416 String component = type.substring(cnt + 1, type.length() - 1);
2417 requireReference(component);
2418 type = "vm." + mangleClassName(component);
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 String component = type.substring(cnt + 1, type.length() - 1);
2446 requireReference(component);
2447 type = "vm." + mangleClassName(component);
2448 emitNoFlush(smapper,
2449 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2450 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2453 emitNoFlush(smapper,
2454 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2455 smapper.getT(0, VarType.REFERENCE, false), type
2461 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2462 for (int j = prev; j <= i; j++) {
2464 final int cc = readUByte(byteCodes, j);
2465 append(Integer.toString(cc));
2469 @JavaScriptBody(args = "msg", body = "")
2470 private static void println(String msg) {
2471 System.err.println(msg);