rt/vm/src/main/java/org/apidesign/vm4brwsr/Bck2Brwsr.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 11 Mar 2015 18:58:39 +0100
branchflow
changeset 1812 4fef6b767f61
parent 1787 ea12a3bb4b33
child 1813 5c30fa1c8c5b
permissions -rw-r--r--
Defining API for registration of a Flow.Analyzer and getting ready for use the one from Graal
     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 
    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     private final Flow.Analyzer flow;
    86 
    87     private Bck2Brwsr(
    88         ObfuscationLevel level, StringArray exported,
    89         StringArray classes, StringArray resources, Resources res,
    90         Boolean extension, StringArray classpath, Flow.Analyzer flow
    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         this.flow = flow;
   100     }
   101     
   102     /** Helper method to generate virtual machine from bytes served by a <code>resources</code>
   103      * provider.
   104      *
   105      * @param out the output to write the generated JavaScript to
   106      * @param resources provider of class files to use
   107      * @param classes additional classes to include in the generated script
   108      * @throws IOException I/O exception can be thrown when something goes wrong
   109      */
   110     public static void generate(Appendable out, Resources resources, String... classes) throws IOException {
   111         newCompiler().resources(resources).addRootClasses(classes).generate(out);
   112     }
   113 
   114     /** Helper method to generate virtual machine from bytes served by a class loader.
   115      *
   116      * @param out the output to write the generated JavaScript to
   117      * @param loader class loader to load needed classes from
   118      * @param classes additional classes to include in the generated script
   119      * @throws IOException I/O exception can be thrown when something goes wrong
   120      */
   121     public static void generate(Appendable out, ClassLoader loader, String... classes) throws IOException {
   122         newCompiler().resources(loader).addRootClasses(classes).generate(out);
   123     }
   124     
   125     /** Creates new instance of Bck2Brwsr compiler which is ready to generate
   126      * empty Bck2Brwsr virtual machine. The instance can be further
   127      * configured by calling chain of methods. For example: 
   128      * <pre>
   129      * {@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)};
   130      * </pre>
   131      * 
   132      * @return new instance of the Bck2Brwsr compiler
   133      * @since 0.5
   134      */
   135     public static Bck2Brwsr newCompiler() {
   136         return new Bck2Brwsr(
   137             ObfuscationLevel.NONE, 
   138             new StringArray(), new StringArray(), new StringArray(), 
   139             null, false, null, null
   140         );
   141     }
   142     
   143     /** Adds exported classes or packages. If the string ends 
   144      * with slash, it is considered a name of package. If it does not,
   145      * it is a name of a class (without <code>.class</code> suffix).
   146      * The exported classes are prevented from being obfuscated. 
   147      * All public classes in exported packages are prevented from
   148      * being obfuscated. By listing the packages or classes in this 
   149      * method, these classes are not guaranteed to be included in
   150      * the generated script. Use {@link #addClasses} to include
   151      * the classes.
   152      * 
   153      * @param exported names of classes and packages to treat as exported
   154      * @return new instances of the Bck2Brwsr compiler which inherits
   155      *   all values from <code>this</code> except list of exported classes
   156      */
   157     public Bck2Brwsr addExported(String... exported) {
   158         return new Bck2Brwsr(
   159             level, this.exported.addAndNew(exported), 
   160             classes, resources, res, extension, classpath, flow
   161         );
   162     }
   163 
   164     /** Adds additional classes 
   165      * to the list of those that should be included in the generated
   166      * JavaScript file.
   167      * These classes are guaranteed to be available in the
   168      * generated virtual machine code accessible using their fully 
   169      * qualified name. This brings the same behavior as if the
   170      * classes were added by {@link #addClasses(java.lang.String...) } and
   171      * exported via {@link #addExported(java.lang.String...)}.
   172      * 
   173      * @param classes the classes to add to the compilation
   174      * @return new instance of the Bck2Brwsr compiler which inherits
   175      * all values from <code>this</code>
   176      */
   177     public Bck2Brwsr addRootClasses(String... classes) {
   178         if (classes.length == 0) {
   179             return this;
   180         } 
   181         return addExported(classes).addClasses(classes);
   182     }
   183     
   184     /** Adds additional classes 
   185      * to the list of those that should be included in the generated
   186      * JavaScript file. These classes are guaranteed to be present,
   187      * but they may not be accessible through their fully qualified
   188      * name.
   189      * 
   190      * @param classes the classes to add to the compilation
   191      * @return new instance of the Bck2Brwsr compiler which inherits
   192      * all values from <code>this</code>
   193      * @since 0.9
   194      */
   195     public Bck2Brwsr addClasses(String... classes) {
   196         if (classes.length == 0) {
   197             return this;
   198         } else {
   199             return new Bck2Brwsr(level, exported, 
   200                 this.classes.addAndNew(classes), resources, res,
   201                 extension, classpath, flow);
   202         }
   203     }
   204     
   205     /** These resources should be made available in the compiled file in
   206      * binary form. These resources can then be loaded
   207      * by {@link ClassLoader#getResource(java.lang.String)} and similar 
   208      * methods.
   209      * 
   210      * @param resources names of the resources to be loaded by {@link Resources#get(java.lang.String)}
   211      * @return new instance of the Bck2Brwsr compiler which inherits
   212      *   all values from <code>this</code> just adds few more resource names
   213      *   for processing
   214      * @since 0.9
   215      */
   216     public Bck2Brwsr addResources(String... resources) {
   217         if (resources.length == 0) {
   218             return this;
   219         } else {
   220             return new Bck2Brwsr(level, exported, this.classes, 
   221                 this.resources.addAndNew(resources), res, extension, classpath, flow
   222             );
   223         }
   224     }
   225     
   226     /** Changes the obfuscation level for the compiler by creating new instance
   227      * which inherits all values from <code>this</code> and adjust the level
   228      * of obfuscation.
   229      * 
   230      * @param level the new level of obfuscation
   231      * @return new instance of the compiler with changed level of obfuscation
   232      * @since 0.5
   233      */
   234     public Bck2Brwsr obfuscation(ObfuscationLevel level) {
   235         return new Bck2Brwsr(level, exported, classes, resources, res, extension, classpath, flow);
   236     }
   237     
   238     /** A way to change the provider of additional resources (classes) for the 
   239      * compiler. 
   240      * 
   241      * @param res the implementation of resources provider
   242      * @return new instance of the compiler with all values remaining the same, just 
   243      *   with different resources provider
   244      * @since 0.5
   245      */
   246     public Bck2Brwsr resources(Resources res) {
   247         return new Bck2Brwsr(
   248             level, exported, classes, resources, 
   249             res, extension, classpath, flow
   250         );
   251     }
   252 
   253     /** Should one generate a library? By default the system generates
   254      * all transitive classes needed by the the transitive closure of
   255      * {@link #addRootClasses(java.lang.String...)} and {@link #addClasses(java.lang.String...)}.
   256      * By turning on the library mode, only classes explicitly listed
   257      * will be included in the archive. The others will be referenced
   258      * as external ones.
   259      * <p>
   260      * A library archive may specify its <em>classpath</em> - e.g. link to
   261      * other libraries that should also be included in the application. 
   262      * One can specify the list of libraries as vararg to this method.
   263      * These are relative URL with respect to location of this library.
   264      * The runtime system then prefers seek for ".js" suffix of the library
   265      * and only then seeks for the classical ".jar" path.
   266      * 
   267      * @param classpath the array of JARs that are referenced by this library -
   268      *   by default gets turned into 
   269      * @return new instance of the compiler with library flag changed
   270      * @since 0.9
   271      */
   272     public Bck2Brwsr library(String... classpath) {
   273         return new Bck2Brwsr(
   274             level, exported, classes, 
   275             resources, res, true, 
   276             StringArray.asList(classpath), flow
   277         );
   278     }
   279     
   280     /** Turns on the standalone mode. E.g. does the opposite of
   281      * calling {@link #library(java.lang.String...)},
   282      * but also allows to specify whether the <em>Bck2Brwsr VM</em> should
   283      * be included at all. If not, only the skeleton of the launcher is
   284      * generated without any additional VM classes referenced.
   285      * 
   286      * @param includeVM should the VM be compiled in, or left out
   287      * @return new instance of the compiler with standalone mode on
   288      * @since 0.9
   289      */
   290     public Bck2Brwsr standalone(boolean includeVM) {
   291         return new Bck2Brwsr(
   292             level, exported, classes, resources, 
   293             res, includeVM ? false : null, null, flow
   294         );
   295     }
   296 
   297     /** A way to change the provider of additional resources (classes) for the 
   298      * compiler by specifying classloader to use for loading them.
   299      * 
   300      * @param loader class loader to load the resources from
   301      * @return new instance of the compiler with all values being the same, just 
   302      *   different resources provider
   303      * @since 0.5
   304      */
   305     public Bck2Brwsr resources(final ClassLoader loader) {
   306         return resources(loader, false);
   307     }
   308 
   309     /** A way to change the provider of additional resources (classes) for the 
   310      * compiler by specifying classloader to use for loading them.
   311      * 
   312      * @param loader class loader to load the resources from
   313      * @param ignoreBootClassPath <code>true</code> if classes loaded
   314      *    from <code>rt.jar</code> 
   315      * @return new instance of the compiler with all values being the same, just 
   316      *   different resources provider
   317      * @since 0.9
   318      */
   319     public Bck2Brwsr resources(final ClassLoader loader, boolean ignoreBootClassPath) {
   320         return resources(new LdrRsrcs(loader, ignoreBootClassPath));
   321     }
   322     
   323     /** A way to register flow analyzer. Such analyzer can optimize the
   324      * representation of cycles inside of method bodies.
   325      * 
   326      * @param flow the analyzer to be consulted with each method body
   327      * @return new instance of the compiler with all values being the same, just 
   328      *   different flow analyzer
   329      * @since 0.15
   330      */
   331     public Bck2Brwsr flowAnalyzer(Flow.Analyzer flow) {
   332         return new Bck2Brwsr(
   333             level, exported, classes, resources, res, 
   334             extension, classpath, flow
   335         );
   336     }
   337     
   338     /** Generates virtual machine based on previous configuration of the 
   339      * compiler.
   340      * 
   341      * @param out the output to write the generated JavaScript to
   342      * @throws IOException I/O exception can be thrown when something goes wrong
   343      * @since 0.5
   344      */
   345     public void generate(Appendable out) throws IOException {
   346         if (level != ObfuscationLevel.NONE) {
   347             try {
   348                 ClosureWrapper.produceTo(out, level, this);
   349                 return;
   350             } catch (IOException ex) {
   351                 throw ex;
   352             } catch (Throwable ex) {
   353                 out.append("/* Failed to obfuscate: " + ex.getMessage()
   354                                + " */\n");
   355             }
   356         }
   357 
   358         VM.compile(out, this);
   359     }
   360     
   361     //
   362     // Internal getters
   363     // 
   364     
   365     Resources getResources() {
   366         return res != null ? res : new LdrRsrcs(Bck2Brwsr.class.getClassLoader(), false);
   367     }
   368     
   369     StringArray allResources() {
   370         return resources;
   371     }
   372 
   373     StringArray classes() {
   374         return classes;
   375     }
   376 
   377     StringArray exported() {
   378         return exported;
   379     }
   380     
   381     boolean isExtension() {
   382         return Boolean.TRUE.equals(extension);
   383     }
   384     
   385     boolean includeVM() {
   386         return extension != null;
   387     }
   388     
   389     StringArray classpath() {
   390         return classpath;
   391     }
   392     
   393     Flow.Analyzer flow() {
   394         return flow;
   395     }
   396 
   397     /** Provider of resources (classes and other files). The 
   398      * {@link #generate(java.lang.Appendable, org.apidesign.vm4brwsr.Bck2Brwsr.Resources, java.lang.String[]) 
   399      * generator method} will call back here for all classes needed during
   400      * translation to JavaScript.
   401      */
   402     public interface Resources {
   403         /** Loads given resource (class or other file like image). The 
   404          * resource name to load bytes for the {@link String} class
   405          * would be <code>"java/lang/String.class"</code>.
   406          * 
   407          * @param resource path to resource to load
   408          * @return the input stream for the resource 
   409          * @throws IOException can be thrown if the loading fails on some error
   410          *   or the file cannot be found
   411          */
   412         public InputStream get(String resource) throws IOException;
   413     }
   414 
   415     /** Represents control flow inside single method.
   416      * Passed into {@link Analyzer#analyze(byte[], org.apidesign.vm4brwsr.Bck2Brwsr.Flow)}
   417      * method that can be registed via {@link Bck2Brwsr#flowAnalyzer(org.apidesign.vm4brwsr.Bck2Brwsr.Flow.Analyzer)}
   418      * method.
   419      * 
   420      * @since 0.15
   421      */
   422     public static final class Flow {
   423         private final byte[] byteCode;
   424         Flow(byte[] byteCode) {
   425             this.byteCode = byteCode;
   426         }
   427         
   428         /** Access to bytecode of the method to analyse.
   429          * 
   430          * @return unmodifiable bytecode of the instructions in the method body
   431          */
   432         public byte[] getMethodByteCode() {
   433             return byteCode;
   434         }
   435         
   436         public void registerCycle(int offset) {
   437         }
   438         
   439         public void registerIf(int offset) {
   440         }
   441         
   442         /** Provider of advanced analysis of the code flow inside of
   443          * method bodies. Register via {@link Bck2Brwsr#flowAnalyzer(org.apidesign.vm4brwsr.Bck2Brwsr.Flow.Analyzer)}
   444          * when constructing the {@link Bck2Brwsr#newCompiler() compiler}.
   445          * 
   446          * @since 0.15
   447          */
   448         public interface Analyzer {
   449             /** Called to analyze method bodies and offer better control flow.
   450              * 
   451              * 
   452              * @param request flow computation request and also a
   453              *    callback interface with methods to define the flow
   454              * @return <code>true</code> if the analysis was successful,
   455              *   <code>false</code> otherwise
   456              */
   457             public boolean analyze(Flow request);
   458         }
   459     }
   460     
   461 }