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 VM(Appendable out, Bck2Brwsr.Resources resources) {
39 this.resources = resources;
40 this.classDataCache = new ClassDataCache(resources);
41 this.exportedSymbols = new ExportedSymbols(resources);
42 this.invokerMethods = new StringArray();
46 // uses VMLazy to load dynamic classes
47 boolean assertsOn = false;
48 assert assertsOn = true;
56 boolean debug(String msg) throws IOException {
60 static void compile(Appendable out, Bck2Brwsr.Resources l, StringArray names, boolean extension) throws IOException {
61 VM vm = extension ? new Extension(out, l) : new Standalone(out, l);
65 private void doCompile(StringArray names) throws IOException {
68 "\n var invoker = function Invoker() {"
69 + "\n return Invoker.target[Invoker.method]"
70 + ".apply(Invoker.target, arguments);"
73 for (String invokerMethod: invokerMethods.toArray()) {
74 out.append("\n invoker." + invokerMethod + " = function(target) {"
75 + "\n invoker.target = target;"
76 + "\n invoker.method = '" + invokerMethod + "';"
77 + "\n return invoker;"
84 protected abstract void generatePrologue() throws IOException;
86 protected abstract void generateEpilogue() throws IOException;
88 protected abstract String generateClass(String className)
91 protected abstract String getExportsObject();
94 protected final void declaredClass(ClassData classData, String mangledName)
96 if (exportedSymbols.isExported(classData)) {
97 out.append("\n").append(getExportsObject()).append("['")
100 .append(accessClass(mangledName))
106 protected void declaredField(FieldData fieldData,
108 String mangledName) throws IOException {
109 if (exportedSymbols.isExported(fieldData)) {
110 exportMember(destObject, mangledName);
115 protected void declaredMethod(MethodData methodData,
117 String mangledName) throws IOException {
118 if (isHierarchyExported(methodData)) {
119 exportMember(destObject, mangledName);
123 private void exportMember(String destObject, String memberName)
125 out.append("\n").append(destObject).append("['")
128 .append(destObject).append(".").append(memberName)
132 private void generateBody(StringArray names) throws IOException {
133 StringArray processed = new StringArray();
134 StringArray initCode = new StringArray();
135 for (String baseClass : names.toArray()) {
136 references.add(baseClass);
139 for (String n : references.toArray()) {
140 if (processed.contains(n)) {
150 String ic = generateClass(name);
152 initCode.add(ic == null ? "" : ic);
153 } catch (RuntimeException ex) {
154 if (out instanceof CharSequence) {
155 CharSequence seq = (CharSequence)out;
156 int lastBlock = seq.length();
157 while (lastBlock-- > 0) {
158 if (seq.charAt(lastBlock) == '{') {
162 throw new IOException("Error while compiling " + name + "\n"
163 + seq.subSequence(lastBlock + 1, seq.length()), ex
166 throw new IOException("Error while compiling " + name + "\n"
173 for (String resource : scripts.toArray()) {
174 while (resource.startsWith("/")) {
175 resource = resource.substring(1);
177 InputStream emul = resources.get(resource);
179 throw new IOException("Can't find " + resource);
181 readResource(emul, out);
183 scripts = new StringArray();
185 StringArray toInit = StringArray.asList(references.toArray());
188 for (String ic : toInit.toArray()) {
189 int indx = processed.indexOf(ic);
191 final String theCode = initCode.toArray()[indx];
192 if (!theCode.isEmpty()) {
193 out.append(theCode).append("\n");
195 initCode.toArray()[indx] = "";
201 private static void readResource(InputStream emul, Appendable out) throws IOException {
205 int ch = emul.read();
209 if (ch < 0 || ch > 255) {
210 throw new IOException("Invalid char in emulation " + ch);
217 out.append((char)ch);
224 out.append('/').append((char)ch);
247 static String toString(String name) throws IOException {
248 StringBuilder sb = new StringBuilder();
249 // compile(sb, name);
250 return sb.toString().toString();
253 private StringArray scripts = new StringArray();
254 private StringArray references = new StringArray();
257 protected boolean requireReference(String cn) {
258 if (references.contains(cn)) {
266 protected void requireScript(String resourcePath) {
267 scripts.add(resourcePath);
271 String assignClass(String className) {
272 return "vm." + className + " = ";
276 String accessClass(String className) {
277 return "vm." + className;
281 protected String accessField(String object, String mangledName,
282 String[] fieldInfoName) throws IOException {
283 final FieldData field =
284 classDataCache.findField(fieldInfoName[0],
287 return accessNonVirtualMember(object, mangledName,
288 (field != null) ? field.cls : null);
292 protected String accessStaticMethod(
295 String[] fieldInfoName) throws IOException {
296 final MethodData method =
297 classDataCache.findMethod(fieldInfoName[0],
300 return accessNonVirtualMember(object, mangledName,
301 (method != null) ? method.cls : null);
305 protected String accessVirtualMethod(
308 String[] fieldInfoName) throws IOException {
309 final ClassData referencedClass =
310 classDataCache.getClassData(fieldInfoName[0]);
311 final MethodData method =
312 classDataCache.findMethod(referencedClass,
317 && (((method.access & ByteCodeParser.ACC_FINAL) != 0)
318 || ((referencedClass.getAccessFlags()
319 & ByteCodeParser.ACC_FINAL) != 0)
320 || !isHierarchyExported(method))) {
321 return object + "." + mangledName;
324 return accessThroughInvoker(object, mangledName);
327 private String accessThroughInvoker(String object, String mangledName) {
328 if (!invokerMethods.contains(mangledName)) {
329 invokerMethods.add(mangledName);
331 return "invoker." + mangledName + '(' + object + ')';
334 private boolean isHierarchyExported(final MethodData methodData)
336 if (exportedSymbols.isExported(methodData)) {
339 if ((methodData.access & (ByteCodeParser.ACC_PRIVATE
340 | ByteCodeParser.ACC_STATIC)) != 0) {
344 final ExportedMethodFinder exportedMethodFinder =
345 new ExportedMethodFinder(exportedSymbols);
347 classDataCache.findMethods(
349 methodData.getName(),
350 methodData.getInternalSig(),
351 exportedMethodFinder);
353 return (exportedMethodFinder.getFound() != null);
356 private static String accessNonVirtualMember(String object,
358 ClassData declaringClass) {
359 return (declaringClass != null) ? object + "." + mangledName
360 : object + "['" + mangledName + "']";
363 private static final class ExportedMethodFinder
364 implements ClassDataCache.TraversalCallback<MethodData> {
365 private final ExportedSymbols exportedSymbols;
366 private MethodData found;
368 public ExportedMethodFinder(final ExportedSymbols exportedSymbols) {
369 this.exportedSymbols = exportedSymbols;
373 public boolean traverse(final MethodData methodData) {
375 if (exportedSymbols.isExported(methodData)) {
379 } catch (final IOException e) {
385 public MethodData getFound() {
390 private static final class Standalone extends VM {
391 private Standalone(Appendable out, Bck2Brwsr.Resources resources) {
392 super(out, resources);
396 protected void generatePrologue() throws IOException {
397 out.append("(function VM(global) {var fillInVMSkeleton = function(vm) {");
401 protected void generateEpilogue() throws IOException {
405 + " var extensions = [];\n"
406 + " global.bck2brwsr = function() {\n"
407 + " var args = Array.prototype.slice.apply(arguments);\n"
408 + " var vm = fillInVMSkeleton({});\n"
409 + " for (var i = 0; i < extensions.length; ++i) {\n"
410 + " extensions[i](vm);\n"
412 + " var loader = {};\n"
413 + " loader.vm = vm;\n"
414 + " loader.loadClass = function(name) {\n"
415 + " var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
416 + " var fn = vm[attr];\n"
417 + " if (fn) return fn(false);\n"
418 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
419 + " load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
421 + " if (vm.loadClass) {\n"
422 + " throw 'Cannot initialize the bck2brwsr VM twice!';\n"
424 + " vm.loadClass = loader.loadClass;\n"
425 + " vm.loadBytes = function(name) {\n"
426 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
427 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
429 + " vm.java_lang_reflect_Array(false);\n"
430 + " vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
431 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\n"
432 + " return loader;\n"
435 " global.bck2brwsr.registerExtension"
436 + " = function(extension) {\n"
437 + " extensions.push(extension);\n"
439 out.append("}(this));");
443 protected String generateClass(String className) throws IOException {
444 ClassData classData = classDataCache.getClassData(className);
445 if (classData == null) {
446 throw new IOException("Can't find class " + className);
448 return compile(classData);
452 protected String getExportsObject() {
457 private static final class Extension extends VM {
458 private Extension(Appendable out, Bck2Brwsr.Resources resources) {
459 super(out, resources);
463 protected void generatePrologue() throws IOException {
464 out.append("bck2brwsr.registerExtension(function(exports) {\n"
465 + " var vm = {};\n");
466 out.append(" function link(n, inst) {\n"
467 + " var cls = n.replace__Ljava_lang_String_2CC("
468 + "'/', '_').toString();\n"
469 + " var dot = n.replace__Ljava_lang_String_2CC("
470 + "'/', '.').toString();\n"
471 + " exports.loadClass(dot);\n"
472 + " vm[cls] = exports[cls];\n"
473 + " return vm[cls](inst);\n"
478 protected void generateEpilogue() throws IOException {
483 protected String generateClass(String className) throws IOException {
484 ClassData classData = classDataCache.getClassData(className);
485 if (classData == null) {
486 out.append("\n").append(assignClass(
487 className.replace('/', '_')))
488 .append("function() {\n return link('")
490 .append("', arguments.length == 0 || arguments[0] === true);"
496 return compile(classData);
500 protected String getExportsObject() {