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