Looks like package-info classes have too old classfile version, but we can accept them as they don't contain any code (the only reason why we require 1.6 target).
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.access = ").append(jc.getAccessFlags()+";");
300 append("\n CLS.$class.cnstr = CLS;");
301 byte[] classAnno = jc.findAnnotationData(false);
302 if (classAnno != null) {
303 append("\n CLS.$class.anno = {");
304 generateAnno(jc, classAnno);
307 for (String init : toInitilize.toArray()) {
308 append("\n ").append(init).append("();");
311 if (jsResource != null) {
312 requireResource(jsResource);
316 append("\n if (arguments.length === 0) {");
317 append("\n if (!(this instanceof CLS)) {");
318 append("\n return new CLS();");
320 for (FieldData v : jc.getFields()) {
321 byte[] onlyArr = v.findAnnotationData(true);
322 if (javaScriptOnly(onlyArr)) continue;
324 append("\n this.fld_").
325 append(className).append('_').
326 append(v.getName()).append(initField(v));
329 append("\n return this;");
331 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
334 declaredClass(jc, className);
336 // StringBuilder sb = new StringBuilder();
337 // for (String init : toInitilize.toArray()) {
338 // sb.append("\n").append(init).append("();");
343 private boolean javaScriptOnly(byte[] anno) throws IOException {
344 String[] only = findAnnotation(anno, jc,
345 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
349 if (only[0] != null && only[1] != null) {
350 append("\n p.").append(only[0]).append(" = ")
351 .append(only[1]).append(";");
353 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
354 append("\n p['").append(only[0]).append("'] = p.")
355 .append(only[0]).append(";");
361 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
362 String jsb = javaScriptBody(destObject, m, true);
366 final String mn = findMethodName(m, new StringBuilder());
367 boolean defineProp = generateMethod(destObject, mn, m);
368 if (mn.equals("class__V")) {
370 toInitilize.add(accessClass(className(jc)) + "(false)['" + mn + "']");
372 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
378 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
379 String jsb = javaScriptBody(destObject, m, false);
383 final String mn = findMethodName(m, new StringBuilder());
384 generateMethod(destObject, mn, m);
388 private boolean generateMethod(String destObject, String name, MethodData m)
390 final StackMapIterator stackMapIterator = m.createStackMapIterator();
391 TrapDataIterator trap = m.getTrapDataIterator();
392 final LocalsMapper lmapper =
393 new LocalsMapper(stackMapIterator.getArguments());
396 "java/lang/Object".equals(jc.getClassName()) ||
397 "java/lang/reflect/Array".equals(jc.getClassName());
400 append("Object.defineProperty(").append(destObject).
401 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
403 append("m = ").append(destObject).append(".").append(name).append(" = function(");
405 lmapper.outputArguments(this, m.isStatic());
406 append(") {").append("\n");
408 final byte[] byteCodes = m.getCode();
409 if (byteCodes == null) {
410 append(" throw 'no code found for ")
411 .append(jc.getClassName()).append('.')
412 .append(m.getName()).append("';\n");
421 final StackMapper smapper = new StackMapper();
424 append(" var ").append(" lcA0 = this;\n");
428 TrapData[] previousTrap = null;
429 boolean wide = false;
431 if (stackMapIterator.isEmpty()) {
437 append("\n var gt = 0;\n");
441 int topMostLabel = 0;
442 for (int i = 0; i < byteCodes.length; i++) {
445 stackMapIterator.advanceTo(i);
446 boolean changeInCatch = trap.advanceTo(i);
447 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
448 if (previousTrap != null) {
449 generateCatch(previousTrap, i, topMostLabel);
453 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
458 if (openBraces > 64) {
459 for (int c = 0; c < 64; c++) {
466 lastStackFrame = stackMapIterator.getFrameIndex();
467 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
468 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
469 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
471 changeInCatch = true;
473 debug(" /* " + i + " */ ");
475 if (changeInCatch && trap.useTry()) {
477 previousTrap = trap.current();
479 final int c = readUByte(byteCodes, i);
482 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
485 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
488 smapper.assign(this, VarType.LONG, lmapper.getL(0));
491 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
494 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
497 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
500 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
503 smapper.assign(this, VarType.LONG, lmapper.getL(1));
506 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
509 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
512 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
515 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
518 smapper.assign(this, VarType.LONG, lmapper.getL(2));
521 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
524 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
527 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
530 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
533 smapper.assign(this, VarType.LONG, lmapper.getL(3));
536 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
539 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
543 final int indx = wide ? readUShort(byteCodes, i++)
544 : readUByte(byteCodes, i);
546 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
551 final int indx = wide ? readUShort(byteCodes, i++)
552 : readUByte(byteCodes, i);
554 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
559 final int indx = wide ? readUShort(byteCodes, i++)
560 : readUByte(byteCodes, i);
562 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
567 final int indx = wide ? readUShort(byteCodes, i++)
568 : readUByte(byteCodes, i);
570 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
575 final int indx = wide ? readUShort(byteCodes, i++)
576 : readUByte(byteCodes, i);
578 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
583 final int indx = wide ? readUShort(byteCodes, i++)
584 : readUByte(byteCodes, i);
586 emit(smapper, this, "var @1 = @2;",
587 lmapper.setI(indx), smapper.popI());
592 final int indx = wide ? readUShort(byteCodes, i++)
593 : readUByte(byteCodes, i);
595 emit(smapper, this, "var @1 = @2;",
596 lmapper.setL(indx), smapper.popL());
601 final int indx = wide ? readUShort(byteCodes, i++)
602 : readUByte(byteCodes, i);
604 emit(smapper, this, "var @1 = @2;",
605 lmapper.setF(indx), smapper.popF());
610 final int indx = wide ? readUShort(byteCodes, i++)
611 : readUByte(byteCodes, i);
613 emit(smapper, this, "var @1 = @2;",
614 lmapper.setD(indx), smapper.popD());
619 final int indx = wide ? readUShort(byteCodes, i++)
620 : readUByte(byteCodes, i);
622 emit(smapper, this, "var @1 = @2;",
623 lmapper.setA(indx), smapper.popA());
627 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
630 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
633 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
636 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
639 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
642 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
645 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
648 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
651 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
654 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
657 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
660 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
663 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
666 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
669 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
672 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
675 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
678 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
681 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
684 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
687 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
690 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
693 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
696 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
699 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
702 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
705 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
708 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
711 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
714 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
717 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
720 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
723 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
724 smapper.getI(1), smapper.popI());
727 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
728 smapper.getL(1), smapper.popL());
731 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
734 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
737 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
738 smapper.getI(1), smapper.popI());
741 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
742 smapper.getL(1), smapper.popL());
745 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
748 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
751 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
754 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
757 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
760 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
763 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
766 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
769 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
772 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
775 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
778 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
781 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
784 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
787 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
790 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
793 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
796 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
800 final int varIndx = wide ? readUShort(byteCodes, i++)
801 : readUByte(byteCodes, i);
803 final int incrBy = wide ? readShort(byteCodes, i++)
807 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
809 emit(smapper, this, "@1 += @2;",
810 lmapper.getI(varIndx),
811 Integer.toString(incrBy));
816 emit(smapper, this, "return;");
819 emit(smapper, this, "return @1;", smapper.popI());
822 emit(smapper, this, "return @1;", smapper.popL());
825 emit(smapper, this, "return @1;", smapper.popF());
828 emit(smapper, this, "return @1;", smapper.popD());
831 emit(smapper, this, "return @1;", smapper.popA());
834 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
837 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
840 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
843 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
847 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
850 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
853 smapper.replace(this, VarType.DOUBLE, "@1",
857 smapper.replace(this, VarType.FLOAT, "@1",
861 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
865 smapper.replace(this, VarType.LONG, "(@1).toLong()",
869 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
873 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
876 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
880 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
882 case opc_aconst_null:
883 smapper.assign(this, VarType.REFERENCE, "null");
886 smapper.assign(this, VarType.INTEGER, "-1");
889 smapper.assign(this, VarType.INTEGER, "0");
892 smapper.assign(this, VarType.DOUBLE, "0");
895 smapper.assign(this, VarType.LONG, "0");
898 smapper.assign(this, VarType.FLOAT, "0");
901 smapper.assign(this, VarType.INTEGER, "1");
904 smapper.assign(this, VarType.LONG, "1");
907 smapper.assign(this, VarType.FLOAT, "1");
910 smapper.assign(this, VarType.DOUBLE, "1");
913 smapper.assign(this, VarType.INTEGER, "2");
916 smapper.assign(this, VarType.FLOAT, "2");
919 smapper.assign(this, VarType.INTEGER, "3");
922 smapper.assign(this, VarType.INTEGER, "4");
925 smapper.assign(this, VarType.INTEGER, "5");
928 int indx = readUByte(byteCodes, ++i);
929 String v = encodeConstant(indx);
930 int type = VarType.fromConstantType(jc.getTag(indx));
931 smapper.assign(this, type, v);
936 int indx = readUShortArg(byteCodes, i);
938 String v = encodeConstant(indx);
939 int type = VarType.fromConstantType(jc.getTag(indx));
940 if (type == VarType.LONG) {
941 final Long lv = new Long(v);
942 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
943 final int hi = (int)(lv.longValue() >> 32);
945 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
947 smapper.assign(this, VarType.LONG,
948 "0x" + Integer.toHexString(hi) + ".next32(0x" +
949 Integer.toHexString(low) + ")"
953 smapper.assign(this, type, v);
958 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
962 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
966 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
969 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
970 "===", topMostLabel);
973 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
974 "!==", topMostLabel);
977 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
981 int indx = i + readShortArg(byteCodes, i);
982 emitIf(smapper, this, "if ((@1) == 0) ",
983 smapper.popI(), i, indx, topMostLabel);
988 int indx = i + readShortArg(byteCodes, i);
989 emitIf(smapper, this, "if ((@1) != 0) ",
990 smapper.popI(), i, indx, topMostLabel);
995 int indx = i + readShortArg(byteCodes, i);
996 emitIf(smapper, this, "if ((@1) < 0) ",
997 smapper.popI(), i, indx, topMostLabel);
1002 int indx = i + readShortArg(byteCodes, i);
1003 emitIf(smapper, this, "if ((@1) <= 0) ",
1004 smapper.popI(), i, indx, topMostLabel);
1009 int indx = i + readShortArg(byteCodes, i);
1010 emitIf(smapper, this, "if ((@1) > 0) ",
1011 smapper.popI(), i, indx, topMostLabel);
1016 int indx = i + readShortArg(byteCodes, i);
1017 emitIf(smapper, this, "if ((@1) >= 0) ",
1018 smapper.popI(), i, indx, topMostLabel);
1022 case opc_ifnonnull: {
1023 int indx = i + readShortArg(byteCodes, i);
1024 emitIf(smapper, this, "if ((@1) !== null) ",
1025 smapper.popA(), i, indx, topMostLabel);
1030 int indx = i + readShortArg(byteCodes, i);
1031 emitIf(smapper, this, "if ((@1) === null) ",
1032 smapper.popA(), i, indx, topMostLabel);
1037 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1038 "!=", topMostLabel);
1041 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1045 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1046 "<=", topMostLabel);
1049 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1053 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1054 ">=", topMostLabel);
1057 smapper.flush(this);
1058 int indx = i + readShortArg(byteCodes, i);
1059 goTo(this, i, indx, topMostLabel);
1063 case opc_lookupswitch: {
1064 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1067 case opc_tableswitch: {
1068 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1071 case opc_invokeinterface: {
1072 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1075 case opc_invokevirtual:
1076 i = invokeVirtualMethod(byteCodes, i, smapper);
1078 case opc_invokespecial:
1079 i = invokeStaticMethod(byteCodes, i, smapper, false);
1081 case opc_invokestatic:
1082 i = invokeStaticMethod(byteCodes, i, smapper, true);
1084 case opc_invokedynamic: {
1085 int indx = readUShortArg(byteCodes, i);
1086 println("invoke dynamic: " + indx);
1087 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1088 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1089 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1090 println(" type: " + methodHandle.cpx1);
1091 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1092 String mcn = mangleClassName(mi[0]);
1093 char[] returnType = {'V'};
1094 StringBuilder cnt = new StringBuilder();
1095 String mn = findMethodName(mi, cnt, returnType);
1096 StringBuilder sb = new StringBuilder();
1097 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1098 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1099 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1100 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1101 sb.append(" mn : ").append(mn).append("\n");
1102 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1103 throw new IOException(sb.toString());
1105 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1106 String type = jc.StringValue(nameAndType.cpx2);
1107 String object = accessClass(mcn) + "(false)";
1108 if (mn.startsWith("cons_")) {
1109 object += ".constructor";
1111 append("var metHan = ");
1112 append(accessStaticMethod(object, mn, mi));
1114 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1116 append(", '").append(mi[1]).append("', ");
1117 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1118 append(methodType).append("'").append(type).append("', null)");
1119 // if (numArguments > 0) {
1121 // for (int j = 1; j < numArguments; ++j) {
1127 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1133 int indx = readUShortArg(byteCodes, i);
1134 String ci = jc.getClassName(indx);
1135 emit(smapper, this, "var @1 = new @2;",
1136 smapper.pushA(), accessClass(mangleClassName(ci)));
1142 int atype = readUByte(byteCodes, ++i);
1143 generateNewArray(atype, smapper);
1145 case opc_anewarray: {
1146 int type = readUShortArg(byteCodes, i);
1148 generateANewArray(type, smapper);
1151 case opc_multianewarray: {
1152 int type = readUShortArg(byteCodes, i);
1154 i = generateMultiANewArray(type, byteCodes, i, smapper);
1157 case opc_arraylength:
1158 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1161 emit(smapper, this, "Array.at(@3, @2, @1);",
1162 smapper.popL(), smapper.popI(), smapper.popA());
1165 emit(smapper, this, "Array.at(@3, @2, @1);",
1166 smapper.popF(), smapper.popI(), smapper.popA());
1169 emit(smapper, this, "Array.at(@3, @2, @1);",
1170 smapper.popD(), smapper.popI(), smapper.popA());
1173 emit(smapper, this, "Array.at(@3, @2, @1);",
1174 smapper.popA(), smapper.popI(), smapper.popA());
1180 emit(smapper, this, "Array.at(@3, @2, @1);",
1181 smapper.popI(), smapper.popI(), smapper.popA());
1184 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1185 smapper.popI(), smapper.getA(0));
1188 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1189 smapper.popI(), smapper.getA(0));
1192 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1193 smapper.popI(), smapper.getA(0));
1196 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1197 smapper.popI(), smapper.getA(0));
1203 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1204 smapper.popI(), smapper.getA(0));
1212 final Variable v = smapper.get(0);
1213 if (smapper.isDirty()) {
1214 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1216 smapper.assign(this, v.getType(), v);
1221 final Variable vi1 = smapper.get(0);
1223 if (vi1.isCategory2()) {
1224 emit(smapper, this, "var @1 = @2;",
1225 smapper.pushT(vi1.getType()), vi1);
1227 final Variable vi2 = smapper.get(1);
1228 emit(smapper, this, "var @1 = @2, @3 = @4;",
1229 smapper.pushT(vi2.getType()), vi2,
1230 smapper.pushT(vi1.getType()), vi1);
1235 final Variable vi1 = smapper.pop(this);
1236 final Variable vi2 = smapper.pop(this);
1237 final Variable vo3 = smapper.pushT(vi1.getType());
1238 final Variable vo2 = smapper.pushT(vi2.getType());
1239 final Variable vo1 = smapper.pushT(vi1.getType());
1241 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1242 vo1, vi1, vo2, vi2, vo3, vo1);
1246 final Variable vi1 = smapper.pop(this);
1247 final Variable vi2 = smapper.pop(this);
1249 if (vi1.isCategory2()) {
1250 final Variable vo3 = smapper.pushT(vi1.getType());
1251 final Variable vo2 = smapper.pushT(vi2.getType());
1252 final Variable vo1 = smapper.pushT(vi1.getType());
1254 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1255 vo1, vi1, vo2, vi2, vo3, vo1);
1257 final Variable vi3 = smapper.pop(this);
1258 final Variable vo5 = smapper.pushT(vi2.getType());
1259 final Variable vo4 = smapper.pushT(vi1.getType());
1260 final Variable vo3 = smapper.pushT(vi3.getType());
1261 final Variable vo2 = smapper.pushT(vi2.getType());
1262 final Variable vo1 = smapper.pushT(vi1.getType());
1264 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1265 vo1, vi1, vo2, vi2, vo3, vi3);
1266 emit(smapper, this, " @1 = @2, @3 = @4;",
1267 vo4, vo1, vo5, vo2);
1272 final Variable vi1 = smapper.pop(this);
1273 final Variable vi2 = smapper.pop(this);
1275 if (vi2.isCategory2()) {
1276 final Variable vo3 = smapper.pushT(vi1.getType());
1277 final Variable vo2 = smapper.pushT(vi2.getType());
1278 final Variable vo1 = smapper.pushT(vi1.getType());
1280 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1281 vo1, vi1, vo2, vi2, vo3, vo1);
1283 final Variable vi3 = smapper.pop(this);
1284 final Variable vo4 = smapper.pushT(vi1.getType());
1285 final Variable vo3 = smapper.pushT(vi3.getType());
1286 final Variable vo2 = smapper.pushT(vi2.getType());
1287 final Variable vo1 = smapper.pushT(vi1.getType());
1289 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1290 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1295 final Variable vi1 = smapper.pop(this);
1296 final Variable vi2 = smapper.pop(this);
1298 if (vi1.isCategory2()) {
1299 if (vi2.isCategory2()) {
1300 final Variable vo3 = smapper.pushT(vi1.getType());
1301 final Variable vo2 = smapper.pushT(vi2.getType());
1302 final Variable vo1 = smapper.pushT(vi1.getType());
1304 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1305 vo1, vi1, vo2, vi2, vo3, vo1);
1307 final Variable vi3 = smapper.pop(this);
1308 final Variable vo4 = smapper.pushT(vi1.getType());
1309 final Variable vo3 = smapper.pushT(vi3.getType());
1310 final Variable vo2 = smapper.pushT(vi2.getType());
1311 final Variable vo1 = smapper.pushT(vi1.getType());
1313 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1314 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1317 final Variable vi3 = smapper.pop(this);
1319 if (vi3.isCategory2()) {
1320 final Variable vo5 = smapper.pushT(vi2.getType());
1321 final Variable vo4 = smapper.pushT(vi1.getType());
1322 final Variable vo3 = smapper.pushT(vi3.getType());
1323 final Variable vo2 = smapper.pushT(vi2.getType());
1324 final Variable vo1 = smapper.pushT(vi1.getType());
1326 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1327 vo1, vi1, vo2, vi2, vo3, vi3);
1328 emit(smapper, this, " @1 = @2, @3 = @4;",
1329 vo4, vo1, vo5, vo2);
1331 final Variable vi4 = smapper.pop(this);
1332 final Variable vo6 = smapper.pushT(vi2.getType());
1333 final Variable vo5 = smapper.pushT(vi1.getType());
1334 final Variable vo4 = smapper.pushT(vi4.getType());
1335 final Variable vo3 = smapper.pushT(vi3.getType());
1336 final Variable vo2 = smapper.pushT(vi2.getType());
1337 final Variable vo1 = smapper.pushT(vi1.getType());
1339 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1340 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1341 emit(smapper, this, " @1 = @2, @3 = @4;",
1342 vo5, vo1, vo6, vo2);
1348 final Variable vi1 = smapper.get(0);
1349 final Variable vi2 = smapper.get(1);
1351 if (vi1.getType() == vi2.getType()) {
1352 final Variable tmp = smapper.pushT(vi1.getType());
1354 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1359 smapper.pushT(vi1.getType());
1360 smapper.pushT(vi2.getType());
1365 smapper.assign(this, VarType.INTEGER,
1366 "(" + Integer.toString(byteCodes[++i]) + ")");
1369 smapper.assign(this, VarType.INTEGER,
1370 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1374 case opc_getfield: {
1375 int indx = readUShortArg(byteCodes, i);
1376 String[] fi = jc.getFieldInfoName(indx);
1377 final int type = VarType.fromFieldType(fi[2].charAt(0));
1378 final String mangleClass = mangleClassName(fi[0]);
1379 final String mangleClassAccess = accessClass(mangleClass);
1380 smapper.replace(this, type, "@2.call(@1)",
1382 accessField(mangleClassAccess + "(false)",
1388 case opc_putfield: {
1389 int indx = readUShortArg(byteCodes, i);
1390 String[] fi = jc.getFieldInfoName(indx);
1391 final int type = VarType.fromFieldType(fi[2].charAt(0));
1392 final String mangleClass = mangleClassName(fi[0]);
1393 final String mangleClassAccess = accessClass(mangleClass);
1394 emit(smapper, this, "@3.call(@2, @1);",
1397 accessField(mangleClassAccess + "(false)",
1402 case opc_getstatic: {
1403 int indx = readUShortArg(byteCodes, i);
1404 String[] fi = jc.getFieldInfoName(indx);
1405 final int type = VarType.fromFieldType(fi[2].charAt(0));
1406 String ac = accessClass(mangleClassName(fi[0]));
1407 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1408 smapper.assign(this, type, af + "()");
1410 addReference(fi[0]);
1413 case opc_putstatic: {
1414 int indx = readUShortArg(byteCodes, i);
1415 String[] fi = jc.getFieldInfoName(indx);
1416 final int type = VarType.fromFieldType(fi[2].charAt(0));
1417 emit(smapper, this, "@1(false)._@2(@3);",
1418 accessClass(mangleClassName(fi[0])), fi[1],
1419 smapper.popT(type));
1421 addReference(fi[0]);
1424 case opc_checkcast: {
1425 int indx = readUShortArg(byteCodes, i);
1426 generateCheckcast(indx, smapper);
1430 case opc_instanceof: {
1431 int indx = readUShortArg(byteCodes, i);
1432 generateInstanceOf(indx, smapper);
1437 final CharSequence v = smapper.popA();
1440 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1441 smapper.pushA(), v);
1445 case opc_monitorenter: {
1446 debug("/* monitor enter */");
1451 case opc_monitorexit: {
1452 debug("/* monitor exit */");
1463 emit(smapper, this, "throw 'unknown bytecode @1';",
1464 Integer.toString(c));
1468 generateByteCodeComment(prev, i, byteCodes);
1474 if (previousTrap != null) {
1475 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1480 while (openBraces-- > 0) {
1491 private int generateIf(StackMapper mapper, byte[] byteCodes,
1492 int i, final CharSequence v2, final CharSequence v1,
1493 final String test, int topMostLabel
1494 ) throws IOException {
1496 int indx = i + readShortArg(byteCodes, i);
1497 append("if ((").append(v1)
1498 .append(") ").append(test).append(" (")
1499 .append(v2).append(")) ");
1500 goTo(this, i, indx, topMostLabel);
1504 private int readInt4(byte[] byteCodes, int offset) {
1505 final int d = byteCodes[offset + 0] << 24;
1506 final int c = byteCodes[offset + 1] << 16;
1507 final int b = byteCodes[offset + 2] << 8;
1508 final int a = byteCodes[offset + 3];
1509 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1511 private static int readUByte(byte[] byteCodes, int offset) {
1512 return byteCodes[offset] & 0xff;
1515 private static int readUShort(byte[] byteCodes, int offset) {
1516 return ((byteCodes[offset] & 0xff) << 8)
1517 | (byteCodes[offset + 1] & 0xff);
1519 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1520 return readUShort(byteCodes, offsetInstruction + 1);
1523 private static int readShort(byte[] byteCodes, int offset) {
1524 int signed = byteCodes[offset];
1525 byte b0 = (byte)signed;
1526 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1528 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1529 return readShort(byteCodes, offsetInstruction + 1);
1532 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1534 Boolean count = null;
1535 boolean array = false;
1537 int firstPos = sig.length();
1538 while (i < descriptor.length()) {
1539 char ch = descriptor.charAt(i++);
1560 if (ch == 'J' || ch == 'D') {
1566 sig.insert(firstPos, ch);
1568 returnType[0] = '[';
1569 sig.insert(firstPos, "_3");
1578 returnType[0] = 'V';
1579 sig.insert(firstPos, 'V');
1582 int next = descriptor.indexOf(';', i);
1583 String realSig = mangleSig(descriptor, i - 1, next + 1);
1588 sig.append(realSig);
1591 sig.insert(firstPos, realSig);
1593 sig.insert(firstPos, "_3");
1595 returnType[0] = 'L';
1604 throw new IllegalStateException("Invalid char: " + ch);
1609 static String mangleSig(String sig) {
1610 return mangleSig(sig, 0, sig.length());
1613 private static String mangleMethodName(String name) {
1614 StringBuilder sb = new StringBuilder(name.length() * 2);
1615 int last = name.length();
1616 for (int i = 0; i < last; i++) {
1617 final char ch = name.charAt(i);
1619 case '_': sb.append("_1"); break;
1620 default: sb.append(ch); break;
1623 return sb.toString();
1625 private static String mangleSig(String txt, int first, int last) {
1626 StringBuilder sb = new StringBuilder((last - first) * 2);
1627 for (int i = first; i < last; i++) {
1628 final char ch = txt.charAt(i);
1630 case '/': sb.append('_'); break;
1631 case '_': sb.append("_1"); break;
1632 case ';': sb.append("_2"); break;
1633 case '[': sb.append("_3"); break;
1635 if (Character.isJavaIdentifierPart(ch)) {
1639 String hex = Integer.toHexString(ch).toLowerCase();
1640 for (int m = hex.length(); m < 4; m++) {
1648 return sb.toString();
1651 private static String mangleClassName(String name) {
1652 return mangleSig(name);
1655 private static String findMethodName(MethodData m, StringBuilder cnt) {
1656 StringBuilder name = new StringBuilder();
1657 if ("<init>".equals(m.getName())) { // NOI18N
1658 name.append("cons"); // NOI18N
1659 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1660 name.append("class"); // NOI18N
1662 name.append(mangleMethodName(m.getName()));
1665 countArgs(m.getInternalSig(), new char[1], name, cnt);
1666 return name.toString();
1669 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1670 StringBuilder name = new StringBuilder();
1671 String descr = mi[2];//mi.getDescriptor();
1673 if ("<init>".equals(nm)) { // NOI18N
1674 name.append("cons"); // NOI18N
1676 name.append(mangleMethodName(nm));
1678 countArgs(descr, returnType, name, cnt);
1679 return name.toString();
1682 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1683 throws IOException {
1684 int methodIndex = readUShortArg(byteCodes, i);
1685 String[] mi = jc.getFieldInfoName(methodIndex);
1686 char[] returnType = { 'V' };
1687 StringBuilder cnt = new StringBuilder();
1688 String mn = findMethodName(mi, cnt, returnType);
1690 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1691 final CharSequence[] vars = new CharSequence[numArguments];
1693 for (int j = numArguments - 1; j >= 0; --j) {
1694 vars[j] = mapper.popValue();
1697 if (returnType[0] != 'V') {
1700 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1704 final String in = mi[0];
1707 in.equals("org/apidesign/html/boot/spi/Fn") ||
1708 in.equals("org/netbeans/html/boot/spi/Fn")
1710 mcn = "java_lang_Class";
1712 mcn = mangleClassName(in);
1714 String object = accessClass(mcn) + "(false)";
1715 if (mn.startsWith("cons_")) {
1716 object += ".constructor";
1718 append(accessStaticMethod(object, mn, mi));
1724 if (numArguments > 0) {
1726 for (int j = 1; j < numArguments; ++j) {
1736 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1737 throws IOException {
1738 int methodIndex = readUShortArg(byteCodes, i);
1739 String[] mi = jc.getFieldInfoName(methodIndex);
1740 char[] returnType = { 'V' };
1741 StringBuilder cnt = new StringBuilder();
1742 String mn = findMethodName(mi, cnt, returnType);
1744 final int numArguments = cnt.length() + 1;
1745 final CharSequence[] vars = new CharSequence[numArguments];
1747 for (int j = numArguments - 1; j >= 0; --j) {
1748 vars[j] = mapper.popValue();
1751 if (returnType[0] != 'V') {
1753 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1757 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1759 for (int j = 1; j < numArguments; ++j) {
1769 private void addReference(String cn) throws IOException {
1770 if (requireReference(cn)) {
1771 debug(" /* needs " + cn + " */");
1775 private void outType(String d, StringBuilder out) {
1777 while (d.charAt(0) == '[') {
1781 if (d.charAt(0) == 'L') {
1782 assert d.charAt(d.length() - 1) == ';';
1783 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1789 private String encodeConstant(int entryIndex) throws IOException {
1790 String[] classRef = { null };
1791 String s = jc.stringValue(entryIndex, classRef);
1792 if (classRef[0] != null) {
1793 if (classRef[0].startsWith("[")) {
1794 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1796 addReference(classRef[0]);
1797 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1803 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1804 byte[] arr = m.findAnnotationData(true);
1808 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1809 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1810 class P extends AnnotationParser {
1816 String[] args = new String[30];
1822 protected void visitAttr(String type, String attr, String at, String value) {
1823 if (type.equals(jvmType)) {
1824 if ("body".equals(attr)) {
1826 } else if ("args".equals(attr)) {
1827 args[cnt++] = value;
1829 throw new IllegalArgumentException(attr);
1832 if (type.equals(htmlType)) {
1834 if ("body".equals(attr)) {
1836 } else if ("args".equals(attr)) {
1837 args[cnt++] = value;
1838 } else if ("javacall".equals(attr)) {
1839 javacall = "1".equals(value);
1840 } else if ("wait4js".equals(attr)) {
1841 // ignore, we always invoke synchronously
1843 throw new IllegalArgumentException(attr);
1850 if (p.body == null) {
1853 StringBuilder cnt = new StringBuilder();
1854 final String mn = findMethodName(m, cnt);
1855 append("m = ").append(destObject).append(".").append(mn);
1856 append(" = function(");
1859 StringBuilder toValue = new StringBuilder();
1860 for (int i = 0; i < cnt.length(); i++) {
1862 space = outputArg(this, p.args, index);
1863 if (p.html4j && space.length() > 0) {
1864 toValue.append("\n ").append(p.args[index]).append(" = ")
1865 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1866 append(p.args[index]).append(");");
1870 append(") {").append("\n");
1871 append(toValue.toString());
1873 int lastSlash = jc.getClassName().lastIndexOf('/');
1874 final String pkg = jc.getClassName().substring(0, lastSlash);
1875 append(mangleCallbacks(pkg, p.body));
1876 requireReference(pkg + "/$JsCallbacks$");
1884 private static CharSequence mangleCallbacks(String pkgName, String body) {
1885 StringBuilder sb = new StringBuilder();
1888 int next = body.indexOf(".@", pos);
1890 sb.append(body.substring(pos));
1891 body = sb.toString();
1896 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1901 String refId = body.substring(ident, next);
1903 sb.append(body.substring(pos, ident));
1905 int sigBeg = body.indexOf('(', next);
1906 int sigEnd = body.indexOf(')', sigBeg);
1907 int colon4 = body.indexOf("::", next);
1908 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1909 throw new IllegalStateException("Malformed body " + body);
1911 String fqn = body.substring(next + 2, colon4);
1912 String method = body.substring(colon4 + 2, sigBeg);
1913 String params = body.substring(sigBeg, sigEnd + 1);
1915 int paramBeg = body.indexOf('(', sigEnd + 1);
1917 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1918 sb.append(mangleJsCallbacks(fqn, method, params, false));
1919 sb.append("(").append(refId);
1920 if (body.charAt(paramBeg + 1) != ')') {
1928 int next = body.indexOf("@", pos);
1933 sb.append(body.substring(pos));
1937 sb = new StringBuilder();
1940 sb.append(body.substring(pos, next));
1942 int sigBeg = body.indexOf('(', next);
1943 int sigEnd = body.indexOf(')', sigBeg);
1944 int colon4 = body.indexOf("::", next);
1945 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1946 throw new IllegalStateException("Malformed body " + body);
1948 String fqn = body.substring(next + 1, colon4);
1949 String method = body.substring(colon4 + 2, sigBeg);
1950 String params = body.substring(sigBeg, sigEnd + 1);
1952 int paramBeg = body.indexOf('(', sigEnd + 1);
1954 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1955 sb.append(mangleJsCallbacks(fqn, method, params, true));
1961 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1962 if (params.startsWith("(")) {
1963 params = params.substring(1);
1965 if (params.endsWith(")")) {
1966 params = params.substring(0, params.length() - 1);
1968 StringBuilder sb = new StringBuilder();
1969 final String fqnu = fqn.replace('.', '_');
1970 final String rfqn = mangleClassName(fqnu);
1971 final String rm = mangleMethodName(method);
1974 StringBuilder pb = new StringBuilder();
1975 int len = params.length();
1977 while (indx < len) {
1978 char ch = params.charAt(indx);
1979 if (ch == '[' || ch == 'L') {
1980 pb.append("Ljava/lang/Object;");
1981 indx = params.indexOf(';', indx) + 1;
1987 srp = mangleSig(pb.toString());
1989 final String rp = mangleSig(params);
1990 final String mrp = mangleMethodName(rp);
1991 sb.append(rfqn).append("$").append(rm).
1992 append('$').append(mrp).append("__Ljava_lang_Object_2");
1994 sb.append('L').append(fqnu).append("_2");
1997 return sb.toString();
2000 private static String className(ClassData jc) {
2001 //return jc.getName().getInternalName().replace('/', '_');
2002 return mangleClassName(jc.getClassName());
2005 private static String[] findAnnotation(
2006 byte[] arr, ClassData cd, final String className,
2007 final String... attrNames
2008 ) throws IOException {
2012 final String[] values = new String[attrNames.length];
2013 final boolean[] found = { false };
2014 final String jvmType = "L" + className.replace('.', '/') + ";";
2015 AnnotationParser ap = new AnnotationParser(false, true) {
2017 protected void visitAttr(String type, String attr, String at, String value) {
2018 if (type.equals(jvmType)) {
2020 for (int i = 0; i < attrNames.length; i++) {
2021 if (attrNames[i].equals(attr)) {
2030 return found[0] ? values : null;
2033 private CharSequence initField(FieldData v) {
2034 final String is = v.getInternalSig();
2035 if (is.length() == 1) {
2036 switch (is.charAt(0)) {
2042 case 'I': return " = 0;";
2044 case 'D': return " = 0.0;";
2046 throw new IllegalStateException(is);
2052 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2053 AnnotationParser ap = new AnnotationParser(true, false) {
2054 int[] cnt = new int[32];
2058 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2059 final String slashType = attrType.substring(1, attrType.length() - 1);
2060 requireReference(slashType);
2062 if (cnt[depth]++ > 0) {
2066 append('"').append(attrType).append("\" : ");
2073 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2079 protected void visitValueStart(String attrName, char type) throws IOException {
2080 if (cnt[depth]++ > 0) {
2084 if (attrName != null) {
2085 append('"').append(attrName).append("\" : ");
2093 protected void visitValueEnd(String attrName, char type) throws IOException {
2101 protected void visitAttr(String type, String attr, String attrType, String value)
2102 throws IOException {
2103 if (attr == null && value == null) {
2110 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2111 throws IOException {
2112 final String slashType = attrType.substring(1, attrType.length() - 1);
2113 requireReference(slashType);
2115 final String cn = mangleClassName(slashType);
2116 append(accessClass(cn))
2117 .append("(false)['valueOf__L").
2119 append("_2Ljava_lang_String_2']('").
2127 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2128 final String name = args[indx];
2132 if (name.contains(",")) {
2133 throw new IOException("Wrong parameter with ',': " + name);
2139 final void emitNoFlush(
2141 final String format, final CharSequence... params
2142 ) throws IOException {
2143 emitImpl(this, format, params);
2145 static final void emit(
2147 final Appendable out,
2148 final String format, final CharSequence... params
2149 ) throws IOException {
2151 emitImpl(out, format, params);
2153 static void emitImpl(final Appendable out,
2154 final String format,
2155 final CharSequence... params) throws IOException {
2156 final int length = format.length();
2159 int paramOffset = format.indexOf('@');
2160 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2161 final char paramChar = format.charAt(paramOffset + 1);
2162 if ((paramChar >= '1') && (paramChar <= '9')) {
2163 final int paramIndex = paramChar - '0' - 1;
2165 out.append(format, processed, paramOffset);
2166 out.append(params[paramIndex]);
2169 processed = paramOffset + 1;
2172 paramOffset = format.indexOf('@', paramOffset + 1);
2175 out.append(format, processed, length);
2178 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2179 append("} catch (e) {\n");
2181 for (TrapData e : traps) {
2185 if (e.catch_cpx != 0) { //not finally
2186 final String classInternalName = jc.getClassName(e.catch_cpx);
2187 addReference(classInternalName);
2188 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2189 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2190 append("var stA0 = e;");
2191 goTo(this, current, e.handler_pc, topMostLabel);
2194 finallyPC = e.handler_pc;
2197 if (finallyPC == -1) {
2200 append("var stA0 = e;");
2201 goTo(this, current, finallyPC, topMostLabel);
2206 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2209 out.append("{ gt = 0; continue X_" + to + "; }");
2211 out.append("{ gt = " + to + "; continue X_0; }");
2214 out.append("{ gt = " + to + "; break IF; }");
2218 private static void emitIf(
2220 Appendable out, String pattern,
2222 int current, int to, int canBack
2223 ) throws IOException {
2225 emitImpl(out, pattern, param);
2226 goTo(out, current, to, canBack);
2229 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2232 case 4: jvmType = "[Z"; break;
2233 case 5: jvmType = "[C"; break;
2234 case 6: jvmType = "[F"; break;
2235 case 7: jvmType = "[D"; break;
2236 case 8: jvmType = "[B"; break;
2237 case 9: jvmType = "[S"; break;
2238 case 10: jvmType = "[I"; break;
2239 case 11: jvmType = "[J"; break;
2240 default: throw new IllegalStateException("Array type: " + atype);
2243 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2244 smapper.popI(), smapper.pushA(), jvmType);
2247 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2248 String typeName = jc.getClassName(type);
2249 String ref = "null";
2250 if (typeName.startsWith("[")) {
2251 typeName = "'[" + typeName + "'";
2253 ref = "vm." + mangleClassName(typeName);
2254 typeName = "'[L" + typeName + ";'";
2257 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2258 smapper.popI(), smapper.pushA(), typeName, ref);
2261 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2262 String typeName = jc.getClassName(type);
2263 int dim = readUByte(byteCodes, ++i);
2264 StringBuilder dims = new StringBuilder();
2266 for (int d = 0; d < dim; d++) {
2268 dims.insert(1, ",");
2270 dims.insert(1, smapper.popI());
2274 if (typeName.charAt(dim) == 'L') {
2275 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2278 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2279 dims.toString(), smapper.pushA(), typeName, fn
2284 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2285 int table = i / 4 * 4 + 4;
2286 int dflt = i + readInt4(byteCodes, table);
2288 int low = readInt4(byteCodes, table);
2290 int high = readInt4(byteCodes, table);
2292 final CharSequence swVar = smapper.popValue();
2293 smapper.flush(this);
2294 append("switch (").append(swVar).append(") {\n");
2295 while (low <= high) {
2296 int offset = i + readInt4(byteCodes, table);
2298 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2301 append(" default: ");
2302 goTo(this, i, dflt, topMostLabel);
2308 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2309 int table = i / 4 * 4 + 4;
2310 int dflt = i + readInt4(byteCodes, table);
2312 int n = readInt4(byteCodes, table);
2314 final CharSequence swVar = smapper.popValue();
2315 smapper.flush(this);
2316 append("switch (").append(swVar).append(") {\n");
2318 int cnstnt = readInt4(byteCodes, table);
2320 int offset = i + readInt4(byteCodes, table);
2322 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2324 append(" default: ");
2325 goTo(this, i, dflt, topMostLabel);
2331 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2332 String type = jc.getClassName(indx);
2333 if (!type.startsWith("[")) {
2335 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2336 smapper.popA(), smapper.pushI(),
2337 type.replace('/', '_'));
2340 while (type.charAt(cnt) == '[') {
2343 if (type.charAt(cnt) == 'L') {
2344 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2346 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2347 smapper.popA(), smapper.pushI(),
2352 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2353 smapper.popA(), smapper.pushI(), type
2359 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2360 String type = jc.getClassName(indx);
2361 if (!type.startsWith("[")) {
2362 emitNoFlush(smapper,
2363 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2364 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2367 while (type.charAt(cnt) == '[') {
2370 if (type.charAt(cnt) == 'L') {
2371 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2372 emitNoFlush(smapper,
2373 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2374 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2377 emitNoFlush(smapper,
2378 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2379 smapper.getT(0, VarType.REFERENCE, false), type
2385 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2386 for (int j = prev; j <= i; j++) {
2388 final int cc = readUByte(byteCodes, j);
2389 append(Integer.toString(cc));
2393 @JavaScriptBody(args = "msg", body = "")
2394 private static void println(String msg) {
2395 System.err.println(msg);