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, names.toArray())
62 : new Standalone(out, l);
64 final StringArray fixedNames =
65 StringArray.asList(Class.class.getName().replace('.', '/'),
66 VM.class.getName().replace('.', '/'));
68 vm.doCompile(fixedNames.addAndNew(names.toArray()));
71 private void doCompile(StringArray names) throws IOException {
74 "\n var invoker = function Invoker() {"
75 + "\n return Invoker.target[Invoker.method]"
76 + ".apply(Invoker.target, arguments);"
79 for (String invokerMethod: invokerMethods.toArray()) {
80 out.append("\n invoker." + invokerMethod + " = function(target) {"
81 + "\n invoker.target = target;"
82 + "\n invoker.method = '" + invokerMethod + "';"
83 + "\n return invoker;"
90 protected abstract void generatePrologue() throws IOException;
92 protected abstract void generateEpilogue() throws IOException;
94 protected abstract String getExportsObject();
96 protected abstract boolean isExternalClass(String className);
99 protected final void declaredClass(ClassData classData, String mangledName)
101 if (exportedSymbols.isExported(classData)) {
102 out.append("\n").append(getExportsObject()).append("['")
105 .append(accessClass(mangledName))
110 protected String generateClass(String className) throws IOException {
111 ClassData classData = classDataCache.getClassData(className);
112 if (classData == null) {
113 throw new IOException("Can't find class " + className);
115 return compile(classData);
119 protected void declaredField(FieldData fieldData,
121 String mangledName) throws IOException {
122 if (exportedSymbols.isExported(fieldData)) {
123 exportMember(destObject, mangledName);
128 protected void declaredMethod(MethodData methodData,
130 String mangledName) throws IOException {
131 if (isHierarchyExported(methodData)) {
132 exportMember(destObject, mangledName);
136 private void exportMember(String destObject, String memberName)
138 out.append("\n").append(destObject).append("['")
141 .append(destObject).append(".").append(memberName)
145 private void generateBody(StringArray names) throws IOException {
146 StringArray processed = new StringArray();
147 StringArray initCode = new StringArray();
148 for (String baseClass : names.toArray()) {
149 references.add(baseClass);
152 for (String n : references.toArray()) {
153 if (processed.contains(n)) {
163 String ic = generateClass(name);
165 initCode.add(ic == null ? "" : ic);
166 } catch (RuntimeException ex) {
167 if (out instanceof CharSequence) {
168 CharSequence seq = (CharSequence)out;
169 int lastBlock = seq.length();
170 while (lastBlock-- > 0) {
171 if (seq.charAt(lastBlock) == '{') {
175 throw new IOException("Error while compiling " + name + "\n"
176 + seq.subSequence(lastBlock + 1, seq.length()), ex
179 throw new IOException("Error while compiling " + name + "\n"
186 for (String resource : scripts.toArray()) {
187 while (resource.startsWith("/")) {
188 resource = resource.substring(1);
190 InputStream emul = resources.get(resource);
192 throw new IOException("Can't find " + resource);
194 readResource(emul, out);
196 scripts = new StringArray();
198 StringArray toInit = StringArray.asList(references.toArray());
201 for (String ic : toInit.toArray()) {
202 int indx = processed.indexOf(ic);
204 final String theCode = initCode.toArray()[indx];
205 if (!theCode.isEmpty()) {
206 out.append(theCode).append("\n");
208 initCode.toArray()[indx] = "";
214 private static void readResource(InputStream emul, Appendable out) throws IOException {
218 int ch = emul.read();
222 if (ch < 0 || ch > 255) {
223 throw new IOException("Invalid char in emulation " + ch);
230 out.append((char)ch);
237 out.append('/').append((char)ch);
260 static String toString(String name) throws IOException {
261 StringBuilder sb = new StringBuilder();
262 // compile(sb, name);
263 return sb.toString().toString();
266 private StringArray scripts = new StringArray();
267 private StringArray references = new StringArray();
270 protected boolean requireReference(String cn) {
271 if (references.contains(cn)) {
279 protected void requireScript(String resourcePath) {
280 scripts.add(resourcePath);
284 String assignClass(String className) {
285 return "vm." + className + " = ";
289 String accessClass(String className) {
290 return "vm." + className;
294 protected String accessField(String object, String mangledName,
295 String[] fieldInfoName) throws IOException {
296 final FieldData field =
297 classDataCache.findField(fieldInfoName[0],
300 return accessNonVirtualMember(object, mangledName,
301 (field != null) ? field.cls : null);
305 protected String accessStaticMethod(
308 String[] fieldInfoName) throws IOException {
309 final MethodData method =
310 classDataCache.findMethod(fieldInfoName[0],
313 return accessNonVirtualMember(object, mangledName,
314 (method != null) ? method.cls : null);
318 protected String accessVirtualMethod(
321 String[] fieldInfoName) throws IOException {
322 final ClassData referencedClass =
323 classDataCache.getClassData(fieldInfoName[0]);
324 final MethodData method =
325 classDataCache.findMethod(referencedClass,
330 && !isExternalClass(method.cls.getClassName())
331 && (((method.access & ByteCodeParser.ACC_FINAL) != 0)
332 || ((referencedClass.getAccessFlags()
333 & ByteCodeParser.ACC_FINAL) != 0)
334 || !isHierarchyExported(method))) {
335 return object + "." + mangledName;
338 return accessThroughInvoker(object, mangledName);
341 private String accessThroughInvoker(String object, String mangledName) {
342 if (!invokerMethods.contains(mangledName)) {
343 invokerMethods.add(mangledName);
345 return "invoker." + mangledName + '(' + object + ')';
348 private boolean isHierarchyExported(final MethodData methodData)
350 if (exportedSymbols.isExported(methodData)) {
353 if ((methodData.access & (ByteCodeParser.ACC_PRIVATE
354 | ByteCodeParser.ACC_STATIC)) != 0) {
358 final ExportedMethodFinder exportedMethodFinder =
359 new ExportedMethodFinder(exportedSymbols);
361 classDataCache.findMethods(
363 methodData.getName(),
364 methodData.getInternalSig(),
365 exportedMethodFinder);
367 return (exportedMethodFinder.getFound() != null);
370 private String accessNonVirtualMember(String object,
372 ClassData declaringClass) {
373 return ((declaringClass != null)
374 && !isExternalClass(declaringClass.getClassName()))
375 ? object + "." + mangledName
376 : object + "['" + mangledName + "']";
379 private static final class ExportedMethodFinder
380 implements ClassDataCache.TraversalCallback<MethodData> {
381 private final ExportedSymbols exportedSymbols;
382 private MethodData found;
384 public ExportedMethodFinder(final ExportedSymbols exportedSymbols) {
385 this.exportedSymbols = exportedSymbols;
389 public boolean traverse(final MethodData methodData) {
391 if (exportedSymbols.isExported(methodData)) {
395 } catch (final IOException e) {
401 public MethodData getFound() {
406 private static final class Standalone extends VM {
407 private Standalone(Appendable out, Bck2Brwsr.Resources resources) {
408 super(out, resources);
412 protected void generatePrologue() throws IOException {
413 out.append("(function VM(global) {var fillInVMSkeleton = function(vm) {");
417 protected void generateEpilogue() throws IOException {
421 + " var extensions = [];\n"
422 + " global.bck2brwsr = function() {\n"
423 + " var args = Array.prototype.slice.apply(arguments);\n"
424 + " var vm = fillInVMSkeleton({});\n"
425 + " for (var i = 0; i < extensions.length; ++i) {\n"
426 + " extensions[i](vm);\n"
428 + " var loader = {};\n"
429 + " loader.vm = vm;\n"
430 + " loader.loadClass = function(name) {\n"
431 + " var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
432 + " var fn = vm[attr];\n"
433 + " if (fn) return fn(false);\n"
434 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
435 + " load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
437 + " if (vm.loadClass) {\n"
438 + " throw 'Cannot initialize the bck2brwsr VM twice!';\n"
440 + " vm.loadClass = loader.loadClass;\n"
441 + " vm.loadBytes = function(name) {\n"
442 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
443 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
445 + " vm.java_lang_reflect_Array(false);\n"
446 + " vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
447 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\n"
448 + " return loader;\n"
451 " global.bck2brwsr.registerExtension"
452 + " = function(extension) {\n"
453 + " extensions.push(extension);\n"
455 out.append("}(this));");
459 protected String getExportsObject() {
464 protected boolean isExternalClass(String className) {
469 private static final class Extension extends VM {
470 private final StringArray extensionClasses;
472 private Extension(Appendable out, Bck2Brwsr.Resources resources,
473 String[] extClassesArray) {
474 super(out, resources);
475 this.extensionClasses = StringArray.asList(extClassesArray);
479 protected void generatePrologue() throws IOException {
480 out.append("bck2brwsr.registerExtension(function(exports) {\n"
481 + " var vm = {};\n");
482 out.append(" function link(n, inst) {\n"
483 + " var cls = n['replace__Ljava_lang_String_2CC']"
484 + "('/', '_').toString();\n"
485 + " var dot = n['replace__Ljava_lang_String_2CC']"
486 + "('/', '.').toString();\n"
487 + " exports.loadClass(dot);\n"
488 + " vm[cls] = exports[cls];\n"
489 + " return vm[cls](inst);\n"
494 protected void generateEpilogue() throws IOException {
499 protected String generateClass(String className) throws IOException {
500 if (isExternalClass(className)) {
501 out.append("\n").append(assignClass(
502 className.replace('/', '_')))
503 .append("function() {\n return link('")
505 .append("', arguments.length == 0 || arguments[0] === true);"
511 return super.generateClass(className);
515 protected String getExportsObject() {
520 protected boolean isExternalClass(String className) {
521 return !extensionClasses.contains(className);