vm/src/main/java/org/apidesign/vm4brwsr/VM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 01 Feb 2013 18:42:07 +0100
branchemul
changeset 644 cfbd4eecb941
parent 442 b107ed66f2e7
child 671 99fa4fe6b980
permissions -rw-r--r--
Can initialize VM with classpath composed of a JAR file and read resources from it
     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         VMLazy.init();
    35         Zips.init();
    36     }
    37 
    38     @Override
    39     boolean debug(String msg) throws IOException {
    40         return false;
    41     }
    42     
    43     static void compile(Bck2Brwsr.Resources l, Appendable out, StringArray names) throws IOException {
    44         new VM(out).doCompile(l, names);
    45     }
    46     protected void doCompile(Bck2Brwsr.Resources l, StringArray names) throws IOException {
    47         out.append("(function VM(global) {");
    48         out.append("\n  var vm = {};");
    49         StringArray processed = new StringArray();
    50         StringArray initCode = new StringArray();
    51         for (String baseClass : names.toArray()) {
    52             references.add(baseClass);
    53             for (;;) {
    54                 String name = null;
    55                 for (String n : references.toArray()) {
    56                     if (processed.contains(n)) {
    57                         continue;
    58                     }
    59                     name = n;
    60                 }
    61                 if (name == null) {
    62                     break;
    63                 }
    64                 InputStream is = loadClass(l, name);
    65                 if (is == null) {
    66                     throw new IOException("Can't find class " + name); 
    67                 }
    68                 try {
    69                     String ic = compile(is);
    70                     processed.add(name);
    71                     initCode.add(ic == null ? "" : ic);
    72                 } catch (RuntimeException ex) {
    73                     if (out instanceof CharSequence) {
    74                         CharSequence seq = (CharSequence)out;
    75                         int lastBlock = seq.length();
    76                         while (lastBlock-- > 0) {
    77                             if (seq.charAt(lastBlock) == '{') {
    78                                 break;
    79                             }
    80                         }
    81                         throw new IOException("Error while compiling " + name + "\n" 
    82                             + seq.subSequence(lastBlock + 1, seq.length()), ex
    83                         );
    84                     } else {
    85                         throw new IOException("Error while compiling " + name + "\n" 
    86                             + out, ex
    87                         );
    88                     }
    89                 }
    90             }
    91 
    92             for (String resource : scripts.toArray()) {
    93                 while (resource.startsWith("/")) {
    94                     resource = resource.substring(1);
    95                 }
    96                 InputStream emul = l.get(resource);
    97                 if (emul == null) {
    98                     throw new IOException("Can't find " + resource);
    99                 }
   100                 readResource(emul, out);
   101             }
   102             scripts = new StringArray();
   103             
   104             StringArray toInit = StringArray.asList(references.toArray());
   105             toInit.reverse();
   106 
   107             for (String ic : toInit.toArray()) {
   108                 int indx = processed.indexOf(ic);
   109                 if (indx >= 0) {
   110                     out.append(initCode.toArray()[indx]).append("\n");
   111                     initCode.toArray()[indx] = "";
   112                 }
   113             }
   114         }
   115         out.append(
   116               "  global.bck2brwsr = function() {\n"
   117             + "    var args = arguments;\n"
   118             + "    var loader = {};\n"
   119             + "    loader.vm = vm;\n"
   120             + "    if (args.length == 1 && typeof args[0] !== 'function') {;\n"
   121             + "      var classpath = args[0];\n"
   122             + "      args[0] = function(name) {\n"
   123             + "        return vm.org_apidesign_vm4brwsr_Zips(false).loadFromCp___3B_3Ljava_lang_Object_2Ljava_lang_String_2(classpath, name);\n"
   124             + "      };\n"
   125             + "    };\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             + "      if (!args[0]) throw 'bck2brwsr initialized without loader function, cannot load ' + name;\n"
   131             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   132             + "        load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   133             + "    }\n"
   134             + "    if (args[0]) {\n"
   135             + "      vm.loadClass = loader.loadClass;\n"
   136             + "      vm.loadBytes = function(name) {\n"
   137             + "        if (!args[0]) throw 'bck2brwsr initialized without loader function, cannot load ' + name;\n"
   138             + "        return args[0](name);\n"
   139             + "      }\n"
   140             + "    }\n"
   141             + "    return loader;\n"
   142             + "  };\n");
   143         out.append("}(this));");
   144     }
   145     private static void readResource(InputStream emul, Appendable out) throws IOException {
   146         try {
   147             int state = 0;
   148             for (;;) {
   149                 int ch = emul.read();
   150                 if (ch == -1) {
   151                     break;
   152                 }
   153                 if (ch < 0 || ch > 255) {
   154                     throw new IOException("Invalid char in emulation " + ch);
   155                 }
   156                 switch (state) {
   157                     case 0: 
   158                         if (ch == '/') {
   159                             state = 1;
   160                         } else {
   161                             out.append((char)ch);
   162                         }
   163                         break;
   164                     case 1:
   165                         if (ch == '*') {
   166                             state = 2;
   167                         } else {
   168                             out.append('/').append((char)ch);
   169                             state = 0;
   170                         }
   171                         break;
   172                     case 2:
   173                         if (ch == '*') {
   174                             state = 3;
   175                         }
   176                         break;
   177                     case 3:
   178                         if (ch == '/') {
   179                             state = 0;
   180                         } else {
   181                             state = 2;
   182                         }
   183                         break;
   184                 }
   185             }
   186         } finally {
   187             emul.close();
   188         }
   189     }
   190 
   191     private static InputStream loadClass(Bck2Brwsr.Resources l, String name) throws IOException {
   192         return l.get(name + ".class"); // NOI18N
   193     }
   194 
   195     static String toString(String name) throws IOException {
   196         StringBuilder sb = new StringBuilder();
   197 //        compile(sb, name);
   198         return sb.toString().toString();
   199     }
   200 
   201     private StringArray scripts = new StringArray();
   202     private StringArray references = new StringArray();
   203     
   204     @Override
   205     protected boolean requireReference(String cn) {
   206         if (references.contains(cn)) {
   207             return false;
   208         }
   209         references.add(cn);
   210         return true;
   211     }
   212 
   213     @Override
   214     protected void requireScript(String resourcePath) {
   215         scripts.add(resourcePath);
   216     }
   217 
   218     @Override
   219     String assignClass(String className) {
   220         return "vm." + className + " = ";
   221     }
   222     
   223     @Override
   224     String accessClass(String className) {
   225         return "vm." + className;
   226     }
   227 }