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