String is like a primitive type. Keep its signature.
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)",
1403 case opc_putfield: {
1404 int indx = readUShortArg(byteCodes, i);
1405 String[] fi = jc.getFieldInfoName(indx);
1406 final int type = VarType.fromFieldType(fi[2].charAt(0));
1407 final String mangleClass = mangleClassName(fi[0]);
1408 final String mangleClassAccess = accessClass(mangleClass);
1409 emit(smapper, this, "@3.call(@2, @1);",
1412 accessField(mangleClassAccess + "(false)",
1417 case opc_getstatic: {
1418 int indx = readUShortArg(byteCodes, i);
1419 String[] fi = jc.getFieldInfoName(indx);
1420 final int type = VarType.fromFieldType(fi[2].charAt(0));
1421 String ac = accessClass(mangleClassName(fi[0]));
1422 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1423 smapper.assign(this, type, af + "()");
1425 addReference(fi[0]);
1428 case opc_putstatic: {
1429 int indx = readUShortArg(byteCodes, i);
1430 String[] fi = jc.getFieldInfoName(indx);
1431 final int type = VarType.fromFieldType(fi[2].charAt(0));
1432 emit(smapper, this, "@1(false)._@2(@3);",
1433 accessClass(mangleClassName(fi[0])), fi[1],
1434 smapper.popT(type));
1436 addReference(fi[0]);
1439 case opc_checkcast: {
1440 int indx = readUShortArg(byteCodes, i);
1441 generateCheckcast(indx, smapper);
1445 case opc_instanceof: {
1446 int indx = readUShortArg(byteCodes, i);
1447 generateInstanceOf(indx, smapper);
1452 final CharSequence v = smapper.popA();
1455 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1456 smapper.pushA(), v);
1460 case opc_monitorenter: {
1461 debug("/* monitor enter */");
1466 case opc_monitorexit: {
1467 debug("/* monitor exit */");
1478 emit(smapper, this, "throw 'unknown bytecode @1';",
1479 Integer.toString(c));
1483 generateByteCodeComment(prev, i, byteCodes);
1489 if (previousTrap != null) {
1490 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1495 while (openBraces-- > 0) {
1506 private int generateIf(StackMapper mapper, byte[] byteCodes,
1507 int i, final CharSequence v2, final CharSequence v1,
1508 final String test, int topMostLabel
1509 ) throws IOException {
1511 int indx = i + readShortArg(byteCodes, i);
1512 append("if ((").append(v1)
1513 .append(") ").append(test).append(" (")
1514 .append(v2).append(")) ");
1515 goTo(this, i, indx, topMostLabel);
1519 private int readInt4(byte[] byteCodes, int offset) {
1520 final int d = byteCodes[offset + 0] << 24;
1521 final int c = byteCodes[offset + 1] << 16;
1522 final int b = byteCodes[offset + 2] << 8;
1523 final int a = byteCodes[offset + 3];
1524 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1526 private static int readUByte(byte[] byteCodes, int offset) {
1527 return byteCodes[offset] & 0xff;
1530 private static int readUShort(byte[] byteCodes, int offset) {
1531 return ((byteCodes[offset] & 0xff) << 8)
1532 | (byteCodes[offset + 1] & 0xff);
1534 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1535 return readUShort(byteCodes, offsetInstruction + 1);
1538 private static int readShort(byte[] byteCodes, int offset) {
1539 int signed = byteCodes[offset];
1540 byte b0 = (byte)signed;
1541 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1543 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1544 return readShort(byteCodes, offsetInstruction + 1);
1547 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1549 Boolean count = null;
1550 boolean array = false;
1552 int firstPos = sig.length();
1553 while (i < descriptor.length()) {
1554 char ch = descriptor.charAt(i++);
1575 if (ch == 'J' || ch == 'D') {
1581 sig.insert(firstPos, ch);
1583 returnType[0] = '[';
1584 sig.insert(firstPos, "_3");
1593 returnType[0] = 'V';
1594 sig.insert(firstPos, 'V');
1597 int next = descriptor.indexOf(';', i);
1598 String realSig = mangleSig(descriptor, i - 1, next + 1);
1603 sig.append(realSig);
1606 sig.insert(firstPos, realSig);
1608 sig.insert(firstPos, "_3");
1610 returnType[0] = 'L';
1619 throw new IllegalStateException("Invalid char: " + ch);
1624 static String mangleSig(String sig) {
1625 return mangleSig(sig, 0, sig.length());
1628 private static String mangleMethodName(String name) {
1629 StringBuilder sb = new StringBuilder(name.length() * 2);
1630 int last = name.length();
1631 for (int i = 0; i < last; i++) {
1632 final char ch = name.charAt(i);
1634 case '_': sb.append("_1"); break;
1635 default: sb.append(ch); break;
1638 return sb.toString();
1640 private static String mangleSig(String txt, int first, int last) {
1641 StringBuilder sb = new StringBuilder((last - first) * 2);
1642 for (int i = first; i < last; i++) {
1643 final char ch = txt.charAt(i);
1645 case '/': sb.append('_'); break;
1646 case '_': sb.append("_1"); break;
1647 case ';': sb.append("_2"); break;
1648 case '[': sb.append("_3"); break;
1650 if (Character.isJavaIdentifierPart(ch)) {
1654 String hex = Integer.toHexString(ch).toLowerCase();
1655 for (int m = hex.length(); m < 4; m++) {
1663 return sb.toString();
1666 private static String mangleClassName(String name) {
1667 return mangleSig(name);
1670 private static String findMethodName(MethodData m, StringBuilder cnt) {
1671 StringBuilder name = new StringBuilder();
1672 if ("<init>".equals(m.getName())) { // NOI18N
1673 name.append("cons"); // NOI18N
1674 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1675 name.append("class"); // NOI18N
1677 name.append(mangleMethodName(m.getName()));
1680 countArgs(m.getInternalSig(), new char[1], name, cnt);
1681 return name.toString();
1684 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1685 StringBuilder name = new StringBuilder();
1686 String descr = mi[2];//mi.getDescriptor();
1688 if ("<init>".equals(nm)) { // NOI18N
1689 name.append("cons"); // NOI18N
1691 name.append(mangleMethodName(nm));
1693 countArgs(descr, returnType, name, cnt);
1694 return name.toString();
1697 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1698 throws IOException {
1699 int methodIndex = readUShortArg(byteCodes, i);
1700 String[] mi = jc.getFieldInfoName(methodIndex);
1701 char[] returnType = { 'V' };
1702 StringBuilder cnt = new StringBuilder();
1703 String mn = findMethodName(mi, cnt, returnType);
1705 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1706 final CharSequence[] vars = new CharSequence[numArguments];
1708 for (int j = numArguments - 1; j >= 0; --j) {
1709 vars[j] = mapper.popValue();
1712 if (returnType[0] != 'V') {
1715 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1719 final String in = mi[0];
1722 in.equals("org/apidesign/html/boot/spi/Fn") ||
1723 in.equals("org/netbeans/html/boot/spi/Fn")
1725 mcn = "java_lang_Class";
1727 mcn = mangleClassName(in);
1729 String object = accessClass(mcn) + "(false)";
1730 if (mn.startsWith("cons_")) {
1731 object += ".constructor";
1733 append(accessStaticMethod(object, mn, mi));
1739 if (numArguments > 0) {
1741 for (int j = 1; j < numArguments; ++j) {
1751 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1752 throws IOException {
1753 int methodIndex = readUShortArg(byteCodes, i);
1754 String[] mi = jc.getFieldInfoName(methodIndex);
1755 char[] returnType = { 'V' };
1756 StringBuilder cnt = new StringBuilder();
1757 String mn = findMethodName(mi, cnt, returnType);
1759 final int numArguments = cnt.length() + 1;
1760 final CharSequence[] vars = new CharSequence[numArguments];
1762 for (int j = numArguments - 1; j >= 0; --j) {
1763 vars[j] = mapper.popValue();
1766 if (returnType[0] != 'V') {
1768 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1772 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1774 for (int j = 1; j < numArguments; ++j) {
1784 private void addReference(String cn) throws IOException {
1785 if (requireReference(cn)) {
1786 debug(" /* needs " + cn + " */");
1790 private void outType(String d, StringBuilder out) {
1792 while (d.charAt(0) == '[') {
1796 if (d.charAt(0) == 'L') {
1797 assert d.charAt(d.length() - 1) == ';';
1798 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1804 private String encodeConstant(int entryIndex) throws IOException {
1805 String[] classRef = { null };
1806 String s = jc.stringValue(entryIndex, classRef);
1807 if (classRef[0] != null) {
1808 if (classRef[0].startsWith("[")) {
1809 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1811 addReference(classRef[0]);
1812 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1818 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1819 byte[] arr = m.findAnnotationData(true);
1823 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1824 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1825 class P extends AnnotationParser {
1831 String[] args = new String[30];
1837 protected void visitAttr(String type, String attr, String at, String value) {
1838 if (type.equals(jvmType)) {
1839 if ("body".equals(attr)) {
1841 } else if ("args".equals(attr)) {
1842 args[cnt++] = value;
1844 throw new IllegalArgumentException(attr);
1847 if (type.equals(htmlType)) {
1849 if ("body".equals(attr)) {
1851 } else if ("args".equals(attr)) {
1852 args[cnt++] = value;
1853 } else if ("javacall".equals(attr)) {
1854 javacall = "1".equals(value);
1855 } else if ("wait4js".equals(attr)) {
1856 // ignore, we always invoke synchronously
1858 throw new IllegalArgumentException(attr);
1865 if (p.body == null) {
1868 StringBuilder cnt = new StringBuilder();
1869 final String mn = findMethodName(m, cnt);
1870 append("m = ").append(destObject).append(".").append(mn);
1871 append(" = function(");
1874 StringBuilder toValue = new StringBuilder();
1875 for (int i = 0; i < cnt.length(); i++) {
1877 space = outputArg(this, p.args, index);
1878 if (p.html4j && space.length() > 0) {
1879 toValue.append("\n ").append(p.args[index]).append(" = ")
1880 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1881 append(p.args[index]).append(");");
1885 append(") {").append("\n");
1886 append(toValue.toString());
1888 int lastSlash = jc.getClassName().lastIndexOf('/');
1889 final String pkg = jc.getClassName().substring(0, lastSlash);
1890 append(mangleCallbacks(pkg, p.body));
1891 requireReference(pkg + "/$JsCallbacks$");
1899 private static CharSequence mangleCallbacks(String pkgName, String body) {
1900 StringBuilder sb = new StringBuilder();
1903 int next = body.indexOf(".@", pos);
1905 sb.append(body.substring(pos));
1906 body = sb.toString();
1911 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1916 String refId = body.substring(ident, next);
1918 sb.append(body.substring(pos, ident));
1920 int sigBeg = body.indexOf('(', next);
1921 int sigEnd = body.indexOf(')', sigBeg);
1922 int colon4 = body.indexOf("::", next);
1923 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1924 throw new IllegalStateException("Malformed body " + body);
1926 String fqn = body.substring(next + 2, colon4);
1927 String method = body.substring(colon4 + 2, sigBeg);
1928 String params = body.substring(sigBeg, sigEnd + 1);
1930 int paramBeg = body.indexOf('(', sigEnd + 1);
1932 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1933 sb.append(mangleJsCallbacks(fqn, method, params, false));
1934 sb.append("(").append(refId);
1935 if (body.charAt(paramBeg + 1) != ')') {
1943 int next = body.indexOf("@", pos);
1948 sb.append(body.substring(pos));
1952 sb = new StringBuilder();
1955 sb.append(body.substring(pos, next));
1957 int sigBeg = body.indexOf('(', next);
1958 int sigEnd = body.indexOf(')', sigBeg);
1959 int colon4 = body.indexOf("::", next);
1960 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1961 throw new IllegalStateException("Malformed body " + body);
1963 String fqn = body.substring(next + 1, colon4);
1964 String method = body.substring(colon4 + 2, sigBeg);
1965 String params = body.substring(sigBeg, sigEnd + 1);
1967 int paramBeg = body.indexOf('(', sigEnd + 1);
1969 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1970 sb.append(mangleJsCallbacks(fqn, method, params, true));
1976 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1977 if (params.startsWith("(")) {
1978 params = params.substring(1);
1980 if (params.endsWith(")")) {
1981 params = params.substring(0, params.length() - 1);
1983 StringBuilder sb = new StringBuilder();
1984 final String fqnu = fqn.replace('.', '_');
1985 final String rfqn = mangleClassName(fqnu);
1986 final String rm = mangleMethodName(method);
1989 StringBuilder pb = new StringBuilder();
1990 int len = params.length();
1992 while (indx < len) {
1993 char ch = params.charAt(indx);
1994 if (ch == '[' || ch == 'L') {
1995 int column = params.indexOf(';', indx) + 1;
1996 if (column > indx) {
1997 String real = params.substring(indx, column);
1998 if ("Ljava/lang/String;".equals(real)) {
1999 pb.append("Ljava/lang/String;");
2004 pb.append("Ljava/lang/Object;");
2011 srp = mangleSig(pb.toString());
2013 final String rp = mangleSig(params);
2014 final String mrp = mangleMethodName(rp);
2015 sb.append(rfqn).append("$").append(rm).
2016 append('$').append(mrp).append("__Ljava_lang_Object_2");
2018 sb.append('L').append(fqnu).append("_2");
2021 return sb.toString();
2024 private static String className(ClassData jc) {
2025 //return jc.getName().getInternalName().replace('/', '_');
2026 return mangleClassName(jc.getClassName());
2029 private static String[] findAnnotation(
2030 byte[] arr, ClassData cd, final String className,
2031 final String... attrNames
2032 ) throws IOException {
2036 final String[] values = new String[attrNames.length];
2037 final boolean[] found = { false };
2038 final String jvmType = "L" + className.replace('.', '/') + ";";
2039 AnnotationParser ap = new AnnotationParser(false, true) {
2041 protected void visitAttr(String type, String attr, String at, String value) {
2042 if (type.equals(jvmType)) {
2044 for (int i = 0; i < attrNames.length; i++) {
2045 if (attrNames[i].equals(attr)) {
2054 return found[0] ? values : null;
2057 private CharSequence initField(FieldData v) {
2058 final String is = v.getInternalSig();
2059 if (is.length() == 1) {
2060 switch (is.charAt(0)) {
2066 case 'I': return " = 0;";
2068 case 'D': return " = 0.0;";
2070 throw new IllegalStateException(is);
2076 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2077 AnnotationParser ap = new AnnotationParser(true, false) {
2078 int[] cnt = new int[32];
2082 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2083 final String slashType = attrType.substring(1, attrType.length() - 1);
2084 requireReference(slashType);
2086 if (cnt[depth]++ > 0) {
2090 append('"').append(attrType).append("\" : ");
2097 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2103 protected void visitValueStart(String attrName, char type) throws IOException {
2104 if (cnt[depth]++ > 0) {
2108 if (attrName != null) {
2109 append('"').append(attrName).append("\" : ");
2117 protected void visitValueEnd(String attrName, char type) throws IOException {
2125 protected void visitAttr(String type, String attr, String attrType, String value)
2126 throws IOException {
2127 if (attr == null && value == null) {
2134 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2135 throws IOException {
2136 final String slashType = attrType.substring(1, attrType.length() - 1);
2137 requireReference(slashType);
2139 final String cn = mangleClassName(slashType);
2140 append(accessClass(cn))
2141 .append("(false)['valueOf__L").
2143 append("_2Ljava_lang_String_2']('").
2151 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2152 final String name = args[indx];
2156 if (name.contains(",")) {
2157 throw new IOException("Wrong parameter with ',': " + name);
2163 final void emitNoFlush(
2165 final String format, final CharSequence... params
2166 ) throws IOException {
2167 emitImpl(this, format, params);
2169 static final void emit(
2171 final Appendable out,
2172 final String format, final CharSequence... params
2173 ) throws IOException {
2175 emitImpl(out, format, params);
2177 static void emitImpl(final Appendable out,
2178 final String format,
2179 final CharSequence... params) throws IOException {
2180 final int length = format.length();
2183 int paramOffset = format.indexOf('@');
2184 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2185 final char paramChar = format.charAt(paramOffset + 1);
2186 if ((paramChar >= '1') && (paramChar <= '9')) {
2187 final int paramIndex = paramChar - '0' - 1;
2189 out.append(format, processed, paramOffset);
2190 out.append(params[paramIndex]);
2193 processed = paramOffset + 1;
2196 paramOffset = format.indexOf('@', paramOffset + 1);
2199 out.append(format, processed, length);
2202 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2203 append("} catch (e) {\n");
2205 for (TrapData e : traps) {
2209 if (e.catch_cpx != 0) { //not finally
2210 final String classInternalName = jc.getClassName(e.catch_cpx);
2211 addReference(classInternalName);
2212 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2213 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2214 append("var stA0 = e;");
2215 goTo(this, current, e.handler_pc, topMostLabel);
2218 finallyPC = e.handler_pc;
2221 if (finallyPC == -1) {
2224 append("var stA0 = e;");
2225 goTo(this, current, finallyPC, topMostLabel);
2230 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2233 out.append("{ gt = 0; continue X_" + to + "; }");
2235 out.append("{ gt = " + to + "; continue X_0; }");
2238 out.append("{ gt = " + to + "; break IF; }");
2242 private static void emitIf(
2244 Appendable out, String pattern,
2246 int current, int to, int canBack
2247 ) throws IOException {
2249 emitImpl(out, pattern, param);
2250 goTo(out, current, to, canBack);
2253 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2256 case 4: jvmType = "[Z"; break;
2257 case 5: jvmType = "[C"; break;
2258 case 6: jvmType = "[F"; break;
2259 case 7: jvmType = "[D"; break;
2260 case 8: jvmType = "[B"; break;
2261 case 9: jvmType = "[S"; break;
2262 case 10: jvmType = "[I"; break;
2263 case 11: jvmType = "[J"; break;
2264 default: throw new IllegalStateException("Array type: " + atype);
2267 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2268 smapper.popI(), smapper.pushA(), jvmType);
2271 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2272 String typeName = jc.getClassName(type);
2273 String ref = "null";
2274 if (typeName.startsWith("[")) {
2275 typeName = "'[" + typeName + "'";
2277 ref = "vm." + mangleClassName(typeName);
2278 typeName = "'[L" + typeName + ";'";
2281 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2282 smapper.popI(), smapper.pushA(), typeName, ref);
2285 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2286 String typeName = jc.getClassName(type);
2287 int dim = readUByte(byteCodes, ++i);
2288 StringBuilder dims = new StringBuilder();
2290 for (int d = 0; d < dim; d++) {
2292 dims.insert(1, ",");
2294 dims.insert(1, smapper.popI());
2298 if (typeName.charAt(dim) == 'L') {
2299 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2302 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2303 dims.toString(), smapper.pushA(), typeName, fn
2308 private int generateTableSwitch(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 low = readInt4(byteCodes, table);
2314 int high = readInt4(byteCodes, table);
2316 final CharSequence swVar = smapper.popValue();
2317 smapper.flush(this);
2318 append("switch (").append(swVar).append(") {\n");
2319 while (low <= high) {
2320 int offset = i + readInt4(byteCodes, table);
2322 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2325 append(" default: ");
2326 goTo(this, i, dflt, topMostLabel);
2332 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2333 int table = i / 4 * 4 + 4;
2334 int dflt = i + readInt4(byteCodes, table);
2336 int n = readInt4(byteCodes, table);
2338 final CharSequence swVar = smapper.popValue();
2339 smapper.flush(this);
2340 append("switch (").append(swVar).append(") {\n");
2342 int cnstnt = readInt4(byteCodes, table);
2344 int offset = i + readInt4(byteCodes, table);
2346 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2348 append(" default: ");
2349 goTo(this, i, dflt, topMostLabel);
2355 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2356 String type = jc.getClassName(indx);
2357 if (!type.startsWith("[")) {
2359 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2360 smapper.popA(), smapper.pushI(),
2361 type.replace('/', '_'));
2364 while (type.charAt(cnt) == '[') {
2367 if (type.charAt(cnt) == 'L') {
2368 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2370 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2371 smapper.popA(), smapper.pushI(),
2376 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2377 smapper.popA(), smapper.pushI(), type
2383 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2384 String type = jc.getClassName(indx);
2385 if (!type.startsWith("[")) {
2386 emitNoFlush(smapper,
2387 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2388 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2391 while (type.charAt(cnt) == '[') {
2394 if (type.charAt(cnt) == 'L') {
2395 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2396 emitNoFlush(smapper,
2397 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2398 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2401 emitNoFlush(smapper,
2402 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2403 smapper.getT(0, VarType.REFERENCE, false), type
2409 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2410 for (int j = prev; j <= i; j++) {
2412 final int cc = readUByte(byteCodes, j);
2413 append(Integer.toString(cc));
2417 @JavaScriptBody(args = "msg", body = "")
2418 private static void println(String msg) {
2419 System.err.println(msg);