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