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