V8 has problems optimizing try/catch. Putting such construct into methods that is always called was certainly not the brightest idea.
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 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 String accessClassFalse(String classOperation) {
89 if (jc.getClassName().replace('/', '_').equals(classOperation)) {
92 return accessClass(classOperation) + "(false)";
95 protected String accessField(String object, String mangledName,
96 String[] fieldInfoName) throws IOException {
97 return object + "." + mangledName;
100 protected String accessStaticMethod(
103 String[] fieldInfoName) throws IOException {
104 return object + "." + mangledName;
107 protected String accessVirtualMethod(
110 String[] fieldInfoName,
112 ) throws IOException {
113 return object + "." + mangledName + '(';
116 protected void declaredClass(ClassData classData, String mangledName)
120 protected void declaredField(FieldData fieldData,
122 String mangledName) throws IOException {
125 protected void declaredMethod(MethodData methodData,
127 String mangledName) throws IOException {
130 /** Prints out a debug message.
132 * @param msg the message
133 * @return true if the message has been printed
134 * @throws IOException
136 boolean debug(String msg) throws IOException {
142 * Converts a given class file to a JavaScript version.
144 * @param classFile input stream with code of the .class file
145 * @return the initialization code for this class, if any. Otherwise <code>null</code>
147 * @throws IOException if something goes wrong during read or write or translating
150 public String compile(InputStream classFile) throws IOException {
151 return compile(new ClassData(classFile));
154 protected String compile(ClassData classData) throws IOException {
156 final String cn = this.jc.getClassName();
157 this.callbacks = cn.endsWith("/$JsCallbacks$");
158 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
159 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
160 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
163 byte[] arrData = jc.findAnnotationData(true);
165 String[] arr = findAnnotation(arrData, jc,
166 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
167 "resource", "processByteCode"
170 if (!arr[0].isEmpty()) {
171 requireScript(arr[0]);
173 if ("0".equals(arr[1])) {
178 final String jsResource;
180 String[] arr = findAnnotation(arrData, jc,
181 "net.java.html.js.JavaScriptResource",
185 if (arr[0].startsWith("/")) {
188 int last = cn.lastIndexOf('/');
189 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
195 String[] proto = findAnnotation(arrData, jc,
196 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
197 "container", "prototype"
199 StringArray toInitilize = new StringArray();
200 final String className = className(jc);
201 append("\n\n").append(assignClass(className));
202 append("function ").append(className).append("() {");
204 append("\n var CLS = ").append(className).append(';');
205 append("\n if (!CLS.$class) {");
207 String sc = jc.getSuperClassName(); // with _
208 append("\n var pp = ").
209 append(accessClass(mangleClassName(sc))).append("(true);");
210 append("\n var p = CLS.prototype = pp;");
211 append("\n var c = p;");
212 append("\n var sprcls = pp.constructor.$class;");
214 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
215 if (proto[0] == null) {
218 append("\n var c = ").append(proto[0]).append(";");
219 append("\n var sprcls = null;");
221 for (FieldData v : jc.getFields()) {
223 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
224 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
228 append("\n CLS.fld_").append(v.getName()).append(initField(v));
229 append("\n m = c._").append(v.getName()).append(" = function (v) {")
230 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
231 .append(" = v; return CLS.fld_").
232 append(v.getName()).append("; };");
234 append("\n m = c._").append(v.getName()).append(" = function (v) {")
235 .append(" if (arguments.length == 1) this.fld_").
236 append(className).append('_').append(v.getName())
237 .append(" = v; return this.fld_").
238 append(className).append('_').append(v.getName())
242 declaredField(v, "c", "_" + v.getName());
244 for (MethodData m : jc.getMethods()) {
245 byte[] onlyArr = m.findAnnotationData(true);
246 if (javaScriptOnly(onlyArr)) continue;
252 mn = generateStaticMethod(destObject, m, toInitilize);
254 if (m.isConstructor()) {
256 mn = generateInstanceMethod(destObject, m);
259 mn = generateInstanceMethod(destObject, m);
262 declaredMethod(m, destObject, mn);
263 byte[] runAnno = m.findAnnotationData(false);
264 if (runAnno != null) {
265 append("\n m.anno = {");
266 generateAnno(jc, runAnno);
269 append("\n m.access = " + m.getAccess()).append(";");
270 append("\n m.cls = CLS;");
272 append("\n c.constructor = CLS;");
273 append("\n function ").append(className).append("fillInstOf(x) {");
274 String instOfName = "$instOf_" + className;
275 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
276 if (jc.isInterface()) {
277 for (MethodData m : jc.getMethods()) {
278 if ((m.getAccess() & ACC_ABSTRACT) == 0
279 && (m.getAccess() & ACC_STATIC) == 0
280 && (m.getAccess() & ACC_PRIVATE) == 0) {
281 final String mn = findMethodName(m, new StringBuilder());
282 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
286 for (String superInterface : jc.getSuperInterfaces()) {
287 String intrfc = superInterface.replace('/', '_');
288 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
289 requireReference(superInterface);
292 append("\n if (!c.hasOwnProperty('fillInstOf')) Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
293 append("\n ").append(className).append("fillInstOf(c);");
294 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
295 append("\n CLS.$class = 'temp';");
296 append("\n CLS.$class = ");
297 append(accessClass("java_lang_Class(true);"));
298 append("\n CLS.$class.jvmName = '").append(cn).append("';");
299 append("\n CLS.$class.superclass = sprcls;");
300 append("\n CLS.$class.interfaces = function() { return [");
302 boolean first = true;
303 for (String intrfc : jc.getSuperInterfaces()) {
307 requireReference(intrfc);
308 String mangledIface = mangleClassName(intrfc);
310 append(accessClass(mangledIface)).append("(false).constructor.$class");
315 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
316 append("\n CLS.$class.cnstr = CLS;");
317 byte[] classAnno = jc.findAnnotationData(false);
318 if (classAnno != null) {
319 append("\n CLS.$class.anno = {");
320 generateAnno(jc, classAnno);
323 for (String init : toInitilize.toArray()) {
324 append("\n ").append(init).append("();");
327 if (jsResource != null) {
328 requireResource(jsResource);
332 append("\n if (arguments.length === 0) {");
333 append("\n if (!(this instanceof CLS)) {");
334 append("\n return new CLS();");
336 for (FieldData v : jc.getFields()) {
337 byte[] onlyArr = v.findAnnotationData(true);
338 if (javaScriptOnly(onlyArr)) continue;
340 append("\n this.fld_").
341 append(className).append('_').
342 append(v.getName()).append(initField(v));
345 append("\n return this;");
347 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
350 declaredClass(jc, className);
352 // StringBuilder sb = new StringBuilder();
353 // for (String init : toInitilize.toArray()) {
354 // sb.append("\n").append(init).append("();");
359 private boolean javaScriptOnly(byte[] anno) throws IOException {
360 String[] only = findAnnotation(anno, jc,
361 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
365 if (only[0] != null && only[1] != null) {
366 append("\n p.").append(only[0]).append(" = ")
367 .append(only[1]).append(";");
369 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
370 append("\n p['").append(only[0]).append("'] = p.")
371 .append(only[0]).append(";");
377 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
378 String jsb = javaScriptBody(destObject, m, true);
382 final String mn = findMethodName(m, new StringBuilder());
383 boolean defineProp = generateMethod(destObject, mn, m);
384 if (mn.equals("class__V")) {
386 toInitilize.add(accessClassFalse(className(jc)) + "['" + mn + "']");
388 toInitilize.add(accessClassFalse(className(jc)) + "." + mn);
394 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
395 String jsb = javaScriptBody(destObject, m, false);
399 final String mn = findMethodName(m, new StringBuilder());
400 generateMethod(destObject, mn, m);
404 private boolean generateMethod(String destObject, String name, MethodData m)
406 final StackMapIterator stackMapIterator = m.createStackMapIterator();
407 TrapDataIterator trap = m.getTrapDataIterator();
408 final LocalsMapper lmapper =
409 new LocalsMapper(stackMapIterator.getArguments());
412 "java/lang/Object".equals(jc.getClassName()) ||
413 "java/lang/reflect/Array".equals(jc.getClassName());
416 append("Object.defineProperty(").append(destObject).
417 append(", '").append(name).append("', { configurable: true, writable: true, value: m = function(");
419 append("m = ").append(destObject).append(".").append(name).append(" = function(");
421 lmapper.outputArguments(this, m.isStatic());
422 append(") {").append("\n");
424 final byte[] byteCodes = m.getCode();
425 if (byteCodes == null) {
426 append(" throw 'no code found for ")
427 .append(jc.getClassName()).append('.')
428 .append(m.getName()).append("';\n");
437 final StackMapper smapper = new StackMapper();
440 append(" var ").append(" lcA0 = this;\n");
444 TrapData[] previousTrap = null;
445 boolean wide = false;
447 if (stackMapIterator.isEmpty()) {
453 append("\n var gt = 0;\n");
457 int topMostLabel = 0;
458 for (int i = 0; i < byteCodes.length; i++) {
461 stackMapIterator.advanceTo(i);
462 boolean changeInCatch = trap.advanceTo(i);
463 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
464 if (previousTrap != null) {
465 generateCatch(previousTrap, i, topMostLabel);
469 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
474 if (openBraces > 64) {
475 for (int c = 0; c < 64; c++) {
482 lastStackFrame = stackMapIterator.getFrameIndex();
483 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
484 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
485 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
487 changeInCatch = true;
489 debug(" /* " + i + " */ ");
491 if (changeInCatch && trap.useTry()) {
493 previousTrap = trap.current();
495 final int c = readUByte(byteCodes, i);
498 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
501 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
504 smapper.assign(this, VarType.LONG, lmapper.getL(0));
507 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
510 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
513 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
516 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
519 smapper.assign(this, VarType.LONG, lmapper.getL(1));
522 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
525 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
528 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
531 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
534 smapper.assign(this, VarType.LONG, lmapper.getL(2));
537 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
540 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
543 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
546 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
549 smapper.assign(this, VarType.LONG, lmapper.getL(3));
552 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
555 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
559 final int indx = wide ? readUShort(byteCodes, i++)
560 : readUByte(byteCodes, i);
562 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
567 final int indx = wide ? readUShort(byteCodes, i++)
568 : readUByte(byteCodes, i);
570 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
575 final int indx = wide ? readUShort(byteCodes, i++)
576 : readUByte(byteCodes, i);
578 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
583 final int indx = wide ? readUShort(byteCodes, i++)
584 : readUByte(byteCodes, i);
586 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
591 final int indx = wide ? readUShort(byteCodes, i++)
592 : readUByte(byteCodes, i);
594 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
599 final int indx = wide ? readUShort(byteCodes, i++)
600 : readUByte(byteCodes, i);
602 emit(smapper, this, "var @1 = @2;",
603 lmapper.setI(indx), smapper.popI());
608 final int indx = wide ? readUShort(byteCodes, i++)
609 : readUByte(byteCodes, i);
611 emit(smapper, this, "var @1 = @2;",
612 lmapper.setL(indx), smapper.popL());
617 final int indx = wide ? readUShort(byteCodes, i++)
618 : readUByte(byteCodes, i);
620 emit(smapper, this, "var @1 = @2;",
621 lmapper.setF(indx), smapper.popF());
626 final int indx = wide ? readUShort(byteCodes, i++)
627 : readUByte(byteCodes, i);
629 emit(smapper, this, "var @1 = @2;",
630 lmapper.setD(indx), smapper.popD());
635 final int indx = wide ? readUShort(byteCodes, i++)
636 : readUByte(byteCodes, i);
638 emit(smapper, this, "var @1 = @2;",
639 lmapper.setA(indx), smapper.popA());
643 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
646 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
649 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
652 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
655 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
658 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
661 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
664 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
667 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
670 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
673 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
676 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
679 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
682 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
685 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
688 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
691 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
694 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
697 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
700 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
703 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
706 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
709 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
712 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
715 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
718 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
721 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
724 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
727 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
730 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
733 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
736 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
739 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
740 smapper.getI(1), smapper.popI());
743 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
744 smapper.getL(1), smapper.popL());
747 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
750 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
753 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
754 smapper.getI(1), smapper.popI());
757 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
758 smapper.getL(1), smapper.popL());
761 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
764 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
767 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
770 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
773 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
776 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
779 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
782 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
785 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
788 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
791 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
794 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
797 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
800 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
803 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
806 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
809 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
812 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
816 final int varIndx = wide ? readUShort(byteCodes, i++)
817 : readUByte(byteCodes, i);
819 final int incrBy = wide ? readShort(byteCodes, i++)
823 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
825 emit(smapper, this, "@1 += @2;",
826 lmapper.getI(varIndx),
827 Integer.toString(incrBy));
832 emit(smapper, this, "return;");
835 emit(smapper, this, "return @1;", smapper.popI());
838 emit(smapper, this, "return @1;", smapper.popL());
841 emit(smapper, this, "return @1;", smapper.popF());
844 emit(smapper, this, "return @1;", smapper.popD());
847 emit(smapper, this, "return @1;", smapper.popA());
850 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
853 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
856 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
859 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
863 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
866 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
869 smapper.replace(this, VarType.DOUBLE, "@1",
873 smapper.replace(this, VarType.FLOAT, "@1",
877 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
881 smapper.replace(this, VarType.LONG, "(@1).toLong()",
885 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
889 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
892 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
896 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
898 case opc_aconst_null:
899 smapper.assign(this, VarType.REFERENCE, "null");
902 smapper.assign(this, VarType.INTEGER, "-1");
905 smapper.assign(this, VarType.INTEGER, "0");
908 smapper.assign(this, VarType.DOUBLE, "0");
911 smapper.assign(this, VarType.LONG, "0");
914 smapper.assign(this, VarType.FLOAT, "0");
917 smapper.assign(this, VarType.INTEGER, "1");
920 smapper.assign(this, VarType.LONG, "1");
923 smapper.assign(this, VarType.FLOAT, "1");
926 smapper.assign(this, VarType.DOUBLE, "1");
929 smapper.assign(this, VarType.INTEGER, "2");
932 smapper.assign(this, VarType.FLOAT, "2");
935 smapper.assign(this, VarType.INTEGER, "3");
938 smapper.assign(this, VarType.INTEGER, "4");
941 smapper.assign(this, VarType.INTEGER, "5");
944 int indx = readUByte(byteCodes, ++i);
945 String v = encodeConstant(indx);
946 int type = VarType.fromConstantType(jc.getTag(indx));
947 smapper.assign(this, type, v);
952 int indx = readUShortArg(byteCodes, i);
954 String v = encodeConstant(indx);
955 int type = VarType.fromConstantType(jc.getTag(indx));
956 if (type == VarType.LONG) {
957 final Long lv = new Long(v);
958 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
959 final int hi = (int)(lv.longValue() >> 32);
961 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
963 smapper.assign(this, VarType.LONG,
964 "0x" + Integer.toHexString(hi) + ".next32(0x" +
965 Integer.toHexString(low) + ")"
969 smapper.assign(this, type, v);
974 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
978 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
982 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
985 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
986 "===", topMostLabel);
989 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
990 "!==", topMostLabel);
993 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
997 int indx = i + readShortArg(byteCodes, i);
998 emitIf(smapper, this, "if ((@1) == 0) ",
999 smapper.popI(), i, indx, topMostLabel);
1004 int indx = i + readShortArg(byteCodes, i);
1005 emitIf(smapper, this, "if ((@1) != 0) ",
1006 smapper.popI(), i, indx, topMostLabel);
1011 int indx = i + readShortArg(byteCodes, i);
1012 emitIf(smapper, this, "if ((@1) < 0) ",
1013 smapper.popI(), i, indx, topMostLabel);
1018 int indx = i + readShortArg(byteCodes, i);
1019 emitIf(smapper, this, "if ((@1) <= 0) ",
1020 smapper.popI(), i, indx, topMostLabel);
1025 int indx = i + readShortArg(byteCodes, i);
1026 emitIf(smapper, this, "if ((@1) > 0) ",
1027 smapper.popI(), i, indx, topMostLabel);
1032 int indx = i + readShortArg(byteCodes, i);
1033 emitIf(smapper, this, "if ((@1) >= 0) ",
1034 smapper.popI(), i, indx, topMostLabel);
1038 case opc_ifnonnull: {
1039 int indx = i + readShortArg(byteCodes, i);
1040 emitIf(smapper, this, "if ((@1) !== null) ",
1041 smapper.popA(), i, indx, topMostLabel);
1046 int indx = i + readShortArg(byteCodes, i);
1047 emitIf(smapper, this, "if ((@1) === null) ",
1048 smapper.popA(), i, indx, topMostLabel);
1053 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1054 "!=", topMostLabel);
1057 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1061 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1062 "<=", topMostLabel);
1065 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1069 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1070 ">=", topMostLabel);
1073 smapper.flush(this);
1074 int indx = i + readShortArg(byteCodes, i);
1075 goTo(this, i, indx, topMostLabel);
1079 case opc_lookupswitch: {
1080 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1083 case opc_tableswitch: {
1084 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1087 case opc_invokeinterface: {
1088 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1091 case opc_invokevirtual:
1092 i = invokeVirtualMethod(byteCodes, i, smapper);
1094 case opc_invokespecial:
1095 i = invokeStaticMethod(byteCodes, i, smapper, false);
1097 case opc_invokestatic:
1098 i = invokeStaticMethod(byteCodes, i, smapper, true);
1100 case opc_invokedynamic: {
1101 int indx = readUShortArg(byteCodes, i);
1102 println("invoke dynamic: " + indx);
1103 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1104 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1105 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1106 println(" type: " + methodHandle.cpx1);
1107 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1108 String mcn = mangleClassName(mi[0]);
1109 char[] returnType = {'V'};
1110 StringBuilder cnt = new StringBuilder();
1111 String mn = findMethodName(mi, cnt, returnType);
1112 StringBuilder sb = new StringBuilder();
1113 sb.append("We don't handle invokedynamic, need to preprocess ahead-of-time:\n");
1114 sb.append(" mi[0]: ").append(mi[0]).append("\n");
1115 sb.append(" mi[1]: ").append(mi[1]).append("\n");
1116 sb.append(" mi[2]: ").append(mi[2]).append("\n");
1117 sb.append(" mn : ").append(mn).append("\n");
1118 sb.append(" name and type: ").append(jc.stringValue(c2.cpx2, true)).append("\n");
1119 throw new IOException(sb.toString());
1121 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1122 String type = jc.StringValue(nameAndType.cpx2);
1123 String object = accessClass(mcn) + "(false)";
1124 if (mn.startsWith("cons_")) {
1125 object += ".constructor";
1127 append("var metHan = ");
1128 append(accessStaticMethod(object, mn, mi));
1130 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1132 append(", '").append(mi[1]).append("', ");
1133 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1134 append(methodType).append("'").append(type).append("', null)");
1135 // if (numArguments > 0) {
1137 // for (int j = 1; j < numArguments; ++j) {
1143 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1149 int indx = readUShortArg(byteCodes, i);
1150 String ci = jc.getClassName(indx);
1151 emit(smapper, this, "var @1 = new @2;",
1152 smapper.pushA(), accessClass(mangleClassName(ci)));
1158 int atype = readUByte(byteCodes, ++i);
1159 generateNewArray(atype, smapper);
1161 case opc_anewarray: {
1162 int type = readUShortArg(byteCodes, i);
1164 generateANewArray(type, smapper);
1167 case opc_multianewarray: {
1168 int type = readUShortArg(byteCodes, i);
1170 i = generateMultiANewArray(type, byteCodes, i, smapper);
1173 case opc_arraylength:
1174 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1177 emit(smapper, this, "Array.at(@3, @2, @1);",
1178 smapper.popL(), smapper.popI(), smapper.popA());
1181 emit(smapper, this, "Array.at(@3, @2, @1);",
1182 smapper.popF(), smapper.popI(), smapper.popA());
1185 emit(smapper, this, "Array.at(@3, @2, @1);",
1186 smapper.popD(), smapper.popI(), smapper.popA());
1189 emit(smapper, this, "Array.at(@3, @2, @1);",
1190 smapper.popA(), smapper.popI(), smapper.popA());
1196 emit(smapper, this, "Array.at(@3, @2, @1);",
1197 smapper.popI(), smapper.popI(), smapper.popA());
1200 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1201 smapper.popI(), smapper.getA(0));
1204 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1205 smapper.popI(), smapper.getA(0));
1208 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1209 smapper.popI(), smapper.getA(0));
1212 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1213 smapper.popI(), smapper.getA(0));
1219 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1220 smapper.popI(), smapper.getA(0));
1228 final Variable v = smapper.get(0);
1229 if (smapper.isDirty()) {
1230 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1232 smapper.assign(this, v.getType(), v);
1237 final Variable vi1 = smapper.get(0);
1239 if (vi1.isCategory2()) {
1240 emit(smapper, this, "var @1 = @2;",
1241 smapper.pushT(vi1.getType()), vi1);
1243 final Variable vi2 = smapper.get(1);
1244 emit(smapper, this, "var @1 = @2, @3 = @4;",
1245 smapper.pushT(vi2.getType()), vi2,
1246 smapper.pushT(vi1.getType()), vi1);
1251 final Variable vi1 = smapper.pop(this);
1252 final Variable vi2 = smapper.pop(this);
1253 final Variable vo3 = smapper.pushT(vi1.getType());
1254 final Variable vo2 = smapper.pushT(vi2.getType());
1255 final Variable vo1 = smapper.pushT(vi1.getType());
1257 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1258 vo1, vi1, vo2, vi2, vo3, vo1);
1262 final Variable vi1 = smapper.pop(this);
1263 final Variable vi2 = smapper.pop(this);
1265 if (vi1.isCategory2()) {
1266 final Variable vo3 = smapper.pushT(vi1.getType());
1267 final Variable vo2 = smapper.pushT(vi2.getType());
1268 final Variable vo1 = smapper.pushT(vi1.getType());
1270 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1271 vo1, vi1, vo2, vi2, vo3, vo1);
1273 final Variable vi3 = smapper.pop(this);
1274 final Variable vo5 = smapper.pushT(vi2.getType());
1275 final Variable vo4 = smapper.pushT(vi1.getType());
1276 final Variable vo3 = smapper.pushT(vi3.getType());
1277 final Variable vo2 = smapper.pushT(vi2.getType());
1278 final Variable vo1 = smapper.pushT(vi1.getType());
1280 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1281 vo1, vi1, vo2, vi2, vo3, vi3);
1282 emit(smapper, this, " @1 = @2, @3 = @4;",
1283 vo4, vo1, vo5, vo2);
1288 final Variable vi1 = smapper.pop(this);
1289 final Variable vi2 = smapper.pop(this);
1291 if (vi2.isCategory2()) {
1292 final Variable vo3 = smapper.pushT(vi1.getType());
1293 final Variable vo2 = smapper.pushT(vi2.getType());
1294 final Variable vo1 = smapper.pushT(vi1.getType());
1296 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1297 vo1, vi1, vo2, vi2, vo3, vo1);
1299 final Variable vi3 = smapper.pop(this);
1300 final Variable vo4 = smapper.pushT(vi1.getType());
1301 final Variable vo3 = smapper.pushT(vi3.getType());
1302 final Variable vo2 = smapper.pushT(vi2.getType());
1303 final Variable vo1 = smapper.pushT(vi1.getType());
1305 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1306 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1311 final Variable vi1 = smapper.pop(this);
1312 final Variable vi2 = smapper.pop(this);
1314 if (vi1.isCategory2()) {
1315 if (vi2.isCategory2()) {
1316 final Variable vo3 = smapper.pushT(vi1.getType());
1317 final Variable vo2 = smapper.pushT(vi2.getType());
1318 final Variable vo1 = smapper.pushT(vi1.getType());
1320 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1321 vo1, vi1, vo2, vi2, vo3, vo1);
1323 final Variable vi3 = smapper.pop(this);
1324 final Variable vo4 = smapper.pushT(vi1.getType());
1325 final Variable vo3 = smapper.pushT(vi3.getType());
1326 final Variable vo2 = smapper.pushT(vi2.getType());
1327 final Variable vo1 = smapper.pushT(vi1.getType());
1329 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1330 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1333 final Variable vi3 = smapper.pop(this);
1335 if (vi3.isCategory2()) {
1336 final Variable vo5 = smapper.pushT(vi2.getType());
1337 final Variable vo4 = smapper.pushT(vi1.getType());
1338 final Variable vo3 = smapper.pushT(vi3.getType());
1339 final Variable vo2 = smapper.pushT(vi2.getType());
1340 final Variable vo1 = smapper.pushT(vi1.getType());
1342 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1343 vo1, vi1, vo2, vi2, vo3, vi3);
1344 emit(smapper, this, " @1 = @2, @3 = @4;",
1345 vo4, vo1, vo5, vo2);
1347 final Variable vi4 = smapper.pop(this);
1348 final Variable vo6 = smapper.pushT(vi2.getType());
1349 final Variable vo5 = smapper.pushT(vi1.getType());
1350 final Variable vo4 = smapper.pushT(vi4.getType());
1351 final Variable vo3 = smapper.pushT(vi3.getType());
1352 final Variable vo2 = smapper.pushT(vi2.getType());
1353 final Variable vo1 = smapper.pushT(vi1.getType());
1355 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1356 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1357 emit(smapper, this, " @1 = @2, @3 = @4;",
1358 vo5, vo1, vo6, vo2);
1364 final Variable vi1 = smapper.get(0);
1365 final Variable vi2 = smapper.get(1);
1367 if (vi1.getType() == vi2.getType()) {
1368 final Variable tmp = smapper.pushT(vi1.getType());
1370 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1375 smapper.pushT(vi1.getType());
1376 smapper.pushT(vi2.getType());
1381 smapper.assign(this, VarType.INTEGER,
1382 "(" + Integer.toString(byteCodes[++i]) + ")");
1385 smapper.assign(this, VarType.INTEGER,
1386 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1390 case opc_getfield: {
1391 int indx = readUShortArg(byteCodes, i);
1392 String[] fi = jc.getFieldInfoName(indx);
1393 final int type = VarType.fromFieldType(fi[2].charAt(0));
1394 final String mangleClass = mangleClassName(fi[0]);
1395 final String mangleClassAccess = accessClassFalse(mangleClass);
1396 smapper.replace(this, type, "@2.call(@1)",
1398 accessField(mangleClassAccess,
1402 addReference(fi[0]);
1405 case opc_putfield: {
1406 int indx = readUShortArg(byteCodes, i);
1407 String[] fi = jc.getFieldInfoName(indx);
1408 final int type = VarType.fromFieldType(fi[2].charAt(0));
1409 final String mangleClass = mangleClassName(fi[0]);
1410 final String mangleClassAccess = accessClassFalse(mangleClass);
1411 emit(smapper, this, "@3.call(@2, @1);",
1414 accessField(mangleClassAccess,
1417 addReference(fi[0]);
1420 case opc_getstatic: {
1421 int indx = readUShortArg(byteCodes, i);
1422 String[] fi = jc.getFieldInfoName(indx);
1423 final int type = VarType.fromFieldType(fi[2].charAt(0));
1424 String ac = accessClassFalse(mangleClassName(fi[0]));
1425 String af = accessField(ac, "_" + fi[1], fi);
1426 smapper.assign(this, type, af + "()");
1428 addReference(fi[0]);
1431 case opc_putstatic: {
1432 int indx = readUShortArg(byteCodes, i);
1433 String[] fi = jc.getFieldInfoName(indx);
1434 final int type = VarType.fromFieldType(fi[2].charAt(0));
1435 emit(smapper, this, "@1._@2(@3);",
1436 accessClassFalse(mangleClassName(fi[0])), fi[1],
1437 smapper.popT(type));
1439 addReference(fi[0]);
1442 case opc_checkcast: {
1443 int indx = readUShortArg(byteCodes, i);
1444 generateCheckcast(indx, smapper);
1448 case opc_instanceof: {
1449 int indx = readUShortArg(byteCodes, i);
1450 generateInstanceOf(indx, smapper);
1455 final CharSequence v = smapper.popA();
1458 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1459 smapper.pushA(), v);
1463 case opc_monitorenter: {
1464 debug("/* monitor enter */");
1469 case opc_monitorexit: {
1470 debug("/* monitor exit */");
1481 emit(smapper, this, "throw 'unknown bytecode @1';",
1482 Integer.toString(c));
1486 generateByteCodeComment(prev, i, byteCodes);
1492 if (previousTrap != null) {
1493 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1498 while (openBraces-- > 0) {
1509 private int generateIf(StackMapper mapper, byte[] byteCodes,
1510 int i, final CharSequence v2, final CharSequence v1,
1511 final String test, int topMostLabel
1512 ) throws IOException {
1514 int indx = i + readShortArg(byteCodes, i);
1515 append("if ((").append(v1)
1516 .append(") ").append(test).append(" (")
1517 .append(v2).append(")) ");
1518 goTo(this, i, indx, topMostLabel);
1522 private int readInt4(byte[] byteCodes, int offset) {
1523 final int d = byteCodes[offset + 0] << 24;
1524 final int c = byteCodes[offset + 1] << 16;
1525 final int b = byteCodes[offset + 2] << 8;
1526 final int a = byteCodes[offset + 3];
1527 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1529 private static int readUByte(byte[] byteCodes, int offset) {
1530 return byteCodes[offset] & 0xff;
1533 private static int readUShort(byte[] byteCodes, int offset) {
1534 return ((byteCodes[offset] & 0xff) << 8)
1535 | (byteCodes[offset + 1] & 0xff);
1537 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1538 return readUShort(byteCodes, offsetInstruction + 1);
1541 private static int readShort(byte[] byteCodes, int offset) {
1542 int signed = byteCodes[offset];
1543 byte b0 = (byte)signed;
1544 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1546 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1547 return readShort(byteCodes, offsetInstruction + 1);
1550 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1552 Boolean count = null;
1553 boolean array = false;
1555 int firstPos = sig.length();
1556 while (i < descriptor.length()) {
1557 char ch = descriptor.charAt(i++);
1578 if (ch == 'J' || ch == 'D') {
1584 sig.insert(firstPos, ch);
1586 returnType[0] = '[';
1587 sig.insert(firstPos, "_3");
1596 returnType[0] = 'V';
1597 sig.insert(firstPos, 'V');
1600 int next = descriptor.indexOf(';', i);
1601 String realSig = mangleSig(descriptor, i - 1, next + 1);
1606 sig.append(realSig);
1609 sig.insert(firstPos, realSig);
1611 sig.insert(firstPos, "_3");
1613 returnType[0] = 'L';
1622 throw new IllegalStateException("Invalid char: " + ch);
1627 static String mangleSig(String sig) {
1628 return mangleSig(sig, 0, sig.length());
1631 private static String mangleMethodName(String name) {
1632 StringBuilder sb = new StringBuilder(name.length() * 2);
1633 int last = name.length();
1634 for (int i = 0; i < last; i++) {
1635 final char ch = name.charAt(i);
1637 case '_': sb.append("_1"); break;
1638 default: sb.append(ch); break;
1641 return sb.toString();
1643 private static String mangleSig(String txt, int first, int last) {
1644 StringBuilder sb = new StringBuilder((last - first) * 2);
1645 for (int i = first; i < last; i++) {
1646 final char ch = txt.charAt(i);
1648 case '/': sb.append('_'); break;
1649 case '_': sb.append("_1"); break;
1650 case ';': sb.append("_2"); break;
1651 case '[': sb.append("_3"); break;
1653 if (Character.isJavaIdentifierPart(ch)) {
1657 String hex = Integer.toHexString(ch).toLowerCase();
1658 for (int m = hex.length(); m < 4; m++) {
1666 return sb.toString();
1669 private static String mangleClassName(String name) {
1670 return mangleSig(name);
1673 private static String findMethodName(MethodData m, StringBuilder cnt) {
1674 StringBuilder name = new StringBuilder();
1675 if ("<init>".equals(m.getName())) { // NOI18N
1676 name.append("cons"); // NOI18N
1677 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1678 name.append("class"); // NOI18N
1680 name.append(mangleMethodName(m.getName()));
1683 countArgs(m.getInternalSig(), new char[1], name, cnt);
1684 return name.toString();
1687 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1688 StringBuilder name = new StringBuilder();
1689 String descr = mi[2];//mi.getDescriptor();
1691 if ("<init>".equals(nm)) { // NOI18N
1692 name.append("cons"); // NOI18N
1694 name.append(mangleMethodName(nm));
1696 countArgs(descr, returnType, name, cnt);
1697 return name.toString();
1700 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1701 throws IOException {
1702 int methodIndex = readUShortArg(byteCodes, i);
1703 String[] mi = jc.getFieldInfoName(methodIndex);
1704 char[] returnType = { 'V' };
1705 StringBuilder cnt = new StringBuilder();
1706 String mn = findMethodName(mi, cnt, returnType);
1708 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1709 final CharSequence[] vars = new CharSequence[numArguments];
1711 for (int j = numArguments - 1; j >= 0; --j) {
1712 vars[j] = mapper.popValue();
1716 "newUpdater__Ljava_util_concurrent_atomic_AtomicIntegerFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1717 && "java/util/concurrent/atomic/AtomicIntegerFieldUpdater".equals(mi[0])
1719 "newUpdater__Ljava_util_concurrent_atomic_AtomicLongFieldUpdater_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1720 && "java/util/concurrent/atomic/AtomicLongFieldUpdater".equals(mi[0])
1722 if (vars[1] instanceof String) {
1723 String field = vars[1].toString();
1724 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1725 vars[1] = "c._" + field.substring(1, field.length() - 1);
1730 "newUpdater__Ljava_util_concurrent_atomic_AtomicReferenceFieldUpdater_2Ljava_lang_Class_2Ljava_lang_Class_2Ljava_lang_String_2".equals(mn)
1731 && "java/util/concurrent/atomic/AtomicReferenceFieldUpdater".equals(mi[0])
1733 if (vars[1] instanceof String) {
1734 String field = vars[2].toString();
1735 if (field.length() > 2 && field.charAt(0) == '"' && field.charAt(field.length() - 1) == '"') {
1736 vars[2] = "c._" + field.substring(1, field.length() - 1);
1741 if (returnType[0] != 'V') {
1744 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1748 final String in = mi[0];
1751 in.equals("org/apidesign/html/boot/spi/Fn") ||
1752 in.equals("org/netbeans/html/boot/spi/Fn")
1754 mcn = "java_lang_Class";
1756 mcn = mangleClassName(in);
1758 String object = accessClassFalse(mcn);
1759 if (mn.startsWith("cons_")) {
1760 object += ".constructor";
1762 append(accessStaticMethod(object, mn, mi));
1768 if (numArguments > 0) {
1770 for (int j = 1; j < numArguments; ++j) {
1780 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1781 throws IOException {
1782 int methodIndex = readUShortArg(byteCodes, i);
1783 String[] mi = jc.getFieldInfoName(methodIndex);
1784 char[] returnType = { 'V' };
1785 StringBuilder cnt = new StringBuilder();
1786 String mn = findMethodName(mi, cnt, returnType);
1788 final int numArguments = cnt.length() + 1;
1789 final CharSequence[] vars = new CharSequence[numArguments];
1791 for (int j = numArguments - 1; j >= 0; --j) {
1792 vars[j] = mapper.popValue();
1795 if (returnType[0] != 'V') {
1798 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1802 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1804 for (int j = 1; j < numArguments; ++j) {
1814 private void addReference(String cn) throws IOException {
1815 if (requireReference(cn)) {
1816 debug(" /* needs " + cn + " */");
1820 private void outType(String d, StringBuilder out) {
1822 while (d.charAt(0) == '[') {
1826 if (d.charAt(0) == 'L') {
1827 assert d.charAt(d.length() - 1) == ';';
1828 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1834 private String encodeConstant(int entryIndex) throws IOException {
1835 String[] classRef = { null };
1836 String s = jc.stringValue(entryIndex, classRef);
1837 if (classRef[0] != null) {
1838 if (classRef[0].startsWith("[")) {
1839 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1841 addReference(classRef[0]);
1842 s = accessClassFalse(mangleClassName(s)) + ".constructor.$class";
1848 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1849 byte[] arr = m.findAnnotationData(true);
1853 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1854 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1855 class P extends AnnotationParser {
1861 String[] args = new String[30];
1867 protected void visitAttr(String type, String attr, String at, String value) {
1868 if (type.equals(jvmType)) {
1869 if ("body".equals(attr)) {
1871 } else if ("args".equals(attr)) {
1872 args[cnt++] = value;
1874 throw new IllegalArgumentException(attr);
1877 if (type.equals(htmlType)) {
1879 if ("body".equals(attr)) {
1881 } else if ("args".equals(attr)) {
1882 args[cnt++] = value;
1883 } else if ("javacall".equals(attr)) {
1884 javacall = "1".equals(value);
1885 } else if ("wait4js".equals(attr)) {
1886 // ignore, we always invoke synchronously
1888 throw new IllegalArgumentException(attr);
1895 if (p.body == null) {
1898 StringBuilder cnt = new StringBuilder();
1899 final String mn = findMethodName(m, cnt);
1900 append("m = ").append(destObject).append(".").append(mn);
1901 append(" = function(");
1904 StringBuilder toValue = new StringBuilder();
1905 for (int i = 0; i < cnt.length(); i++) {
1907 space = outputArg(this, p.args, index);
1908 if (p.html4j && space.length() > 0) {
1909 toValue.append("\n ").append(p.args[index]).append(" = ")
1910 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1911 append(p.args[index]).append(");");
1915 append(") {").append("\n");
1916 append(toValue.toString());
1918 int lastSlash = jc.getClassName().lastIndexOf('/');
1919 final String pkg = jc.getClassName().substring(0, lastSlash);
1920 append(mangleCallbacks(pkg, p.body));
1921 requireReference(pkg + "/$JsCallbacks$");
1929 private static CharSequence mangleCallbacks(String pkgName, String body) {
1930 StringBuilder sb = new StringBuilder();
1933 int next = body.indexOf(".@", pos);
1935 sb.append(body.substring(pos));
1936 body = sb.toString();
1941 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1946 String refId = body.substring(ident, next);
1948 sb.append(body.substring(pos, ident));
1950 int sigBeg = body.indexOf('(', next);
1951 int sigEnd = body.indexOf(')', sigBeg);
1952 int colon4 = body.indexOf("::", next);
1953 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1954 throw new IllegalStateException("Malformed body " + body);
1956 String fqn = body.substring(next + 2, colon4);
1957 String method = body.substring(colon4 + 2, sigBeg);
1958 String params = body.substring(sigBeg, sigEnd + 1);
1960 int paramBeg = body.indexOf('(', sigEnd + 1);
1962 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1963 sb.append(mangleJsCallbacks(fqn, method, params, false));
1964 sb.append("(").append(refId);
1965 if (body.charAt(paramBeg + 1) != ')') {
1973 int next = body.indexOf("@", pos);
1978 sb.append(body.substring(pos));
1982 sb = new StringBuilder();
1985 sb.append(body.substring(pos, next));
1987 int sigBeg = body.indexOf('(', next);
1988 int sigEnd = body.indexOf(')', sigBeg);
1989 int colon4 = body.indexOf("::", next);
1990 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1991 throw new IllegalStateException("Malformed body " + body);
1993 String fqn = body.substring(next + 1, colon4);
1994 String method = body.substring(colon4 + 2, sigBeg);
1995 String params = body.substring(sigBeg, sigEnd + 1);
1997 int paramBeg = body.indexOf('(', sigEnd + 1);
1999 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
2000 sb.append(mangleJsCallbacks(fqn, method, params, true));
2006 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2007 if (params.startsWith("(")) {
2008 params = params.substring(1);
2010 if (params.endsWith(")")) {
2011 params = params.substring(0, params.length() - 1);
2013 StringBuilder sb = new StringBuilder();
2014 final String fqnu = fqn.replace('.', '_');
2015 final String rfqn = mangleClassName(fqnu);
2016 final String rm = mangleMethodName(method);
2019 StringBuilder pb = new StringBuilder();
2020 int len = params.length();
2022 while (indx < len) {
2023 char ch = params.charAt(indx);
2024 if (ch == '[' || ch == 'L') {
2025 int column = params.indexOf(';', indx) + 1;
2026 if (column > indx) {
2027 String real = params.substring(indx, column);
2028 if ("Ljava/lang/String;".equals(real)) {
2029 pb.append("Ljava/lang/String;");
2034 pb.append("Ljava/lang/Object;");
2041 srp = mangleSig(pb.toString());
2043 final String rp = mangleSig(params);
2044 final String mrp = mangleMethodName(rp);
2045 sb.append(rfqn).append("$").append(rm).
2046 append('$').append(mrp).append("__Ljava_lang_Object_2");
2048 sb.append('L').append(fqnu).append("_2");
2051 return sb.toString();
2054 private static String className(ClassData jc) {
2055 //return jc.getName().getInternalName().replace('/', '_');
2056 return mangleClassName(jc.getClassName());
2059 private static String[] findAnnotation(
2060 byte[] arr, ClassData cd, final String className,
2061 final String... attrNames
2062 ) throws IOException {
2066 final String[] values = new String[attrNames.length];
2067 final boolean[] found = { false };
2068 final String jvmType = "L" + className.replace('.', '/') + ";";
2069 AnnotationParser ap = new AnnotationParser(false, true) {
2071 protected void visitAttr(String type, String attr, String at, String value) {
2072 if (type.equals(jvmType)) {
2074 for (int i = 0; i < attrNames.length; i++) {
2075 if (attrNames[i].equals(attr)) {
2084 return found[0] ? values : null;
2087 private CharSequence initField(FieldData v) {
2088 final String is = v.getInternalSig();
2089 if (is.length() == 1) {
2090 switch (is.charAt(0)) {
2096 case 'I': return " = 0;";
2098 case 'D': return " = 0.0;";
2100 throw new IllegalStateException(is);
2106 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2107 AnnotationParser ap = new AnnotationParser(true, false) {
2108 int[] cnt = new int[32];
2112 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2113 final String slashType = attrType.substring(1, attrType.length() - 1);
2114 requireReference(slashType);
2116 if (cnt[depth]++ > 0) {
2120 append('"').append(attrType).append("\" : ");
2127 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2133 protected void visitValueStart(String attrName, char type) throws IOException {
2134 if (cnt[depth]++ > 0) {
2138 if (attrName != null) {
2139 append('"').append(attrName).append("\" : ");
2147 protected void visitValueEnd(String attrName, char type) throws IOException {
2155 protected void visitAttr(String type, String attr, String attrType, String value)
2156 throws IOException {
2157 if (attr == null && value == null) {
2164 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2165 throws IOException {
2166 final String slashType = attrType.substring(1, attrType.length() - 1);
2167 requireReference(slashType);
2169 final String cn = mangleClassName(slashType);
2170 append(accessClassFalse(cn))
2171 .append("['valueOf__L").
2173 append("_2Ljava_lang_String_2']('").
2181 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2182 final String name = args[indx];
2186 if (name.contains(",")) {
2187 throw new IOException("Wrong parameter with ',': " + name);
2193 final void emitNoFlush(
2195 final String format, final CharSequence... params
2196 ) throws IOException {
2197 emitImpl(this, format, params);
2199 static final void emit(
2201 final Appendable out,
2202 final String format, final CharSequence... params
2203 ) throws IOException {
2205 emitImpl(out, format, params);
2207 static void emitImpl(final Appendable out,
2208 final String format,
2209 final CharSequence... params) throws IOException {
2210 final int length = format.length();
2213 int paramOffset = format.indexOf('@');
2214 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2215 final char paramChar = format.charAt(paramOffset + 1);
2216 if ((paramChar >= '1') && (paramChar <= '9')) {
2217 final int paramIndex = paramChar - '0' - 1;
2219 out.append(format, processed, paramOffset);
2220 out.append(params[paramIndex]);
2223 processed = paramOffset + 1;
2226 paramOffset = format.indexOf('@', paramOffset + 1);
2229 out.append(format, processed, length);
2232 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2233 append("} catch (e) {\n");
2235 for (TrapData e : traps) {
2239 if (e.catch_cpx != 0) { //not finally
2240 final String classInternalName = jc.getClassName(e.catch_cpx);
2241 addReference(classInternalName);
2242 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2243 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2244 append("var stA0 = e;");
2245 goTo(this, current, e.handler_pc, topMostLabel);
2248 finallyPC = e.handler_pc;
2251 if (finallyPC == -1) {
2254 append("var stA0 = e;");
2255 goTo(this, current, finallyPC, topMostLabel);
2260 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2263 out.append("{ gt = 0; continue X_" + to + "; }");
2265 out.append("{ gt = " + to + "; continue X_0; }");
2268 out.append("{ gt = " + to + "; break IF; }");
2272 private static void emitIf(
2274 Appendable out, String pattern,
2276 int current, int to, int canBack
2277 ) throws IOException {
2279 emitImpl(out, pattern, param);
2280 goTo(out, current, to, canBack);
2283 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2286 case 4: jvmType = "[Z"; break;
2287 case 5: jvmType = "[C"; break;
2288 case 6: jvmType = "[F"; break;
2289 case 7: jvmType = "[D"; break;
2290 case 8: jvmType = "[B"; break;
2291 case 9: jvmType = "[S"; break;
2292 case 10: jvmType = "[I"; break;
2293 case 11: jvmType = "[J"; break;
2294 default: throw new IllegalStateException("Array type: " + atype);
2297 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2298 smapper.popI(), smapper.pushA(), jvmType);
2301 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2302 String typeName = jc.getClassName(type);
2303 String ref = "null";
2304 if (typeName.startsWith("[")) {
2305 typeName = "'[" + typeName + "'";
2307 ref = "vm." + mangleClassName(typeName);
2308 typeName = "'[L" + typeName + ";'";
2311 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2312 smapper.popI(), smapper.pushA(), typeName, ref);
2315 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2316 String typeName = jc.getClassName(type);
2317 int dim = readUByte(byteCodes, ++i);
2318 StringBuilder dims = new StringBuilder();
2320 for (int d = 0; d < dim; d++) {
2322 dims.insert(1, ",");
2324 dims.insert(1, smapper.popI());
2328 if (typeName.charAt(dim) == 'L') {
2329 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2332 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2333 dims.toString(), smapper.pushA(), typeName, fn
2338 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2339 int table = i / 4 * 4 + 4;
2340 int dflt = i + readInt4(byteCodes, table);
2342 int low = readInt4(byteCodes, table);
2344 int high = readInt4(byteCodes, table);
2346 final CharSequence swVar = smapper.popValue();
2347 smapper.flush(this);
2348 append("switch (").append(swVar).append(") {\n");
2349 while (low <= high) {
2350 int offset = i + readInt4(byteCodes, table);
2352 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2355 append(" default: ");
2356 goTo(this, i, dflt, topMostLabel);
2362 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2363 int table = i / 4 * 4 + 4;
2364 int dflt = i + readInt4(byteCodes, table);
2366 int n = readInt4(byteCodes, table);
2368 final CharSequence swVar = smapper.popValue();
2369 smapper.flush(this);
2370 append("switch (").append(swVar).append(") {\n");
2372 int cnstnt = readInt4(byteCodes, table);
2374 int offset = i + readInt4(byteCodes, table);
2376 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2378 append(" default: ");
2379 goTo(this, i, dflt, topMostLabel);
2385 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2386 String type = jc.getClassName(indx);
2387 if (!type.startsWith("[")) {
2389 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2390 smapper.popA(), smapper.pushI(),
2391 type.replace('/', '_'));
2394 while (type.charAt(cnt) == '[') {
2397 if (type.charAt(cnt) == 'L') {
2398 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2400 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2401 smapper.popA(), smapper.pushI(),
2406 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2407 smapper.popA(), smapper.pushI(), type
2413 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2414 String type = jc.getClassName(indx);
2415 if (!type.startsWith("[")) {
2416 emitNoFlush(smapper,
2417 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2418 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2421 while (type.charAt(cnt) == '[') {
2424 if (type.charAt(cnt) == 'L') {
2425 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2426 emitNoFlush(smapper,
2427 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2428 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2431 emitNoFlush(smapper,
2432 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2433 smapper.getT(0, VarType.REFERENCE, false), type
2439 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2440 for (int j = prev; j <= i; j++) {
2442 final int cc = readUByte(byteCodes, j);
2443 append(Integer.toString(cc));
2447 @JavaScriptBody(args = "msg", body = "")
2448 private static void println(String msg) {
2449 System.err.println(msg);