rt/vm/src/main/java/org/apidesign/vm4brwsr/Bck2Brwsr.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 27 Apr 2014 22:40:17 +0200
branchclosure
changeset 1493 234fea368401
parent 1491 4a1398eff4fb
child 1495 d5dd07b45f79
permissions -rw-r--r--
Initial infrastructure to export resources
     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 import org.apidesign.bck2brwsr.core.Exported;
    23 
    24 /** Build your own virtual machine! Use methods in this class to generate
    25  * a skeleton JVM in JavaScript that contains pre-compiled classes of your
    26  * choice. The generated script defines one JavaScript method that can
    27  * be used to bootstrap and load the virtual machine: <pre>
    28  * var vm = bck2brwsr();
    29  * var main = vm.loadClass('org.your.pkg.Main');
    30  * main.main__V_3Ljava_lang_String_2(null);
    31  * </pre>
    32  * In case one wants to initialize the virtual machine with ability to
    33  * load classes lazily when needed, one can provide a loader function to
    34  * when creating the virtual machine: <pre>
    35  * var vm = bck2brwsr(function(resource) { 
    36  *   return null; // byte[] for the resource
    37  * });
    38  * </pre>
    39  * In this scenario, when a request for an unknown class is made, the loader
    40  * function is asked for its byte code and the system dynamically transforms
    41  * it to JavaScript.
    42  * <p>
    43  * Instead of a loader function, one can also provide a URL to a JAR file.
    44  * The <code>bck2brwsr</code> system will do its best to download the file
    45  * and provide loader function for it automatically.
    46  * <p>
    47  * One can provide as many loader functions and JAR URL references as necessary.
    48  * Then the initialization code would look like:<pre>
    49  * var vm = bck2brwsr(url1, url2, fnctn1, url3, functn2);
    50  * </pre>
    51  * The provided URLs and loader functions will be consulted one by one.
    52  *
    53  * @author Jaroslav Tulach <jtulach@netbeans.org>
    54  */
    55 public final class Bck2Brwsr {
    56     private final ObfuscationLevel level;
    57     private final StringArray rootcls;
    58     private final StringArray classes;
    59     private final StringArray resources;
    60     private final Resources res;
    61     private final boolean extension;
    62 
    63     private Bck2Brwsr(ObfuscationLevel level, StringArray rootcls, StringArray classes, StringArray resources, Resources res, boolean extension) {
    64         this.level = level;
    65         this.rootcls = rootcls;
    66         this.classes = classes;
    67         this.resources = resources;
    68         this.res = res;
    69         this.extension = extension;
    70     }
    71     
    72     /** Helper method to generate virtual machine from bytes served by a <code>resources</code>
    73      * provider.
    74      *
    75      * @param out the output to write the generated JavaScript to
    76      * @param resources provider of class files to use
    77      * @param classes additional classes to include in the generated script
    78      * @throws IOException I/O exception can be thrown when something goes wrong
    79      */
    80     public static void generate(Appendable out, Resources resources, String... classes) throws IOException {
    81         newCompiler().resources(resources).addRootClasses(classes).generate(out);
    82     }
    83 
    84     /** Helper method to generate virtual machine from bytes served by a class loader.
    85      *
    86      * @param out the output to write the generated JavaScript to
    87      * @param loader class loader to load needed classes from
    88      * @param classes additional classes to include in the generated script
    89      * @throws IOException I/O exception can be thrown when something goes wrong
    90      */
    91     public static void generate(Appendable out, ClassLoader loader, String... classes) throws IOException {
    92         newCompiler().resources(loader).addRootClasses(classes).generate(out);
    93     }
    94     
    95     /** Creates new instance of Bck2Brwsr compiler which is ready to generate
    96      * empty Bck2Brwsr virtual machine. The instance can be further
    97      * configured by calling chain of methods. For example: 
    98      * <pre>
    99      * {@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)};
   100      * </pre>
   101      * 
   102      * @return new instance of the Bck2Brwsr compiler
   103      * @since 0.5
   104      */
   105     public static Bck2Brwsr newCompiler() {
   106         return new Bck2Brwsr(ObfuscationLevel.NONE, new StringArray(), new StringArray(), new StringArray(), null, false);
   107     }
   108 
   109     /** Adds additional classes 
   110      * to the list of those that should be included in the generated
   111      * JavaScript file.
   112      * These classes are guaranteed to be available in the
   113      * generated virtual machine code accessible using their fully 
   114      * qualified name. This brings the same behavior as if the
   115      * classes were added by {@link #addClasses(java.lang.String...) } and
   116      * were annotated with {@link Exported} annotation.
   117      * 
   118      * @param classes the classes to add to the compilation
   119      * @return new instance of the Bck2Brwsr compiler which inherits
   120      * all values from <code>this</code>
   121      */
   122     public Bck2Brwsr addRootClasses(String... classes) {
   123         if (classes.length == 0) {
   124             return this;
   125         } else {
   126             return new Bck2Brwsr(level, rootcls.addAndNew(classes), this.classes, resources, res,
   127                                  extension);
   128         }
   129     }
   130     
   131     /** Adds additional classes 
   132      * to the list of those that should be included in the generated
   133      * JavaScript file. These classes are guaranteed to be present,
   134      * but they may not be accessible through their fully qualified
   135      * name.
   136      * 
   137      * @param classes the classes to add to the compilation
   138      * @return new instance of the Bck2Brwsr compiler which inherits
   139      * all values from <code>this</code>
   140      * @since 0.9
   141      */
   142     public Bck2Brwsr addClasses(String... classes) {
   143         if (classes.length == 0) {
   144             return this;
   145         } else {
   146             return new Bck2Brwsr(level, rootcls, this.classes.addAndNew(classes), resources, res,
   147                 extension);
   148         }
   149     }
   150     
   151     /** These resources should be made available in the compiled file in
   152      * binary form. These resources can then be loaded
   153      * by {@link ClassLoader#getResource(java.lang.String)} and similar 
   154      * methods.
   155      * 
   156      * @param resources names of the resources to be loaded by {@link Resources#get(java.lang.String)}
   157      * @return new instance of the Bck2Brwsr compiler which inherits
   158      *   all values from <code>this</code> just adds few more resource names
   159      *   for processing
   160      * @since 0.9
   161      */
   162     public Bck2Brwsr addResources(String... resources) {
   163         if (resources.length == 0) {
   164             return this;
   165         } else {
   166             return new Bck2Brwsr(level, rootcls, this.classes, 
   167                 this.resources.addAndNew(resources), res, extension
   168             );
   169         }
   170     }
   171     
   172     /** Changes the obfuscation level for the compiler by creating new instance
   173      * which inherits all values from <code>this</code> and adjust the level
   174      * of obfuscation.
   175      * 
   176      * @param level the new level of obfuscation
   177      * @return new instance of the compiler with changed level of obfuscation
   178      * @since 0.5
   179      */
   180     public Bck2Brwsr obfuscation(ObfuscationLevel level) {
   181         return new Bck2Brwsr(level, rootcls, classes, resources, res, extension);
   182     }
   183     
   184     /** A way to change the provider of additional resources (classes) for the 
   185      * compiler. 
   186      * 
   187      * @param res the implementation of resources provider
   188      * @return new instance of the compiler with all values remaining the same, just 
   189      *   with different resources provider
   190      * @since 0.5
   191      */
   192     public Bck2Brwsr resources(Resources res) {
   193         return new Bck2Brwsr(level, rootcls, classes, resources, res, extension);
   194     }
   195 
   196     /** Should one generate a library? By default the system generates
   197      * all transitive classes needed by the the transitive closure of
   198      * {@link #addRootClasses(java.lang.String...)} and {@link #addClasses(java.lang.String...)}.
   199      * By turning on the library mode, only classes explicitly listed
   200      * will be included in the archive. The others will be referenced
   201      * as external ones.
   202      * 
   203      * @param library turn on the library mode?
   204      * @return new instance of the compiler with library flag changed
   205      * @since 0.9
   206      */
   207     public Bck2Brwsr library(boolean library) {
   208         return new Bck2Brwsr(level, rootcls, classes, resources, res, library);
   209     }
   210 
   211     /** A way to change the provider of additional resources (classes) for the 
   212      * compiler by specifying classloader to use for loading them.
   213      * 
   214      * @param loader class loader to load the resources from
   215      * @return new instance of the compiler with all values being the same, just 
   216      *   different resources provider
   217      * @since 0.5
   218      */
   219     public Bck2Brwsr resources(final ClassLoader loader) {
   220         return resources(new LdrRsrcs(loader));
   221     }
   222     
   223     /** Generates virtual machine based on previous configuration of the 
   224      * compiler.
   225      * 
   226      * @param out the output to write the generated JavaScript to
   227      * @since 0.5
   228      */
   229     public void generate(Appendable out) throws IOException {
   230         if (level != ObfuscationLevel.NONE) {
   231             try {
   232                 ClosureWrapper.produceTo(out, level, this);
   233                 return;
   234             } catch (IOException ex) {
   235                 throw ex;
   236             } catch (Throwable ex) {
   237                 out.append("/* Failed to obfuscate: " + ex.getMessage()
   238                                + " */\n");
   239             }
   240         }
   241 
   242         VM.compile(out, this);
   243     }
   244     
   245     //
   246     // Internal getters
   247     // 
   248     
   249     Resources getResources() {
   250         return res != null ? res : new LdrRsrcs(Bck2Brwsr.class.getClassLoader());
   251     }
   252     
   253     String[] allClasses() {
   254         return classes.addAndNew(rootcls.toArray()).toArray();
   255     }
   256     
   257     StringArray rootClasses() {
   258         return rootcls;
   259     }
   260     
   261     boolean isExtension() {
   262         return extension;
   263     }
   264 
   265     /** Provider of resources (classes and other files). The 
   266      * {@link #generate(java.lang.Appendable, org.apidesign.vm4brwsr.Bck2Brwsr.Resources, java.lang.String[]) 
   267      * generator method} will call back here for all classes needed during
   268      * translation to JavaScript.
   269      */
   270     public interface Resources {
   271         /** Loads given resource (class or other file like image). The 
   272          * resource name to load bytes for the {@link String} class
   273          * would be <code>"java/lang/String.class"</code>.
   274          * 
   275          * @param resource path to resource to load
   276          * @return the input stream for the resource 
   277          * @throws IOException can be thrown if the loading fails on some error
   278          *   or the file cannot be found
   279          */
   280         public InputStream get(String resource) throws IOException;
   281     }
   282 }