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