2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.util.Arrays;
23 import org.apidesign.bck2brwsr.core.JavaScriptBody;
24 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
26 /** Translator of the code inside class files to JavaScript.
28 * @author Jaroslav Tulach <jtulach@netbeans.org>
30 abstract class ByteCodeToJavaScript implements Appendable {
32 private final Appendable out;
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 protected String accessField(String object, String mangledName,
90 String[] fieldInfoName) throws IOException {
91 return object + "." + mangledName;
94 protected String accessStaticMethod(
97 String[] fieldInfoName) throws IOException {
98 return object + "." + mangledName;
101 protected String accessVirtualMethod(
104 String[] fieldInfoName,
106 ) throws IOException {
107 return object + "." + mangledName + '(';
110 protected void declaredClass(ClassData classData, String mangledName)
114 protected void declaredField(FieldData fieldData,
116 String mangledName) throws IOException {
119 protected void declaredMethod(MethodData methodData,
121 String mangledName) throws IOException {
124 /** Prints out a debug message.
126 * @param msg the message
127 * @return true if the message has been printed
128 * @throws IOException
130 boolean debug(String msg) throws IOException {
136 * Converts a given class file to a JavaScript version.
138 * @param classFile input stream with code of the .class file
139 * @return the initialization code for this class, if any. Otherwise <code>null</code>
141 * @throws IOException if something goes wrong during read or write or translating
144 public String compile(InputStream classFile) throws IOException {
145 return compile(new ClassData(classFile));
148 protected String compile(ClassData classData) throws IOException {
150 final String cn = this.jc.getClassName();
151 this.callbacks = cn.endsWith("/$JsCallbacks$");
152 if (jc.getMajor_version() < 50 && !cn.endsWith("/package-info")) {
153 throw new IOException("Can't compile " + cn + ". Class file version " + jc.getMajor_version() + "."
154 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
157 byte[] arrData = jc.findAnnotationData(true);
159 String[] arr = findAnnotation(arrData, jc,
160 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
161 "resource", "processByteCode"
164 if (!arr[0].isEmpty()) {
165 requireScript(arr[0]);
167 if ("0".equals(arr[1])) {
172 final String jsResource;
174 String[] arr = findAnnotation(arrData, jc,
175 "net.java.html.js.JavaScriptResource",
179 if (arr[0].startsWith("/")) {
182 int last = cn.lastIndexOf('/');
183 jsResource = cn.substring(0, last + 1).replace('.', '/') + arr[0];
189 String[] proto = findAnnotation(arrData, jc,
190 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
191 "container", "prototype"
193 StringArray toInitilize = new StringArray();
194 final String className = className(jc);
195 append("\n\n").append(assignClass(className));
196 append("function ").append(className).append("() {");
198 append("\n var CLS = ").append(className).append(';');
199 append("\n if (!CLS.$class) {");
201 String sc = jc.getSuperClassName(); // with _
202 append("\n var pp = ").
203 append(accessClass(mangleClassName(sc))).append("(true);");
204 append("\n var p = CLS.prototype = pp;");
205 append("\n var c = p;");
206 append("\n var sprcls = pp.constructor.$class;");
208 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
209 if (proto[0] == null) {
212 append("\n var c = ").append(proto[0]).append(";");
213 append("\n var sprcls = null;");
215 for (FieldData v : jc.getFields()) {
217 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
218 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
222 append("\n CLS.fld_").append(v.getName()).append(initField(v));
223 append("\n m = c._").append(v.getName()).append(" = function (v) {")
224 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
225 .append(" = v; return CLS.fld_").
226 append(v.getName()).append("; };");
228 append("\n m = c._").append(v.getName()).append(" = function (v) {")
229 .append(" if (arguments.length == 1) this.fld_").
230 append(className).append('_').append(v.getName())
231 .append(" = v; return this.fld_").
232 append(className).append('_').append(v.getName())
236 declaredField(v, "c", "_" + v.getName());
238 for (MethodData m : jc.getMethods()) {
239 byte[] onlyArr = m.findAnnotationData(true);
240 if (javaScriptOnly(onlyArr)) continue;
246 mn = generateStaticMethod(destObject, m, toInitilize);
248 if (m.isConstructor()) {
250 mn = generateInstanceMethod(destObject, m);
253 mn = generateInstanceMethod(destObject, m);
256 declaredMethod(m, destObject, mn);
257 byte[] runAnno = m.findAnnotationData(false);
258 if (runAnno != null) {
259 append("\n m.anno = {");
260 generateAnno(jc, runAnno);
263 append("\n m.access = " + m.getAccess()).append(";");
264 append("\n m.cls = CLS;");
266 append("\n c.constructor = CLS;");
267 append("\n function ").append(className).append("fillInstOf(x) {");
268 String instOfName = "$instOf_" + className;
269 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
270 if (jc.isInterface()) {
271 for (MethodData m : jc.getMethods()) {
272 if ((m.getAccess() & ACC_ABSTRACT) == 0
273 && (m.getAccess() & ACC_STATIC) == 0
274 && (m.getAccess() & ACC_PRIVATE) == 0) {
275 final String mn = findMethodName(m, new StringBuilder());
277 append("\n if (!x['").append(mn).append("']) Object.defineProperty(x, '").append(mn).append("', { value : c['").append(mn).append("']});");
278 append("\n } catch (ignore) {");
283 for (String superInterface : jc.getSuperInterfaces()) {
284 String intrfc = superInterface.replace('/', '_');
285 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
286 requireReference(superInterface);
290 append("\n Object.defineProperty(c, 'fillInstOf', { value: ").append(className).append("fillInstOf });");
291 append("\n ").append(className).append("fillInstOf(c);");
292 append("\n } catch (ignore) {");
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(accessClass(className(jc)) + "(false)['" + mn + "']");
388 toInitilize.add(accessClass(className(jc)) + "(false)." + 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 = accessClass(mangleClass);
1396 smapper.replace(this, type, "@2.call(@1)",
1398 accessField(mangleClassAccess + "(false)",
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 = accessClass(mangleClass);
1411 emit(smapper, this, "@3.call(@2, @1);",
1414 accessField(mangleClassAccess + "(false)",
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 = accessClass(mangleClassName(fi[0]));
1425 String af = accessField(ac + "(false)", "_" + 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(false)._@2(@3);",
1436 accessClass(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 = accessClass(mcn) + "(false)";
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') {
1797 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1801 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1803 for (int j = 1; j < numArguments; ++j) {
1813 private void addReference(String cn) throws IOException {
1814 if (requireReference(cn)) {
1815 debug(" /* needs " + cn + " */");
1819 private void outType(String d, StringBuilder out) {
1821 while (d.charAt(0) == '[') {
1825 if (d.charAt(0) == 'L') {
1826 assert d.charAt(d.length() - 1) == ';';
1827 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1833 private String encodeConstant(int entryIndex) throws IOException {
1834 String[] classRef = { null };
1835 String s = jc.stringValue(entryIndex, classRef);
1836 if (classRef[0] != null) {
1837 if (classRef[0].startsWith("[")) {
1838 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1840 addReference(classRef[0]);
1841 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1847 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1848 byte[] arr = m.findAnnotationData(true);
1852 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1853 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1854 class P extends AnnotationParser {
1860 String[] args = new String[30];
1866 protected void visitAttr(String type, String attr, String at, String value) {
1867 if (type.equals(jvmType)) {
1868 if ("body".equals(attr)) {
1870 } else if ("args".equals(attr)) {
1871 args[cnt++] = value;
1873 throw new IllegalArgumentException(attr);
1876 if (type.equals(htmlType)) {
1878 if ("body".equals(attr)) {
1880 } else if ("args".equals(attr)) {
1881 args[cnt++] = value;
1882 } else if ("javacall".equals(attr)) {
1883 javacall = "1".equals(value);
1884 } else if ("wait4js".equals(attr)) {
1885 // ignore, we always invoke synchronously
1887 throw new IllegalArgumentException(attr);
1894 if (p.body == null) {
1897 StringBuilder cnt = new StringBuilder();
1898 final String mn = findMethodName(m, cnt);
1899 append("m = ").append(destObject).append(".").append(mn);
1900 append(" = function(");
1903 StringBuilder toValue = new StringBuilder();
1904 for (int i = 0; i < cnt.length(); i++) {
1906 space = outputArg(this, p.args, index);
1907 if (p.html4j && space.length() > 0) {
1908 toValue.append("\n ").append(p.args[index]).append(" = ")
1909 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1910 append(p.args[index]).append(");");
1914 append(") {").append("\n");
1915 append(toValue.toString());
1917 int lastSlash = jc.getClassName().lastIndexOf('/');
1918 final String pkg = jc.getClassName().substring(0, lastSlash);
1919 append(mangleCallbacks(pkg, p.body));
1920 requireReference(pkg + "/$JsCallbacks$");
1928 private static CharSequence mangleCallbacks(String pkgName, String body) {
1929 StringBuilder sb = new StringBuilder();
1932 int next = body.indexOf(".@", pos);
1934 sb.append(body.substring(pos));
1935 body = sb.toString();
1940 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1945 String refId = body.substring(ident, next);
1947 sb.append(body.substring(pos, ident));
1949 int sigBeg = body.indexOf('(', next);
1950 int sigEnd = body.indexOf(')', sigBeg);
1951 int colon4 = body.indexOf("::", next);
1952 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1953 throw new IllegalStateException("Malformed body " + body);
1955 String fqn = body.substring(next + 2, colon4);
1956 String method = body.substring(colon4 + 2, sigBeg);
1957 String params = body.substring(sigBeg, sigEnd + 1);
1959 int paramBeg = body.indexOf('(', sigEnd + 1);
1961 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1962 sb.append(mangleJsCallbacks(fqn, method, params, false));
1963 sb.append("(").append(refId);
1964 if (body.charAt(paramBeg + 1) != ')') {
1972 int next = body.indexOf("@", pos);
1977 sb.append(body.substring(pos));
1981 sb = new StringBuilder();
1984 sb.append(body.substring(pos, next));
1986 int sigBeg = body.indexOf('(', next);
1987 int sigEnd = body.indexOf(')', sigBeg);
1988 int colon4 = body.indexOf("::", next);
1989 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1990 throw new IllegalStateException("Malformed body " + body);
1992 String fqn = body.substring(next + 1, colon4);
1993 String method = body.substring(colon4 + 2, sigBeg);
1994 String params = body.substring(sigBeg, sigEnd + 1);
1996 int paramBeg = body.indexOf('(', sigEnd + 1);
1998 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1999 sb.append(mangleJsCallbacks(fqn, method, params, true));
2005 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
2006 if (params.startsWith("(")) {
2007 params = params.substring(1);
2009 if (params.endsWith(")")) {
2010 params = params.substring(0, params.length() - 1);
2012 StringBuilder sb = new StringBuilder();
2013 final String fqnu = fqn.replace('.', '_');
2014 final String rfqn = mangleClassName(fqnu);
2015 final String rm = mangleMethodName(method);
2018 StringBuilder pb = new StringBuilder();
2019 int len = params.length();
2021 while (indx < len) {
2022 char ch = params.charAt(indx);
2023 if (ch == '[' || ch == 'L') {
2024 int column = params.indexOf(';', indx) + 1;
2025 if (column > indx) {
2026 String real = params.substring(indx, column);
2027 if ("Ljava/lang/String;".equals(real)) {
2028 pb.append("Ljava/lang/String;");
2033 pb.append("Ljava/lang/Object;");
2040 srp = mangleSig(pb.toString());
2042 final String rp = mangleSig(params);
2043 final String mrp = mangleMethodName(rp);
2044 sb.append(rfqn).append("$").append(rm).
2045 append('$').append(mrp).append("__Ljava_lang_Object_2");
2047 sb.append('L').append(fqnu).append("_2");
2050 return sb.toString();
2053 private static String className(ClassData jc) {
2054 //return jc.getName().getInternalName().replace('/', '_');
2055 return mangleClassName(jc.getClassName());
2058 private static String[] findAnnotation(
2059 byte[] arr, ClassData cd, final String className,
2060 final String... attrNames
2061 ) throws IOException {
2065 final String[] values = new String[attrNames.length];
2066 final boolean[] found = { false };
2067 final String jvmType = "L" + className.replace('.', '/') + ";";
2068 AnnotationParser ap = new AnnotationParser(false, true) {
2070 protected void visitAttr(String type, String attr, String at, String value) {
2071 if (type.equals(jvmType)) {
2073 for (int i = 0; i < attrNames.length; i++) {
2074 if (attrNames[i].equals(attr)) {
2083 return found[0] ? values : null;
2086 private CharSequence initField(FieldData v) {
2087 final String is = v.getInternalSig();
2088 if (is.length() == 1) {
2089 switch (is.charAt(0)) {
2095 case 'I': return " = 0;";
2097 case 'D': return " = 0.0;";
2099 throw new IllegalStateException(is);
2105 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2106 AnnotationParser ap = new AnnotationParser(true, false) {
2107 int[] cnt = new int[32];
2111 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2112 final String slashType = attrType.substring(1, attrType.length() - 1);
2113 requireReference(slashType);
2115 if (cnt[depth]++ > 0) {
2119 append('"').append(attrType).append("\" : ");
2126 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2132 protected void visitValueStart(String attrName, char type) throws IOException {
2133 if (cnt[depth]++ > 0) {
2137 if (attrName != null) {
2138 append('"').append(attrName).append("\" : ");
2146 protected void visitValueEnd(String attrName, char type) throws IOException {
2154 protected void visitAttr(String type, String attr, String attrType, String value)
2155 throws IOException {
2156 if (attr == null && value == null) {
2163 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2164 throws IOException {
2165 final String slashType = attrType.substring(1, attrType.length() - 1);
2166 requireReference(slashType);
2168 final String cn = mangleClassName(slashType);
2169 append(accessClass(cn))
2170 .append("(false)['valueOf__L").
2172 append("_2Ljava_lang_String_2']('").
2180 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2181 final String name = args[indx];
2185 if (name.contains(",")) {
2186 throw new IOException("Wrong parameter with ',': " + name);
2192 final void emitNoFlush(
2194 final String format, final CharSequence... params
2195 ) throws IOException {
2196 emitImpl(this, format, params);
2198 static final void emit(
2200 final Appendable out,
2201 final String format, final CharSequence... params
2202 ) throws IOException {
2204 emitImpl(out, format, params);
2206 static void emitImpl(final Appendable out,
2207 final String format,
2208 final CharSequence... params) throws IOException {
2209 final int length = format.length();
2212 int paramOffset = format.indexOf('@');
2213 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2214 final char paramChar = format.charAt(paramOffset + 1);
2215 if ((paramChar >= '1') && (paramChar <= '9')) {
2216 final int paramIndex = paramChar - '0' - 1;
2218 out.append(format, processed, paramOffset);
2219 out.append(params[paramIndex]);
2222 processed = paramOffset + 1;
2225 paramOffset = format.indexOf('@', paramOffset + 1);
2228 out.append(format, processed, length);
2231 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2232 append("} catch (e) {\n");
2234 for (TrapData e : traps) {
2238 if (e.catch_cpx != 0) { //not finally
2239 final String classInternalName = jc.getClassName(e.catch_cpx);
2240 addReference(classInternalName);
2241 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2242 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2243 append("var stA0 = e;");
2244 goTo(this, current, e.handler_pc, topMostLabel);
2247 finallyPC = e.handler_pc;
2250 if (finallyPC == -1) {
2253 append("var stA0 = e;");
2254 goTo(this, current, finallyPC, topMostLabel);
2259 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2262 out.append("{ gt = 0; continue X_" + to + "; }");
2264 out.append("{ gt = " + to + "; continue X_0; }");
2267 out.append("{ gt = " + to + "; break IF; }");
2271 private static void emitIf(
2273 Appendable out, String pattern,
2275 int current, int to, int canBack
2276 ) throws IOException {
2278 emitImpl(out, pattern, param);
2279 goTo(out, current, to, canBack);
2282 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2285 case 4: jvmType = "[Z"; break;
2286 case 5: jvmType = "[C"; break;
2287 case 6: jvmType = "[F"; break;
2288 case 7: jvmType = "[D"; break;
2289 case 8: jvmType = "[B"; break;
2290 case 9: jvmType = "[S"; break;
2291 case 10: jvmType = "[I"; break;
2292 case 11: jvmType = "[J"; break;
2293 default: throw new IllegalStateException("Array type: " + atype);
2296 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2297 smapper.popI(), smapper.pushA(), jvmType);
2300 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2301 String typeName = jc.getClassName(type);
2302 String ref = "null";
2303 if (typeName.startsWith("[")) {
2304 typeName = "'[" + typeName + "'";
2306 ref = "vm." + mangleClassName(typeName);
2307 typeName = "'[L" + typeName + ";'";
2310 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2311 smapper.popI(), smapper.pushA(), typeName, ref);
2314 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2315 String typeName = jc.getClassName(type);
2316 int dim = readUByte(byteCodes, ++i);
2317 StringBuilder dims = new StringBuilder();
2319 for (int d = 0; d < dim; d++) {
2321 dims.insert(1, ",");
2323 dims.insert(1, smapper.popI());
2327 if (typeName.charAt(dim) == 'L') {
2328 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2331 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2332 dims.toString(), smapper.pushA(), typeName, fn
2337 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2338 int table = i / 4 * 4 + 4;
2339 int dflt = i + readInt4(byteCodes, table);
2341 int low = readInt4(byteCodes, table);
2343 int high = readInt4(byteCodes, table);
2345 final CharSequence swVar = smapper.popValue();
2346 smapper.flush(this);
2347 append("switch (").append(swVar).append(") {\n");
2348 while (low <= high) {
2349 int offset = i + readInt4(byteCodes, table);
2351 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2354 append(" default: ");
2355 goTo(this, i, dflt, topMostLabel);
2361 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2362 int table = i / 4 * 4 + 4;
2363 int dflt = i + readInt4(byteCodes, table);
2365 int n = readInt4(byteCodes, table);
2367 final CharSequence swVar = smapper.popValue();
2368 smapper.flush(this);
2369 append("switch (").append(swVar).append(") {\n");
2371 int cnstnt = readInt4(byteCodes, table);
2373 int offset = i + readInt4(byteCodes, table);
2375 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2377 append(" default: ");
2378 goTo(this, i, dflt, topMostLabel);
2384 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2385 String type = jc.getClassName(indx);
2386 if (!type.startsWith("[")) {
2388 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2389 smapper.popA(), smapper.pushI(),
2390 type.replace('/', '_'));
2393 while (type.charAt(cnt) == '[') {
2396 if (type.charAt(cnt) == 'L') {
2397 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2399 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2400 smapper.popA(), smapper.pushI(),
2405 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2406 smapper.popA(), smapper.pushI(), type
2412 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2413 String type = jc.getClassName(indx);
2414 if (!type.startsWith("[")) {
2415 emitNoFlush(smapper,
2416 "if (@1 !== null && !@1['$instOf_@2']) vm.java_lang_Class(false).castEx();",
2417 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2420 while (type.charAt(cnt) == '[') {
2423 if (type.charAt(cnt) == 'L') {
2424 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2425 emitNoFlush(smapper,
2426 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) vm.java_lang_Class(false).castEx();",
2427 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2430 emitNoFlush(smapper,
2431 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) vm.java_lang_Class(false).castEx();",
2432 smapper.getT(0, VarType.REFERENCE, false), type
2438 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2439 for (int j = prev; j <= i; j++) {
2441 final int cc = readUByte(byteCodes, j);
2442 append(Integer.toString(cc));
2446 @JavaScriptBody(args = "msg", body = "")
2447 private static void println(String msg) {
2448 System.err.println(msg);