Different meaning of root vs. added classes. Ability to explicitly enumerate classes that should be exported and available with fully qualified name.
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,
67 Bck2Brwsr.Resources l,
68 StringArray rootNames,
71 ) throws IOException {
72 StringArray both = names.addAndNew(rootNames.toArray());
74 VM vm = extension ? new Extension(out, l, both.toArray(), rootNames)
75 : new Standalone(out, l, rootNames);
77 final StringArray fixedNames = new StringArray();
79 for (final Class<?> fixedClass: FIXED_DEPENDENCIES) {
80 fixedNames.add(fixedClass.getName().replace('.', '/'));
83 vm.doCompile(fixedNames.addAndNew(both.toArray()));
86 private void doCompile(StringArray names) throws IOException {
89 "\n var invoker = function Invoker() {"
90 + "\n return Invoker.target[Invoker.method]"
91 + ".apply(Invoker.target, arguments);"
94 for (String invokerMethod: invokerMethods.toArray()) {
95 out.append("\n invoker." + invokerMethod + " = function(target) {"
96 + "\n invoker.target = target;"
97 + "\n invoker.method = '" + invokerMethod + "';"
98 + "\n return invoker;"
105 protected abstract void generatePrologue() throws IOException;
107 protected abstract void generateEpilogue() throws IOException;
109 protected abstract String getExportsObject();
111 protected abstract boolean isExternalClass(String className);
114 protected final void declaredClass(ClassData classData, String mangledName)
116 if (exportedSymbols.isExported(classData)) {
117 out.append("\n").append(getExportsObject()).append("['")
120 .append(accessClass(mangledName))
125 protected String generateClass(String className) throws IOException {
126 ClassData classData = classDataCache.getClassData(className);
127 if (classData == null) {
128 throw new IOException("Can't find class " + className);
130 return compile(classData);
134 protected void declaredField(FieldData fieldData,
136 String mangledName) throws IOException {
137 if (exportedSymbols.isExported(fieldData)) {
138 exportMember(destObject, mangledName);
143 protected void declaredMethod(MethodData methodData,
145 String mangledName) throws IOException {
146 if (isHierarchyExported(methodData)) {
147 exportMember(destObject, mangledName);
151 private void exportMember(String destObject, String memberName)
153 out.append("\n").append(destObject).append("['")
156 .append(destObject).append(".").append(memberName)
160 private void generateBody(StringArray names) throws IOException {
161 StringArray processed = new StringArray();
162 StringArray initCode = new StringArray();
163 for (String baseClass : names.toArray()) {
164 references.add(baseClass);
167 for (String n : references.toArray()) {
168 if (processed.contains(n)) {
178 String ic = generateClass(name);
180 initCode.add(ic == null ? "" : ic);
181 } catch (RuntimeException ex) {
182 if (out instanceof CharSequence) {
183 CharSequence seq = (CharSequence)out;
184 int lastBlock = seq.length();
185 while (lastBlock-- > 0) {
186 if (seq.charAt(lastBlock) == '{') {
190 throw new IOException("Error while compiling " + name + "\n"
191 + seq.subSequence(lastBlock + 1, seq.length()), ex
194 throw new IOException("Error while compiling " + name + "\n"
201 for (String resource : scripts.toArray()) {
202 while (resource.startsWith("/")) {
203 resource = resource.substring(1);
205 InputStream emul = resources.get(resource);
207 throw new IOException("Can't find " + resource);
209 readResource(emul, out);
211 scripts = new StringArray();
213 StringArray toInit = StringArray.asList(references.toArray());
216 for (String ic : toInit.toArray()) {
217 int indx = processed.indexOf(ic);
219 final String theCode = initCode.toArray()[indx];
220 if (!theCode.isEmpty()) {
221 out.append(theCode).append("\n");
223 initCode.toArray()[indx] = "";
229 private static void readResource(InputStream emul, Appendable out) throws IOException {
233 int ch = emul.read();
237 if (ch < 0 || ch > 255) {
238 throw new IOException("Invalid char in emulation " + ch);
245 out.append((char)ch);
252 out.append('/').append((char)ch);
275 static String toString(String name) throws IOException {
276 StringBuilder sb = new StringBuilder();
277 // compile(sb, name);
278 return sb.toString().toString();
281 private StringArray scripts = new StringArray();
282 private StringArray references = new StringArray();
285 protected boolean requireReference(String cn) {
286 if (references.contains(cn)) {
294 protected void requireScript(String resourcePath) {
295 scripts.add(resourcePath);
299 String assignClass(String className) {
300 return "vm." + className + " = ";
304 String accessClass(String className) {
305 return "vm." + className;
309 protected String accessField(String object, String mangledName,
310 String[] fieldInfoName) throws IOException {
311 final FieldData field =
312 classDataCache.findField(fieldInfoName[0],
315 return accessNonVirtualMember(object, mangledName,
316 (field != null) ? field.cls : null);
320 protected String accessStaticMethod(
323 String[] fieldInfoName) throws IOException {
324 final MethodData method =
325 classDataCache.findMethod(fieldInfoName[0],
328 return accessNonVirtualMember(object, mangledName,
329 (method != null) ? method.cls : null);
333 protected String accessVirtualMethod(
336 String[] fieldInfoName) throws IOException {
337 final ClassData referencedClass =
338 classDataCache.getClassData(fieldInfoName[0]);
339 final MethodData method =
340 classDataCache.findMethod(referencedClass,
345 && !isExternalClass(method.cls.getClassName())
346 && (((method.access & ByteCodeParser.ACC_FINAL) != 0)
347 || ((referencedClass.getAccessFlags()
348 & ByteCodeParser.ACC_FINAL) != 0)
349 || !isHierarchyExported(method))) {
350 return object + "." + mangledName;
353 return accessThroughInvoker(object, mangledName);
356 private String accessThroughInvoker(String object, String mangledName) {
357 if (!invokerMethods.contains(mangledName)) {
358 invokerMethods.add(mangledName);
360 return "invoker." + mangledName + '(' + object + ')';
363 private boolean isHierarchyExported(final MethodData methodData)
365 if (exportedSymbols.isExported(methodData)) {
368 if ((methodData.access & (ByteCodeParser.ACC_PRIVATE
369 | ByteCodeParser.ACC_STATIC)) != 0) {
373 final ExportedMethodFinder exportedMethodFinder =
374 new ExportedMethodFinder(exportedSymbols);
376 classDataCache.findMethods(
378 methodData.getName(),
379 methodData.getInternalSig(),
380 exportedMethodFinder);
382 return (exportedMethodFinder.getFound() != null);
385 private String accessNonVirtualMember(String object,
387 ClassData declaringClass) {
388 return ((declaringClass != null)
389 && !isExternalClass(declaringClass.getClassName()))
390 ? object + "." + mangledName
391 : object + "['" + mangledName + "']";
394 private static final class ExportedMethodFinder
395 implements ClassDataCache.TraversalCallback<MethodData> {
396 private final ExportedSymbols exportedSymbols;
397 private MethodData found;
399 public ExportedMethodFinder(final ExportedSymbols exportedSymbols) {
400 this.exportedSymbols = exportedSymbols;
404 public boolean traverse(final MethodData methodData) {
406 if (exportedSymbols.isExported(methodData)) {
410 } catch (final IOException e) {
416 public MethodData getFound() {
421 private static final class Standalone extends VM {
422 private Standalone(Appendable out, Bck2Brwsr.Resources resources, StringArray explicitlyExported) {
423 super(out, resources, explicitlyExported);
427 protected void generatePrologue() throws IOException {
428 out.append("(function VM(global) {var fillInVMSkeleton = function(vm) {");
432 protected void generateEpilogue() throws IOException {
436 + " var extensions = [];\n"
437 + " global.bck2brwsr = function() {\n"
438 + " var args = Array.prototype.slice.apply(arguments);\n"
439 + " var vm = fillInVMSkeleton({});\n"
440 + " for (var i = 0; i < extensions.length; ++i) {\n"
441 + " extensions[i](vm);\n"
443 + " var knownExtensions = extensions.length;\n"
444 + " var loader = {};\n"
445 + " loader.vm = vm;\n"
446 + " loader.loadClass = function(name) {\n"
447 + " var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
448 + " var fn = vm[attr];\n"
449 + " if (fn) return fn(false);\n"
451 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
452 + " load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
453 + " } catch (err) {\n"
454 + " while (knownExtensions < extensions.length) {\n"
455 + " extensions[knownExtensions++](vm);\n"
457 + " fn = vm[attr];\n"
458 + " if (fn) return fn(false);\n"
462 + " if (vm.loadClass) {\n"
463 + " throw 'Cannot initialize the bck2brwsr VM twice!';\n"
465 + " vm.loadClass = loader.loadClass;\n"
466 + " vm.loadBytes = function(name) {\n"
467 + " return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
468 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
470 + " vm.java_lang_reflect_Array(false);\n"
471 + " vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
472 + " loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\n"
473 + " return loader;\n"
476 " global.bck2brwsr.registerExtension = function(extension) {\n"
477 + " extensions.push(extension);\n"
480 out.append("}(this));");
484 protected String getExportsObject() {
489 protected boolean isExternalClass(String className) {
494 private static final class Extension extends VM {
495 private final StringArray extensionClasses;
497 private Extension(Appendable out, Bck2Brwsr.Resources resources,
498 String[] extClassesArray, StringArray explicitlyExported) {
499 super(out, resources, explicitlyExported);
500 this.extensionClasses = StringArray.asList(extClassesArray);
504 protected void generatePrologue() throws IOException {
505 out.append("bck2brwsr.registerExtension(function(exports) {\n"
506 + " var vm = {};\n");
507 out.append(" function link(n, inst) {\n"
508 + " var cls = n['replace__Ljava_lang_String_2CC']"
509 + "('/', '_').toString();\n"
510 + " var dot = n['replace__Ljava_lang_String_2CC']"
511 + "('/', '.').toString();\n"
512 + " exports.loadClass(dot);\n"
513 + " vm[cls] = exports[cls];\n"
514 + " return vm[cls](inst);\n"
519 protected void generateEpilogue() throws IOException {
524 protected String generateClass(String className) throws IOException {
525 if (isExternalClass(className)) {
526 out.append("\n").append(assignClass(
527 className.replace('/', '_')))
528 .append("function() {\n return link('")
530 .append("', arguments.length == 0 || arguments[0] === true);"
536 return super.generateClass(className);
540 protected String getExportsObject() {
545 protected boolean isExternalClass(String className) {
546 return !extensionClasses.contains(className);