Can execute VMTest in browser, if it is annotated with @Exported annotation like the BooleanTest
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.vm4brwsr.ByteCodeParser.ClassData;
23 import org.apidesign.vm4brwsr.ByteCodeParser.FieldData;
24 import org.apidesign.vm4brwsr.ByteCodeParser.MethodData;
26 /** Generator of JavaScript from bytecode of classes on classpath of the VM.
28 * @author Jaroslav Tulach <jtulach@netbeans.org>
30 abstract class VM extends ByteCodeToJavaScript {
31 protected final ClassDataCache classDataCache;
33 private final Bck2Brwsr.Resources resources;
34 private final ExportedSymbols exportedSymbols;
35 private final StringArray invokerMethods;
37 private static final Class<?> FIXED_DEPENDENCIES[] = {
39 ArithmeticException.class,
43 private VM(Appendable out, Bck2Brwsr.Resources resources) {
45 this.resources = resources;
46 this.classDataCache = new ClassDataCache(resources);
47 this.exportedSymbols = new ExportedSymbols(resources);
48 this.invokerMethods = new StringArray();
52 // uses VMLazy to load dynamic classes
53 boolean assertsOn = false;
54 assert assertsOn = true;
62 boolean debug(String msg) throws IOException {
66 static void compile(Appendable out, Bck2Brwsr.Resources l, StringArray names, boolean extension) throws IOException {
67 VM vm = extension ? new Extension(out, l, names.toArray())
68 : new Standalone(out, l);
70 final StringArray fixedNames = new StringArray();
72 for (final Class<?> fixedClass: FIXED_DEPENDENCIES) {
73 fixedNames.add(fixedClass.getName().replace('.', '/'));
76 vm.doCompile(fixedNames.addAndNew(names.toArray()));
79 private void doCompile(StringArray names) throws IOException {
82 "\n var invoker = function Invoker() {"
83 + "\n return Invoker.target[Invoker.method]"
84 + ".apply(Invoker.target, arguments);"
87 for (String invokerMethod: invokerMethods.toArray()) {
88 out.append("\n invoker." + invokerMethod + " = function(target) {"
89 + "\n invoker.target = target;"
90 + "\n invoker.method = '" + invokerMethod + "';"
91 + "\n return invoker;"
98 protected abstract void generatePrologue() throws IOException;
100 protected abstract void generateEpilogue() throws IOException;
102 protected abstract String getExportsObject();
104 protected abstract boolean isExternalClass(String className);
107 protected final void declaredClass(ClassData classData, String mangledName)
109 if (exportedSymbols.isExported(classData)) {
110 out.append("\n").append(getExportsObject()).append("['")
113 .append(accessClass(mangledName))
118 protected String generateClass(String className) throws IOException {
119 ClassData classData = classDataCache.getClassData(className);
120 if (classData == null) {
121 throw new IOException("Can't find class " + className);
123 return compile(classData);
127 protected void declaredField(FieldData fieldData,
129 String mangledName) throws IOException {
130 if (exportedSymbols.isExported(fieldData)) {
131 exportMember(destObject, mangledName);
136 protected void declaredMethod(MethodData methodData,
138 String mangledName) throws IOException {
139 if (isHierarchyExported(methodData)) {
140 exportMember(destObject, mangledName);
144 private void exportMember(String destObject, String memberName)
146 out.append("\n").append(destObject).append("['")
149 .append(destObject).append(".").append(memberName)
153 private void generateBody(StringArray names) throws IOException {
154 StringArray processed = new StringArray();
155 StringArray initCode = new StringArray();
156 for (String baseClass : names.toArray()) {
157 references.add(baseClass);
160 for (String n : references.toArray()) {
161 if (processed.contains(n)) {
171 String ic = generateClass(name);
173 initCode.add(ic == null ? "" : ic);
174 } catch (RuntimeException ex) {
175 if (out instanceof CharSequence) {
176 CharSequence seq = (CharSequence)out;
177 int lastBlock = seq.length();
178 while (lastBlock-- > 0) {
179 if (seq.charAt(lastBlock) == '{') {
183 throw new IOException("Error while compiling " + name + "\n"
184 + seq.subSequence(lastBlock + 1, seq.length()), ex
187 throw new IOException("Error while compiling " + name + "\n"
194 for (String resource : scripts.toArray()) {
195 while (resource.startsWith("/")) {
196 resource = resource.substring(1);
198 InputStream emul = resources.get(resource);
200 throw new IOException("Can't find " + resource);
202 readResource(emul, out);
204 scripts = new StringArray();
206 StringArray toInit = StringArray.asList(references.toArray());
209 for (String ic : toInit.toArray()) {
210 int indx = processed.indexOf(ic);
212 final String theCode = initCode.toArray()[indx];
213 if (!theCode.isEmpty()) {
214 out.append(theCode).append("\n");
216 initCode.toArray()[indx] = "";
222 private static void readResource(InputStream emul, Appendable out) throws IOException {
226 int ch = emul.read();
230 if (ch < 0 || ch > 255) {
231 throw new IOException("Invalid char in emulation " + ch);
238 out.append((char)ch);
245 out.append('/').append((char)ch);
268 static String toString(String name) throws IOException {
269 StringBuilder sb = new StringBuilder();
270 // compile(sb, name);
271 return sb.toString().toString();
274 private StringArray scripts = new StringArray();
275 private StringArray references = new StringArray();
278 protected boolean requireReference(String cn) {
279 if (references.contains(cn)) {
287 protected void requireScript(String resourcePath) {
288 scripts.add(resourcePath);
292 String assignClass(String className) {
293 return "vm." + className + " = ";
297 String accessClass(String className) {
298 return "vm." + className;
302 protected String accessField(String object, String mangledName,
303 String[] fieldInfoName) throws IOException {
304 final FieldData field =
305 classDataCache.findField(fieldInfoName[0],
308 return accessNonVirtualMember(object, mangledName,
309 (field != null) ? field.cls : null);
313 protected String accessStaticMethod(
316 String[] fieldInfoName) throws IOException {
317 final MethodData method =
318 classDataCache.findMethod(fieldInfoName[0],
321 return accessNonVirtualMember(object, mangledName,
322 (method != null) ? method.cls : null);
326 protected String accessVirtualMethod(
329 String[] fieldInfoName) throws IOException {
330 final ClassData referencedClass =
331 classDataCache.getClassData(fieldInfoName[0]);
332 final MethodData method =
333 classDataCache.findMethod(referencedClass,
338 && !isExternalClass(method.cls.getClassName())
339 && (((method.access & ByteCodeParser.ACC_FINAL) != 0)
340 || ((referencedClass.getAccessFlags()
341 & ByteCodeParser.ACC_FINAL) != 0)
342 || !isHierarchyExported(method))) {
343 return object + "." + mangledName;
346 return accessThroughInvoker(object, mangledName);
349 private String accessThroughInvoker(String object, String mangledName) {
350 if (!invokerMethods.contains(mangledName)) {
351 invokerMethods.add(mangledName);
353 return "invoker." + mangledName + '(' + object + ')';
356 private boolean isHierarchyExported(final MethodData methodData)
358 if (exportedSymbols.isExported(methodData)) {
361 if ((methodData.access & (ByteCodeParser.ACC_PRIVATE
362 | ByteCodeParser.ACC_STATIC)) != 0) {
366 final ExportedMethodFinder exportedMethodFinder =
367 new ExportedMethodFinder(exportedSymbols);
369 classDataCache.findMethods(
371 methodData.getName(),
372 methodData.getInternalSig(),
373 exportedMethodFinder);
375 return (exportedMethodFinder.getFound() != null);
378 private String accessNonVirtualMember(String object,
380 ClassData declaringClass) {
381 return ((declaringClass != null)
382 && !isExternalClass(declaringClass.getClassName()))
383 ? object + "." + mangledName
384 : object + "['" + mangledName + "']";
387 private static final class ExportedMethodFinder
388 implements ClassDataCache.TraversalCallback<MethodData> {
389 private final ExportedSymbols exportedSymbols;
390 private MethodData found;
392 public ExportedMethodFinder(final ExportedSymbols exportedSymbols) {
393 this.exportedSymbols = exportedSymbols;
397 public boolean traverse(final MethodData methodData) {
399 if (exportedSymbols.isExported(methodData)) {
403 } catch (final IOException e) {
409 public MethodData getFound() {
414 private static final class Standalone extends VM {
415 private Standalone(Appendable out, Bck2Brwsr.Resources resources) {
416 super(out, resources);
420 protected void generatePrologue() throws IOException {
421 out.append("(function VM(global) {var fillInVMSkeleton = function(vm) {");
425 protected void generateEpilogue() throws IOException {
429 + " var extensions = [];\n"
430 + " global.bck2brwsr = function() {\n"
431 + " var args = Array.prototype.slice.apply(arguments);\n"
432 + " var vm = fillInVMSkeleton({});\n"
433 + " for (var i = 0; i < extensions.length; ++i) {\n"
434 + " extensions[i](vm);\n"
436 + " var knownExtensions = extensions.length;\n"
437 + " var loader = {};\n"
438 + " loader.vm = vm;\n"
439 + " loader.loadClass = function(name) {\n"
440 + " var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
441 + " var fn = vm[attr];\n"
442 + " if (fn) return fn(false);\n"
444 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
445 + " load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
446 + " } catch (err) {\n"
447 + " while (knownExtensions < extensions.length) {\n"
448 + " extensions[knownExtensions++](vm);\n"
450 + " fn = vm[attr];\n"
451 + " if (fn) return fn(false);\n"
455 + " if (vm.loadClass) {\n"
456 + " throw 'Cannot initialize the bck2brwsr VM twice!';\n"
458 + " vm.loadClass = loader.loadClass;\n"
459 + " vm.loadBytes = function(name) {\n"
460 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
461 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
463 + " vm.java_lang_reflect_Array(false);\n"
464 + " vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
465 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\n"
466 + " return loader;\n"
469 " global.bck2brwsr.registerExtension = function(extension) {\n"
470 + " extensions.push(extension);\n"
473 out.append("}(this));");
477 protected String getExportsObject() {
482 protected boolean isExternalClass(String className) {
487 private static final class Extension extends VM {
488 private final StringArray extensionClasses;
490 private Extension(Appendable out, Bck2Brwsr.Resources resources,
491 String[] extClassesArray) {
492 super(out, resources);
493 this.extensionClasses = StringArray.asList(extClassesArray);
497 protected void generatePrologue() throws IOException {
498 out.append("bck2brwsr.registerExtension(function(exports) {\n"
499 + " var vm = {};\n");
500 out.append(" function link(n, inst) {\n"
501 + " var cls = n['replace__Ljava_lang_String_2CC']"
502 + "('/', '_').toString();\n"
503 + " var dot = n['replace__Ljava_lang_String_2CC']"
504 + "('/', '.').toString();\n"
505 + " exports.loadClass(dot);\n"
506 + " vm[cls] = exports[cls];\n"
507 + " return vm[cls](inst);\n"
512 protected void generateEpilogue() throws IOException {
517 protected String generateClass(String className) throws IOException {
518 if (isExternalClass(className)) {
519 out.append("\n").append(assignClass(
520 className.replace('/', '_')))
521 .append("function() {\n return link('")
523 .append("', arguments.length == 0 || arguments[0] === true);"
529 return super.generateClass(className);
533 protected String getExportsObject() {
538 protected boolean isExternalClass(String className) {
539 return !extensionClasses.contains(className);