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, StringArray explicitlyExported) {
45 this.resources = resources;
46 this.classDataCache = new ClassDataCache(resources);
47 this.exportedSymbols = new ExportedSymbols(resources, explicitlyExported);
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,
68 ) throws IOException {
69 String[] both = config.allClasses();
71 VM vm = config.isExtension() ?
72 new Extension(out, config.getResources(), both, config.rootClasses())
74 new Standalone(out, config.getResources(), config.rootClasses());
76 final StringArray fixedNames = new StringArray();
78 for (final Class<?> fixedClass: FIXED_DEPENDENCIES) {
79 fixedNames.add(fixedClass.getName().replace('.', '/'));
82 vm.doCompile(fixedNames.addAndNew(both));
85 private void doCompile(StringArray names) throws IOException {
88 "\n var invoker = function Invoker() {"
89 + "\n return Invoker.target[Invoker.method]"
90 + ".apply(Invoker.target, arguments);"
93 for (String invokerMethod: invokerMethods.toArray()) {
94 out.append("\n invoker." + invokerMethod + " = function(target) {"
95 + "\n invoker.target = target;"
96 + "\n invoker.method = '" + invokerMethod + "';"
97 + "\n return invoker;"
104 protected abstract void generatePrologue() throws IOException;
106 protected abstract void generateEpilogue() throws IOException;
108 protected abstract String getExportsObject();
110 protected abstract boolean isExternalClass(String className);
113 protected final void declaredClass(ClassData classData, String mangledName)
115 if (exportedSymbols.isExported(classData)) {
116 out.append("\n").append(getExportsObject()).append("['")
119 .append(accessClass(mangledName))
124 protected String generateClass(String className) throws IOException {
125 ClassData classData = classDataCache.getClassData(className);
126 if (classData == null) {
127 throw new IOException("Can't find class " + className);
129 return compile(classData);
133 protected void declaredField(FieldData fieldData,
135 String mangledName) throws IOException {
136 if (exportedSymbols.isExported(fieldData)) {
137 exportMember(destObject, mangledName);
142 protected void declaredMethod(MethodData methodData,
144 String mangledName) throws IOException {
145 if (isHierarchyExported(methodData)) {
146 exportMember(destObject, mangledName);
150 private void exportMember(String destObject, String memberName)
152 out.append("\n").append(destObject).append("['")
155 .append(destObject).append(".").append(memberName)
159 private void generateBody(StringArray names) throws IOException {
160 StringArray processed = new StringArray();
161 StringArray initCode = new StringArray();
162 for (String baseClass : names.toArray()) {
163 references.add(baseClass);
166 for (String n : references.toArray()) {
167 if (processed.contains(n)) {
177 String ic = generateClass(name);
179 initCode.add(ic == null ? "" : ic);
180 } catch (RuntimeException ex) {
181 if (out instanceof CharSequence) {
182 CharSequence seq = (CharSequence)out;
183 int lastBlock = seq.length();
184 while (lastBlock-- > 0) {
185 if (seq.charAt(lastBlock) == '{') {
189 throw new IOException("Error while compiling " + name + "\n"
190 + seq.subSequence(lastBlock + 1, seq.length()), ex
193 throw new IOException("Error while compiling " + name + "\n"
200 for (String resource : scripts.toArray()) {
201 while (resource.startsWith("/")) {
202 resource = resource.substring(1);
204 InputStream emul = resources.get(resource);
206 throw new IOException("Can't find " + resource);
208 readResource(emul, out);
210 scripts = new StringArray();
212 StringArray toInit = StringArray.asList(references.toArray());
215 for (String ic : toInit.toArray()) {
216 int indx = processed.indexOf(ic);
218 final String theCode = initCode.toArray()[indx];
219 if (!theCode.isEmpty()) {
220 out.append(theCode).append("\n");
222 initCode.toArray()[indx] = "";
228 private static void readResource(InputStream emul, Appendable out) throws IOException {
232 int ch = emul.read();
236 if (ch < 0 || ch > 255) {
237 throw new IOException("Invalid char in emulation " + ch);
244 out.append((char)ch);
251 out.append('/').append((char)ch);
274 static String toString(String name) throws IOException {
275 StringBuilder sb = new StringBuilder();
276 // compile(sb, name);
277 return sb.toString().toString();
280 private StringArray scripts = new StringArray();
281 private StringArray references = new StringArray();
284 protected boolean requireReference(String cn) {
285 if (references.contains(cn)) {
293 protected void requireScript(String resourcePath) {
294 scripts.add(resourcePath);
298 String assignClass(String className) {
299 return "vm." + className + " = ";
303 String accessClass(String className) {
304 return "vm." + className;
308 protected String accessField(String object, String mangledName,
309 String[] fieldInfoName) throws IOException {
310 final FieldData field =
311 classDataCache.findField(fieldInfoName[0],
314 return accessNonVirtualMember(object, mangledName,
315 (field != null) ? field.cls : null);
319 protected String accessStaticMethod(
322 String[] fieldInfoName) throws IOException {
323 final MethodData method =
324 classDataCache.findMethod(fieldInfoName[0],
327 return accessNonVirtualMember(object, mangledName,
328 (method != null) ? method.cls : null);
332 protected String accessVirtualMethod(
335 String[] fieldInfoName) throws IOException {
336 final ClassData referencedClass =
337 classDataCache.getClassData(fieldInfoName[0]);
338 final MethodData method =
339 classDataCache.findMethod(referencedClass,
344 && !isExternalClass(method.cls.getClassName())
345 && (((method.access & ByteCodeParser.ACC_FINAL) != 0)
346 || ((referencedClass.getAccessFlags()
347 & ByteCodeParser.ACC_FINAL) != 0)
348 || !isHierarchyExported(method))) {
349 return object + "." + mangledName;
352 return accessThroughInvoker(object, mangledName);
355 private String accessThroughInvoker(String object, String mangledName) {
356 if (!invokerMethods.contains(mangledName)) {
357 invokerMethods.add(mangledName);
359 return "invoker." + mangledName + '(' + object + ')';
362 private boolean isHierarchyExported(final MethodData methodData)
364 if (exportedSymbols.isExported(methodData)) {
367 if ((methodData.access & (ByteCodeParser.ACC_PRIVATE
368 | ByteCodeParser.ACC_STATIC)) != 0) {
372 final ExportedMethodFinder exportedMethodFinder =
373 new ExportedMethodFinder(exportedSymbols);
375 classDataCache.findMethods(
377 methodData.getName(),
378 methodData.getInternalSig(),
379 exportedMethodFinder);
381 return (exportedMethodFinder.getFound() != null);
384 private String accessNonVirtualMember(String object,
386 ClassData declaringClass) {
387 return ((declaringClass != null)
388 && !isExternalClass(declaringClass.getClassName()))
389 ? object + "." + mangledName
390 : object + "['" + mangledName + "']";
393 private static final class ExportedMethodFinder
394 implements ClassDataCache.TraversalCallback<MethodData> {
395 private final ExportedSymbols exportedSymbols;
396 private MethodData found;
398 public ExportedMethodFinder(final ExportedSymbols exportedSymbols) {
399 this.exportedSymbols = exportedSymbols;
403 public boolean traverse(final MethodData methodData) {
405 if (exportedSymbols.isExported(methodData)) {
409 } catch (final IOException e) {
415 public MethodData getFound() {
420 private static final class Standalone extends VM {
421 private Standalone(Appendable out, Bck2Brwsr.Resources resources, StringArray explicitlyExported) {
422 super(out, resources, explicitlyExported);
426 protected void generatePrologue() throws IOException {
427 out.append("(function VM(global) {var fillInVMSkeleton = function(vm) {");
431 protected void generateEpilogue() throws IOException {
435 + " var extensions = [];\n"
436 + " global.bck2brwsr = function() {\n"
437 + " var args = Array.prototype.slice.apply(arguments);\n"
438 + " var vm = fillInVMSkeleton({});\n"
439 + " for (var i = 0; i < extensions.length; ++i) {\n"
440 + " extensions[i](vm);\n"
442 + " var knownExtensions = extensions.length;\n"
443 + " var loader = {};\n"
444 + " loader.vm = vm;\n"
445 + " loader.loadClass = function(name) {\n"
446 + " var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
447 + " var fn = vm[attr];\n"
448 + " if (fn) return fn(false);\n"
450 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
451 + " load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
452 + " } catch (err) {\n"
453 + " while (knownExtensions < extensions.length) {\n"
454 + " extensions[knownExtensions++](vm);\n"
456 + " fn = vm[attr];\n"
457 + " if (fn) return fn(false);\n"
461 + " if (vm.loadClass) {\n"
462 + " throw 'Cannot initialize the bck2brwsr VM twice!';\n"
464 + " vm.loadClass = loader.loadClass;\n"
465 + " vm.loadBytes = function(name) {\n"
466 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
467 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
469 + " vm.java_lang_reflect_Array(false);\n"
470 + " vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
471 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\n"
472 + " return loader;\n"
475 " global.bck2brwsr.registerExtension = function(extension) {\n"
476 + " extensions.push(extension);\n"
479 out.append("}(this));");
483 protected String getExportsObject() {
488 protected boolean isExternalClass(String className) {
493 private static final class Extension extends VM {
494 private final StringArray extensionClasses;
496 private Extension(Appendable out, Bck2Brwsr.Resources resources,
497 String[] extClassesArray, StringArray explicitlyExported) {
498 super(out, resources, explicitlyExported);
499 this.extensionClasses = StringArray.asList(extClassesArray);
503 protected void generatePrologue() throws IOException {
504 out.append("bck2brwsr.registerExtension(function(exports) {\n"
505 + " var vm = {};\n");
506 out.append(" function link(n, inst) {\n"
507 + " var cls = n['replace__Ljava_lang_String_2CC']"
508 + "('/', '_').toString();\n"
509 + " var dot = n['replace__Ljava_lang_String_2CC']"
510 + "('/', '.').toString();\n"
511 + " exports.loadClass(dot);\n"
512 + " vm[cls] = exports[cls];\n"
513 + " return vm[cls](inst);\n"
518 protected void generateEpilogue() throws IOException {
523 protected String generateClass(String className) throws IOException {
524 if (isExternalClass(className)) {
525 out.append("\n").append(assignClass(
526 className.replace('/', '_')))
527 .append("function() {\n return link('")
529 .append("', arguments.length == 0 || arguments[0] === true);"
535 return super.generateClass(className);
539 protected String getExportsObject() {
544 protected boolean isExternalClass(String className) {
545 return !extensionClasses.contains(className);