Generate the ClassCastException via java.lang.Class as that one is always known to be exported
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 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 boolean outChanged;
33 private boolean callbacks;
35 protected ByteCodeToJavaScript(Appendable out) {
40 public final Appendable append(CharSequence csq) throws IOException {
47 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
48 out.append(csq, start, end);
54 public final Appendable append(char c) throws IOException {
60 /* Collects additional required resources.
62 * @param internalClassName classes that were referenced and should be loaded in order the
63 * generated JavaScript code works properly. The names are in internal
64 * JVM form so String is <code>java/lang/String</code>.
66 protected abstract boolean requireReference(String internalClassName);
69 * @param resourcePath name of resources to read
71 protected abstract void requireScript(String resourcePath) throws IOException;
73 protected abstract void requireResource(String resourcePath) throws IOException;
75 /** Allows subclasses to redefine what field a function representing a
76 * class gets assigned. By default it returns the suggested name followed
77 * by <code>" = "</code>;
79 * @param className suggested name of the class
81 /* protected */ String assignClass(String className) {
82 return className + " = ";
84 /* protected */ String accessClass(String classOperation) {
85 return classOperation;
88 protected String accessField(String object, String mangledName,
89 String[] fieldInfoName) throws IOException {
90 return object + "." + mangledName;
93 protected String accessStaticMethod(
96 String[] fieldInfoName) throws IOException {
97 return object + "." + mangledName;
100 protected String accessVirtualMethod(
103 String[] fieldInfoName,
105 ) throws IOException {
106 return object + "." + mangledName + '(';
109 protected void declaredClass(ClassData classData, String mangledName)
113 protected void declaredField(FieldData fieldData,
115 String mangledName) throws IOException {
118 protected void declaredMethod(MethodData methodData,
120 String mangledName) throws IOException {
123 /** Prints out a debug message.
125 * @param msg the message
126 * @return true if the message has been printed
127 * @throws IOException
129 boolean debug(String msg) throws IOException {
135 * Converts a given class file to a JavaScript version.
137 * @param classFile input stream with code of the .class file
138 * @return the initialization code for this class, if any. Otherwise <code>null</code>
140 * @throws IOException if something goes wrong during read or write or translating
143 public String compile(InputStream classFile) throws IOException {
144 return compile(new ClassData(classFile));
147 protected String compile(ClassData classData) throws IOException {
149 final String cn = this.jc.getClassName();
150 this.callbacks = cn.endsWith("/$JsCallbacks$");
151 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
152 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
153 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
156 byte[] arrData = jc.findAnnotationData(true);
158 String[] arr = findAnnotation(arrData, jc,
159 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
160 "resource", "processByteCode"
163 if (!arr[0].isEmpty()) {
164 requireScript(arr[0]);
166 if ("0".equals(arr[1])) {
171 final String jsResource;
173 String[] arr = findAnnotation(arrData, jc,
174 "net.java.html.js.JavaScriptResource",
178 if (arr[0].startsWith("/")) {
181 int last = cn.lastIndexOf('/');
182 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
188 String[] proto = findAnnotation(arrData, jc,
189 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
190 "container", "prototype"
192 StringArray toInitilize = new StringArray();
193 final String className = className(jc);
194 append("\n\n").append(assignClass(className));
195 append("function ").append(className).append("() {");
197 append("\n var CLS = ").append(className).append(';');
198 append("\n if (!CLS.$class) {");
200 String sc = jc.getSuperClassName(); // with _
201 append("\n var pp = ").
202 append(accessClass(mangleClassName(sc))).append("(true);");
203 append("\n var p = CLS.prototype = pp;");
204 append("\n var c = p;");
205 append("\n var sprcls = pp.constructor.$class;");
207 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
208 if (proto[0] == null) {
211 append("\n var c = ").append(proto[0]).append(";");
212 append("\n var sprcls = null;");
214 for (FieldData v : jc.getFields()) {
216 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
217 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
221 append("\n CLS.fld_").append(v.getName()).append(initField(v));
222 append("\n m = c._").append(v.getName()).append(" = function (v) {")
223 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
224 .append(" = v; return CLS.fld_").
225 append(v.getName()).append("; };");
227 append("\n m = c._").append(v.getName()).append(" = function (v) {")
228 .append(" if (arguments.length == 1) this.fld_").
229 append(className).append('_').append(v.getName())
230 .append(" = v; return this.fld_").
231 append(className).append('_').append(v.getName())
235 declaredField(v, "c", "_" + v.getName());
237 for (MethodData m : jc.getMethods()) {
238 byte[] onlyArr = m.findAnnotationData(true);
239 if (javaScriptOnly(onlyArr)) continue;
245 mn = generateStaticMethod(destObject, m, toInitilize);
247 if (m.isConstructor()) {
249 mn = generateInstanceMethod(destObject, m);
252 mn = generateInstanceMethod(destObject, m);
255 declaredMethod(m, destObject, mn);
256 byte[] runAnno = m.findAnnotationData(false);
257 if (runAnno != null) {
258 append("\n m.anno = {");
259 generateAnno(jc, runAnno);
262 append("\n m.access = " + m.getAccess()).append(";");
263 append("\n m.cls = CLS;");
265 append("\n c.constructor = CLS;");
266 append("\n function ").append(className).append("fillInstOf(x) {");
267 String instOfName = "$instOf_" + className;
268 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
269 if (jc.isInterface()) {
270 for (MethodData m : jc.getMethods()) {
271 if ((m.getAccess() & ACC_ABSTRACT) == 0
272 && (m.getAccess() & ACC_STATIC) == 0
273 && (m.getAccess() & ACC_PRIVATE) == 0) {
274 final String mn = findMethodName(m, new StringBuilder());
276 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
277 append("\n } catch (ignore) {");
282 for (String superInterface : jc.getSuperInterfaces()) {
283 String intrfc = superInterface.replace('/', '_');
284 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
285 requireReference(superInterface);
289 append("\n Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
290 append("\n ").append(className).append("fillInstOf(c);");
291 append("\n } catch (ignore) {");
293 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
294 append("\n CLS.$class = 'temp';");
295 append("\n CLS.$class = ");
296 append(accessClass("java_lang_Class(true);"));
297 append("\n CLS.$class.jvmName = '").append(cn).append("';");
298 append("\n CLS.$class.superclass = sprcls;");
299 append("\n CLS.$class.interfaces = function() { return [");
301 boolean first = true;
302 for (String intrfc : jc.getSuperInterfaces()) {
306 requireReference(intrfc);
307 String mangledIface = mangleClassName(intrfc);
309 append(accessClass(mangledIface)).append("(false).constructor.$class");
314 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
315 append("\n CLS.$class.cnstr = CLS;");
316 byte[] classAnno = jc.findAnnotationData(false);
317 if (classAnno != null) {
318 append("\n CLS.$class.anno = {");
319 generateAnno(jc, classAnno);
322 for (String init : toInitilize.toArray()) {
323 append("\n ").append(init).append("();");
326 if (jsResource != null) {
327 requireResource(jsResource);
331 append("\n if (arguments.length === 0) {");
332 append("\n if (!(this instanceof CLS)) {");
333 append("\n return new CLS();");
335 for (FieldData v : jc.getFields()) {
336 byte[] onlyArr = v.findAnnotationData(true);
337 if (javaScriptOnly(onlyArr)) continue;
339 append("\n this.fld_").
340 append(className).append('_').
341 append(v.getName()).append(initField(v));
344 append("\n return this;");
346 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
349 declaredClass(jc, className);
351 // StringBuilder sb = new StringBuilder();
352 // for (String init : toInitilize.toArray()) {
353 // sb.append("\n").append(init).append("();");
358 private boolean javaScriptOnly(byte[] anno) throws IOException {
359 String[] only = findAnnotation(anno, jc,
360 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
364 if (only[0] != null && only[1] != null) {
365 append("\n p.").append(only[0]).append(" = ")
366 .append(only[1]).append(";");
368 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
369 append("\n p['").append(only[0]).append("'] = p.")
370 .append(only[0]).append(";");
376 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
377 String jsb = javaScriptBody(destObject, m, true);
381 final String mn = findMethodName(m, new StringBuilder());
382 boolean defineProp = generateMethod(destObject, mn, m);
383 if (mn.equals("class__V")) {
385 toInitilize.add(accessClass(className(jc)) + "(false)['" + mn + "']");
387 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
393 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
394 String jsb = javaScriptBody(destObject, m, false);
398 final String mn = findMethodName(m, new StringBuilder());
399 generateMethod(destObject, mn, m);
403 private boolean generateMethod(String destObject, String name, MethodData m)
405 final StackMapIterator stackMapIterator = m.createStackMapIterator();
406 TrapDataIterator trap = m.getTrapDataIterator();
407 final LocalsMapper lmapper =
408 new LocalsMapper(stackMapIterator.getArguments());
411 "java/lang/Object".equals(jc.getClassName()) ||
412 "java/lang/reflect/Array".equals(jc.getClassName());
415 append("Object.defineProperty(").append(destObject).
416 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
418 append("m = ").append(destObject).append(".").append(name).append(" = function(");
420 lmapper.outputArguments(this, m.isStatic());
421 append(") {").append("\n");
423 final byte[] byteCodes = m.getCode();
424 if (byteCodes == null) {
425 append(" throw 'no code found for ")
426 .append(jc.getClassName()).append('.')
427 .append(m.getName()).append("';\n");
436 final StackMapper smapper = new StackMapper();
439 append(" var ").append(" lcA0 = this;\n");
443 TrapData[] previousTrap = null;
444 boolean wide = false;
446 if (stackMapIterator.isEmpty()) {
452 append("\n var gt = 0;\n");
456 int topMostLabel = 0;
457 for (int i = 0; i < byteCodes.length; i++) {
460 stackMapIterator.advanceTo(i);
461 boolean changeInCatch = trap.advanceTo(i);
462 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
463 if (previousTrap != null) {
464 generateCatch(previousTrap, i, topMostLabel);
468 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
473 if (openBraces > 64) {
474 for (int c = 0; c < 64; c++) {
481 lastStackFrame = stackMapIterator.getFrameIndex();
482 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
483 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
484 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
486 changeInCatch = true;
488 debug(" /* " + i + " */ ");
490 if (changeInCatch && trap.useTry()) {
492 previousTrap = trap.current();
494 final int c = readUByte(byteCodes, i);
497 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
500 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
503 smapper.assign(this, VarType.LONG, lmapper.getL(0));
506 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
509 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
512 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
515 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
518 smapper.assign(this, VarType.LONG, lmapper.getL(1));
521 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
524 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
527 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
530 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
533 smapper.assign(this, VarType.LONG, lmapper.getL(2));
536 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
539 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
542 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
545 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
548 smapper.assign(this, VarType.LONG, lmapper.getL(3));
551 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
554 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
558 final int indx = wide ? readUShort(byteCodes, i++)
559 : readUByte(byteCodes, i);
561 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
566 final int indx = wide ? readUShort(byteCodes, i++)
567 : readUByte(byteCodes, i);
569 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
574 final int indx = wide ? readUShort(byteCodes, i++)
575 : readUByte(byteCodes, i);
577 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
582 final int indx = wide ? readUShort(byteCodes, i++)
583 : readUByte(byteCodes, i);
585 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
590 final int indx = wide ? readUShort(byteCodes, i++)
591 : readUByte(byteCodes, i);
593 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
598 final int indx = wide ? readUShort(byteCodes, i++)
599 : readUByte(byteCodes, i);
601 emit(smapper, this, "var @1 = @2;",
602 lmapper.setI(indx), smapper.popI());
607 final int indx = wide ? readUShort(byteCodes, i++)
608 : readUByte(byteCodes, i);
610 emit(smapper, this, "var @1 = @2;",
611 lmapper.setL(indx), smapper.popL());
616 final int indx = wide ? readUShort(byteCodes, i++)
617 : readUByte(byteCodes, i);
619 emit(smapper, this, "var @1 = @2;",
620 lmapper.setF(indx), smapper.popF());
625 final int indx = wide ? readUShort(byteCodes, i++)
626 : readUByte(byteCodes, i);
628 emit(smapper, this, "var @1 = @2;",
629 lmapper.setD(indx), smapper.popD());
634 final int indx = wide ? readUShort(byteCodes, i++)
635 : readUByte(byteCodes, i);
637 emit(smapper, this, "var @1 = @2;",
638 lmapper.setA(indx), smapper.popA());
642 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
645 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
648 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
651 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
654 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
657 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
660 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
663 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
666 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
669 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
672 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
675 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
678 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
681 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
684 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
687 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
690 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
693 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
696 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
699 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
702 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
705 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
708 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
711 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
714 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
717 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
720 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
723 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
726 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
729 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
732 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
735 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
738 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
739 smapper.getI(1), smapper.popI());
742 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
743 smapper.getL(1), smapper.popL());
746 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
749 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
752 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
753 smapper.getI(1), smapper.popI());
756 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
757 smapper.getL(1), smapper.popL());
760 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
763 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
766 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
769 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
772 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
775 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
778 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
781 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
784 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
787 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
790 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
793 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
796 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
799 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
802 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
805 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
808 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
811 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
815 final int varIndx = wide ? readUShort(byteCodes, i++)
816 : readUByte(byteCodes, i);
818 final int incrBy = wide ? readShort(byteCodes, i++)
822 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
824 emit(smapper, this, "@1 += @2;",
825 lmapper.getI(varIndx),
826 Integer.toString(incrBy));
831 emit(smapper, this, "return;");
834 emit(smapper, this, "return @1;", smapper.popI());
837 emit(smapper, this, "return @1;", smapper.popL());
840 emit(smapper, this, "return @1;", smapper.popF());
843 emit(smapper, this, "return @1;", smapper.popD());
846 emit(smapper, this, "return @1;", smapper.popA());
849 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
852 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
855 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
858 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
862 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
865 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
868 smapper.replace(this, VarType.DOUBLE, "@1",
872 smapper.replace(this, VarType.FLOAT, "@1",
876 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
880 smapper.replace(this, VarType.LONG, "(@1).toLong()",
884 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
888 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
891 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
895 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
897 case opc_aconst_null:
898 smapper.assign(this, VarType.REFERENCE, "null");
901 smapper.assign(this, VarType.INTEGER, "-1");
904 smapper.assign(this, VarType.INTEGER, "0");
907 smapper.assign(this, VarType.DOUBLE, "0");
910 smapper.assign(this, VarType.LONG, "0");
913 smapper.assign(this, VarType.FLOAT, "0");
916 smapper.assign(this, VarType.INTEGER, "1");
919 smapper.assign(this, VarType.LONG, "1");
922 smapper.assign(this, VarType.FLOAT, "1");
925 smapper.assign(this, VarType.DOUBLE, "1");
928 smapper.assign(this, VarType.INTEGER, "2");
931 smapper.assign(this, VarType.FLOAT, "2");
934 smapper.assign(this, VarType.INTEGER, "3");
937 smapper.assign(this, VarType.INTEGER, "4");
940 smapper.assign(this, VarType.INTEGER, "5");
943 int indx = readUByte(byteCodes, ++i);
944 String v = encodeConstant(indx);
945 int type = VarType.fromConstantType(jc.getTag(indx));
946 smapper.assign(this, type, v);
951 int indx = readUShortArg(byteCodes, i);
953 String v = encodeConstant(indx);
954 int type = VarType.fromConstantType(jc.getTag(indx));
955 if (type == VarType.LONG) {
956 final Long lv = new Long(v);
957 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
958 final int hi = (int)(lv.longValue() >> 32);
960 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
962 smapper.assign(this, VarType.LONG,
963 "0x" + Integer.toHexString(hi) + ".next32(0x" +
964 Integer.toHexString(low) + ")"
968 smapper.assign(this, type, v);
973 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
977 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
981 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
984 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
985 "===", topMostLabel);
988 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
989 "!==", topMostLabel);
992 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
996 int indx = i + readShortArg(byteCodes, i);
997 emitIf(smapper, this, "if ((@1) == 0) ",
998 smapper.popI(), i, indx, topMostLabel);
1003 int indx = i + readShortArg(byteCodes, i);
1004 emitIf(smapper, this, "if ((@1) != 0) ",
1005 smapper.popI(), i, indx, topMostLabel);
1010 int indx = i + readShortArg(byteCodes, i);
1011 emitIf(smapper, this, "if ((@1) < 0) ",
1012 smapper.popI(), i, indx, 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);
1037 case opc_ifnonnull: {
1038 int indx = i + readShortArg(byteCodes, i);
1039 emitIf(smapper, this, "if ((@1) !== null) ",
1040 smapper.popA(), i, indx, topMostLabel);
1045 int indx = i + readShortArg(byteCodes, i);
1046 emitIf(smapper, this, "if ((@1) === null) ",
1047 smapper.popA(), i, indx, topMostLabel);
1052 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1053 "!=", topMostLabel);
1056 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1060 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1061 "<=", topMostLabel);
1064 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1068 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1069 ">=", topMostLabel);
1072 smapper.flush(this);
1073 int indx = i + readShortArg(byteCodes, i);
1074 goTo(this, i, indx, topMostLabel);
1078 case opc_lookupswitch: {
1079 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1082 case opc_tableswitch: {
1083 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1086 case opc_invokeinterface: {
1087 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1090 case opc_invokevirtual:
1091 i = invokeVirtualMethod(byteCodes, i, smapper);
1093 case opc_invokespecial:
1094 i = invokeStaticMethod(byteCodes, i, smapper, false);
1096 case opc_invokestatic:
1097 i = invokeStaticMethod(byteCodes, i, smapper, true);
1099 case opc_invokedynamic: {
1100 int indx = readUShortArg(byteCodes, i);
1101 println("invoke dynamic: " + indx);
1102 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1103 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1104 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1105 println(" type: " + methodHandle.cpx1);
1106 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1107 String mcn = mangleClassName(mi[0]);
1108 char[] returnType = {'V'};
1109 StringBuilder cnt = new StringBuilder();
1110 String mn = findMethodName(mi, cnt, returnType);
1111 StringBuilder sb = new StringBuilder();
1112 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1113 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1114 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1115 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1116 sb.append(" mn : ").append(mn).append("\n");
1117 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1118 throw new IOException(sb.toString());
1120 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1121 String type = jc.StringValue(nameAndType.cpx2);
1122 String object = accessClass(mcn) + "(false)";
1123 if (mn.startsWith("cons_")) {
1124 object += ".constructor";
1126 append("var metHan = ");
1127 append(accessStaticMethod(object, mn, mi));
1129 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1131 append(", '").append(mi[1]).append("', ");
1132 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1133 append(methodType).append("'").append(type).append("', null)");
1134 // if (numArguments > 0) {
1136 // for (int j = 1; j < numArguments; ++j) {
1142 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1148 int indx = readUShortArg(byteCodes, i);
1149 String ci = jc.getClassName(indx);
1150 emit(smapper, this, "var @1 = new @2;",
1151 smapper.pushA(), accessClass(mangleClassName(ci)));
1157 int atype = readUByte(byteCodes, ++i);
1158 generateNewArray(atype, smapper);
1160 case opc_anewarray: {
1161 int type = readUShortArg(byteCodes, i);
1163 generateANewArray(type, smapper);
1166 case opc_multianewarray: {
1167 int type = readUShortArg(byteCodes, i);
1169 i = generateMultiANewArray(type, byteCodes, i, smapper);
1172 case opc_arraylength:
1173 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1176 emit(smapper, this, "Array.at(@3, @2, @1);",
1177 smapper.popL(), smapper.popI(), smapper.popA());
1180 emit(smapper, this, "Array.at(@3, @2, @1);",
1181 smapper.popF(), smapper.popI(), smapper.popA());
1184 emit(smapper, this, "Array.at(@3, @2, @1);",
1185 smapper.popD(), smapper.popI(), smapper.popA());
1188 emit(smapper, this, "Array.at(@3, @2, @1);",
1189 smapper.popA(), smapper.popI(), smapper.popA());
1195 emit(smapper, this, "Array.at(@3, @2, @1);",
1196 smapper.popI(), smapper.popI(), smapper.popA());
1199 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1200 smapper.popI(), smapper.getA(0));
1203 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1204 smapper.popI(), smapper.getA(0));
1207 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1208 smapper.popI(), smapper.getA(0));
1211 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1212 smapper.popI(), smapper.getA(0));
1218 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1219 smapper.popI(), smapper.getA(0));
1227 final Variable v = smapper.get(0);
1228 if (smapper.isDirty()) {
1229 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1231 smapper.assign(this, v.getType(), v);
1236 final Variable vi1 = smapper.get(0);
1238 if (vi1.isCategory2()) {
1239 emit(smapper, this, "var @1 = @2;",
1240 smapper.pushT(vi1.getType()), vi1);
1242 final Variable vi2 = smapper.get(1);
1243 emit(smapper, this, "var @1 = @2, @3 = @4;",
1244 smapper.pushT(vi2.getType()), vi2,
1245 smapper.pushT(vi1.getType()), vi1);
1250 final Variable vi1 = smapper.pop(this);
1251 final Variable vi2 = smapper.pop(this);
1252 final Variable vo3 = smapper.pushT(vi1.getType());
1253 final Variable vo2 = smapper.pushT(vi2.getType());
1254 final Variable vo1 = smapper.pushT(vi1.getType());
1256 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1257 vo1, vi1, vo2, vi2, vo3, vo1);
1261 final Variable vi1 = smapper.pop(this);
1262 final Variable vi2 = smapper.pop(this);
1264 if (vi1.isCategory2()) {
1265 final Variable vo3 = smapper.pushT(vi1.getType());
1266 final Variable vo2 = smapper.pushT(vi2.getType());
1267 final Variable vo1 = smapper.pushT(vi1.getType());
1269 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1270 vo1, vi1, vo2, vi2, vo3, vo1);
1272 final Variable vi3 = smapper.pop(this);
1273 final Variable vo5 = smapper.pushT(vi2.getType());
1274 final Variable vo4 = smapper.pushT(vi1.getType());
1275 final Variable vo3 = smapper.pushT(vi3.getType());
1276 final Variable vo2 = smapper.pushT(vi2.getType());
1277 final Variable vo1 = smapper.pushT(vi1.getType());
1279 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1280 vo1, vi1, vo2, vi2, vo3, vi3);
1281 emit(smapper, this, " @1 = @2, @3 = @4;",
1282 vo4, vo1, vo5, vo2);
1287 final Variable vi1 = smapper.pop(this);
1288 final Variable vi2 = smapper.pop(this);
1290 if (vi2.isCategory2()) {
1291 final Variable vo3 = smapper.pushT(vi1.getType());
1292 final Variable vo2 = smapper.pushT(vi2.getType());
1293 final Variable vo1 = smapper.pushT(vi1.getType());
1295 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1296 vo1, vi1, vo2, vi2, vo3, vo1);
1298 final Variable vi3 = smapper.pop(this);
1299 final Variable vo4 = smapper.pushT(vi1.getType());
1300 final Variable vo3 = smapper.pushT(vi3.getType());
1301 final Variable vo2 = smapper.pushT(vi2.getType());
1302 final Variable vo1 = smapper.pushT(vi1.getType());
1304 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1305 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1310 final Variable vi1 = smapper.pop(this);
1311 final Variable vi2 = smapper.pop(this);
1313 if (vi1.isCategory2()) {
1314 if (vi2.isCategory2()) {
1315 final Variable vo3 = smapper.pushT(vi1.getType());
1316 final Variable vo2 = smapper.pushT(vi2.getType());
1317 final Variable vo1 = smapper.pushT(vi1.getType());
1319 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1320 vo1, vi1, vo2, vi2, vo3, vo1);
1322 final Variable vi3 = smapper.pop(this);
1323 final Variable vo4 = smapper.pushT(vi1.getType());
1324 final Variable vo3 = smapper.pushT(vi3.getType());
1325 final Variable vo2 = smapper.pushT(vi2.getType());
1326 final Variable vo1 = smapper.pushT(vi1.getType());
1328 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1329 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1332 final Variable vi3 = smapper.pop(this);
1334 if (vi3.isCategory2()) {
1335 final Variable vo5 = smapper.pushT(vi2.getType());
1336 final Variable vo4 = smapper.pushT(vi1.getType());
1337 final Variable vo3 = smapper.pushT(vi3.getType());
1338 final Variable vo2 = smapper.pushT(vi2.getType());
1339 final Variable vo1 = smapper.pushT(vi1.getType());
1341 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1342 vo1, vi1, vo2, vi2, vo3, vi3);
1343 emit(smapper, this, " @1 = @2, @3 = @4;",
1344 vo4, vo1, vo5, vo2);
1346 final Variable vi4 = smapper.pop(this);
1347 final Variable vo6 = smapper.pushT(vi2.getType());
1348 final Variable vo5 = smapper.pushT(vi1.getType());
1349 final Variable vo4 = smapper.pushT(vi4.getType());
1350 final Variable vo3 = smapper.pushT(vi3.getType());
1351 final Variable vo2 = smapper.pushT(vi2.getType());
1352 final Variable vo1 = smapper.pushT(vi1.getType());
1354 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1355 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1356 emit(smapper, this, " @1 = @2, @3 = @4;",
1357 vo5, vo1, vo6, vo2);
1363 final Variable vi1 = smapper.get(0);
1364 final Variable vi2 = smapper.get(1);
1366 if (vi1.getType() == vi2.getType()) {
1367 final Variable tmp = smapper.pushT(vi1.getType());
1369 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1374 smapper.pushT(vi1.getType());
1375 smapper.pushT(vi2.getType());
1380 smapper.assign(this, VarType.INTEGER,
1381 "(" + Integer.toString(byteCodes[++i]) + ")");
1384 smapper.assign(this, VarType.INTEGER,
1385 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1389 case opc_getfield: {
1390 int indx = readUShortArg(byteCodes, i);
1391 String[] fi = jc.getFieldInfoName(indx);
1392 final int type = VarType.fromFieldType(fi[2].charAt(0));
1393 final String mangleClass = mangleClassName(fi[0]);
1394 final String mangleClassAccess = accessClass(mangleClass);
1395 smapper.replace(this, type, "@2.call(@1)",
1397 accessField(mangleClassAccess + "(false)",
1401 addReference(fi[0]);
1404 case opc_putfield: {
1405 int indx = readUShortArg(byteCodes, i);
1406 String[] fi = jc.getFieldInfoName(indx);
1407 final int type = VarType.fromFieldType(fi[2].charAt(0));
1408 final String mangleClass = mangleClassName(fi[0]);
1409 final String mangleClassAccess = accessClass(mangleClass);
1410 emit(smapper, this, "@3.call(@2, @1);",
1413 accessField(mangleClassAccess + "(false)",
1416 addReference(fi[0]);
1419 case opc_getstatic: {
1420 int indx = readUShortArg(byteCodes, i);
1421 String[] fi = jc.getFieldInfoName(indx);
1422 final int type = VarType.fromFieldType(fi[2].charAt(0));
1423 String ac = accessClass(mangleClassName(fi[0]));
1424 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1425 smapper.assign(this, type, af + "()");
1427 addReference(fi[0]);
1430 case opc_putstatic: {
1431 int indx = readUShortArg(byteCodes, i);
1432 String[] fi = jc.getFieldInfoName(indx);
1433 final int type = VarType.fromFieldType(fi[2].charAt(0));
1434 emit(smapper, this, "@1(false)._@2(@3);",
1435 accessClass(mangleClassName(fi[0])), fi[1],
1436 smapper.popT(type));
1438 addReference(fi[0]);
1441 case opc_checkcast: {
1442 int indx = readUShortArg(byteCodes, i);
1443 generateCheckcast(indx, smapper);
1447 case opc_instanceof: {
1448 int indx = readUShortArg(byteCodes, i);
1449 generateInstanceOf(indx, smapper);
1454 final CharSequence v = smapper.popA();
1457 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1458 smapper.pushA(), v);
1462 case opc_monitorenter: {
1463 debug("/* monitor enter */");
1468 case opc_monitorexit: {
1469 debug("/* monitor exit */");
1480 emit(smapper, this, "throw 'unknown bytecode @1';",
1481 Integer.toString(c));
1485 generateByteCodeComment(prev, i, byteCodes);
1491 if (previousTrap != null) {
1492 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1497 while (openBraces-- > 0) {
1508 private int generateIf(StackMapper mapper, byte[] byteCodes,
1509 int i, final CharSequence v2, final CharSequence v1,
1510 final String test, int topMostLabel
1511 ) throws IOException {
1513 int indx = i + readShortArg(byteCodes, i);
1514 append("if ((").append(v1)
1515 .append(") ").append(test).append(" (")
1516 .append(v2).append(")) ");
1517 goTo(this, i, indx, topMostLabel);
1521 private int readInt4(byte[] byteCodes, int offset) {
1522 final int d = byteCodes[offset + 0] << 24;
1523 final int c = byteCodes[offset + 1] << 16;
1524 final int b = byteCodes[offset + 2] << 8;
1525 final int a = byteCodes[offset + 3];
1526 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1528 private static int readUByte(byte[] byteCodes, int offset) {
1529 return byteCodes[offset] & 0xff;
1532 private static int readUShort(byte[] byteCodes, int offset) {
1533 return ((byteCodes[offset] & 0xff) << 8)
1534 | (byteCodes[offset + 1] & 0xff);
1536 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1537 return readUShort(byteCodes, offsetInstruction + 1);
1540 private static int readShort(byte[] byteCodes, int offset) {
1541 int signed = byteCodes[offset];
1542 byte b0 = (byte)signed;
1543 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1545 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1546 return readShort(byteCodes, offsetInstruction + 1);
1549 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1551 Boolean count = null;
1552 boolean array = false;
1554 int firstPos = sig.length();
1555 while (i < descriptor.length()) {
1556 char ch = descriptor.charAt(i++);
1577 if (ch == 'J' || ch == 'D') {
1583 sig.insert(firstPos, ch);
1585 returnType[0] = '[';
1586 sig.insert(firstPos, "_3");
1595 returnType[0] = 'V';
1596 sig.insert(firstPos, 'V');
1599 int next = descriptor.indexOf(';', i);
1600 String realSig = mangleSig(descriptor, i - 1, next + 1);
1605 sig.append(realSig);
1608 sig.insert(firstPos, realSig);
1610 sig.insert(firstPos, "_3");
1612 returnType[0] = 'L';
1621 throw new IllegalStateException("Invalid char: " + ch);
1626 static String mangleSig(String sig) {
1627 return mangleSig(sig, 0, sig.length());
1630 private static String mangleMethodName(String name) {
1631 StringBuilder sb = new StringBuilder(name.length() * 2);
1632 int last = name.length();
1633 for (int i = 0; i < last; i++) {
1634 final char ch = name.charAt(i);
1636 case '_': sb.append("_1"); break;
1637 default: sb.append(ch); break;
1640 return sb.toString();
1642 private static String mangleSig(String txt, int first, int last) {
1643 StringBuilder sb = new StringBuilder((last - first) * 2);
1644 for (int i = first; i < last; i++) {
1645 final char ch = txt.charAt(i);
1647 case '/': sb.append('_'); break;
1648 case '_': sb.append("_1"); break;
1649 case ';': sb.append("_2"); break;
1650 case '[': sb.append("_3"); break;
1652 if (Character.isJavaIdentifierPart(ch)) {
1656 String hex = Integer.toHexString(ch).toLowerCase();
1657 for (int m = hex.length(); m < 4; m++) {
1665 return sb.toString();
1668 private static String mangleClassName(String name) {
1669 return mangleSig(name);
1672 private static String findMethodName(MethodData m, StringBuilder cnt) {
1673 StringBuilder name = new StringBuilder();
1674 if ("<init>".equals(m.getName())) { // NOI18N
1675 name.append("cons"); // NOI18N
1676 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1677 name.append("class"); // NOI18N
1679 name.append(mangleMethodName(m.getName()));
1682 countArgs(m.getInternalSig(), new char[1], name, cnt);
1683 return name.toString();
1686 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1687 StringBuilder name = new StringBuilder();
1688 String descr = mi[2];//mi.getDescriptor();
1690 if ("<init>".equals(nm)) { // NOI18N
1691 name.append("cons"); // NOI18N
1693 name.append(mangleMethodName(nm));
1695 countArgs(descr, returnType, name, cnt);
1696 return name.toString();
1699 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1700 throws IOException {
1701 int methodIndex = readUShortArg(byteCodes, i);
1702 String[] mi = jc.getFieldInfoName(methodIndex);
1703 char[] returnType = { 'V' };
1704 StringBuilder cnt = new StringBuilder();
1705 String mn = findMethodName(mi, cnt, returnType);
1707 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1708 final CharSequence[] vars = new CharSequence[numArguments];
1710 for (int j = numArguments - 1; j >= 0; --j) {
1711 vars[j] = mapper.popValue();
1714 if (returnType[0] != 'V') {
1717 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1721 final String in = mi[0];
1724 in.equals("org/apidesign/html/boot/spi/Fn") ||
1725 in.equals("org/netbeans/html/boot/spi/Fn")
1727 mcn = "java_lang_Class";
1729 mcn = mangleClassName(in);
1731 String object = accessClass(mcn) + "(false)";
1732 if (mn.startsWith("cons_")) {
1733 object += ".constructor";
1735 append(accessStaticMethod(object, mn, mi));
1741 if (numArguments > 0) {
1743 for (int j = 1; j < numArguments; ++j) {
1753 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1754 throws IOException {
1755 int methodIndex = readUShortArg(byteCodes, i);
1756 String[] mi = jc.getFieldInfoName(methodIndex);
1757 char[] returnType = { 'V' };
1758 StringBuilder cnt = new StringBuilder();
1759 String mn = findMethodName(mi, cnt, returnType);
1761 final int numArguments = cnt.length() + 1;
1762 final CharSequence[] vars = new CharSequence[numArguments];
1764 for (int j = numArguments - 1; j >= 0; --j) {
1765 vars[j] = mapper.popValue();
1768 if (returnType[0] != 'V') {
1770 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1774 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1776 for (int j = 1; j < numArguments; ++j) {
1786 private void addReference(String cn) throws IOException {
1787 if (requireReference(cn)) {
1788 debug(" /* needs " + cn + " */");
1792 private void outType(String d, StringBuilder out) {
1794 while (d.charAt(0) == '[') {
1798 if (d.charAt(0) == 'L') {
1799 assert d.charAt(d.length() - 1) == ';';
1800 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1806 private String encodeConstant(int entryIndex) throws IOException {
1807 String[] classRef = { null };
1808 String s = jc.stringValue(entryIndex, classRef);
1809 if (classRef[0] != null) {
1810 if (classRef[0].startsWith("[")) {
1811 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1813 addReference(classRef[0]);
1814 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1820 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1821 byte[] arr = m.findAnnotationData(true);
1825 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1826 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1827 class P extends AnnotationParser {
1833 String[] args = new String[30];
1839 protected void visitAttr(String type, String attr, String at, String value) {
1840 if (type.equals(jvmType)) {
1841 if ("body".equals(attr)) {
1843 } else if ("args".equals(attr)) {
1844 args[cnt++] = value;
1846 throw new IllegalArgumentException(attr);
1849 if (type.equals(htmlType)) {
1851 if ("body".equals(attr)) {
1853 } else if ("args".equals(attr)) {
1854 args[cnt++] = value;
1855 } else if ("javacall".equals(attr)) {
1856 javacall = "1".equals(value);
1857 } else if ("wait4js".equals(attr)) {
1858 // ignore, we always invoke synchronously
1860 throw new IllegalArgumentException(attr);
1867 if (p.body == null) {
1870 StringBuilder cnt = new StringBuilder();
1871 final String mn = findMethodName(m, cnt);
1872 append("m = ").append(destObject).append(".").append(mn);
1873 append(" = function(");
1876 StringBuilder toValue = new StringBuilder();
1877 for (int i = 0; i < cnt.length(); i++) {
1879 space = outputArg(this, p.args, index);
1880 if (p.html4j && space.length() > 0) {
1881 toValue.append("\n ").append(p.args[index]).append(" = ")
1882 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1883 append(p.args[index]).append(");");
1887 append(") {").append("\n");
1888 append(toValue.toString());
1890 int lastSlash = jc.getClassName().lastIndexOf('/');
1891 final String pkg = jc.getClassName().substring(0, lastSlash);
1892 append(mangleCallbacks(pkg, p.body));
1893 requireReference(pkg + "/$JsCallbacks$");
1901 private static CharSequence mangleCallbacks(String pkgName, String body) {
1902 StringBuilder sb = new StringBuilder();
1905 int next = body.indexOf(".@", pos);
1907 sb.append(body.substring(pos));
1908 body = sb.toString();
1913 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1918 String refId = body.substring(ident, next);
1920 sb.append(body.substring(pos, ident));
1922 int sigBeg = body.indexOf('(', next);
1923 int sigEnd = body.indexOf(')', sigBeg);
1924 int colon4 = body.indexOf("::", next);
1925 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1926 throw new IllegalStateException("Malformed body " + body);
1928 String fqn = body.substring(next + 2, colon4);
1929 String method = body.substring(colon4 + 2, sigBeg);
1930 String params = body.substring(sigBeg, sigEnd + 1);
1932 int paramBeg = body.indexOf('(', sigEnd + 1);
1934 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1935 sb.append(mangleJsCallbacks(fqn, method, params, false));
1936 sb.append("(").append(refId);
1937 if (body.charAt(paramBeg + 1) != ')') {
1945 int next = body.indexOf("@", pos);
1950 sb.append(body.substring(pos));
1954 sb = new StringBuilder();
1957 sb.append(body.substring(pos, next));
1959 int sigBeg = body.indexOf('(', next);
1960 int sigEnd = body.indexOf(')', sigBeg);
1961 int colon4 = body.indexOf("::", next);
1962 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1963 throw new IllegalStateException("Malformed body " + body);
1965 String fqn = body.substring(next + 1, colon4);
1966 String method = body.substring(colon4 + 2, sigBeg);
1967 String params = body.substring(sigBeg, sigEnd + 1);
1969 int paramBeg = body.indexOf('(', sigEnd + 1);
1971 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1972 sb.append(mangleJsCallbacks(fqn, method, params, true));
1978 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1979 if (params.startsWith("(")) {
1980 params = params.substring(1);
1982 if (params.endsWith(")")) {
1983 params = params.substring(0, params.length() - 1);
1985 StringBuilder sb = new StringBuilder();
1986 final String fqnu = fqn.replace('.', '_');
1987 final String rfqn = mangleClassName(fqnu);
1988 final String rm = mangleMethodName(method);
1991 StringBuilder pb = new StringBuilder();
1992 int len = params.length();
1994 while (indx < len) {
1995 char ch = params.charAt(indx);
1996 if (ch == '[' || ch == 'L') {
1997 int column = params.indexOf(';', indx) + 1;
1998 if (column > indx) {
1999 String real = params.substring(indx, column);
2000 if ("Ljava/lang/String;".equals(real)) {
2001 pb.append("Ljava/lang/String;");
2006 pb.append("Ljava/lang/Object;");
2013 srp = mangleSig(pb.toString());
2015 final String rp = mangleSig(params);
2016 final String mrp = mangleMethodName(rp);
2017 sb.append(rfqn).append("$").append(rm).
2018 append('$').append(mrp).append("__Ljava_lang_Object_2");
2020 sb.append('L').append(fqnu).append("_2");
2023 return sb.toString();
2026 private static String className(ClassData jc) {
2027 //return jc.getName().getInternalName().replace('/', '_');
2028 return mangleClassName(jc.getClassName());
2031 private static String[] findAnnotation(
2032 byte[] arr, ClassData cd, final String className,
2033 final String... attrNames
2034 ) throws IOException {
2038 final String[] values = new String[attrNames.length];
2039 final boolean[] found = { false };
2040 final String jvmType = "L" + className.replace('.', '/') + ";";
2041 AnnotationParser ap = new AnnotationParser(false, true) {
2043 protected void visitAttr(String type, String attr, String at, String value) {
2044 if (type.equals(jvmType)) {
2046 for (int i = 0; i < attrNames.length; i++) {
2047 if (attrNames[i].equals(attr)) {
2056 return found[0] ? values : null;
2059 private CharSequence initField(FieldData v) {
2060 final String is = v.getInternalSig();
2061 if (is.length() == 1) {
2062 switch (is.charAt(0)) {
2068 case 'I': return " = 0;";
2070 case 'D': return " = 0.0;";
2072 throw new IllegalStateException(is);
2078 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2079 AnnotationParser ap = new AnnotationParser(true, false) {
2080 int[] cnt = new int[32];
2084 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2085 final String slashType = attrType.substring(1, attrType.length() - 1);
2086 requireReference(slashType);
2088 if (cnt[depth]++ > 0) {
2092 append('"').append(attrType).append("\" : ");
2099 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2105 protected void visitValueStart(String attrName, char type) throws IOException {
2106 if (cnt[depth]++ > 0) {
2110 if (attrName != null) {
2111 append('"').append(attrName).append("\" : ");
2119 protected void visitValueEnd(String attrName, char type) throws IOException {
2127 protected void visitAttr(String type, String attr, String attrType, String value)
2128 throws IOException {
2129 if (attr == null && value == null) {
2136 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2137 throws IOException {
2138 final String slashType = attrType.substring(1, attrType.length() - 1);
2139 requireReference(slashType);
2141 final String cn = mangleClassName(slashType);
2142 append(accessClass(cn))
2143 .append("(false)['valueOf__L").
2145 append("_2Ljava_lang_String_2']('").
2153 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2154 final String name = args[indx];
2158 if (name.contains(",")) {
2159 throw new IOException("Wrong parameter with ',': " + name);
2165 final void emitNoFlush(
2167 final String format, final CharSequence... params
2168 ) throws IOException {
2169 emitImpl(this, format, params);
2171 static final void emit(
2173 final Appendable out,
2174 final String format, final CharSequence... params
2175 ) throws IOException {
2177 emitImpl(out, format, params);
2179 static void emitImpl(final Appendable out,
2180 final String format,
2181 final CharSequence... params) throws IOException {
2182 final int length = format.length();
2185 int paramOffset = format.indexOf('@');
2186 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2187 final char paramChar = format.charAt(paramOffset + 1);
2188 if ((paramChar >= '1') && (paramChar <= '9')) {
2189 final int paramIndex = paramChar - '0' - 1;
2191 out.append(format, processed, paramOffset);
2192 out.append(params[paramIndex]);
2195 processed = paramOffset + 1;
2198 paramOffset = format.indexOf('@', paramOffset + 1);
2201 out.append(format, processed, length);
2204 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2205 append("} catch (e) {\n");
2207 for (TrapData e : traps) {
2211 if (e.catch_cpx != 0) { //not finally
2212 final String classInternalName = jc.getClassName(e.catch_cpx);
2213 addReference(classInternalName);
2214 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2215 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2216 append("var stA0 = e;");
2217 goTo(this, current, e.handler_pc, topMostLabel);
2220 finallyPC = e.handler_pc;
2223 if (finallyPC == -1) {
2226 append("var stA0 = e;");
2227 goTo(this, current, finallyPC, topMostLabel);
2232 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2235 out.append("{ gt = 0; continue X_" + to + "; }");
2237 out.append("{ gt = " + to + "; continue X_0; }");
2240 out.append("{ gt = " + to + "; break IF; }");
2244 private static void emitIf(
2246 Appendable out, String pattern,
2248 int current, int to, int canBack
2249 ) throws IOException {
2251 emitImpl(out, pattern, param);
2252 goTo(out, current, to, canBack);
2255 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2258 case 4: jvmType = "[Z"; break;
2259 case 5: jvmType = "[C"; break;
2260 case 6: jvmType = "[F"; break;
2261 case 7: jvmType = "[D"; break;
2262 case 8: jvmType = "[B"; break;
2263 case 9: jvmType = "[S"; break;
2264 case 10: jvmType = "[I"; break;
2265 case 11: jvmType = "[J"; break;
2266 default: throw new IllegalStateException("Array type: " + atype);
2269 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2270 smapper.popI(), smapper.pushA(), jvmType);
2273 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2274 String typeName = jc.getClassName(type);
2275 String ref = "null";
2276 if (typeName.startsWith("[")) {
2277 typeName = "'[" + typeName + "'";
2279 ref = "vm." + mangleClassName(typeName);
2280 typeName = "'[L" + typeName + ";'";
2283 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2284 smapper.popI(), smapper.pushA(), typeName, ref);
2287 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2288 String typeName = jc.getClassName(type);
2289 int dim = readUByte(byteCodes, ++i);
2290 StringBuilder dims = new StringBuilder();
2292 for (int d = 0; d < dim; d++) {
2294 dims.insert(1, ",");
2296 dims.insert(1, smapper.popI());
2300 if (typeName.charAt(dim) == 'L') {
2301 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2304 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2305 dims.toString(), smapper.pushA(), typeName, fn
2310 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2311 int table = i / 4 * 4 + 4;
2312 int dflt = i + readInt4(byteCodes, table);
2314 int low = readInt4(byteCodes, table);
2316 int high = readInt4(byteCodes, table);
2318 final CharSequence swVar = smapper.popValue();
2319 smapper.flush(this);
2320 append("switch (").append(swVar).append(") {\n");
2321 while (low <= high) {
2322 int offset = i + readInt4(byteCodes, table);
2324 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2327 append(" default: ");
2328 goTo(this, i, dflt, topMostLabel);
2334 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2335 int table = i / 4 * 4 + 4;
2336 int dflt = i + readInt4(byteCodes, table);
2338 int n = readInt4(byteCodes, table);
2340 final CharSequence swVar = smapper.popValue();
2341 smapper.flush(this);
2342 append("switch (").append(swVar).append(") {\n");
2344 int cnstnt = readInt4(byteCodes, table);
2346 int offset = i + readInt4(byteCodes, table);
2348 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2350 append(" default: ");
2351 goTo(this, i, dflt, topMostLabel);
2357 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2358 String type = jc.getClassName(indx);
2359 if (!type.startsWith("[")) {
2361 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2362 smapper.popA(), smapper.pushI(),
2363 type.replace('/', '_'));
2366 while (type.charAt(cnt) == '[') {
2369 if (type.charAt(cnt) == 'L') {
2370 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2372 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2373 smapper.popA(), smapper.pushI(),
2378 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2379 smapper.popA(), smapper.pushI(), type
2385 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2386 String type = jc.getClassName(indx);
2387 if (!type.startsWith("[")) {
2388 emitNoFlush(smapper,
2389 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2390 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2393 while (type.charAt(cnt) == '[') {
2396 if (type.charAt(cnt) == 'L') {
2397 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2398 emitNoFlush(smapper,
2399 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2400 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2403 emitNoFlush(smapper,
2404 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2405 smapper.getT(0, VarType.REFERENCE, false), type
2411 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2412 for (int j = prev; j <= i; j++) {
2414 final int cc = readUByte(byteCodes, j);
2415 append(Integer.toString(cc));
2419 @JavaScriptBody(args = "msg", body = "")
2420 private static void println(String msg) {
2421 System.err.println(msg);