vm/src/main/java/org/apidesign/vm4brwsr/GenJS.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 07 Dec 2012 06:29:54 +0100
branchlazyvm
changeset 277 e4b9eee9be83
parent 276 aeb9fe11cd60
permissions -rw-r--r--
Lazy loading is now part of GenJS
     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.IOException;
    21 import java.io.InputStream;
    22 import java.net.URL;
    23 import java.util.Enumeration;
    24 
    25 /** Generator of JavaScript from bytecode of classes on classpath of the VM.
    26  *
    27  * @author Jaroslav Tulach <jtulach@netbeans.org>
    28  */
    29 class GenJS extends ByteCodeToJavaScript {
    30     public GenJS(Appendable out) {
    31         super(out);
    32     }
    33     
    34     static {
    35         // uses VMLazy to load dynamic classes
    36         VMLazy.init();
    37     }
    38     
    39     static void compile(Appendable out, String... names) throws IOException {
    40         compile(out, StringArray.asList(names));
    41     }
    42     static void compile(ClassLoader l, Appendable out, String... names) throws IOException {
    43         compile(l, out, StringArray.asList(names));
    44     }
    45     static void compile(Appendable out, StringArray names) throws IOException {
    46         compile(GenJS.class.getClassLoader(), out, names);
    47     }
    48     static void compile(ClassLoader l, Appendable out, StringArray names) throws IOException {
    49         new GenJS(out).doCompile(l, names);
    50     }
    51     protected void doCompile(ClassLoader l, StringArray names) throws IOException {
    52         out.append("(function VM(global) {");
    53         out.append("\n  var vm = {};");
    54         StringArray processed = new StringArray();
    55         StringArray initCode = new StringArray();
    56         for (String baseClass : names.toArray()) {
    57             references.add(baseClass);
    58             for (;;) {
    59                 String name = null;
    60                 for (String n : references.toArray()) {
    61                     if (processed.contains(n)) {
    62                         continue;
    63                     }
    64                     name = n;
    65                 }
    66                 if (name == null) {
    67                     break;
    68                 }
    69                 InputStream is = loadClass(l, name);
    70                 if (is == null) {
    71                     throw new IOException("Can't find class " + name); 
    72                 }
    73                 try {
    74                     String ic = compile(is);
    75                     processed.add(name);
    76                     initCode.add(ic == null ? "" : ic);
    77                 } catch (RuntimeException ex) {
    78                     if (out instanceof CharSequence) {
    79                         CharSequence seq = (CharSequence)out;
    80                         int lastBlock = seq.length();
    81                         while (lastBlock-- > 0) {
    82                             if (seq.charAt(lastBlock) == '{') {
    83                                 break;
    84                             }
    85                         }
    86                         throw new IOException("Error while compiling " + name + "\n" 
    87                             + seq.subSequence(lastBlock + 1, seq.length()), ex
    88                         );
    89                     } else {
    90                         throw new IOException("Error while compiling " + name + "\n" 
    91                             + out, ex
    92                         );
    93                     }
    94                 }
    95             }
    96 
    97             for (String resource : scripts.toArray()) {
    98                 while (resource.startsWith("/")) {
    99                     resource = resource.substring(1);
   100                 }
   101                 InputStream emul = l.getResourceAsStream(resource);
   102                 if (emul == null) {
   103                     throw new IOException("Can't find " + resource);
   104                 }
   105                 readResource(emul, out);
   106             }
   107             scripts = new StringArray();
   108             
   109             StringArray toInit = StringArray.asList(references.toArray());
   110             toInit.reverse();
   111 
   112             for (String ic : toInit.toArray()) {
   113                 int indx = processed.indexOf(ic);
   114                 if (indx >= 0) {
   115                     out.append(initCode.toArray()[indx]).append("\n");
   116                     initCode.toArray()[indx] = "";
   117                 }
   118             }
   119         }
   120         out.append(
   121               "  global.bck2brwsr = function() {\n"
   122             + "    var args = arguments;\n"
   123             + "    var loader = {};\n"
   124             + "    loader.vm = vm;\n"
   125             + "    loader.loadClass = function(name) {\n"
   126             + "      var attr = name.replace__Ljava_lang_String_2CC(name, '.','_');\n"
   127             + "      var fn = vm[attr];\n"
   128             + "      if (fn) return fn(false);\n"
   129             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   130             + "        load___3Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   131             + "    }\n"
   132             + "    return loader;\n"
   133             + "  };\n");
   134         out.append("}(this));");
   135     }
   136     private static void readResource(InputStream emul, Appendable out) throws IOException {
   137         try {
   138             int state = 0;
   139             for (;;) {
   140                 int ch = emul.read();
   141                 if (ch == -1) {
   142                     break;
   143                 }
   144                 if (ch < 0 || ch > 255) {
   145                     throw new IOException("Invalid char in emulation " + ch);
   146                 }
   147                 switch (state) {
   148                     case 0: 
   149                         if (ch == '/') {
   150                             state = 1;
   151                         } else {
   152                             out.append((char)ch);
   153                         }
   154                         break;
   155                     case 1:
   156                         if (ch == '*') {
   157                             state = 2;
   158                         } else {
   159                             out.append('/').append((char)ch);
   160                             state = 0;
   161                         }
   162                         break;
   163                     case 2:
   164                         if (ch == '*') {
   165                             state = 3;
   166                         }
   167                         break;
   168                     case 3:
   169                         if (ch == '/') {
   170                             state = 0;
   171                         } else {
   172                             state = 2;
   173                         }
   174                         break;
   175                 }
   176             }
   177         } finally {
   178             emul.close();
   179         }
   180     }
   181 
   182     private static InputStream loadClass(ClassLoader l, String name) throws IOException {
   183         Enumeration<URL> en = l.getResources(name + ".class");
   184         URL u = null;
   185         while (en.hasMoreElements()) {
   186             u = en.nextElement();
   187         }
   188         if (u == null) {
   189             throw new IOException("Can't find " + name);
   190         }
   191         if (u.toExternalForm().contains("rt.jar!")) {
   192             throw new IOException("No emulation for " + u);
   193         }
   194         return u.openStream();
   195     }
   196 
   197     static String toString(String name) throws IOException {
   198         StringBuilder sb = new StringBuilder();
   199         compile(sb, name);
   200         return sb.toString().toString();
   201     }
   202 
   203     private StringArray scripts = new StringArray();
   204     private StringArray references = new StringArray();
   205     
   206     @Override
   207     protected boolean requireReference(String cn) {
   208         if (references.contains(cn)) {
   209             return false;
   210         }
   211         references.add(cn);
   212         return true;
   213     }
   214 
   215     @Override
   216     protected void requireScript(String resourcePath) {
   217         scripts.add(resourcePath);
   218     }
   219 
   220     @Override
   221     String assignClass(String className) {
   222         return "vm." + className + " = ";
   223     }
   224     
   225     @Override
   226     String accessClass(String className) {
   227         return "vm." + className;
   228     }
   229 }