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