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