rt/vm/src/main/java/org/apidesign/vm4brwsr/Bck2Brwsr.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 22 May 2014 10:48:09 +0200
branchclosure
changeset 1584 7b6295731c30
parent 1583 89b6b369c13d
child 1604 7665471a56c1
permissions -rw-r--r--
Static compilator demo is capable to load itself from individual extension files
     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 
    62     private Bck2Brwsr(
    63         ObfuscationLevel level, 
    64         StringArray exported, StringArray classes, StringArray resources, 
    65         Resources res, Boolean extension
    66     ) {
    67         this.level = level;
    68         this.exported = exported;
    69         this.classes = classes;
    70         this.resources = resources;
    71         this.res = res;
    72         this.extension = extension;
    73     }
    74     
    75     /** Helper method to generate virtual machine from bytes served by a <code>resources</code>
    76      * provider.
    77      *
    78      * @param out the output to write the generated JavaScript to
    79      * @param resources provider of class files to use
    80      * @param classes additional classes to include in the generated script
    81      * @throws IOException I/O exception can be thrown when something goes wrong
    82      */
    83     public static void generate(Appendable out, Resources resources, String... classes) throws IOException {
    84         newCompiler().resources(resources).addRootClasses(classes).generate(out);
    85     }
    86 
    87     /** Helper method to generate virtual machine from bytes served by a class loader.
    88      *
    89      * @param out the output to write the generated JavaScript to
    90      * @param loader class loader to load needed classes from
    91      * @param classes additional classes to include in the generated script
    92      * @throws IOException I/O exception can be thrown when something goes wrong
    93      */
    94     public static void generate(Appendable out, ClassLoader loader, String... classes) throws IOException {
    95         newCompiler().resources(loader).addRootClasses(classes).generate(out);
    96     }
    97     
    98     /** Creates new instance of Bck2Brwsr compiler which is ready to generate
    99      * empty Bck2Brwsr virtual machine. The instance can be further
   100      * configured by calling chain of methods. For example: 
   101      * <pre>
   102      * {@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)};
   103      * </pre>
   104      * 
   105      * @return new instance of the Bck2Brwsr compiler
   106      * @since 0.5
   107      */
   108     public static Bck2Brwsr newCompiler() {
   109         return new Bck2Brwsr(ObfuscationLevel.NONE, new StringArray(), new StringArray(), new StringArray(), null, false);
   110     }
   111     
   112     /** Adds exported classes or packages. If the string ends 
   113      * with slash, it is considered a name of package. If it does not,
   114      * it is a name of a class (without <code>.class</code> suffix).
   115      * The exported classes are prevented from being obfuscated. 
   116      * All public classes in exported packages are prevented from
   117      * being obfuscated. By listing the packages or classes in this 
   118      * method, these classes are not guaranteed to be included in
   119      * the generated script. Use {@link #addClasses} to include
   120      * the classes.
   121      * 
   122      * @param exported names of classes and packages to treat as exported
   123      * @return new instances of the Bck2Brwsr compiler which inherits
   124      *   all values from <code>this</code> except list of exported classes
   125      */
   126     public Bck2Brwsr addExported(String... exported) {
   127         return new Bck2Brwsr(
   128             level, this.exported.addAndNew(exported), 
   129             classes, resources, res, extension
   130         );
   131     }
   132 
   133     /** Adds additional classes 
   134      * to the list of those that should be included in the generated
   135      * JavaScript file.
   136      * These classes are guaranteed to be available in the
   137      * generated virtual machine code accessible using their fully 
   138      * qualified name. This brings the same behavior as if the
   139      * classes were added by {@link #addClasses(java.lang.String...) } and
   140      * exported via {@link #addExported(java.lang.String...)}.
   141      * 
   142      * @param classes the classes to add to the compilation
   143      * @return new instance of the Bck2Brwsr compiler which inherits
   144      * all values from <code>this</code>
   145      */
   146     public Bck2Brwsr addRootClasses(String... classes) {
   147         if (classes.length == 0) {
   148             return this;
   149         } 
   150         return addExported(classes).addClasses(classes);
   151     }
   152     
   153     /** Adds additional classes 
   154      * to the list of those that should be included in the generated
   155      * JavaScript file. These classes are guaranteed to be present,
   156      * but they may not be accessible through their fully qualified
   157      * name.
   158      * 
   159      * @param classes the classes to add to the compilation
   160      * @return new instance of the Bck2Brwsr compiler which inherits
   161      * all values from <code>this</code>
   162      * @since 0.9
   163      */
   164     public Bck2Brwsr addClasses(String... classes) {
   165         if (classes.length == 0) {
   166             return this;
   167         } else {
   168             return new Bck2Brwsr(level, exported, 
   169                 this.classes.addAndNew(classes), resources, res,
   170                 extension);
   171         }
   172     }
   173     
   174     /** These resources should be made available in the compiled file in
   175      * binary form. These resources can then be loaded
   176      * by {@link ClassLoader#getResource(java.lang.String)} and similar 
   177      * methods.
   178      * 
   179      * @param resources names of the resources to be loaded by {@link Resources#get(java.lang.String)}
   180      * @return new instance of the Bck2Brwsr compiler which inherits
   181      *   all values from <code>this</code> just adds few more resource names
   182      *   for processing
   183      * @since 0.9
   184      */
   185     public Bck2Brwsr addResources(String... resources) {
   186         if (resources.length == 0) {
   187             return this;
   188         } else {
   189             return new Bck2Brwsr(level, exported, this.classes, 
   190                 this.resources.addAndNew(resources), res, extension
   191             );
   192         }
   193     }
   194     
   195     /** Changes the obfuscation level for the compiler by creating new instance
   196      * which inherits all values from <code>this</code> and adjust the level
   197      * of obfuscation.
   198      * 
   199      * @param level the new level of obfuscation
   200      * @return new instance of the compiler with changed level of obfuscation
   201      * @since 0.5
   202      */
   203     public Bck2Brwsr obfuscation(ObfuscationLevel level) {
   204         return new Bck2Brwsr(level, exported, classes, resources, res, extension);
   205     }
   206     
   207     /** A way to change the provider of additional resources (classes) for the 
   208      * compiler. 
   209      * 
   210      * @param res the implementation of resources provider
   211      * @return new instance of the compiler with all values remaining the same, just 
   212      *   with different resources provider
   213      * @since 0.5
   214      */
   215     public Bck2Brwsr resources(Resources res) {
   216         return new Bck2Brwsr(level, exported, classes, resources, res, extension);
   217     }
   218 
   219     /** Should one generate a library? By default the system generates
   220      * all transitive classes needed by the the transitive closure of
   221      * {@link #addRootClasses(java.lang.String...)} and {@link #addClasses(java.lang.String...)}.
   222      * By turning on the library mode, only classes explicitly listed
   223      * will be included in the archive. The others will be referenced
   224      * as external ones.
   225      * 
   226      * @param library turn on the library mode?
   227      * @return new instance of the compiler with library flag changed
   228      * @since 0.9
   229      */
   230     public Bck2Brwsr library(boolean library) {
   231         return new Bck2Brwsr(level, exported, classes, resources, res, library);
   232     }
   233     
   234     /** Turns on the standalone mode. E.g. acts like {@link #library(boolean) library(false)},
   235      * but also allows to specify whether the <em>Bck2Brwsr VM</em> should
   236      * be included at all. If not, only the skeleton of the launcher is
   237      * generated without any additional VM classes referenced.
   238      * 
   239      * @param includeVM should the VM be compiled in, or left out
   240      * @return new instance of the compiler with standalone mode on
   241      * @since 0.9
   242      */
   243     public Bck2Brwsr standalone(boolean includeVM) {
   244         return new Bck2Brwsr(level, exported, classes, resources, res, includeVM ? false : null);
   245     }
   246 
   247     /** A way to change the provider of additional resources (classes) for the 
   248      * compiler by specifying classloader to use for loading them.
   249      * 
   250      * @param loader class loader to load the resources from
   251      * @return new instance of the compiler with all values being the same, just 
   252      *   different resources provider
   253      * @since 0.5
   254      */
   255     public Bck2Brwsr resources(final ClassLoader loader) {
   256         return resources(loader, false);
   257     }
   258 
   259     /** A way to change the provider of additional resources (classes) for the 
   260      * compiler by specifying classloader to use for loading them.
   261      * 
   262      * @param loader class loader to load the resources from
   263      * @param ignoreBootClassPath <code>true</code> if classes loaded
   264      *    from <code>rt.jar</code> 
   265      * @return new instance of the compiler with all values being the same, just 
   266      *   different resources provider
   267      * @since 0.9
   268      */
   269     public Bck2Brwsr resources(final ClassLoader loader, boolean ignoreBootClassPath) {
   270         return resources(new LdrRsrcs(loader, ignoreBootClassPath));
   271     }
   272     
   273     /** Generates virtual machine based on previous configuration of the 
   274      * compiler.
   275      * 
   276      * @param out the output to write the generated JavaScript to
   277      * @since 0.5
   278      */
   279     public void generate(Appendable out) throws IOException {
   280         if (level != ObfuscationLevel.NONE) {
   281             try {
   282                 ClosureWrapper.produceTo(out, level, this);
   283                 return;
   284             } catch (IOException ex) {
   285                 throw ex;
   286             } catch (Throwable ex) {
   287                 out.append("/* Failed to obfuscate: " + ex.getMessage()
   288                                + " */\n");
   289             }
   290         }
   291 
   292         VM.compile(out, this);
   293     }
   294     
   295     //
   296     // Internal getters
   297     // 
   298     
   299     Resources getResources() {
   300         return res != null ? res : new LdrRsrcs(Bck2Brwsr.class.getClassLoader(), false);
   301     }
   302     
   303     StringArray allResources() {
   304         return resources;
   305     }
   306 
   307     StringArray classes() {
   308         return classes;
   309     }
   310 
   311     StringArray exported() {
   312         return exported;
   313     }
   314     
   315     boolean isExtension() {
   316         return Boolean.TRUE.equals(extension);
   317     }
   318     
   319     boolean includeVM() {
   320         return extension != null;
   321     }
   322 
   323     /** Provider of resources (classes and other files). The 
   324      * {@link #generate(java.lang.Appendable, org.apidesign.vm4brwsr.Bck2Brwsr.Resources, java.lang.String[]) 
   325      * generator method} will call back here for all classes needed during
   326      * translation to JavaScript.
   327      */
   328     public interface Resources {
   329         /** Loads given resource (class or other file like image). The 
   330          * resource name to load bytes for the {@link String} class
   331          * would be <code>"java/lang/String.class"</code>.
   332          * 
   333          * @param resource path to resource to load
   334          * @return the input stream for the resource 
   335          * @throws IOException can be thrown if the loading fails on some error
   336          *   or the file cannot be found
   337          */
   338         public InputStream get(String resource) throws IOException;
   339     }
   340 }