rt/vm/src/main/java/org/apidesign/vm4brwsr/Bck2Brwsr.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 28 May 2014 09:07:48 +0200
branchclosure
changeset 1608 5186733b7e07
parent 1584 7b6295731c30
child 1609 752f48257d4a
permissions -rw-r--r--
Load scripts asynchronously
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     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.
     8  *
     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.
    13  *
    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.
    17  */
    18 package org.apidesign.vm4brwsr;
    19 
    20 import java.io.IOException;
    21 import java.io.InputStream;
    22 
    23 /** Build your own virtual machine! Use methods in this class to generate
    24  * a skeleton JVM in JavaScript that contains pre-compiled classes of your
    25  * choice. The generated script defines one JavaScript method that can
    26  * be used to bootstrap and load the virtual machine: <pre>
    27  * var vm = bck2brwsr();
    28  * var main = vm.loadClass('org.your.pkg.Main');
    29  * main.main__V_3Ljava_lang_String_2(null);
    30  * </pre>
    31  * In case one wants to initialize the virtual machine with ability to
    32  * load classes lazily when needed, one can provide a loader function to
    33  * when creating the virtual machine: <pre>
    34  * var vm = bck2brwsr(function(resource) { 
    35  *   return null; // byte[] for the resource
    36  * });
    37  * </pre>
    38  * In this scenario, when a request for an unknown class is made, the loader
    39  * function is asked for its byte code and the system dynamically transforms
    40  * it to JavaScript.
    41  * <p>
    42  * Instead of a loader function, one can also provide a URL to a JAR file.
    43  * The <code>bck2brwsr</code> system will do its best to download the file
    44  * and provide loader function for it automatically.
    45  * <p>
    46  * One can provide as many loader functions and JAR URL references as necessary.
    47  * Then the initialization code would look like:<pre>
    48  * var vm = bck2brwsr(url1, url2, fnctn1, url3, functn2);
    49  * </pre>
    50  * The provided URLs and loader functions will be consulted one by one.
    51  *
    52  * @author Jaroslav Tulach <jtulach@netbeans.org>
    53  */
    54 public final class Bck2Brwsr {
    55     private final ObfuscationLevel level;
    56     private final StringArray exported;
    57     private final StringArray classes;
    58     private final StringArray resources;
    59     private final Resources res;
    60     private final Boolean extension;
    61     private final StringArray classpath;
    62 
    63     private Bck2Brwsr(
    64             ObfuscationLevel level, 
    65             StringArray exported, StringArray classes, StringArray resources, 
    66             Resources res, 
    67             Boolean extension, StringArray classpath
    68     ) {
    69         this.level = level;
    70         this.exported = exported;
    71         this.classes = classes;
    72         this.resources = resources;
    73         this.res = res;
    74         this.extension = extension;
    75         this.classpath = classpath;
    76     }
    77     
    78     /** Helper method to generate virtual machine from bytes served by a <code>resources</code>
    79      * provider.
    80      *
    81      * @param out the output to write the generated JavaScript to
    82      * @param resources provider of class files to use
    83      * @param classes additional classes to include in the generated script
    84      * @throws IOException I/O exception can be thrown when something goes wrong
    85      */
    86     public static void generate(Appendable out, Resources resources, String... classes) throws IOException {
    87         newCompiler().resources(resources).addRootClasses(classes).generate(out);
    88     }
    89 
    90     /** Helper method to generate virtual machine from bytes served by a class loader.
    91      *
    92      * @param out the output to write the generated JavaScript to
    93      * @param loader class loader to load needed classes from
    94      * @param classes additional classes to include in the generated script
    95      * @throws IOException I/O exception can be thrown when something goes wrong
    96      */
    97     public static void generate(Appendable out, ClassLoader loader, String... classes) throws IOException {
    98         newCompiler().resources(loader).addRootClasses(classes).generate(out);
    99     }
   100     
   101     /** Creates new instance of Bck2Brwsr compiler which is ready to generate
   102      * empty Bck2Brwsr virtual machine. The instance can be further
   103      * configured by calling chain of methods. For example: 
   104      * <pre>
   105      * {@link #createCompiler()}.{@link #resources(org.apidesign.vm4brwsr.Bck2Brwsr.Resources) resources(loader)}.{@link #addRootClasses(java.lang.String[]) addRootClasses("your/Clazz")}.{@link #generate(java.lang.Appendable) generate(out)};
   106      * </pre>
   107      * 
   108      * @return new instance of the Bck2Brwsr compiler
   109      * @since 0.5
   110      */
   111     public static Bck2Brwsr newCompiler() {
   112         return new Bck2Brwsr(
   113             ObfuscationLevel.NONE, 
   114             new StringArray(), new StringArray(), new StringArray(), 
   115             null, false, null
   116         );
   117     }
   118     
   119     /** Adds exported classes or packages. If the string ends 
   120      * with slash, it is considered a name of package. If it does not,
   121      * it is a name of a class (without <code>.class</code> suffix).
   122      * The exported classes are prevented from being obfuscated. 
   123      * All public classes in exported packages are prevented from
   124      * being obfuscated. By listing the packages or classes in this 
   125      * method, these classes are not guaranteed to be included in
   126      * the generated script. Use {@link #addClasses} to include
   127      * the classes.
   128      * 
   129      * @param exported names of classes and packages to treat as exported
   130      * @return new instances of the Bck2Brwsr compiler which inherits
   131      *   all values from <code>this</code> except list of exported classes
   132      */
   133     public Bck2Brwsr addExported(String... exported) {
   134         return new Bck2Brwsr(
   135             level, this.exported.addAndNew(exported), 
   136             classes, resources, res, extension, classpath
   137         );
   138     }
   139 
   140     /** Adds additional classes 
   141      * to the list of those that should be included in the generated
   142      * JavaScript file.
   143      * These classes are guaranteed to be available in the
   144      * generated virtual machine code accessible using their fully 
   145      * qualified name. This brings the same behavior as if the
   146      * classes were added by {@link #addClasses(java.lang.String...) } and
   147      * exported via {@link #addExported(java.lang.String...)}.
   148      * 
   149      * @param classes the classes to add to the compilation
   150      * @return new instance of the Bck2Brwsr compiler which inherits
   151      * all values from <code>this</code>
   152      */
   153     public Bck2Brwsr addRootClasses(String... classes) {
   154         if (classes.length == 0) {
   155             return this;
   156         } 
   157         return addExported(classes).addClasses(classes);
   158     }
   159     
   160     /** Adds additional classes 
   161      * to the list of those that should be included in the generated
   162      * JavaScript file. These classes are guaranteed to be present,
   163      * but they may not be accessible through their fully qualified
   164      * name.
   165      * 
   166      * @param classes the classes to add to the compilation
   167      * @return new instance of the Bck2Brwsr compiler which inherits
   168      * all values from <code>this</code>
   169      * @since 0.9
   170      */
   171     public Bck2Brwsr addClasses(String... classes) {
   172         if (classes.length == 0) {
   173             return this;
   174         } else {
   175             return new Bck2Brwsr(level, exported, 
   176                 this.classes.addAndNew(classes), resources, res,
   177                 extension, classpath);
   178         }
   179     }
   180     
   181     /** These resources should be made available in the compiled file in
   182      * binary form. These resources can then be loaded
   183      * by {@link ClassLoader#getResource(java.lang.String)} and similar 
   184      * methods.
   185      * 
   186      * @param resources names of the resources to be loaded by {@link Resources#get(java.lang.String)}
   187      * @return new instance of the Bck2Brwsr compiler which inherits
   188      *   all values from <code>this</code> just adds few more resource names
   189      *   for processing
   190      * @since 0.9
   191      */
   192     public Bck2Brwsr addResources(String... resources) {
   193         if (resources.length == 0) {
   194             return this;
   195         } else {
   196             return new Bck2Brwsr(level, exported, this.classes, 
   197                 this.resources.addAndNew(resources), res, extension, classpath
   198             );
   199         }
   200     }
   201     
   202     /** Changes the obfuscation level for the compiler by creating new instance
   203      * which inherits all values from <code>this</code> and adjust the level
   204      * of obfuscation.
   205      * 
   206      * @param level the new level of obfuscation
   207      * @return new instance of the compiler with changed level of obfuscation
   208      * @since 0.5
   209      */
   210     public Bck2Brwsr obfuscation(ObfuscationLevel level) {
   211         return new Bck2Brwsr(level, exported, classes, resources, res, extension, classpath);
   212     }
   213     
   214     /** A way to change the provider of additional resources (classes) for the 
   215      * compiler. 
   216      * 
   217      * @param res the implementation of resources provider
   218      * @return new instance of the compiler with all values remaining the same, just 
   219      *   with different resources provider
   220      * @since 0.5
   221      */
   222     public Bck2Brwsr resources(Resources res) {
   223         return new Bck2Brwsr(
   224             level, exported, classes, resources, 
   225             res, extension, classpath
   226         );
   227     }
   228 
   229     /** Should one generate a library? By default the system generates
   230      * all transitive classes needed by the the transitive closure of
   231      * {@link #addRootClasses(java.lang.String...)} and {@link #addClasses(java.lang.String...)}.
   232      * By turning on the library mode, only classes explicitly listed
   233      * will be included in the archive. The others will be referenced
   234      * as external ones.
   235      * <p>
   236      * A library archive may specify its <em>classpath</em> - e.g. link to
   237      * other libraries that should also be included in the application. 
   238      * One can specify the list of libraries as vararg to this method.
   239      * These are relative URL with respect to location of this library.
   240      * The runtime system then prefers seek for ".js" suffix of the library
   241      * and only then seeks for the classical ".jar" path.
   242      * 
   243      * @param classpath the array of JARs that are referenced by this library -
   244      *   by default gets turned into 
   245      * @return new instance of the compiler with library flag changed
   246      * @since 0.9
   247      */
   248     public Bck2Brwsr library(String... classpath) {
   249         return new Bck2Brwsr(
   250             level, exported, classes, 
   251             resources, res, true, 
   252             StringArray.asList(classpath)
   253         );
   254     }
   255     
   256     /** Turns on the standalone mode. E.g. acts like {@link #library(boolean) library(false)},
   257      * but also allows to specify whether the <em>Bck2Brwsr VM</em> should
   258      * be included at all. If not, only the skeleton of the launcher is
   259      * generated without any additional VM classes referenced.
   260      * 
   261      * @param includeVM should the VM be compiled in, or left out
   262      * @return new instance of the compiler with standalone mode on
   263      * @since 0.9
   264      */
   265     public Bck2Brwsr standalone(boolean includeVM) {
   266         return new Bck2Brwsr(
   267             level, exported, classes, resources, 
   268             res, includeVM ? false : null, null
   269         );
   270     }
   271 
   272     /** A way to change the provider of additional resources (classes) for the 
   273      * compiler by specifying classloader to use for loading them.
   274      * 
   275      * @param loader class loader to load the resources from
   276      * @return new instance of the compiler with all values being the same, just 
   277      *   different resources provider
   278      * @since 0.5
   279      */
   280     public Bck2Brwsr resources(final ClassLoader loader) {
   281         return resources(loader, false);
   282     }
   283 
   284     /** A way to change the provider of additional resources (classes) for the 
   285      * compiler by specifying classloader to use for loading them.
   286      * 
   287      * @param loader class loader to load the resources from
   288      * @param ignoreBootClassPath <code>true</code> if classes loaded
   289      *    from <code>rt.jar</code> 
   290      * @return new instance of the compiler with all values being the same, just 
   291      *   different resources provider
   292      * @since 0.9
   293      */
   294     public Bck2Brwsr resources(final ClassLoader loader, boolean ignoreBootClassPath) {
   295         return resources(new LdrRsrcs(loader, ignoreBootClassPath));
   296     }
   297     
   298     /** Generates virtual machine based on previous configuration of the 
   299      * compiler.
   300      * 
   301      * @param out the output to write the generated JavaScript to
   302      * @since 0.5
   303      */
   304     public void generate(Appendable out) throws IOException {
   305         if (level != ObfuscationLevel.NONE) {
   306             try {
   307                 ClosureWrapper.produceTo(out, level, this);
   308                 return;
   309             } catch (IOException ex) {
   310                 throw ex;
   311             } catch (Throwable ex) {
   312                 out.append("/* Failed to obfuscate: " + ex.getMessage()
   313                                + " */\n");
   314             }
   315         }
   316 
   317         VM.compile(out, this);
   318     }
   319     
   320     //
   321     // Internal getters
   322     // 
   323     
   324     Resources getResources() {
   325         return res != null ? res : new LdrRsrcs(Bck2Brwsr.class.getClassLoader(), false);
   326     }
   327     
   328     StringArray allResources() {
   329         return resources;
   330     }
   331 
   332     StringArray classes() {
   333         return classes;
   334     }
   335 
   336     StringArray exported() {
   337         return exported;
   338     }
   339     
   340     boolean isExtension() {
   341         return Boolean.TRUE.equals(extension);
   342     }
   343     
   344     boolean includeVM() {
   345         return extension != null;
   346     }
   347     
   348     StringArray classpath() {
   349         return classpath;
   350     }
   351 
   352     /** Provider of resources (classes and other files). The 
   353      * {@link #generate(java.lang.Appendable, org.apidesign.vm4brwsr.Bck2Brwsr.Resources, java.lang.String[]) 
   354      * generator method} will call back here for all classes needed during
   355      * translation to JavaScript.
   356      */
   357     public interface Resources {
   358         /** Loads given resource (class or other file like image). The 
   359          * resource name to load bytes for the {@link String} class
   360          * would be <code>"java/lang/String.class"</code>.
   361          * 
   362          * @param resource path to resource to load
   363          * @return the input stream for the resource 
   364          * @throws IOException can be thrown if the loading fails on some error
   365          *   or the file cannot be found
   366          */
   367         public InputStream get(String resource) throws IOException;
   368     }
   369 }