rt/vm/src/main/java/org/apidesign/vm4brwsr/VMLazy.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 09 Nov 2014 10:36:08 +0100
changeset 1722 fd3a354d6e8f
parent 1579 d009c6ca8ce1
child 1787 ea12a3bb4b33
permissions -rw-r--r--
Don't initialize @JavaScriptBody resources sooner than their methods are called.
     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.ByteArrayInputStream;
    21 import java.io.IOException;
    22 import java.io.InputStream;
    23 import org.apidesign.bck2brwsr.core.Exported;
    24 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    25 
    26 /**
    27  *
    28  * @author Jaroslav Tulach <jtulach@netbeans.org>
    29  */
    30 final class VMLazy {
    31     private final Object vm;
    32     private final Object[] args;
    33     
    34     private VMLazy(Object vm, Object[] args) {
    35         this.vm = vm;
    36         this.args = args;
    37     }
    38     
    39     static void init() {
    40     }
    41     
    42     @Exported
    43     static Object load(Object loader, String name, Object[] arguments, byte[] arr) 
    44     throws IOException, ClassNotFoundException {
    45         if (arr == null) {
    46             throw new ClassNotFoundException(name);
    47         }
    48         return new VMLazy(loader, arguments).defineClass(arr, name, false);
    49     }
    50 
    51     @Exported
    52     Object load(String name, boolean instance)
    53     throws IOException, ClassNotFoundException {
    54         String res = name.replace('.', '/') + ".class";
    55         byte[] arr = ClassPath.loadBytes(res, args, 0);
    56         if (arr == null) {
    57             throw new ClassNotFoundException(name);
    58         }
    59         
    60         return defineClass(arr, name, instance);
    61     }
    62 
    63     private Object defineClass(byte[] arr, String name, boolean instance) throws IOException {
    64         StringBuilder out = new StringBuilder(65535);
    65         out.append("var vm = arguments[0];\n");
    66         int prelude = out.length();
    67         String initCode = new Gen(this, out).compile(new ByteArrayInputStream(arr));
    68         String code = out.toString().toString();
    69         String under = name.replace('.', '_');
    70         Object fn = applyCode(vm, under, code, instance);
    71         
    72         if (!initCode.isEmpty()) {
    73             out.setLength(prelude);
    74             out.append(initCode);
    75             code = out.toString().toString();
    76             applyCode(vm, null, code, false);
    77         }            
    78         
    79         return fn;
    80     }
    81 
    82     @JavaScriptBody(args = {"vm", "name", "script", "instance" }, body =
    83         "try {\n" +
    84         "  new Function(script)(vm, name);\n" +
    85         "} catch (ex) {\n" +
    86         "  throw 'Cannot compile ' + name + ' ' + ex + ' line: ' + ex.lineNumber + ' script:\\n' + script;\n" +
    87         "}\n" +
    88         "return name != null ? vm[name](instance) : null;\n"
    89     )
    90     private static native Object applyCode(Object vm, String name, String script, boolean instance);
    91     
    92     
    93     private static final class Gen extends ByteCodeToJavaScript {
    94         private final VMLazy lazy;
    95 
    96         public Gen(VMLazy vm, Appendable out) {
    97             super(out);
    98             this.lazy = vm;
    99         }
   100         
   101         @JavaScriptBody(args = {"n"},
   102         body =
   103         "var cls = n.replace__Ljava_lang_String_2CC('/','_').toString();"
   104         + "\nvar dot = n.replace__Ljava_lang_String_2CC('/','.').toString();"
   105         + "\nvar lazy = this._lazy();"
   106         + "\nvar vm = lazy._vm();"
   107         + "\nif (vm[cls]) return false;"
   108         + "\nvm[cls] = function() {"
   109         + "\n  var instance = arguments.length == 0 || arguments[0] === true;"
   110         + "\n  return lazy.load__Ljava_lang_Object_2Ljava_lang_String_2Z(dot, instance);"
   111         + "\n};"
   112         + "\nreturn true;")
   113         @Override
   114         protected boolean requireReference(String internalClassName) {
   115             throw new UnsupportedOperationException();
   116         }
   117 
   118         @Override
   119         protected void requireScript(String resourcePath) throws IOException {
   120             if (!resourcePath.startsWith("/")) {
   121                 resourcePath = "/" + resourcePath;
   122             }
   123             String code = readCode(resourcePath);
   124             applyCode(lazy.vm, null, code, false);
   125         }
   126 
   127         private String readCode(String resourcePath) throws IOException {
   128             InputStream is = getClass().getResourceAsStream(resourcePath);
   129             StringBuilder sb = new StringBuilder();
   130             for (;;) {
   131                 int ch = is.read();
   132                 if (ch == -1) {
   133                     break;
   134                 }
   135                 sb.append((char)ch);
   136             }
   137             return sb.toString();
   138         }
   139 
   140         @Override
   141         String assignClass(String className) {
   142             return "vm[arguments[1]]=";
   143         }
   144 
   145         @Override
   146         String accessClass(String classOperation) {
   147             return "vm." + classOperation;
   148         }
   149 
   150         @Override
   151         protected void requireResource(String resourcePath) throws IOException {
   152             requireReference(resourcePath);
   153         }
   154     }
   155 }