2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 2 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. Look for COPYING file in the top folder.
16 * If not, see http://opensource.org/licenses/GPL-2.0.
18 package org.apidesign.vm4brwsr;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import org.apidesign.bck2brwsr.core.JavaScriptBody;
23 import static org.apidesign.vm4brwsr.ByteCodeParser.*;
25 /** Translator of the code inside class files to JavaScript.
27 * @author Jaroslav Tulach <jtulach@netbeans.org>
29 abstract class ByteCodeToJavaScript implements Appendable {
31 private final Appendable out;
32 private boolean outChanged;
33 private boolean callbacks;
35 protected ByteCodeToJavaScript(Appendable out) {
40 public final Appendable append(CharSequence csq) throws IOException {
47 public final Appendable append(CharSequence csq, int start, int end) throws IOException {
48 out.append(csq, start, end);
54 public final Appendable append(char c) throws IOException {
60 /* Collects additional required resources.
62 * @param internalClassName classes that were referenced and should be loaded in order the
63 * generated JavaScript code works properly. The names are in internal
64 * JVM form so String is <code>java/lang/String</code>.
66 protected abstract boolean requireReference(String internalClassName);
69 * @param resourcePath name of resources to read
71 protected abstract void requireScript(String resourcePath) throws IOException;
73 /** Allows subclasses to redefine what field a function representing a
74 * class gets assigned. By default it returns the suggested name followed
75 * by <code>" = "</code>;
77 * @param className suggested name of the class
79 /* protected */ String assignClass(String className) {
80 return className + " = ";
82 /* protected */ String accessClass(String classOperation) {
83 return classOperation;
86 protected String accessField(String object, String mangledName,
87 String[] fieldInfoName) throws IOException {
88 return object + "." + mangledName;
91 protected String accessStaticMethod(
94 String[] fieldInfoName) throws IOException {
95 return object + "." + mangledName;
98 protected String accessVirtualMethod(
101 String[] fieldInfoName,
103 ) throws IOException {
104 return object + "." + mangledName + '(';
107 protected void declaredClass(ClassData classData, String mangledName)
111 protected void declaredField(FieldData fieldData,
113 String mangledName) throws IOException {
116 protected void declaredMethod(MethodData methodData,
118 String mangledName) throws IOException {
121 /** Prints out a debug message.
123 * @param msg the message
124 * @return true if the message has been printed
125 * @throws IOException
127 boolean debug(String msg) throws IOException {
133 * Converts a given class file to a JavaScript version.
135 * @param classFile input stream with code of the .class file
136 * @return the initialization code for this class, if any. Otherwise <code>null</code>
138 * @throws IOException if something goes wrong during read or write or translating
141 public String compile(InputStream classFile) throws IOException {
142 return compile(new ClassData(classFile));
145 protected String compile(ClassData classData) throws IOException {
147 this.callbacks = this.jc.getClassName().endsWith("/$JsCallbacks$");
148 if (jc.getMajor_version() < 50) {
149 throw new IOException("Can't compile " + jc.getClassName() + ". Class file version " + jc.getMajor_version() + "."
150 + jc.getMinor_version() + " - recompile with -target 1.6 (at least)."
153 byte[] arrData = jc.findAnnotationData(true);
155 String[] arr = findAnnotation(arrData, jc,
156 "org.apidesign.bck2brwsr.core.ExtraJavaScript",
157 "resource", "processByteCode"
160 if (!arr[0].isEmpty()) {
161 requireScript(arr[0]);
163 if ("0".equals(arr[1])) {
169 String[] arr = findAnnotation(arrData, jc,
170 "net.java.html.js.JavaScriptResource",
174 if (arr[0].startsWith("/")) {
175 requireScript(arr[0]);
177 int last = jc.getClassName().lastIndexOf('/');
179 jc.getClassName().substring(0, last + 1).replace('.', '/') + arr[0]
184 String[] proto = findAnnotation(arrData, jc,
185 "org.apidesign.bck2brwsr.core.JavaScriptPrototype",
186 "container", "prototype"
188 StringArray toInitilize = new StringArray();
189 final String className = className(jc);
190 append("\n\n").append(assignClass(className));
191 append("function ").append(className).append("() {");
192 append("\n var CLS = ").append(className).append(';');
193 append("\n if (!CLS.$class) {");
195 String sc = jc.getSuperClassName(); // with _
196 append("\n var pp = ").
197 append(accessClass(mangleClassName(sc))).append("(true);");
198 append("\n var p = CLS.prototype = pp;");
199 append("\n var c = p;");
200 append("\n var sprcls = pp.constructor.$class;");
202 append("\n var p = CLS.prototype = ").append(proto[1]).append(";");
203 if (proto[0] == null) {
206 append("\n var c = ").append(proto[0]).append(";");
207 append("\n var sprcls = null;");
209 for (FieldData v : jc.getFields()) {
211 if ((v.access & ACC_FINAL) != 0 && v.hasConstantValue()) {
212 if (v.getInternalSig().length() == 1 || v.getInternalSig().equals("Ljava/lang/String;")) {
216 append("\n CLS.fld_").append(v.getName()).append(initField(v));
217 append("\n c._").append(v.getName()).append(" = function (v) {")
218 .append(" if (arguments.length == 1) CLS.fld_").append(v.getName())
219 .append(" = v; return CLS.fld_").
220 append(v.getName()).append("; };");
222 append("\n c._").append(v.getName()).append(" = function (v) {")
223 .append(" if (arguments.length == 1) this.fld_").
224 append(className).append('_').append(v.getName())
225 .append(" = v; return this.fld_").
226 append(className).append('_').append(v.getName())
230 declaredField(v, "c", "_" + v.getName());
232 for (MethodData m : jc.getMethods()) {
233 byte[] onlyArr = m.findAnnotationData(true);
234 if (javaScriptOnly(onlyArr)) continue;
240 mn = generateStaticMethod(destObject, m, toInitilize);
242 if (m.isConstructor()) {
244 mn = generateInstanceMethod(destObject, m);
247 mn = generateInstanceMethod(destObject, m);
250 declaredMethod(m, destObject, mn);
251 byte[] runAnno = m.findAnnotationData(false);
252 if (runAnno != null) {
253 append("\n ").append(destObject).append(".").append(mn).append(".anno = {");
254 generateAnno(jc, runAnno);
257 append("\n ").append(destObject).append(".").append(mn).append(".access = " + m.getAccess()).append(";");
258 append("\n ").append(destObject).append(".").append(mn).append(".cls = CLS;");
260 append("\n c.constructor = CLS;");
261 append("\n function fillInstOf(x) {");
262 String instOfName = "$instOf_" + className;
263 append("\n Object.defineProperty(x, '").append(instOfName).append("', { value : true });");
264 for (String superInterface : jc.getSuperInterfaces()) {
265 String intrfc = superInterface.replace('/', '_');
266 append("\n vm.").append(intrfc).append("(false)['fillInstOf'](x);");
267 requireReference(superInterface);
271 append("\n Object.defineProperty(c, 'fillInstOf', { value: fillInstOf });");
272 append("\n fillInstOf(c);");
273 append("\n } catch (ignore) {");
275 // obfuscationDelegate.exportJSProperty(this, "c", instOfName);
276 append("\n CLS.$class = 'temp';");
277 append("\n CLS.$class = ");
278 append(accessClass("java_lang_Class(true);"));
279 append("\n CLS.$class.jvmName = '").append(jc.getClassName()).append("';");
280 append("\n CLS.$class.superclass = sprcls;");
281 append("\n CLS.$class.access = ").append(jc.getAccessFlags()+";");
282 append("\n CLS.$class.cnstr = CLS;");
283 byte[] classAnno = jc.findAnnotationData(false);
284 if (classAnno != null) {
285 append("\n CLS.$class.anno = {");
286 generateAnno(jc, classAnno);
289 for (String init : toInitilize.toArray()) {
290 append("\n ").append(init).append("();");
293 append("\n if (arguments.length === 0) {");
294 append("\n if (!(this instanceof CLS)) {");
295 append("\n return new CLS();");
297 for (FieldData v : jc.getFields()) {
298 byte[] onlyArr = v.findAnnotationData(true);
299 if (javaScriptOnly(onlyArr)) continue;
301 append("\n this.fld_").
302 append(className).append('_').
303 append(v.getName()).append(initField(v));
306 append("\n return this;");
308 append("\n return arguments[0] ? new CLS() : CLS.prototype;");
311 declaredClass(jc, className);
313 // StringBuilder sb = new StringBuilder();
314 // for (String init : toInitilize.toArray()) {
315 // sb.append("\n").append(init).append("();");
320 private boolean javaScriptOnly(byte[] anno) throws IOException {
321 String[] only = findAnnotation(anno, jc,
322 "org.apidesign.bck2brwsr.core.JavaScriptOnly",
326 if (only[0] != null && only[1] != null) {
327 append("\n p.").append(only[0]).append(" = ")
328 .append(only[1]).append(";");
330 if (ExportedSymbols.isMarkedAsExported(anno, jc)) {
331 append("\n p['").append(only[0]).append("'] = p.")
332 .append(only[0]).append(";");
338 private String generateStaticMethod(String destObject, MethodData m, StringArray toInitilize) throws IOException {
339 String jsb = javaScriptBody(destObject, m, true);
343 final String mn = findMethodName(m, new StringBuilder());
344 if (mn.equals("class__V")) {
345 toInitilize.add(accessClass(className(jc)) + "(false)." + mn);
347 generateMethod(destObject, mn, m);
351 private String generateInstanceMethod(String destObject, MethodData m) throws IOException {
352 String jsb = javaScriptBody(destObject, m, false);
356 final String mn = findMethodName(m, new StringBuilder());
357 generateMethod(destObject, mn, m);
361 private void generateMethod(String destObject, String name, MethodData m)
363 final StackMapIterator stackMapIterator = m.createStackMapIterator();
364 TrapDataIterator trap = m.getTrapDataIterator();
365 final LocalsMapper lmapper =
366 new LocalsMapper(stackMapIterator.getArguments());
368 boolean obj = "java/lang/Object".equals(jc.getClassName());
371 append("Object.defineProperty(").append(destObject).
372 append(", '").append(name).append("', { configurable: true, writable: true, value: function(");
374 append(destObject).append(".").append(name).append(" = function(");
376 lmapper.outputArguments(this, m.isStatic());
377 append(") {").append("\n");
379 final byte[] byteCodes = m.getCode();
380 if (byteCodes == null) {
381 append(" throw 'no code found for ")
382 .append(jc.getClassName()).append('.')
383 .append(m.getName()).append("';\n");
391 final StackMapper smapper = new StackMapper();
394 append(" var ").append(" lcA0 = this;\n");
398 TrapData[] previousTrap = null;
399 boolean wide = false;
401 if (stackMapIterator.isEmpty()) {
407 append("\n var gt = 0;\n");
411 int topMostLabel = 0;
412 for (int i = 0; i < byteCodes.length; i++) {
415 stackMapIterator.advanceTo(i);
416 boolean changeInCatch = trap.advanceTo(i);
417 if (changeInCatch || lastStackFrame != stackMapIterator.getFrameIndex()) {
418 if (previousTrap != null) {
419 generateCatch(previousTrap, i, topMostLabel);
423 if (lastStackFrame != stackMapIterator.getFrameIndex()) {
428 if (openBraces > 64) {
429 for (int c = 0; c < 64; c++) {
436 lastStackFrame = stackMapIterator.getFrameIndex();
437 lmapper.syncWithFrameLocals(stackMapIterator.getFrameLocals());
438 smapper.syncWithFrameStack(stackMapIterator.getFrameStack());
439 append(" X_" + i).append(": for (;;) { IF: if (gt <= " + i + ") {\n");
441 changeInCatch = true;
443 debug(" /* " + i + " */ ");
445 if (changeInCatch && trap.useTry()) {
447 previousTrap = trap.current();
449 final int c = readUByte(byteCodes, i);
452 smapper.assign(this, VarType.REFERENCE, lmapper.getA(0));
455 smapper.assign(this, VarType.INTEGER, lmapper.getI(0));
458 smapper.assign(this, VarType.LONG, lmapper.getL(0));
461 smapper.assign(this, VarType.FLOAT, lmapper.getF(0));
464 smapper.assign(this, VarType.DOUBLE, lmapper.getD(0));
467 smapper.assign(this, VarType.REFERENCE, lmapper.getA(1));
470 smapper.assign(this, VarType.INTEGER, lmapper.getI(1));
473 smapper.assign(this, VarType.LONG, lmapper.getL(1));
476 smapper.assign(this, VarType.FLOAT, lmapper.getF(1));
479 smapper.assign(this, VarType.DOUBLE, lmapper.getD(1));
482 smapper.assign(this, VarType.REFERENCE, lmapper.getA(2));
485 smapper.assign(this, VarType.INTEGER, lmapper.getI(2));
488 smapper.assign(this, VarType.LONG, lmapper.getL(2));
491 smapper.assign(this, VarType.FLOAT, lmapper.getF(2));
494 smapper.assign(this, VarType.DOUBLE, lmapper.getD(2));
497 smapper.assign(this, VarType.REFERENCE, lmapper.getA(3));
500 smapper.assign(this, VarType.INTEGER, lmapper.getI(3));
503 smapper.assign(this, VarType.LONG, lmapper.getL(3));
506 smapper.assign(this, VarType.FLOAT, lmapper.getF(3));
509 smapper.assign(this, VarType.DOUBLE, lmapper.getD(3));
513 final int indx = wide ? readUShort(byteCodes, i++)
514 : readUByte(byteCodes, i);
516 smapper.assign(this, VarType.INTEGER, lmapper.getI(indx));
521 final int indx = wide ? readUShort(byteCodes, i++)
522 : readUByte(byteCodes, i);
524 smapper.assign(this, VarType.LONG, lmapper.getL(indx));
529 final int indx = wide ? readUShort(byteCodes, i++)
530 : readUByte(byteCodes, i);
532 smapper.assign(this, VarType.FLOAT, lmapper.getF(indx));
537 final int indx = wide ? readUShort(byteCodes, i++)
538 : readUByte(byteCodes, i);
540 smapper.assign(this, VarType.DOUBLE, lmapper.getD(indx));
545 final int indx = wide ? readUShort(byteCodes, i++)
546 : readUByte(byteCodes, i);
548 smapper.assign(this, VarType.REFERENCE, lmapper.getA(indx));
553 final int indx = wide ? readUShort(byteCodes, i++)
554 : readUByte(byteCodes, i);
556 emit(smapper, this, "var @1 = @2;",
557 lmapper.setI(indx), smapper.popI());
562 final int indx = wide ? readUShort(byteCodes, i++)
563 : readUByte(byteCodes, i);
565 emit(smapper, this, "var @1 = @2;",
566 lmapper.setL(indx), smapper.popL());
571 final int indx = wide ? readUShort(byteCodes, i++)
572 : readUByte(byteCodes, i);
574 emit(smapper, this, "var @1 = @2;",
575 lmapper.setF(indx), smapper.popF());
580 final int indx = wide ? readUShort(byteCodes, i++)
581 : readUByte(byteCodes, i);
583 emit(smapper, this, "var @1 = @2;",
584 lmapper.setD(indx), smapper.popD());
589 final int indx = wide ? readUShort(byteCodes, i++)
590 : readUByte(byteCodes, i);
592 emit(smapper, this, "var @1 = @2;",
593 lmapper.setA(indx), smapper.popA());
597 emit(smapper, this, "var @1 = @2;", lmapper.setA(0), smapper.popA());
600 emit(smapper, this, "var @1 = @2;", lmapper.setI(0), smapper.popI());
603 emit(smapper, this, "var @1 = @2;", lmapper.setL(0), smapper.popL());
606 emit(smapper, this, "var @1 = @2;", lmapper.setF(0), smapper.popF());
609 emit(smapper, this, "var @1 = @2;", lmapper.setD(0), smapper.popD());
612 emit(smapper, this, "var @1 = @2;", lmapper.setA(1), smapper.popA());
615 emit(smapper, this, "var @1 = @2;", lmapper.setI(1), smapper.popI());
618 emit(smapper, this, "var @1 = @2;", lmapper.setL(1), smapper.popL());
621 emit(smapper, this, "var @1 = @2;", lmapper.setF(1), smapper.popF());
624 emit(smapper, this, "var @1 = @2;", lmapper.setD(1), smapper.popD());
627 emit(smapper, this, "var @1 = @2;", lmapper.setA(2), smapper.popA());
630 emit(smapper, this, "var @1 = @2;", lmapper.setI(2), smapper.popI());
633 emit(smapper, this, "var @1 = @2;", lmapper.setL(2), smapper.popL());
636 emit(smapper, this, "var @1 = @2;", lmapper.setF(2), smapper.popF());
639 emit(smapper, this, "var @1 = @2;", lmapper.setD(2), smapper.popD());
642 emit(smapper, this, "var @1 = @2;", lmapper.setA(3), smapper.popA());
645 emit(smapper, this, "var @1 = @2;", lmapper.setI(3), smapper.popI());
648 emit(smapper, this, "var @1 = @2;", lmapper.setL(3), smapper.popL());
651 emit(smapper, this, "var @1 = @2;", lmapper.setF(3), smapper.popF());
654 emit(smapper, this, "var @1 = @2;", lmapper.setD(3), smapper.popD());
657 smapper.replace(this, VarType.INTEGER, "(@1).add32(@2)", smapper.getI(1), smapper.popI());
660 smapper.replace(this, VarType.LONG, "(@1).add64(@2)", smapper.getL(1), smapper.popL());
663 smapper.replace(this, VarType.FLOAT, "(@1 + @2)", smapper.getF(1), smapper.popF());
666 smapper.replace(this, VarType.DOUBLE, "(@1 + @2)", smapper.getD(1), smapper.popD());
669 smapper.replace(this, VarType.INTEGER, "(@1).sub32(@2)", smapper.getI(1), smapper.popI());
672 smapper.replace(this, VarType.LONG, "(@1).sub64(@2)", smapper.getL(1), smapper.popL());
675 smapper.replace(this, VarType.FLOAT, "(@1 - @2)", smapper.getF(1), smapper.popF());
678 smapper.replace(this, VarType.DOUBLE, "(@1 - @2)", smapper.getD(1), smapper.popD());
681 smapper.replace(this, VarType.INTEGER, "(@1).mul32(@2)", smapper.getI(1), smapper.popI());
684 smapper.replace(this, VarType.LONG, "(@1).mul64(@2)", smapper.getL(1), smapper.popL());
687 smapper.replace(this, VarType.FLOAT, "(@1 * @2)", smapper.getF(1), smapper.popF());
690 smapper.replace(this, VarType.DOUBLE, "(@1 * @2)", smapper.getD(1), smapper.popD());
693 smapper.replace(this, VarType.INTEGER, "(@1).div32(@2)",
694 smapper.getI(1), smapper.popI());
697 smapper.replace(this, VarType.LONG, "(@1).div64(@2)",
698 smapper.getL(1), smapper.popL());
701 smapper.replace(this, VarType.FLOAT, "(@1 / @2)", smapper.getF(1), smapper.popF());
704 smapper.replace(this, VarType.DOUBLE, "(@1 / @2)", smapper.getD(1), smapper.popD());
707 smapper.replace(this, VarType.INTEGER, "(@1).mod32(@2)",
708 smapper.getI(1), smapper.popI());
711 smapper.replace(this, VarType.LONG, "(@1).mod64(@2)",
712 smapper.getL(1), smapper.popL());
715 smapper.replace(this, VarType.FLOAT, "(@1 % @2)", smapper.getF(1), smapper.popF());
718 smapper.replace(this, VarType.DOUBLE, "(@1 % @2)", smapper.getD(1), smapper.popD());
721 smapper.replace(this, VarType.INTEGER, "(@1 & @2)", smapper.getI(1), smapper.popI());
724 smapper.replace(this, VarType.LONG, "(@1).and64(@2)", smapper.getL(1), smapper.popL());
727 smapper.replace(this, VarType.INTEGER, "(@1 | @2)", smapper.getI(1), smapper.popI());
730 smapper.replace(this, VarType.LONG, "(@1).or64(@2)", smapper.getL(1), smapper.popL());
733 smapper.replace(this, VarType.INTEGER, "(@1 ^ @2)", smapper.getI(1), smapper.popI());
736 smapper.replace(this, VarType.LONG, "(@1).xor64(@2)", smapper.getL(1), smapper.popL());
739 smapper.replace(this, VarType.INTEGER, "(@1).neg32()", smapper.getI(0));
742 smapper.replace(this, VarType.LONG, "(@1).neg64()", smapper.getL(0));
745 smapper.replace(this, VarType.FLOAT, "(-@1)", smapper.getF(0));
748 smapper.replace(this, VarType.DOUBLE, "(-@1)", smapper.getD(0));
751 smapper.replace(this, VarType.INTEGER, "(@1 << @2)", smapper.getI(1), smapper.popI());
754 smapper.replace(this, VarType.LONG, "(@1).shl64(@2)", smapper.getL(1), smapper.popI());
757 smapper.replace(this, VarType.INTEGER, "(@1 >> @2)", smapper.getI(1), smapper.popI());
760 smapper.replace(this, VarType.LONG, "(@1).shr64(@2)", smapper.getL(1), smapper.popI());
763 smapper.replace(this, VarType.INTEGER, "(@1 >>> @2)", smapper.getI(1), smapper.popI());
766 smapper.replace(this, VarType.LONG, "(@1).ushr64(@2)", smapper.getL(1), smapper.popI());
770 final int varIndx = wide ? readUShort(byteCodes, i++)
771 : readUByte(byteCodes, i);
773 final int incrBy = wide ? readShort(byteCodes, i++)
777 emit(smapper, this, "@1++;", lmapper.getI(varIndx));
779 emit(smapper, this, "@1 += @2;",
780 lmapper.getI(varIndx),
781 Integer.toString(incrBy));
786 emit(smapper, this, "return;");
789 emit(smapper, this, "return @1;", smapper.popI());
792 emit(smapper, this, "return @1;", smapper.popL());
795 emit(smapper, this, "return @1;", smapper.popF());
798 emit(smapper, this, "return @1;", smapper.popD());
801 emit(smapper, this, "return @1;", smapper.popA());
804 smapper.replace(this, VarType.LONG, "@1", smapper.getI(0));
807 smapper.replace(this, VarType.FLOAT, "@1", smapper.getI(0));
810 smapper.replace(this, VarType.DOUBLE, "@1", smapper.getI(0));
813 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()", smapper.getL(0));
817 smapper.replace(this, VarType.FLOAT, "(@1).toFP()", smapper.getL(0));
820 smapper.replace(this, VarType.DOUBLE, "(@1).toFP()", smapper.getL(0));
823 smapper.replace(this, VarType.DOUBLE, "@1",
827 smapper.replace(this, VarType.FLOAT, "@1",
831 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
835 smapper.replace(this, VarType.LONG, "(@1).toLong()",
839 smapper.replace(this, VarType.INTEGER, "(@1).toInt32()",
843 smapper.replace(this, VarType.LONG, "(@1).toLong()", smapper.getD(0));
846 smapper.replace(this, VarType.INTEGER, "(@1).toInt8()", smapper.getI(0));
850 smapper.replace(this, VarType.INTEGER, "(@1).toInt16()", smapper.getI(0));
852 case opc_aconst_null:
853 smapper.assign(this, VarType.REFERENCE, "null");
856 smapper.assign(this, VarType.INTEGER, "-1");
859 smapper.assign(this, VarType.INTEGER, "0");
862 smapper.assign(this, VarType.DOUBLE, "0");
865 smapper.assign(this, VarType.LONG, "0");
868 smapper.assign(this, VarType.FLOAT, "0");
871 smapper.assign(this, VarType.INTEGER, "1");
874 smapper.assign(this, VarType.LONG, "1");
877 smapper.assign(this, VarType.FLOAT, "1");
880 smapper.assign(this, VarType.DOUBLE, "1");
883 smapper.assign(this, VarType.INTEGER, "2");
886 smapper.assign(this, VarType.FLOAT, "2");
889 smapper.assign(this, VarType.INTEGER, "3");
892 smapper.assign(this, VarType.INTEGER, "4");
895 smapper.assign(this, VarType.INTEGER, "5");
898 int indx = readUByte(byteCodes, ++i);
899 String v = encodeConstant(indx);
900 int type = VarType.fromConstantType(jc.getTag(indx));
901 smapper.assign(this, type, v);
906 int indx = readUShortArg(byteCodes, i);
908 String v = encodeConstant(indx);
909 int type = VarType.fromConstantType(jc.getTag(indx));
910 if (type == VarType.LONG) {
911 final Long lv = new Long(v);
912 final int low = (int)(lv.longValue() & 0xFFFFFFFF);
913 final int hi = (int)(lv.longValue() >> 32);
915 smapper.assign(this, VarType.LONG, "0x" + Integer.toHexString(low));
917 smapper.assign(this, VarType.LONG,
918 "0x" + Integer.toHexString(hi) + ".next32(0x" +
919 Integer.toHexString(low) + ")"
923 smapper.assign(this, type, v);
928 smapper.replace(this, VarType.INTEGER, "(@2).compare64(@1)", smapper.popL(), smapper.getL(0));
932 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popF(), smapper.getF(0));
936 smapper.replace(this, VarType.INTEGER, "(@2).compare(@1)", smapper.popD(), smapper.getD(0));
939 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
940 "===", topMostLabel);
943 i = generateIf(smapper, byteCodes, i, smapper.popA(), smapper.popA(),
944 "!==", topMostLabel);
947 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
951 int indx = i + readShortArg(byteCodes, i);
952 emitIf(smapper, this, "if ((@1) == 0) ",
953 smapper.popI(), i, indx, topMostLabel);
958 int indx = i + readShortArg(byteCodes, i);
959 emitIf(smapper, this, "if ((@1) != 0) ",
960 smapper.popI(), i, indx, topMostLabel);
965 int indx = i + readShortArg(byteCodes, i);
966 emitIf(smapper, this, "if ((@1) < 0) ",
967 smapper.popI(), i, indx, topMostLabel);
972 int indx = i + readShortArg(byteCodes, i);
973 emitIf(smapper, this, "if ((@1) <= 0) ",
974 smapper.popI(), i, indx, topMostLabel);
979 int indx = i + readShortArg(byteCodes, i);
980 emitIf(smapper, this, "if ((@1) > 0) ",
981 smapper.popI(), i, indx, topMostLabel);
986 int indx = i + readShortArg(byteCodes, i);
987 emitIf(smapper, this, "if ((@1) >= 0) ",
988 smapper.popI(), i, indx, topMostLabel);
992 case opc_ifnonnull: {
993 int indx = i + readShortArg(byteCodes, i);
994 emitIf(smapper, this, "if ((@1) !== null) ",
995 smapper.popA(), i, indx, topMostLabel);
1000 int indx = i + readShortArg(byteCodes, i);
1001 emitIf(smapper, this, "if ((@1) === null) ",
1002 smapper.popA(), i, indx, topMostLabel);
1007 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1008 "!=", topMostLabel);
1011 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1015 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1016 "<=", topMostLabel);
1019 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1023 i = generateIf(smapper, byteCodes, i, smapper.popI(), smapper.popI(),
1024 ">=", topMostLabel);
1027 smapper.flush(this);
1028 int indx = i + readShortArg(byteCodes, i);
1029 goTo(this, i, indx, topMostLabel);
1033 case opc_lookupswitch: {
1034 i = generateLookupSwitch(i, byteCodes, smapper, topMostLabel);
1037 case opc_tableswitch: {
1038 i = generateTableSwitch(i, byteCodes, smapper, topMostLabel);
1041 case opc_invokeinterface: {
1042 i = invokeVirtualMethod(byteCodes, i, smapper) + 2;
1045 case opc_invokevirtual:
1046 i = invokeVirtualMethod(byteCodes, i, smapper);
1048 case opc_invokespecial:
1049 i = invokeStaticMethod(byteCodes, i, smapper, false);
1051 case opc_invokestatic:
1052 i = invokeStaticMethod(byteCodes, i, smapper, true);
1054 case opc_invokedynamic: {
1055 int indx = readUShortArg(byteCodes, i);
1056 println("invoke dynamic: " + indx);
1057 ByteCodeParser.CPX2 c2 = jc.getCpoolEntry(indx);
1058 BootMethodData bm = jc.getBootMethod(c2.cpx1);
1059 CPX2 methodHandle = jc.getCpoolEntry(bm.method);
1060 println(" type: " + methodHandle.cpx1);
1061 String[] mi = jc.getFieldInfoName(methodHandle.cpx2);
1062 String mcn = mangleClassName(mi[0]);
1063 char[] returnType = {'V'};
1064 StringBuilder cnt = new StringBuilder();
1065 String mn = findMethodName(mi, cnt, returnType);
1066 println(" mi[0]: " + mi[0]);
1067 println(" mi[1]: " + mi[1]);
1068 println(" mi[2]: " + mi[2]);
1069 println(" mn : " + mn);
1070 println(" name and type: " + jc.stringValue(c2.cpx2, true));
1071 CPX2 nameAndType = jc.getCpoolEntry(c2.cpx2);
1072 String type = jc.StringValue(nameAndType.cpx2);
1073 String object = accessClass(mcn) + "(false)";
1074 if (mn.startsWith("cons_")) {
1075 object += ".constructor";
1077 append("var metHan = ");
1078 append(accessStaticMethod(object, mn, mi));
1080 String lookup = accessClass("java_lang_invoke_MethodHandles") + "(false).findFor__Ljava_lang_invoke_MethodHandles$Lookup_2Ljava_lang_Class_2(CLS.$class)";
1082 append(", '").append(mi[1]).append("', ");
1083 String methodType = accessClass("java_lang_invoke_MethodType") + "(false).fromMethodDescriptorString__Ljava_lang_invoke_MethodType_2Ljava_lang_String_2Ljava_lang_ClassLoader_2(";
1084 append(methodType).append("'").append(type).append("', null)");
1085 // if (numArguments > 0) {
1087 // for (int j = 1; j < numArguments; ++j) {
1093 emit(smapper, this, "throw 'Invoke dynamic: ' + @1 + ': ' + metHan;", "" + indx);
1098 int indx = readUShortArg(byteCodes, i);
1099 String ci = jc.getClassName(indx);
1100 emit(smapper, this, "var @1 = new @2;",
1101 smapper.pushA(), accessClass(mangleClassName(ci)));
1107 int atype = readUByte(byteCodes, ++i);
1108 generateNewArray(atype, smapper);
1110 case opc_anewarray: {
1111 int type = readUShortArg(byteCodes, i);
1113 generateANewArray(type, smapper);
1116 case opc_multianewarray: {
1117 int type = readUShortArg(byteCodes, i);
1119 i = generateMultiANewArray(type, byteCodes, i, smapper);
1122 case opc_arraylength:
1123 smapper.replace(this, VarType.INTEGER, "(@1).length", smapper.getA(0));
1126 emit(smapper, this, "Array.at(@3, @2, @1);",
1127 smapper.popL(), smapper.popI(), smapper.popA());
1130 emit(smapper, this, "Array.at(@3, @2, @1);",
1131 smapper.popF(), smapper.popI(), smapper.popA());
1134 emit(smapper, this, "Array.at(@3, @2, @1);",
1135 smapper.popD(), smapper.popI(), smapper.popA());
1138 emit(smapper, this, "Array.at(@3, @2, @1);",
1139 smapper.popA(), smapper.popI(), smapper.popA());
1145 emit(smapper, this, "Array.at(@3, @2, @1);",
1146 smapper.popI(), smapper.popI(), smapper.popA());
1149 smapper.replace(this, VarType.LONG, "Array.at(@2, @1)",
1150 smapper.popI(), smapper.getA(0));
1153 smapper.replace(this, VarType.FLOAT, "Array.at(@2, @1)",
1154 smapper.popI(), smapper.getA(0));
1157 smapper.replace(this, VarType.DOUBLE, "Array.at(@2, @1)",
1158 smapper.popI(), smapper.getA(0));
1161 smapper.replace(this, VarType.REFERENCE, "Array.at(@2, @1)",
1162 smapper.popI(), smapper.getA(0));
1168 smapper.replace(this, VarType.INTEGER, "Array.at(@2, @1)",
1169 smapper.popI(), smapper.getA(0));
1177 final Variable v = smapper.get(0);
1178 if (smapper.isDirty()) {
1179 emit(smapper, this, "var @1 = @2;", smapper.pushT(v.getType()), v);
1181 smapper.assign(this, v.getType(), v);
1186 final Variable vi1 = smapper.get(0);
1188 if (vi1.isCategory2()) {
1189 emit(smapper, this, "var @1 = @2;",
1190 smapper.pushT(vi1.getType()), vi1);
1192 final Variable vi2 = smapper.get(1);
1193 emit(smapper, this, "var @1 = @2, @3 = @4;",
1194 smapper.pushT(vi2.getType()), vi2,
1195 smapper.pushT(vi1.getType()), vi1);
1200 final Variable vi1 = smapper.pop(this);
1201 final Variable vi2 = smapper.pop(this);
1202 final Variable vo3 = smapper.pushT(vi1.getType());
1203 final Variable vo2 = smapper.pushT(vi2.getType());
1204 final Variable vo1 = smapper.pushT(vi1.getType());
1206 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1207 vo1, vi1, vo2, vi2, vo3, vo1);
1211 final Variable vi1 = smapper.pop(this);
1212 final Variable vi2 = smapper.pop(this);
1214 if (vi1.isCategory2()) {
1215 final Variable vo3 = smapper.pushT(vi1.getType());
1216 final Variable vo2 = smapper.pushT(vi2.getType());
1217 final Variable vo1 = smapper.pushT(vi1.getType());
1219 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1220 vo1, vi1, vo2, vi2, vo3, vo1);
1222 final Variable vi3 = smapper.pop(this);
1223 final Variable vo5 = smapper.pushT(vi2.getType());
1224 final Variable vo4 = smapper.pushT(vi1.getType());
1225 final Variable vo3 = smapper.pushT(vi3.getType());
1226 final Variable vo2 = smapper.pushT(vi2.getType());
1227 final Variable vo1 = smapper.pushT(vi1.getType());
1229 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1230 vo1, vi1, vo2, vi2, vo3, vi3);
1231 emit(smapper, this, " @1 = @2, @3 = @4;",
1232 vo4, vo1, vo5, vo2);
1237 final Variable vi1 = smapper.pop(this);
1238 final Variable vi2 = smapper.pop(this);
1240 if (vi2.isCategory2()) {
1241 final Variable vo3 = smapper.pushT(vi1.getType());
1242 final Variable vo2 = smapper.pushT(vi2.getType());
1243 final Variable vo1 = smapper.pushT(vi1.getType());
1245 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1246 vo1, vi1, vo2, vi2, vo3, vo1);
1248 final Variable vi3 = smapper.pop(this);
1249 final Variable vo4 = smapper.pushT(vi1.getType());
1250 final Variable vo3 = smapper.pushT(vi3.getType());
1251 final Variable vo2 = smapper.pushT(vi2.getType());
1252 final Variable vo1 = smapper.pushT(vi1.getType());
1254 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1255 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1260 final Variable vi1 = smapper.pop(this);
1261 final Variable vi2 = smapper.pop(this);
1263 if (vi1.isCategory2()) {
1264 if (vi2.isCategory2()) {
1265 final Variable vo3 = smapper.pushT(vi1.getType());
1266 final Variable vo2 = smapper.pushT(vi2.getType());
1267 final Variable vo1 = smapper.pushT(vi1.getType());
1269 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6;",
1270 vo1, vi1, vo2, vi2, vo3, vo1);
1272 final Variable vi3 = smapper.pop(this);
1273 final Variable vo4 = smapper.pushT(vi1.getType());
1274 final Variable vo3 = smapper.pushT(vi3.getType());
1275 final Variable vo2 = smapper.pushT(vi2.getType());
1276 final Variable vo1 = smapper.pushT(vi1.getType());
1278 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8;",
1279 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vo1);
1282 final Variable vi3 = smapper.pop(this);
1284 if (vi3.isCategory2()) {
1285 final Variable vo5 = smapper.pushT(vi2.getType());
1286 final Variable vo4 = smapper.pushT(vi1.getType());
1287 final Variable vo3 = smapper.pushT(vi3.getType());
1288 final Variable vo2 = smapper.pushT(vi2.getType());
1289 final Variable vo1 = smapper.pushT(vi1.getType());
1291 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6,",
1292 vo1, vi1, vo2, vi2, vo3, vi3);
1293 emit(smapper, this, " @1 = @2, @3 = @4;",
1294 vo4, vo1, vo5, vo2);
1296 final Variable vi4 = smapper.pop(this);
1297 final Variable vo6 = smapper.pushT(vi2.getType());
1298 final Variable vo5 = smapper.pushT(vi1.getType());
1299 final Variable vo4 = smapper.pushT(vi4.getType());
1300 final Variable vo3 = smapper.pushT(vi3.getType());
1301 final Variable vo2 = smapper.pushT(vi2.getType());
1302 final Variable vo1 = smapper.pushT(vi1.getType());
1304 emit(smapper, this, "var @1 = @2, @3 = @4, @5 = @6, @7 = @8,",
1305 vo1, vi1, vo2, vi2, vo3, vi3, vo4, vi4);
1306 emit(smapper, this, " @1 = @2, @3 = @4;",
1307 vo5, vo1, vo6, vo2);
1313 final Variable vi1 = smapper.get(0);
1314 final Variable vi2 = smapper.get(1);
1316 if (vi1.getType() == vi2.getType()) {
1317 final Variable tmp = smapper.pushT(vi1.getType());
1319 emit(smapper, this, "var @1 = @2, @2 = @3, @3 = @1;",
1324 smapper.pushT(vi1.getType());
1325 smapper.pushT(vi2.getType());
1330 smapper.assign(this, VarType.INTEGER,
1331 "(" + Integer.toString(byteCodes[++i]) + ")");
1334 smapper.assign(this, VarType.INTEGER,
1335 "(" + Integer.toString(readShortArg(byteCodes, i)) + ")"
1339 case opc_getfield: {
1340 int indx = readUShortArg(byteCodes, i);
1341 String[] fi = jc.getFieldInfoName(indx);
1342 final int type = VarType.fromFieldType(fi[2].charAt(0));
1343 final String mangleClass = mangleClassName(fi[0]);
1344 final String mangleClassAccess = accessClass(mangleClass);
1345 smapper.replace(this, type, "@2.call(@1)",
1347 accessField(mangleClassAccess + "(false)",
1353 case opc_putfield: {
1354 int indx = readUShortArg(byteCodes, i);
1355 String[] fi = jc.getFieldInfoName(indx);
1356 final int type = VarType.fromFieldType(fi[2].charAt(0));
1357 final String mangleClass = mangleClassName(fi[0]);
1358 final String mangleClassAccess = accessClass(mangleClass);
1359 emit(smapper, this, "@3.call(@2, @1);",
1362 accessField(mangleClassAccess + "(false)",
1367 case opc_getstatic: {
1368 int indx = readUShortArg(byteCodes, i);
1369 String[] fi = jc.getFieldInfoName(indx);
1370 final int type = VarType.fromFieldType(fi[2].charAt(0));
1371 String ac = accessClass(mangleClassName(fi[0]));
1372 String af = accessField(ac + "(false)", "_" + fi[1], fi);
1373 smapper.assign(this, type, af + "()");
1375 addReference(fi[0]);
1378 case opc_putstatic: {
1379 int indx = readUShortArg(byteCodes, i);
1380 String[] fi = jc.getFieldInfoName(indx);
1381 final int type = VarType.fromFieldType(fi[2].charAt(0));
1382 emit(smapper, this, "@1(false)._@2(@3);",
1383 accessClass(mangleClassName(fi[0])), fi[1],
1384 smapper.popT(type));
1386 addReference(fi[0]);
1389 case opc_checkcast: {
1390 int indx = readUShortArg(byteCodes, i);
1391 generateCheckcast(indx, smapper);
1395 case opc_instanceof: {
1396 int indx = readUShortArg(byteCodes, i);
1397 generateInstanceOf(indx, smapper);
1402 final CharSequence v = smapper.popA();
1405 emit(smapper, this, "{ var @1 = @2; throw @2; }",
1406 smapper.pushA(), v);
1410 case opc_monitorenter: {
1411 debug("/* monitor enter */");
1416 case opc_monitorexit: {
1417 debug("/* monitor exit */");
1428 emit(smapper, this, "throw 'unknown bytecode @1';",
1429 Integer.toString(c));
1433 generateByteCodeComment(prev, i, byteCodes);
1439 if (previousTrap != null) {
1440 generateCatch(previousTrap, byteCodes.length, topMostLabel);
1445 while (openBraces-- > 0) {
1455 private int generateIf(StackMapper mapper, byte[] byteCodes,
1456 int i, final CharSequence v2, final CharSequence v1,
1457 final String test, int topMostLabel
1458 ) throws IOException {
1460 int indx = i + readShortArg(byteCodes, i);
1461 append("if ((").append(v1)
1462 .append(") ").append(test).append(" (")
1463 .append(v2).append(")) ");
1464 goTo(this, i, indx, topMostLabel);
1468 private int readInt4(byte[] byteCodes, int offset) {
1469 final int d = byteCodes[offset + 0] << 24;
1470 final int c = byteCodes[offset + 1] << 16;
1471 final int b = byteCodes[offset + 2] << 8;
1472 final int a = byteCodes[offset + 3];
1473 return (d & 0xff000000) | (c & 0xff0000) | (b & 0xff00) | (a & 0xff);
1475 private static int readUByte(byte[] byteCodes, int offset) {
1476 return byteCodes[offset] & 0xff;
1479 private static int readUShort(byte[] byteCodes, int offset) {
1480 return ((byteCodes[offset] & 0xff) << 8)
1481 | (byteCodes[offset + 1] & 0xff);
1483 private static int readUShortArg(byte[] byteCodes, int offsetInstruction) {
1484 return readUShort(byteCodes, offsetInstruction + 1);
1487 private static int readShort(byte[] byteCodes, int offset) {
1488 int signed = byteCodes[offset];
1489 byte b0 = (byte)signed;
1490 return (b0 << 8) | (byteCodes[offset + 1] & 0xff);
1492 private static int readShortArg(byte[] byteCodes, int offsetInstruction) {
1493 return readShort(byteCodes, offsetInstruction + 1);
1496 private static void countArgs(String descriptor, char[] returnType, StringBuilder sig, StringBuilder cnt) {
1498 Boolean count = null;
1499 boolean array = false;
1501 int firstPos = sig.length();
1502 while (i < descriptor.length()) {
1503 char ch = descriptor.charAt(i++);
1524 if (ch == 'J' || ch == 'D') {
1530 sig.insert(firstPos, ch);
1532 returnType[0] = '[';
1533 sig.insert(firstPos, "_3");
1542 returnType[0] = 'V';
1543 sig.insert(firstPos, 'V');
1546 int next = descriptor.indexOf(';', i);
1547 String realSig = mangleSig(descriptor, i - 1, next + 1);
1552 sig.append(realSig);
1555 sig.insert(firstPos, realSig);
1557 sig.insert(firstPos, "_3");
1559 returnType[0] = 'L';
1568 throw new IllegalStateException("Invalid char: " + ch);
1573 static String mangleSig(String sig) {
1574 return mangleSig(sig, 0, sig.length());
1577 private static String mangleMethodName(String name) {
1578 StringBuilder sb = new StringBuilder(name.length() * 2);
1579 int last = name.length();
1580 for (int i = 0; i < last; i++) {
1581 final char ch = name.charAt(i);
1583 case '_': sb.append("_1"); break;
1584 default: sb.append(ch); break;
1587 return sb.toString();
1589 private static String mangleSig(String txt, int first, int last) {
1590 StringBuilder sb = new StringBuilder((last - first) * 2);
1591 for (int i = first; i < last; i++) {
1592 final char ch = txt.charAt(i);
1594 case '/': sb.append('_'); break;
1595 case '_': sb.append("_1"); break;
1596 case ';': sb.append("_2"); break;
1597 case '[': sb.append("_3"); break;
1599 if (Character.isJavaIdentifierPart(ch)) {
1603 String hex = Integer.toHexString(ch).toLowerCase();
1604 for (int m = hex.length(); m < 4; m++) {
1612 return sb.toString();
1615 private static String mangleClassName(String name) {
1616 return mangleSig(name);
1619 private static String findMethodName(MethodData m, StringBuilder cnt) {
1620 StringBuilder name = new StringBuilder();
1621 if ("<init>".equals(m.getName())) { // NOI18N
1622 name.append("cons"); // NOI18N
1623 } else if ("<clinit>".equals(m.getName())) { // NOI18N
1624 name.append("class"); // NOI18N
1626 name.append(mangleMethodName(m.getName()));
1629 countArgs(m.getInternalSig(), new char[1], name, cnt);
1630 return name.toString();
1633 static String findMethodName(String[] mi, StringBuilder cnt, char[] returnType) {
1634 StringBuilder name = new StringBuilder();
1635 String descr = mi[2];//mi.getDescriptor();
1637 if ("<init>".equals(nm)) { // NOI18N
1638 name.append("cons"); // NOI18N
1640 name.append(mangleMethodName(nm));
1642 countArgs(descr, returnType, name, cnt);
1643 return name.toString();
1646 private int invokeStaticMethod(byte[] byteCodes, int i, final StackMapper mapper, boolean isStatic)
1647 throws IOException {
1648 int methodIndex = readUShortArg(byteCodes, i);
1649 String[] mi = jc.getFieldInfoName(methodIndex);
1650 char[] returnType = { 'V' };
1651 StringBuilder cnt = new StringBuilder();
1652 String mn = findMethodName(mi, cnt, returnType);
1654 final int numArguments = isStatic ? cnt.length() : cnt.length() + 1;
1655 final CharSequence[] vars = new CharSequence[numArguments];
1657 for (int j = numArguments - 1; j >= 0; --j) {
1658 vars[j] = mapper.popValue();
1661 if (returnType[0] != 'V') {
1664 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1668 final String in = mi[0];
1670 if (callbacks && in.equals("org/apidesign/html/boot/spi/Fn")) {
1671 mcn = "java_lang_Class";
1673 mcn = mangleClassName(in);
1675 String object = accessClass(mcn) + "(false)";
1676 if (mn.startsWith("cons_")) {
1677 object += ".constructor";
1679 append(accessStaticMethod(object, mn, mi));
1685 if (numArguments > 0) {
1687 for (int j = 1; j < numArguments; ++j) {
1697 private int invokeVirtualMethod(byte[] byteCodes, int i, final StackMapper mapper)
1698 throws IOException {
1699 int methodIndex = readUShortArg(byteCodes, i);
1700 String[] mi = jc.getFieldInfoName(methodIndex);
1701 char[] returnType = { 'V' };
1702 StringBuilder cnt = new StringBuilder();
1703 String mn = findMethodName(mi, cnt, returnType);
1705 final int numArguments = cnt.length() + 1;
1706 final CharSequence[] vars = new CharSequence[numArguments];
1708 for (int j = numArguments - 1; j >= 0; --j) {
1709 vars[j] = mapper.popValue();
1712 if (returnType[0] != 'V') {
1714 .append(mapper.pushT(VarType.fromFieldType(returnType[0])))
1718 append(accessVirtualMethod(vars[0].toString(), mn, mi, numArguments));
1720 for (int j = 1; j < numArguments; ++j) {
1730 private void addReference(String cn) throws IOException {
1731 if (requireReference(cn)) {
1732 debug(" /* needs " + cn + " */");
1736 private void outType(String d, StringBuilder out) {
1738 while (d.charAt(0) == '[') {
1742 if (d.charAt(0) == 'L') {
1743 assert d.charAt(d.length() - 1) == ';';
1744 out.append(d.replace('/', '_').substring(0, d.length() - 1));
1750 private String encodeConstant(int entryIndex) throws IOException {
1751 String[] classRef = { null };
1752 String s = jc.stringValue(entryIndex, classRef);
1753 if (classRef[0] != null) {
1754 if (classRef[0].startsWith("[")) {
1755 s = accessClass("java_lang_Class") + "(false)['forName__Ljava_lang_Class_2Ljava_lang_String_2']('" + classRef[0] + "')";
1757 addReference(classRef[0]);
1758 s = accessClass(mangleClassName(s)) + "(false).constructor.$class";
1764 private String javaScriptBody(String destObject, MethodData m, boolean isStatic) throws IOException {
1765 byte[] arr = m.findAnnotationData(true);
1769 final String jvmType = "Lorg/apidesign/bck2brwsr/core/JavaScriptBody;";
1770 final String htmlType = "Lnet/java/html/js/JavaScriptBody;";
1771 class P extends AnnotationParser {
1777 String[] args = new String[30];
1783 protected void visitAttr(String type, String attr, String at, String value) {
1784 if (type.equals(jvmType)) {
1785 if ("body".equals(attr)) {
1787 } else if ("args".equals(attr)) {
1788 args[cnt++] = value;
1790 throw new IllegalArgumentException(attr);
1793 if (type.equals(htmlType)) {
1795 if ("body".equals(attr)) {
1797 } else if ("args".equals(attr)) {
1798 args[cnt++] = value;
1799 } else if ("javacall".equals(attr)) {
1800 javacall = "1".equals(value);
1801 } else if ("wait4js".equals(attr)) {
1802 // ignore, we always invoke synchronously
1804 throw new IllegalArgumentException(attr);
1811 if (p.body == null) {
1814 StringBuilder cnt = new StringBuilder();
1815 final String mn = findMethodName(m, cnt);
1816 append(destObject).append(".").append(mn);
1817 append(" = function(");
1820 StringBuilder toValue = new StringBuilder();
1821 for (int i = 0; i < cnt.length(); i++) {
1823 space = outputArg(this, p.args, index);
1824 if (p.html4j && space.length() > 0) {
1825 toValue.append("\n ").append(p.args[index]).append(" = ")
1826 .append(accessClass("java_lang_Class")).append("(false).toJS(").
1827 append(p.args[index]).append(");");
1831 append(") {").append("\n");
1832 append(toValue.toString());
1834 int lastSlash = jc.getClassName().lastIndexOf('/');
1835 final String pkg = jc.getClassName().substring(0, lastSlash);
1836 append(mangleCallbacks(pkg, p.body));
1837 requireReference(pkg + "/$JsCallbacks$");
1845 private static CharSequence mangleCallbacks(String pkgName, String body) {
1846 StringBuilder sb = new StringBuilder();
1849 int next = body.indexOf(".@", pos);
1851 sb.append(body.substring(pos));
1852 body = sb.toString();
1857 if (!Character.isJavaIdentifierPart(body.charAt(--ident))) {
1862 String refId = body.substring(ident, next);
1864 sb.append(body.substring(pos, ident));
1866 int sigBeg = body.indexOf('(', next);
1867 int sigEnd = body.indexOf(')', sigBeg);
1868 int colon4 = body.indexOf("::", next);
1869 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1870 throw new IllegalStateException("Malformed body " + body);
1872 String fqn = body.substring(next + 2, colon4);
1873 String method = body.substring(colon4 + 2, sigBeg);
1874 String params = body.substring(sigBeg, sigEnd + 1);
1876 int paramBeg = body.indexOf('(', sigEnd + 1);
1878 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1879 sb.append(mangleJsCallbacks(fqn, method, params, false));
1880 sb.append("(").append(refId);
1881 if (body.charAt(paramBeg + 1) != ')') {
1889 int next = body.indexOf("@", pos);
1894 sb.append(body.substring(pos));
1898 sb = new StringBuilder();
1901 sb.append(body.substring(pos, next));
1903 int sigBeg = body.indexOf('(', next);
1904 int sigEnd = body.indexOf(')', sigBeg);
1905 int colon4 = body.indexOf("::", next);
1906 if (sigBeg == -1 || sigEnd == -1 || colon4 == -1) {
1907 throw new IllegalStateException("Malformed body " + body);
1909 String fqn = body.substring(next + 1, colon4);
1910 String method = body.substring(colon4 + 2, sigBeg);
1911 String params = body.substring(sigBeg, sigEnd + 1);
1913 int paramBeg = body.indexOf('(', sigEnd + 1);
1915 sb.append("vm.").append(pkgName.replace('/', '_')).append("_$JsCallbacks$(false)._VM().");
1916 sb.append(mangleJsCallbacks(fqn, method, params, true));
1922 static String mangleJsCallbacks(String fqn, String method, String params, boolean isStatic) {
1923 if (params.startsWith("(")) {
1924 params = params.substring(1);
1926 if (params.endsWith(")")) {
1927 params = params.substring(0, params.length() - 1);
1929 StringBuilder sb = new StringBuilder();
1930 final String fqnu = fqn.replace('.', '_');
1931 final String rfqn = mangleClassName(fqnu);
1932 final String rm = mangleMethodName(method);
1935 StringBuilder pb = new StringBuilder();
1936 int len = params.length();
1938 while (indx < len) {
1939 char ch = params.charAt(indx);
1940 if (ch == '[' || ch == 'L') {
1941 pb.append("Ljava/lang/Object;");
1942 indx = params.indexOf(';', indx) + 1;
1948 srp = mangleSig(pb.toString());
1950 final String rp = mangleSig(params);
1951 final String mrp = mangleMethodName(rp);
1952 sb.append(rfqn).append("$").append(rm).
1953 append('$').append(mrp).append("__Ljava_lang_Object_2");
1955 sb.append('L').append(fqnu).append("_2");
1958 return sb.toString();
1961 private static String className(ClassData jc) {
1962 //return jc.getName().getInternalName().replace('/', '_');
1963 return mangleClassName(jc.getClassName());
1966 private static String[] findAnnotation(
1967 byte[] arr, ClassData cd, final String className,
1968 final String... attrNames
1969 ) throws IOException {
1973 final String[] values = new String[attrNames.length];
1974 final boolean[] found = { false };
1975 final String jvmType = "L" + className.replace('.', '/') + ";";
1976 AnnotationParser ap = new AnnotationParser(false, true) {
1978 protected void visitAttr(String type, String attr, String at, String value) {
1979 if (type.equals(jvmType)) {
1981 for (int i = 0; i < attrNames.length; i++) {
1982 if (attrNames[i].equals(attr)) {
1991 return found[0] ? values : null;
1994 private CharSequence initField(FieldData v) {
1995 final String is = v.getInternalSig();
1996 if (is.length() == 1) {
1997 switch (is.charAt(0)) {
2003 case 'I': return " = 0;";
2005 case 'D': return " = 0.0;";
2007 throw new IllegalStateException(is);
2013 private void generateAnno(ClassData cd, byte[] data) throws IOException {
2014 AnnotationParser ap = new AnnotationParser(true, false) {
2015 int[] cnt = new int[32];
2019 protected void visitAnnotationStart(String attrType, boolean top) throws IOException {
2020 final String slashType = attrType.substring(1, attrType.length() - 1);
2021 requireReference(slashType);
2023 if (cnt[depth]++ > 0) {
2027 append('"').append(attrType).append("\" : ");
2034 protected void visitAnnotationEnd(String type, boolean top) throws IOException {
2040 protected void visitValueStart(String attrName, char type) throws IOException {
2041 if (cnt[depth]++ > 0) {
2045 if (attrName != null) {
2046 append('"').append(attrName).append("\" : ");
2054 protected void visitValueEnd(String attrName, char type) throws IOException {
2062 protected void visitAttr(String type, String attr, String attrType, String value)
2063 throws IOException {
2064 if (attr == null && value == null) {
2071 protected void visitEnumAttr(String type, String attr, String attrType, String value)
2072 throws IOException {
2073 final String slashType = attrType.substring(1, attrType.length() - 1);
2074 requireReference(slashType);
2076 final String cn = mangleClassName(slashType);
2077 append(accessClass(cn))
2078 .append("(false)['valueOf__L").
2080 append("_2Ljava_lang_String_2']('").
2088 private static String outputArg(Appendable out, String[] args, int indx) throws IOException {
2089 final String name = args[indx];
2093 if (name.contains(",")) {
2094 throw new IOException("Wrong parameter with ',': " + name);
2100 final void emitNoFlush(
2102 final String format, final CharSequence... params
2103 ) throws IOException {
2104 emitImpl(this, format, params);
2106 static final void emit(
2108 final Appendable out,
2109 final String format, final CharSequence... params
2110 ) throws IOException {
2112 emitImpl(out, format, params);
2114 static void emitImpl(final Appendable out,
2115 final String format,
2116 final CharSequence... params) throws IOException {
2117 final int length = format.length();
2120 int paramOffset = format.indexOf('@');
2121 while ((paramOffset != -1) && (paramOffset < (length - 1))) {
2122 final char paramChar = format.charAt(paramOffset + 1);
2123 if ((paramChar >= '1') && (paramChar <= '9')) {
2124 final int paramIndex = paramChar - '0' - 1;
2126 out.append(format, processed, paramOffset);
2127 out.append(params[paramIndex]);
2130 processed = paramOffset + 1;
2133 paramOffset = format.indexOf('@', paramOffset + 1);
2136 out.append(format, processed, length);
2139 private void generateCatch(TrapData[] traps, int current, int topMostLabel) throws IOException {
2140 append("} catch (e) {\n");
2142 for (TrapData e : traps) {
2146 if (e.catch_cpx != 0) { //not finally
2147 final String classInternalName = jc.getClassName(e.catch_cpx);
2148 addReference(classInternalName);
2149 append("e = vm.java_lang_Class(false).bck2BrwsrThrwrbl(e);");
2150 append("if (e['$instOf_" + classInternalName.replace('/', '_') + "']) {");
2151 append("var stA0 = e;");
2152 goTo(this, current, e.handler_pc, topMostLabel);
2155 finallyPC = e.handler_pc;
2158 if (finallyPC == -1) {
2161 append("var stA0 = e;");
2162 goTo(this, current, finallyPC, topMostLabel);
2167 private static void goTo(Appendable out, int current, int to, int canBack) throws IOException {
2170 out.append("{ gt = 0; continue X_" + to + "; }");
2172 out.append("{ gt = " + to + "; continue X_0; }");
2175 out.append("{ gt = " + to + "; break IF; }");
2179 private static void emitIf(
2181 Appendable out, String pattern,
2183 int current, int to, int canBack
2184 ) throws IOException {
2186 emitImpl(out, pattern, param);
2187 goTo(out, current, to, canBack);
2190 private void generateNewArray(int atype, final StackMapper smapper) throws IOException, IllegalStateException {
2193 case 4: jvmType = "[Z"; break;
2194 case 5: jvmType = "[C"; break;
2195 case 6: jvmType = "[F"; break;
2196 case 7: jvmType = "[D"; break;
2197 case 8: jvmType = "[B"; break;
2198 case 9: jvmType = "[S"; break;
2199 case 10: jvmType = "[I"; break;
2200 case 11: jvmType = "[J"; break;
2201 default: throw new IllegalStateException("Array type: " + atype);
2204 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](true, '@3', null, @1);",
2205 smapper.popI(), smapper.pushA(), jvmType);
2208 private void generateANewArray(int type, final StackMapper smapper) throws IOException {
2209 String typeName = jc.getClassName(type);
2210 String ref = "null";
2211 if (typeName.startsWith("[")) {
2212 typeName = "'[" + typeName + "'";
2214 ref = "vm." + mangleClassName(typeName);
2215 typeName = "'[L" + typeName + ";'";
2218 "var @2 = Array.prototype['newArray__Ljava_lang_Object_2ZLjava_lang_String_2Ljava_lang_Object_2I'](false, @3, @4, @1);",
2219 smapper.popI(), smapper.pushA(), typeName, ref);
2222 private int generateMultiANewArray(int type, final byte[] byteCodes, int i, final StackMapper smapper) throws IOException {
2223 String typeName = jc.getClassName(type);
2224 int dim = readUByte(byteCodes, ++i);
2225 StringBuilder dims = new StringBuilder();
2227 for (int d = 0; d < dim; d++) {
2229 dims.insert(1, ",");
2231 dims.insert(1, smapper.popI());
2235 if (typeName.charAt(dim) == 'L') {
2236 fn = "vm." + mangleClassName(typeName.substring(dim + 1, typeName.length() - 1));
2239 "var @2 = Array.prototype['multiNewArray__Ljava_lang_Object_2Ljava_lang_String_2_3ILjava_lang_Object_2']('@3', @1, @4);",
2240 dims.toString(), smapper.pushA(), typeName, fn
2245 private int generateTableSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2246 int table = i / 4 * 4 + 4;
2247 int dflt = i + readInt4(byteCodes, table);
2249 int low = readInt4(byteCodes, table);
2251 int high = readInt4(byteCodes, table);
2253 final CharSequence swVar = smapper.popValue();
2254 smapper.flush(this);
2255 append("switch (").append(swVar).append(") {\n");
2256 while (low <= high) {
2257 int offset = i + readInt4(byteCodes, table);
2259 append(" case " + low).append(":"); goTo(this, i, offset, topMostLabel); append('\n');
2262 append(" default: ");
2263 goTo(this, i, dflt, topMostLabel);
2269 private int generateLookupSwitch(int i, final byte[] byteCodes, final StackMapper smapper, int topMostLabel) throws IOException {
2270 int table = i / 4 * 4 + 4;
2271 int dflt = i + readInt4(byteCodes, table);
2273 int n = readInt4(byteCodes, table);
2275 final CharSequence swVar = smapper.popValue();
2276 smapper.flush(this);
2277 append("switch (").append(swVar).append(") {\n");
2279 int cnstnt = readInt4(byteCodes, table);
2281 int offset = i + readInt4(byteCodes, table);
2283 append(" case " + cnstnt).append(": "); goTo(this, i, offset, topMostLabel); append('\n');
2285 append(" default: ");
2286 goTo(this, i, dflt, topMostLabel);
2292 private void generateInstanceOf(int indx, final StackMapper smapper) throws IOException {
2293 String type = jc.getClassName(indx);
2294 if (!type.startsWith("[")) {
2296 "var @2 = @1 != null && @1['$instOf_@3'] ? 1 : 0;",
2297 smapper.popA(), smapper.pushI(),
2298 type.replace('/', '_'));
2301 while (type.charAt(cnt) == '[') {
2304 if (type.charAt(cnt) == 'L') {
2305 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2307 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @4, @3);",
2308 smapper.popA(), smapper.pushI(),
2313 "var @2 = Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@3');",
2314 smapper.popA(), smapper.pushI(), type
2320 private void generateCheckcast(int indx, final StackMapper smapper) throws IOException {
2321 String type = jc.getClassName(indx);
2322 if (!type.startsWith("[")) {
2323 emitNoFlush(smapper,
2324 "if (@1 !== null && !@1['$instOf_@2']) throw vm.java_lang_ClassCastException(true);",
2325 smapper.getT(0, VarType.REFERENCE, false), type.replace('/', '_'));
2328 while (type.charAt(cnt) == '[') {
2331 if (type.charAt(cnt) == 'L') {
2332 type = "vm." + mangleClassName(type.substring(cnt + 1, type.length() - 1));
2333 emitNoFlush(smapper,
2334 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2ILjava_lang_Object_2'](@1, @3, @2)) throw vm.java_lang_ClassCastException(true);",
2335 smapper.getT(0, VarType.REFERENCE, false), type, "" + cnt
2338 emitNoFlush(smapper,
2339 "if (@1 !== null && !Array.prototype['isInstance__ZLjava_lang_Object_2Ljava_lang_String_2'](@1, '@2')) throw vm.java_lang_ClassCastException(true);",
2340 smapper.getT(0, VarType.REFERENCE, false), type
2346 private void generateByteCodeComment(int prev, int i, final byte[] byteCodes) throws IOException {
2347 for (int j = prev; j <= i; j++) {
2349 final int cc = readUByte(byteCodes, j);
2350 append(Integer.toString(cc));
2354 @JavaScriptBody(args = "msg", body = "")
2355 private static void println(String msg) {
2356 System.err.println(msg);