Attempting to use for+switch flow and compare it to current nested-for one. jbox2d seems to preform similarly well.
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import org.apidesign.bck2brwsr.core.JavaScriptBody;
23 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
25 /** Translator of the code inside class files to JavaScript.
27 * @author Jaroslav Tulach <jtulach@netbeans.org>
29 abstract class ByteCodeToJavaScript implements Appendable {
31 private final Appendable out;
32 private final StringArray classRefs = new StringArray();
33 private boolean outChanged;
34 private boolean callbacks;
36 protected ByteCodeToJavaScript(Appendable out) {
41 public final Appendable append(CharSequence csq) throws IOException {
48 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
49 out.append(csq, start, end);
55 public final Appendable append(char c) throws IOException {
61 /* Collects additional required resources.
63 * @param internalClassName classes that were referenced and should be loaded in order the
64 * generated JavaScript code works properly. The names are in internal
65 * JVM form so String is <code>java/lang/String</code>.
67 protected abstract boolean requireReference(String internalClassName);
70 * @param resourcePath name of resources to read
72 protected abstract void requireScript(String resourcePath) throws IOException;
74 protected abstract void requireResource(String resourcePath) throws IOException;
76 /** Allows subclasses to redefine what field a function representing a
77 * class gets assigned. By default it returns the suggested name followed
78 * by <code>" = "</code>;
80 * @param className suggested name of the class
82 /* protected */ String assignClass(String className) {
83 return className + " = ";
85 /* protected */ String accessClass(String classOperation) {
86 return classOperation;
89 final String accessClassFalse(String classOperation) {
90 if (jc.getClassName().replace('/', '_').equals(classOperation)) {
93 classRefs.addIfMissing(classOperation);
94 return "(refs_" + classOperation + " || (refs_" + classOperation + " = " + accessClass(classOperation) + "(false)))";
97 protected String accessField(String object, String mangledName,
98 String[] fieldInfoName) throws IOException {
99 return object + "." + mangledName;
102 protected String accessStaticMethod(
105 String[] fieldInfoName) throws IOException {
106 return object + "." + mangledName;
109 protected String accessVirtualMethod(
112 String[] fieldInfoName,
114 ) throws IOException {
115 return object + "." + mangledName + '(';
118 protected void declaredClass(ClassData classData, String mangledName)
122 protected void declaredField(FieldData fieldData,
124 String mangledName) throws IOException {
127 protected void declaredMethod(MethodData methodData,
129 String mangledName) throws IOException {
132 /** Prints out a debug message.
134 * @param msg the message
135 * @return true if the message has been printed
136 * @throws IOException
138 boolean debug(String msg) throws IOException {
144 * Converts a given class file to a JavaScript version.
146 * @param classFile input stream with code of the .class file
147 * @return the initialization code for this class, if any. Otherwise <code>null</code>
149 * @throws IOException if something goes wrong during read or write or translating
152 public String compile(InputStream classFile) throws IOException {
153 return compile(new ClassData(classFile));
156 protected String compile(ClassData classData) throws IOException {
158 final String cn = this.jc.getClassName();
160 return compileImpl(cn);
161 } catch (IOException ex) {
162 throw new IOException("Cannot compile " + cn + ":", ex);
166 private String compileImpl(final String cn) throws IOException {
167 this.callbacks = cn.endsWith("/$JsCallbacks$");
168 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
169 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
170 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
173 byte[] arrData = jc.findAnnotationData(true);
175 String[] arr = findAnnotation(arrData, jc,
176 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
177 "resource", "processByteCode"
180 if (!arr[0].isEmpty()) {
181 requireScript(arr[0]);
183 if ("0".equals(arr[1])) {
188 final String jsResource;
190 String[] arr = findAnnotation(arrData, jc,
191 "net.java.html.js.JavaScriptResource",
195 if (arr[0].startsWith("/")) {
198 int last = cn.lastIndexOf('/');
199 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
205 String[] proto = findAnnotation(arrData, jc,
206 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
207 "container", "prototype"
209 StringArray toInitilize = new StringArray();
210 final String className = className(jc);
211 append("\n\n").append(assignClass(className));
212 append("function ").append(className).append("() {");
214 append("\n var CLS = ").append(className).append(';');
215 append("\n if (!CLS.$class) {");
217 String sc = jc.getSuperClassName(); // with _
218 append("\n var pp = ").
219 append(accessClass(mangleClassName(sc))).append("(true);");
220 append("\n var p = CLS.prototype = pp;");
221 append("\n var c = p;");
222 append("\n var sprcls = pp.constructor.$class;");
224 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
225 if (proto[0] == null) {
228 append("\n var c = ").append(proto[0]).append(";");
229 append("\n var sprcls = null;");
231 for (FieldData v : jc.getFields()) {
233 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
234 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
238 append("\n CLS.fld_").append(v.getName()).append(initField(v));
239 append("\n m = c._").append(v.getName()).append(" = function (v) {")
240 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
241 .append(" = v; return CLS.fld_").
242 append(v.getName()).append("; };");
244 append("\n m = c._").append(v.getName()).append(" = function (v) {")
245 .append(" if (arguments.length == 1) this.fld_").
246 append(className).append('_').append(v.getName())
247 .append(" = v; return this.fld_").
248 append(className).append('_').append(v.getName())
252 declaredField(v, "c", "_" + v.getName());
254 for (MethodData m : jc.getMethods()) {
255 byte[] onlyArr = m.findAnnotationData(true);
256 if (javaScriptOnly(onlyArr)) continue;
262 mn = generateStaticMethod(destObject, m, toInitilize);
264 if (m.isConstructor()) {
266 mn = generateInstanceMethod(destObject, m);
269 mn = generateInstanceMethod(destObject, m);
272 declaredMethod(m, destObject, mn);
273 byte[] runAnno = m.findAnnotationData(false);
274 if (runAnno != null) {
275 append("\n m.anno = {");
276 generateAnno(jc, runAnno);
279 append("\n m.access = " + m.getAccess()).append(";");
280 append("\n m.cls = CLS;");
282 append("\n c.constructor = CLS;");
283 append("\n function ").append(className).append("fillInstOf(x) {");
284 String instOfName = "$instOf_" + className;
285 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
286 if (jc.isInterface()) {
287 for (MethodData m : jc.getMethods()) {
288 if ((m.getAccess() & ACC_ABSTRACT) == 0
289 && (m.getAccess() & ACC_STATIC) == 0
290 && (m.getAccess() & ACC_PRIVATE) == 0) {
291 final String mn = findMethodName(m, new StringBuilder());
292 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
296 for (String superInterface : jc.getSuperInterfaces()) {
297 String intrfc = superInterface.replace('/', '_');
298 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
299 requireReference(superInterface);
302 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
303 append("\n ").append(className).append("fillInstOf(c);");
304 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
305 append("\n CLS.$class = 'temp';");
306 append("\n CLS.$class = ");
307 append(accessClass("java_lang_Class(true);"));
308 append("\n CLS.$class.jvmName = '").append(cn).append("';");
309 append("\n CLS.$class.superclass = sprcls;");
310 append("\n CLS.$class.interfaces = function() { return [");
312 boolean first = true;
313 for (String intrfc : jc.getSuperInterfaces()) {
317 requireReference(intrfc);
318 String mangledIface = mangleClassName(intrfc);
320 append(accessClass(mangledIface)).append("(false).constructor.$class");
325 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
326 append("\n CLS.$class.cnstr = CLS;");
327 byte[] classAnno = jc.findAnnotationData(false);
328 if (classAnno != null) {
329 append("\n CLS.$class.anno = {");
330 generateAnno(jc, classAnno);
333 for (String init : toInitilize.toArray()) {
334 append("\n ").append(init).append("();");
336 for (String ref : classRefs.toArray()) {
337 append("\n var refs_").append(ref).append(";");
341 if (jsResource != null) {
342 requireResource(jsResource);
346 append("\n if (arguments.length === 0) {");
347 append("\n if (!(this instanceof CLS)) {");
348 append("\n return new CLS();");
350 for (FieldData v : jc.getFields()) {
351 byte[] onlyArr = v.findAnnotationData(true);
352 if (javaScriptOnly(onlyArr)) continue;
354 append("\n this.fld_").
355 append(className).append('_').
356 append(v.getName()).append(initField(v));
359 append("\n return this;");
361 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
364 declaredClass(jc, className);
366 // StringBuilder sb = new StringBuilder();
367 // for (String init : toInitilize.toArray()) {
368 // sb.append("\n").append(init).append("();");
373 private boolean javaScriptOnly(byte[] anno) throws IOException {
374 String[] only = findAnnotation(anno, jc,
375 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
379 if (only[0] != null && only[1] != null) {
380 append("\n p.").append(only[0]).append(" = ")
381 .append(only[1]).append(";");
383 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
384 append("\n p['").append(only[0]).append("'] = p.")
385 .append(only[0]).append(";");
391 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
392 String jsb = javaScriptBody(destObject, m, true);
396 final String mn = findMethodName(m, new StringBuilder());
397 boolean defineProp = generateMethod(destObject, mn, m);
398 if (mn.equals("class__V")) {
400 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
402 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
408 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
409 String jsb = javaScriptBody(destObject, m, false);
413 final String mn = findMethodName(m, new StringBuilder());
414 generateMethod(destObject, mn, m);
418 private boolean generateMethod(String destObject, String name, MethodData m)
420 final StackMapIterator stackMapIterator = m.createStackMapIterator();
421 TrapDataIterator trap = m.getTrapDataIterator();
422 final LocalsMapper lmapper =
423 new LocalsMapper(stackMapIterator.getArguments());
426 "java/lang/Object".equals(jc.getClassName()) ||
427 "java/lang/reflect/Array".equals(jc.getClassName());
430 append("Object.defineProperty(").append(destObject).
431 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
433 append("m = ").append(destObject).append(".").append(name).append(" = function(");
435 lmapper.outputArguments(this, m.isStatic());
436 append(") {").append("\n");
438 final byte[] byteCodes = m.getCode();
439 if (byteCodes == null) {
440 if (debug(" throw 'no code found for ")) {
442 .append(jc.getClassName()).append('.')
443 .append(m.getName()).append("';\n");
453 final StackMapper smapper = new StackMapper();
456 append(" var ").append(" lcA0 = this;\n");
460 TrapData[] previousTrap = null;
461 boolean wide = false;
463 if (stackMapIterator.isEmpty()) {
469 out.append("\n var gt = 0;\n for(;;) switch(gt) {\n");
472 int topMostLabel = 0;
473 for (int i = 0; i < byteCodes.length; i++) {
476 stackMapIterator.advanceTo(i);
477 boolean changeInCatch = trap.advanceTo(i);
478 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
479 if (previousTrap != null) {
480 generateCatch(previousTrap, i, topMostLabel);
484 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
486 lastStackFrame = stackMapIterator.getFrameIndex();
487 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
488 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
489 out.append(" case " + i).append(": ");
490 changeInCatch = true;
492 debug(" /* " + i + " */ ");
494 if (changeInCatch && trap.useTry()) {
496 previousTrap = trap.current();
498 final int c = readUByte(byteCodes, i);
501 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
504 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
507 smapper.assign(this, VarType.LONG, lmapper.getL(0));
510 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
513 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
516 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
519 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
522 smapper.assign(this, VarType.LONG, lmapper.getL(1));
525 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
528 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
531 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
534 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
537 smapper.assign(this, VarType.LONG, lmapper.getL(2));
540 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
543 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
546 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
549 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
552 smapper.assign(this, VarType.LONG, lmapper.getL(3));
555 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
558 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
562 final int indx = wide ? readUShort(byteCodes, i++)
563 : readUByte(byteCodes, i);
565 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
570 final int indx = wide ? readUShort(byteCodes, i++)
571 : readUByte(byteCodes, i);
573 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
578 final int indx = wide ? readUShort(byteCodes, i++)
579 : readUByte(byteCodes, i);
581 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
586 final int indx = wide ? readUShort(byteCodes, i++)
587 : readUByte(byteCodes, i);
589 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
594 final int indx = wide ? readUShort(byteCodes, i++)
595 : readUByte(byteCodes, i);
597 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
602 final int indx = wide ? readUShort(byteCodes, i++)
603 : readUByte(byteCodes, i);
605 emit(smapper, this, "var @1 = @2;",
606 lmapper.setI(indx), smapper.popI());
611 final int indx = wide ? readUShort(byteCodes, i++)
612 : readUByte(byteCodes, i);
614 emit(smapper, this, "var @1 = @2;",
615 lmapper.setL(indx), smapper.popL());
620 final int indx = wide ? readUShort(byteCodes, i++)
621 : readUByte(byteCodes, i);
623 emit(smapper, this, "var @1 = @2;",
624 lmapper.setF(indx), smapper.popF());
629 final int indx = wide ? readUShort(byteCodes, i++)
630 : readUByte(byteCodes, i);
632 emit(smapper, this, "var @1 = @2;",
633 lmapper.setD(indx), smapper.popD());
638 final int indx = wide ? readUShort(byteCodes, i++)
639 : readUByte(byteCodes, i);
641 emit(smapper, this, "var @1 = @2;",
642 lmapper.setA(indx), smapper.popA());
646 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
649 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
652 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
655 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
658 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
661 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
664 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
667 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
670 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
673 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
676 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
679 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
682 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
685 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
688 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
691 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
694 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
697 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
700 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
703 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
706 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
709 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
712 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
715 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
718 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
721 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
724 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
727 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
730 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
733 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
736 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
739 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
742 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
743 smapper.getI(1), smapper.popI());
746 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
747 smapper.getL(1), smapper.popL());
750 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
753 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
756 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
757 smapper.getI(1), smapper.popI());
760 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
761 smapper.getL(1), smapper.popL());
764 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
767 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
770 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
773 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
776 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
779 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
782 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
785 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
788 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
791 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
794 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
797 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
800 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
803 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
806 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
809 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
812 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
815 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
819 final int varIndx = wide ? readUShort(byteCodes, i++)
820 : readUByte(byteCodes, i);
822 final int incrBy = wide ? readShort(byteCodes, i++)
826 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
828 emit(smapper, this, "@1 += @2;",
829 lmapper.getI(varIndx),
830 Integer.toString(incrBy));
835 emit(smapper, this, "return;");
838 emit(smapper, this, "return @1;", smapper.popI());
841 emit(smapper, this, "return @1;", smapper.popL());
844 emit(smapper, this, "return @1;", smapper.popF());
847 emit(smapper, this, "return @1;", smapper.popD());
850 emit(smapper, this, "return @1;", smapper.popA());
853 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
856 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
859 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
862 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
866 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
869 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
872 smapper.replace(this, VarType.DOUBLE, "@1",
876 smapper.replace(this, VarType.FLOAT, "@1",
880 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
884 smapper.replace(this, VarType.LONG, "(@1).toLong()",
888 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
892 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
895 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
899 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
901 case opc_aconst_null:
902 smapper.assign(this, VarType.REFERENCE, "null");
905 smapper.assign(this, VarType.INTEGER, "-1");
908 smapper.assign(this, VarType.INTEGER, "0");
911 smapper.assign(this, VarType.DOUBLE, "0");
914 smapper.assign(this, VarType.LONG, "0");
917 smapper.assign(this, VarType.FLOAT, "0");
920 smapper.assign(this, VarType.INTEGER, "1");
923 smapper.assign(this, VarType.LONG, "1");
926 smapper.assign(this, VarType.FLOAT, "1");
929 smapper.assign(this, VarType.DOUBLE, "1");
932 smapper.assign(this, VarType.INTEGER, "2");
935 smapper.assign(this, VarType.FLOAT, "2");
938 smapper.assign(this, VarType.INTEGER, "3");
941 smapper.assign(this, VarType.INTEGER, "4");
944 smapper.assign(this, VarType.INTEGER, "5");
947 int indx = readUByte(byteCodes, ++i);
948 String v = encodeConstant(indx);
949 int type = VarType.fromConstantType(jc.getTag(indx));
950 smapper.assign(this, type, v);
955 int indx = readUShortArg(byteCodes, i);
957 String v = encodeConstant(indx);
958 int type = VarType.fromConstantType(jc.getTag(indx));
959 if (type == VarType.LONG) {
960 final Long lv = new Long(v);
961 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
962 final int hi = (int)(lv.longValue() >> 32);
964 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
966 smapper.assign(this, VarType.LONG,
967 "0x" + Integer.toHexString(hi) + ".next32(0x" +
968 Integer.toHexString(low) + ")"
972 smapper.assign(this, type, v);
977 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
981 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
982 smapper.popF(), smapper.popF(), smapper.pushI());
986 emit(smapper, this, "var @3 = (@2 == @1) ? 0 : ((@2 < @1) ? -1 : 1);",
987 smapper.popD(), smapper.popD(), smapper.pushI());
990 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
991 "===", topMostLabel);
994 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
995 "!==", topMostLabel);
998 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
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);
1023 int indx = i + readShortArg(byteCodes, i);
1024 emitIf(smapper, this, "if ((@1) <= 0) ",
1025 smapper.popI(), i, indx, topMostLabel);
1030 int indx = i + readShortArg(byteCodes, i);
1031 emitIf(smapper, this, "if ((@1) > 0) ",
1032 smapper.popI(), i, indx, topMostLabel);
1037 int indx = i + readShortArg(byteCodes, i);
1038 emitIf(smapper, this, "if ((@1) >= 0) ",
1039 smapper.popI(), i, indx, topMostLabel);
1043 case opc_ifnonnull: {
1044 int indx = i + readShortArg(byteCodes, i);
1045 emitIf(smapper, this, "if ((@1) !== null) ",
1046 smapper.popA(), i, indx, topMostLabel);
1051 int indx = i + readShortArg(byteCodes, i);
1052 emitIf(smapper, this, "if ((@1) === null) ",
1053 smapper.popA(), i, indx, topMostLabel);
1058 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1059 "!=", topMostLabel);
1062 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1066 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1067 "<=", topMostLabel);
1070 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1074 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1075 ">=", topMostLabel);
1078 smapper.flush(this);
1079 int indx = i + readShortArg(byteCodes, i);
1080 goTo(this, i, indx, topMostLabel);
1084 case opc_lookupswitch: {
1085 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1088 case opc_tableswitch: {
1089 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1092 case opc_invokeinterface: {
1093 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1096 case opc_invokevirtual:
1097 i = invokeVirtualMethod(byteCodes, i, smapper);
1099 case opc_invokespecial:
1100 i = invokeStaticMethod(byteCodes, i, smapper, false);
1102 case opc_invokestatic:
1103 i = invokeStaticMethod(byteCodes, i, smapper, true);
1105 case opc_invokedynamic: {
1106 int indx = readUShortArg(byteCodes, i);
1107 println("invoke dynamic: " + indx);
1108 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1109 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1110 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1111 println(" type: " + methodHandle.cpx1);
1112 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1113 String mcn = mangleClassName(mi[0]);
1114 char[] returnType = {'V'};
1115 StringBuilder cnt = new StringBuilder();
1116 String mn = findMethodName(mi, cnt, returnType);
1117 StringBuilder sb = new StringBuilder();
1118 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1119 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1120 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1121 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1122 sb.append(" mn : ").append(mn).append("\n");
1123 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1124 throw new IOException(sb.toString());
1126 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1127 String type = jc.StringValue(nameAndType.cpx2);
1128 String object = accessClass(mcn) + "(false)";
1129 if (mn.startsWith("cons_")) {
1130 object += ".constructor";
1132 append("var metHan = ");
1133 append(accessStaticMethod(object, mn, mi));
1135 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1137 append(", '").append(mi[1]).append("', ");
1138 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1139 append(methodType).append("'").append(type).append("', null)");
1140 // if (numArguments > 0) {
1142 // for (int j = 1; j < numArguments; ++j) {
1148 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1154 int indx = readUShortArg(byteCodes, i);
1155 String ci = jc.getClassName(indx);
1156 emit(smapper, this, "var @1 = new @2;",
1157 smapper.pushA(), accessClass(mangleClassName(ci)));
1163 int atype = readUByte(byteCodes, ++i);
1164 generateNewArray(atype, smapper);
1166 case opc_anewarray: {
1167 int type = readUShortArg(byteCodes, i);
1169 generateANewArray(type, smapper);
1172 case opc_multianewarray: {
1173 int type = readUShortArg(byteCodes, i);
1175 i = generateMultiANewArray(type, byteCodes, i, smapper);
1178 case opc_arraylength:
1179 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1182 emit(smapper, this, "Array.at(@3, @2, @1);",
1183 smapper.popL(), smapper.popI(), smapper.popA());
1186 emit(smapper, this, "Array.at(@3, @2, @1);",
1187 smapper.popF(), smapper.popI(), smapper.popA());
1190 emit(smapper, this, "Array.at(@3, @2, @1);",
1191 smapper.popD(), smapper.popI(), smapper.popA());
1194 emit(smapper, this, "Array.at(@3, @2, @1);",
1195 smapper.popA(), smapper.popI(), smapper.popA());
1201 emit(smapper, this, "Array.at(@3, @2, @1);",
1202 smapper.popI(), smapper.popI(), smapper.popA());
1205 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1206 smapper.popI(), smapper.getA(0));
1209 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1210 smapper.popI(), smapper.getA(0));
1213 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1214 smapper.popI(), smapper.getA(0));
1217 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1218 smapper.popI(), smapper.getA(0));
1224 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1225 smapper.popI(), smapper.getA(0));
1233 final Variable v = smapper.get(0);
1234 if (smapper.isDirty()) {
1235 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1237 smapper.assign(this, v.getType(), v);
1242 final Variable vi1 = smapper.get(0);
1244 if (vi1.isCategory2()) {
1245 emit(smapper, this, "var @1 = @2;",
1246 smapper.pushT(vi1.getType()), vi1);
1248 final Variable vi2 = smapper.get(1);
1249 emit(smapper, this, "var @1 = @2, @3 = @4;",
1250 smapper.pushT(vi2.getType()), vi2,
1251 smapper.pushT(vi1.getType()), vi1);
1256 final Variable vi1 = smapper.pop(this);
1257 final Variable vi2 = smapper.pop(this);
1258 final Variable vo3 = smapper.pushT(vi1.getType());
1259 final Variable vo2 = smapper.pushT(vi2.getType());
1260 final Variable vo1 = smapper.pushT(vi1.getType());
1262 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1263 vo1, vi1, vo2, vi2, vo3, vo1);
1267 final Variable vi1 = smapper.pop(this);
1268 final Variable vi2 = smapper.pop(this);
1270 if (vi1.isCategory2()) {
1271 final Variable vo3 = smapper.pushT(vi1.getType());
1272 final Variable vo2 = smapper.pushT(vi2.getType());
1273 final Variable vo1 = smapper.pushT(vi1.getType());
1275 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1276 vo1, vi1, vo2, vi2, vo3, vo1);
1278 final Variable vi3 = smapper.pop(this);
1279 final Variable vo5 = smapper.pushT(vi2.getType());
1280 final Variable vo4 = smapper.pushT(vi1.getType());
1281 final Variable vo3 = smapper.pushT(vi3.getType());
1282 final Variable vo2 = smapper.pushT(vi2.getType());
1283 final Variable vo1 = smapper.pushT(vi1.getType());
1285 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1286 vo1, vi1, vo2, vi2, vo3, vi3);
1287 emit(smapper, this, " @1 = @2, @3 = @4;",
1288 vo4, vo1, vo5, vo2);
1293 final Variable vi1 = smapper.pop(this);
1294 final Variable vi2 = smapper.pop(this);
1296 if (vi2.isCategory2()) {
1297 final Variable vo3 = smapper.pushT(vi1.getType());
1298 final Variable vo2 = smapper.pushT(vi2.getType());
1299 final Variable vo1 = smapper.pushT(vi1.getType());
1301 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1302 vo1, vi1, vo2, vi2, vo3, vo1);
1304 final Variable vi3 = smapper.pop(this);
1305 final Variable vo4 = smapper.pushT(vi1.getType());
1306 final Variable vo3 = smapper.pushT(vi3.getType());
1307 final Variable vo2 = smapper.pushT(vi2.getType());
1308 final Variable vo1 = smapper.pushT(vi1.getType());
1310 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1311 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1316 final Variable vi1 = smapper.pop(this);
1317 final Variable vi2 = smapper.pop(this);
1319 if (vi1.isCategory2()) {
1320 if (vi2.isCategory2()) {
1321 final Variable vo3 = smapper.pushT(vi1.getType());
1322 final Variable vo2 = smapper.pushT(vi2.getType());
1323 final Variable vo1 = smapper.pushT(vi1.getType());
1325 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1326 vo1, vi1, vo2, vi2, vo3, vo1);
1328 final Variable vi3 = smapper.pop(this);
1329 final Variable vo4 = smapper.pushT(vi1.getType());
1330 final Variable vo3 = smapper.pushT(vi3.getType());
1331 final Variable vo2 = smapper.pushT(vi2.getType());
1332 final Variable vo1 = smapper.pushT(vi1.getType());
1334 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1335 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1338 final Variable vi3 = smapper.pop(this);
1340 if (vi3.isCategory2()) {
1341 final Variable vo5 = smapper.pushT(vi2.getType());
1342 final Variable vo4 = smapper.pushT(vi1.getType());
1343 final Variable vo3 = smapper.pushT(vi3.getType());
1344 final Variable vo2 = smapper.pushT(vi2.getType());
1345 final Variable vo1 = smapper.pushT(vi1.getType());
1347 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1348 vo1, vi1, vo2, vi2, vo3, vi3);
1349 emit(smapper, this, " @1 = @2, @3 = @4;",
1350 vo4, vo1, vo5, vo2);
1352 final Variable vi4 = smapper.pop(this);
1353 final Variable vo6 = smapper.pushT(vi2.getType());
1354 final Variable vo5 = smapper.pushT(vi1.getType());
1355 final Variable vo4 = smapper.pushT(vi4.getType());
1356 final Variable vo3 = smapper.pushT(vi3.getType());
1357 final Variable vo2 = smapper.pushT(vi2.getType());
1358 final Variable vo1 = smapper.pushT(vi1.getType());
1360 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1361 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1362 emit(smapper, this, " @1 = @2, @3 = @4;",
1363 vo5, vo1, vo6, vo2);
1369 final Variable vi1 = smapper.get(0);
1370 final Variable vi2 = smapper.get(1);
1372 if (vi1.getType() == vi2.getType()) {
1373 final Variable tmp = smapper.pushT(vi1.getType());
1375 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1380 smapper.pushT(vi1.getType());
1381 smapper.pushT(vi2.getType());
1386 smapper.assign(this, VarType.INTEGER,
1387 "(" + Integer.toString(byteCodes[++i]) + ")");
1390 smapper.assign(this, VarType.INTEGER,
1391 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1395 case opc_getfield: {
1396 int indx = readUShortArg(byteCodes, i);
1397 String[] fi = jc.getFieldInfoName(indx);
1398 final int type = VarType.fromFieldType(fi[2].charAt(0));
1399 final String mangleClass = mangleClassName(fi[0]);
1400 final String mangleClassAccess = accessClassFalse(mangleClass);
1401 smapper.replace(this, type, "@2.call(@1)",
1403 accessField(mangleClassAccess,
1407 addReference(fi[0]);
1410 case opc_putfield: {
1411 int indx = readUShortArg(byteCodes, i);
1412 String[] fi = jc.getFieldInfoName(indx);
1413 final int type = VarType.fromFieldType(fi[2].charAt(0));
1414 final String mangleClass = mangleClassName(fi[0]);
1415 final String mangleClassAccess = accessClassFalse(mangleClass);
1416 emit(smapper, this, "@3.call(@2, @1);",
1419 accessField(mangleClassAccess,
1422 addReference(fi[0]);
1425 case opc_getstatic: {
1426 int indx = readUShortArg(byteCodes, i);
1427 String[] fi = jc.getFieldInfoName(indx);
1428 final int type = VarType.fromFieldType(fi[2].charAt(0));
1429 String ac = accessClassFalse(mangleClassName(fi[0]));
1430 String af = accessField(ac, "_" + fi[1], fi);
1431 smapper.assign(this, type, af + "()");
1433 addReference(fi[0]);
1436 case opc_putstatic: {
1437 int indx = readUShortArg(byteCodes, i);
1438 String[] fi = jc.getFieldInfoName(indx);
1439 final int type = VarType.fromFieldType(fi[2].charAt(0));
1440 emit(smapper, this, "@1._@2(@3);",
1441 accessClassFalse(mangleClassName(fi[0])), fi[1],
1442 smapper.popT(type));
1444 addReference(fi[0]);
1447 case opc_checkcast: {
1448 int indx = readUShortArg(byteCodes, i);
1449 generateCheckcast(indx, smapper);
1453 case opc_instanceof: {
1454 int indx = readUShortArg(byteCodes, i);
1455 generateInstanceOf(indx, smapper);
1460 final CharSequence v = smapper.popA();
1463 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1464 smapper.pushA(), v);
1468 case opc_monitorenter: {
1469 debug("/* monitor enter */");
1474 case opc_monitorexit: {
1475 debug("/* monitor exit */");
1486 emit(smapper, this, "throw 'unknown bytecode @1';",
1487 Integer.toString(c));
1491 generateByteCodeComment(prev, i, byteCodes);
1497 if (previousTrap != null) {
1498 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1511 private int generateIf(StackMapper mapper, byte[] byteCodes,
1512 int i, final CharSequence v2, final CharSequence v1,
1513 final String test, int topMostLabel
1514 ) throws IOException {
1516 int indx = i + readShortArg(byteCodes, i);
1517 append("if ((").append(v1)
1518 .append(") ").append(test).append(" (")
1519 .append(v2).append(")) ");
1520 goTo(this, i, indx, topMostLabel);
1524 private int readInt4(byte[] byteCodes, int offset) {
1525 final int d = byteCodes[offset + 0] << 24;
1526 final int c = byteCodes[offset + 1] << 16;
1527 final int b = byteCodes[offset + 2] << 8;
1528 final int a = byteCodes[offset + 3];
1529 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1531 private static int readUByte(byte[] byteCodes, int offset) {
1532 return byteCodes[offset] & 0xff;
1535 private static int readUShort(byte[] byteCodes, int offset) {
1536 return ((byteCodes[offset] & 0xff) << 8)
1537 | (byteCodes[offset + 1] & 0xff);
1539 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1540 return readUShort(byteCodes, offsetInstruction + 1);
1543 private static int readShort(byte[] byteCodes, int offset) {
1544 int signed = byteCodes[offset];
1545 byte b0 = (byte)signed;
1546 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1548 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1549 return readShort(byteCodes, offsetInstruction + 1);
1552 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1554 Boolean count = null;
1555 boolean array = false;
1557 int firstPos = sig.length();
1558 while (i < descriptor.length()) {
1559 char ch = descriptor.charAt(i++);
1580 if (ch == 'J' || ch == 'D') {
1586 sig.insert(firstPos, ch);
1588 returnType[0] = '[';
1589 sig.insert(firstPos, "_3");
1598 returnType[0] = 'V';
1599 sig.insert(firstPos, 'V');
1602 int next = descriptor.indexOf(';', i);
1603 String realSig = mangleSig(descriptor, i - 1, next + 1);
1608 sig.append(realSig);
1611 sig.insert(firstPos, realSig);
1613 sig.insert(firstPos, "_3");
1615 returnType[0] = 'L';
1624 throw new IllegalStateException("Invalid char: " + ch);
1629 static String mangleSig(String sig) {
1630 return mangleSig(sig, 0, sig.length());
1633 private static String mangleMethodName(String name) {
1634 StringBuilder sb = new StringBuilder(name.length() * 2);
1635 int last = name.length();
1636 for (int i = 0; i < last; i++) {
1637 final char ch = name.charAt(i);
1639 case '_': sb.append("_1"); break;
1640 default: sb.append(ch); break;
1643 return sb.toString();
1645 private static String mangleSig(String txt, int first, int last) {
1646 StringBuilder sb = new StringBuilder((last - first) * 2);
1647 for (int i = first; i < last; i++) {
1648 final char ch = txt.charAt(i);
1650 case '/': sb.append('_'); break;
1651 case '_': sb.append("_1"); break;
1652 case ';': sb.append("_2"); break;
1653 case '[': sb.append("_3"); break;
1655 if (Character.isJavaIdentifierPart(ch)) {
1659 String hex = Integer.toHexString(ch).toLowerCase();
1660 for (int m = hex.length(); m < 4; m++) {
1668 return sb.toString();
1671 private static String mangleClassName(String name) {
1672 return mangleSig(name);
1675 private static String findMethodName(MethodData m, StringBuilder cnt) {
1676 StringBuilder name = new StringBuilder();
1677 if ("<init>".equals(m.getName())) { // NOI18N
1678 name.append("cons"); // NOI18N
1679 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1680 name.append("class"); // NOI18N
1682 name.append(mangleMethodName(m.getName()));
1685 countArgs(m.getInternalSig(), new char[1], name, cnt);
1686 return name.toString();
1689 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1690 StringBuilder name = new StringBuilder();
1691 String descr = mi[2];//mi.getDescriptor();
1693 if ("<init>".equals(nm)) { // NOI18N
1694 name.append("cons"); // NOI18N
1696 name.append(mangleMethodName(nm));
1698 countArgs(descr, returnType, name, cnt);
1699 return name.toString();
1702 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1703 throws IOException {
1704 int methodIndex = readUShortArg(byteCodes, i);
1705 String[] mi = jc.getFieldInfoName(methodIndex);
1706 char[] returnType = { 'V' };
1707 StringBuilder cnt = new StringBuilder();
1708 String mn = findMethodName(mi, cnt, returnType);
1710 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1711 final CharSequence[] vars = new CharSequence[numArguments];
1713 for (int j = numArguments - 1; j >= 0; --j) {
1714 vars[j] = mapper.popValue();
1718 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1719 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1721 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1722 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1724 if (vars[1] instanceof String) {
1725 String field = vars[1].toString();
1726 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1727 vars[1] = "c._" + field.substring(1, field.length() - 1);
1732 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1733 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1735 if (vars[1] instanceof String) {
1736 String field = vars[2].toString();
1737 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1738 vars[2] = "c._" + field.substring(1, field.length() - 1);
1743 if (returnType[0] != 'V') {
1746 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1750 final String in = mi[0];
1753 in.equals("org/apidesign/html/boot/spi/Fn") ||
1754 in.equals("org/netbeans/html/boot/spi/Fn")
1756 mcn = "java_lang_Class";
1758 mcn = mangleClassName(in);
1760 String object = accessClassFalse(mcn);
1761 if (mn.startsWith("cons_")) {
1762 object += ".constructor";
1764 append(accessStaticMethod(object, mn, mi));
1770 if (numArguments > 0) {
1772 for (int j = 1; j < numArguments; ++j) {
1782 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1783 throws IOException {
1784 int methodIndex = readUShortArg(byteCodes, i);
1785 String[] mi = jc.getFieldInfoName(methodIndex);
1786 char[] returnType = { 'V' };
1787 StringBuilder cnt = new StringBuilder();
1788 String mn = findMethodName(mi, cnt, returnType);
1790 final int numArguments = cnt.length() + 1;
1791 final CharSequence[] vars = new CharSequence[numArguments];
1793 for (int j = numArguments - 1; j >= 0; --j) {
1794 vars[j] = mapper.popValue();
1797 if (returnType[0] != 'V') {
1800 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1804 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1806 for (int j = 1; j < numArguments; ++j) {
1816 private void addReference(String cn) throws IOException {
1817 if (requireReference(cn)) {
1818 debug(" /* needs " + cn + " */");
1822 private void outType(String d, StringBuilder out) {
1824 while (d.charAt(0) == '[') {
1828 if (d.charAt(0) == 'L') {
1829 assert d.charAt(d.length() - 1) == ';';
1830 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1836 private String encodeConstant(int entryIndex) throws IOException {
1837 String[] classRef = { null };
1838 String s = jc.stringValue(entryIndex, classRef);
1839 if (classRef[0] != null) {
1840 if (classRef[0].startsWith("[")) {
1841 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1843 addReference(classRef[0]);
1844 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1850 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1851 byte[] arr = m.findAnnotationData(true);
1855 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1856 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1857 class P extends AnnotationParser {
1863 String[] args = new String[30];
1869 protected void visitAttr(String type, String attr, String at, String value) {
1870 if (type.equals(jvmType)) {
1871 if ("body".equals(attr)) {
1873 } else if ("args".equals(attr)) {
1874 args[cnt++] = value;
1876 throw new IllegalArgumentException(attr);
1879 if (type.equals(htmlType)) {
1881 if ("body".equals(attr)) {
1883 } else if ("args".equals(attr)) {
1884 args[cnt++] = value;
1885 } else if ("javacall".equals(attr)) {
1886 javacall = "1".equals(value);
1887 } else if ("wait4js".equals(attr)) {
1888 // ignore, we always invoke synchronously
1890 throw new IllegalArgumentException(attr);
1897 if (p.body == null) {
1900 StringBuilder cnt = new StringBuilder();
1901 final String mn = findMethodName(m, cnt);
1902 append("m = ").append(destObject).append(".").append(mn);
1903 append(" = function(");
1906 StringBuilder toValue = new StringBuilder();
1907 for (int i = 0; i < cnt.length(); i++) {
1909 space = outputArg(this, p.args, index);
1910 if (p.html4j && space.length() > 0) {
1911 toValue.append("\n ").append(p.args[index]).append(" = ")
1912 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1913 append(p.args[index]).append(");");
1917 append(") {").append("\n");
1918 append(toValue.toString());
1920 int lastSlash = jc.getClassName().lastIndexOf('/');
1921 final String pkg = jc.getClassName().substring(0, lastSlash);
1922 append(mangleCallbacks(pkg, p.body));
1923 requireReference(pkg + "/$JsCallbacks$");
1931 private static CharSequence mangleCallbacks(String pkgName, String body) {
1932 StringBuilder sb = new StringBuilder();
1935 int next = body.indexOf(".@", pos);
1937 sb.append(body.substring(pos));
1938 body = sb.toString();
1943 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1948 String refId = body.substring(ident, next);
1950 sb.append(body.substring(pos, ident));
1952 int sigBeg = body.indexOf('(', next);
1953 int sigEnd = body.indexOf(')', sigBeg);
1954 int colon4 = body.indexOf("::", next);
1955 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1956 throw new IllegalStateException("Malformed body " + body);
1958 String fqn = body.substring(next + 2, colon4);
1959 String method = body.substring(colon4 + 2, sigBeg);
1960 String params = body.substring(sigBeg, sigEnd + 1);
1962 int paramBeg = body.indexOf('(', sigEnd + 1);
1964 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1965 sb.append(mangleJsCallbacks(fqn, method, params, false));
1966 sb.append("(").append(refId);
1967 if (body.charAt(paramBeg + 1) != ')') {
1975 int next = body.indexOf("@", pos);
1980 sb.append(body.substring(pos));
1984 sb = new StringBuilder();
1987 sb.append(body.substring(pos, next));
1989 int sigBeg = body.indexOf('(', next);
1990 int sigEnd = body.indexOf(')', sigBeg);
1991 int colon4 = body.indexOf("::", next);
1992 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1993 throw new IllegalStateException("Malformed body " + body);
1995 String fqn = body.substring(next + 1, colon4);
1996 String method = body.substring(colon4 + 2, sigBeg);
1997 String params = body.substring(sigBeg, sigEnd + 1);
1999 int paramBeg = body.indexOf('(', sigEnd + 1);
2001 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2002 sb.append(mangleJsCallbacks(fqn, method, params, true));
2008 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2009 if (params.startsWith("(")) {
2010 params = params.substring(1);
2012 if (params.endsWith(")")) {
2013 params = params.substring(0, params.length() - 1);
2015 StringBuilder sb = new StringBuilder();
2016 final String fqnu = fqn.replace('.', '_');
2017 final String rfqn = mangleClassName(fqnu);
2018 final String rm = mangleMethodName(method);
2021 StringBuilder pb = new StringBuilder();
2022 int len = params.length();
2024 while (indx < len) {
2025 char ch = params.charAt(indx);
2026 if (ch == '[' || ch == 'L') {
2027 int column = params.indexOf(';', indx) + 1;
2028 if (column > indx) {
2029 String real = params.substring(indx, column);
2030 if ("Ljava/lang/String;".equals(real)) {
2031 pb.append("Ljava/lang/String;");
2036 pb.append("Ljava/lang/Object;");
2043 srp = mangleSig(pb.toString());
2045 final String rp = mangleSig(params);
2046 final String mrp = mangleMethodName(rp);
2047 sb.append(rfqn).append("$").append(rm).
2048 append('$').append(mrp).append("__Ljava_lang_Object_2");
2050 sb.append('L').append(fqnu).append("_2");
2053 return sb.toString();
2056 private static String className(ClassData jc) {
2057 //return jc.getName().getInternalName().replace('/', '_');
2058 return mangleClassName(jc.getClassName());
2061 private static String[] findAnnotation(
2062 byte[] arr, ClassData cd, final String className,
2063 final String... attrNames
2064 ) throws IOException {
2068 final String[] values = new String[attrNames.length];
2069 final boolean[] found = { false };
2070 final String jvmType = "L" + className.replace('.', '/') + ";";
2071 AnnotationParser ap = new AnnotationParser(false, true) {
2073 protected void visitAttr(String type, String attr, String at, String value) {
2074 if (type.equals(jvmType)) {
2076 for (int i = 0; i < attrNames.length; i++) {
2077 if (attrNames[i].equals(attr)) {
2086 return found[0] ? values : null;
2089 private CharSequence initField(FieldData v) {
2090 final String is = v.getInternalSig();
2091 if (is.length() == 1) {
2092 switch (is.charAt(0)) {
2098 case 'I': return " = 0;";
2100 case 'D': return " = 0.0;";
2102 throw new IllegalStateException(is);
2108 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2109 AnnotationParser ap = new AnnotationParser(true, false) {
2110 int[] cnt = new int[32];
2114 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2115 final String slashType = attrType.substring(1, attrType.length() - 1);
2116 requireReference(slashType);
2118 if (cnt[depth]++ > 0) {
2122 append('"').append(attrType).append("\" : ");
2129 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2135 protected void visitValueStart(String attrName, char type) throws IOException {
2136 if (cnt[depth]++ > 0) {
2140 if (attrName != null) {
2141 append('"').append(attrName).append("\" : ");
2149 protected void visitValueEnd(String attrName, char type) throws IOException {
2157 protected void visitAttr(String type, String attr, String attrType, String value)
2158 throws IOException {
2159 if (attr == null && value == null) {
2166 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2167 throws IOException {
2168 final String slashType = attrType.substring(1, attrType.length() - 1);
2169 requireReference(slashType);
2171 final String cn = mangleClassName(slashType);
2172 append(accessClassFalse(cn))
2173 .append("['valueOf__L").
2175 append("_2Ljava_lang_String_2']('").
2183 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2184 final String name = args[indx];
2188 if (name.contains(",")) {
2189 throw new IOException("Wrong parameter with ',': " + name);
2195 final void emitNoFlush(
2197 final String format, final CharSequence... params
2198 ) throws IOException {
2199 emitImpl(this, format, params);
2201 static final void emit(
2203 final Appendable out,
2204 final String format, final CharSequence... params
2205 ) throws IOException {
2207 emitImpl(out, format, params);
2209 static void emitImpl(final Appendable out,
2210 final String format,
2211 final CharSequence... params) throws IOException {
2212 final int length = format.length();
2215 int paramOffset = format.indexOf('@');
2216 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2217 final char paramChar = format.charAt(paramOffset + 1);
2218 if ((paramChar >= '1') && (paramChar <= '9')) {
2219 final int paramIndex = paramChar - '0' - 1;
2221 out.append(format, processed, paramOffset);
2222 out.append(params[paramIndex]);
2225 processed = paramOffset + 1;
2228 paramOffset = format.indexOf('@', paramOffset + 1);
2231 out.append(format, processed, length);
2234 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2235 append("} catch (e) {\n");
2237 for (TrapData e : traps) {
2241 if (e.catch_cpx != 0) { //not finally
2242 final String classInternalName = jc.getClassName(e.catch_cpx);
2243 addReference(classInternalName);
2244 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2245 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2246 append("var stA0 = e;");
2247 goTo(this, current, e.handler_pc, topMostLabel);
2250 finallyPC = e.handler_pc;
2253 if (finallyPC == -1) {
2256 append("var stA0 = e;");
2257 goTo(this, current, finallyPC, topMostLabel);
2262 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2263 out.append("{ gt = " + to + "; continue; }");
2266 private static void emitIf(
2268 Appendable out, String pattern,
2270 int current, int to, int canBack
2271 ) throws IOException {
2273 emitImpl(out, pattern, param);
2274 goTo(out, current, to, canBack);
2277 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2280 case 4: jvmType = "[Z"; break;
2281 case 5: jvmType = "[C"; break;
2282 case 6: jvmType = "[F"; break;
2283 case 7: jvmType = "[D"; break;
2284 case 8: jvmType = "[B"; break;
2285 case 9: jvmType = "[S"; break;
2286 case 10: jvmType = "[I"; break;
2287 case 11: jvmType = "[J"; break;
2288 default: throw new IllegalStateException("Array type: " + atype);
2291 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2292 smapper.popI(), smapper.pushA(), jvmType);
2295 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2296 String typeName = jc.getClassName(type);
2297 String ref = "null";
2298 if (typeName.startsWith("[")) {
2299 typeName = "'[" + typeName + "'";
2301 ref = "vm." + mangleClassName(typeName);
2302 typeName = "'[L" + typeName + ";'";
2305 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2306 smapper.popI(), smapper.pushA(), typeName, ref);
2309 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2310 String typeName = jc.getClassName(type);
2311 int dim = readUByte(byteCodes, ++i);
2312 StringBuilder dims = new StringBuilder();
2314 for (int d = 0; d < dim; d++) {
2316 dims.insert(1, ",");
2318 dims.insert(1, smapper.popI());
2322 if (typeName.charAt(dim) == 'L') {
2323 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2326 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2327 dims.toString(), smapper.pushA(), typeName, fn
2332 private int generateTableSwitch(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 low = readInt4(byteCodes, table);
2338 int high = readInt4(byteCodes, table);
2340 final CharSequence swVar = smapper.popValue();
2341 smapper.flush(this);
2342 append("switch (").append(swVar).append(") {\n");
2343 while (low <= high) {
2344 int offset = i + readInt4(byteCodes, table);
2346 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2349 append(" default: ");
2350 goTo(this, i, dflt, topMostLabel);
2356 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2357 int table = i / 4 * 4 + 4;
2358 int dflt = i + readInt4(byteCodes, table);
2360 int n = readInt4(byteCodes, table);
2362 final CharSequence swVar = smapper.popValue();
2363 smapper.flush(this);
2364 append("switch (").append(swVar).append(") {\n");
2366 int cnstnt = readInt4(byteCodes, table);
2368 int offset = i + readInt4(byteCodes, table);
2370 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2372 append(" default: ");
2373 goTo(this, i, dflt, topMostLabel);
2379 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2380 String type = jc.getClassName(indx);
2381 if (!type.startsWith("[")) {
2383 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2384 smapper.popA(), smapper.pushI(),
2385 type.replace('/', '_'));
2388 while (type.charAt(cnt) == '[') {
2391 if (type.charAt(cnt) == 'L') {
2392 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2394 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2395 smapper.popA(), smapper.pushI(),
2400 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2401 smapper.popA(), smapper.pushI(), type
2407 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2408 String type = jc.getClassName(indx);
2409 if (!type.startsWith("[")) {
2410 emitNoFlush(smapper,
2411 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2412 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2415 while (type.charAt(cnt) == '[') {
2418 if (type.charAt(cnt) == 'L') {
2419 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2420 emitNoFlush(smapper,
2421 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2422 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2425 emitNoFlush(smapper,
2426 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2427 smapper.getT(0, VarType.REFERENCE, false), type
2433 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2434 for (int j = prev; j <= i; j++) {
2436 final int cc = readUByte(byteCodes, j);
2437 append(Integer.toString(cc));
2441 @JavaScriptBody(args = "msg", body = "")
2442 private static void println(String msg) {
2443 System.err.println(msg);