vm/src/main/java/org/apidesign/vm4brwsr/VM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 05 Feb 2013 13:19:06 +0100
branchemul
changeset 671 99fa4fe6b980
parent 644 cfbd4eecb941
child 702 fa42b3d8cbbc
permissions -rw-r--r--
Don't really initialize the classes. Just pretend they will be initialized so bck2brwsr includes them in transitive closure
     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             + "    loader.vm = vm;\n"
   124             + "    if (args.length == 1 && typeof args[0] !== 'function') {;\n"
   125             + "      var classpath = args[0];\n"
   126             + "      args[0] = function(name) {\n"
   127             + "        return vm.org_apidesign_vm4brwsr_Zips(false).loadFromCp___3B_3Ljava_lang_Object_2Ljava_lang_String_2(classpath, name);\n"
   128             + "      };\n"
   129             + "    };\n"
   130             + "    loader.loadClass = function(name) {\n"
   131             + "      var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
   132             + "      var fn = vm[attr];\n"
   133             + "      if (fn) return fn(false);\n"
   134             + "      if (!args[0]) throw 'bck2brwsr initialized without loader function, cannot load ' + name;\n"
   135             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   136             + "        load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   137             + "    }\n"
   138             + "    if (args[0]) {\n"
   139             + "      vm.loadClass = loader.loadClass;\n"
   140             + "      vm.loadBytes = function(name) {\n"
   141             + "        if (!args[0]) throw 'bck2brwsr initialized without loader function, cannot load ' + name;\n"
   142             + "        return args[0](name);\n"
   143             + "      }\n"
   144             + "    }\n"
   145             + "    return loader;\n"
   146             + "  };\n");
   147         out.append("}(this));");
   148     }
   149     private static void readResource(InputStream emul, Appendable out) throws IOException {
   150         try {
   151             int state = 0;
   152             for (;;) {
   153                 int ch = emul.read();
   154                 if (ch == -1) {
   155                     break;
   156                 }
   157                 if (ch < 0 || ch > 255) {
   158                     throw new IOException("Invalid char in emulation " + ch);
   159                 }
   160                 switch (state) {
   161                     case 0: 
   162                         if (ch == '/') {
   163                             state = 1;
   164                         } else {
   165                             out.append((char)ch);
   166                         }
   167                         break;
   168                     case 1:
   169                         if (ch == '*') {
   170                             state = 2;
   171                         } else {
   172                             out.append('/').append((char)ch);
   173                             state = 0;
   174                         }
   175                         break;
   176                     case 2:
   177                         if (ch == '*') {
   178                             state = 3;
   179                         }
   180                         break;
   181                     case 3:
   182                         if (ch == '/') {
   183                             state = 0;
   184                         } else {
   185                             state = 2;
   186                         }
   187                         break;
   188                 }
   189             }
   190         } finally {
   191             emul.close();
   192         }
   193     }
   194 
   195     private static InputStream loadClass(Bck2Brwsr.Resources l, String name) throws IOException {
   196         return l.get(name + ".class"); // NOI18N
   197     }
   198 
   199     static String toString(String name) throws IOException {
   200         StringBuilder sb = new StringBuilder();
   201 //        compile(sb, name);
   202         return sb.toString().toString();
   203     }
   204 
   205     private StringArray scripts = new StringArray();
   206     private StringArray references = new StringArray();
   207     
   208     @Override
   209     protected boolean requireReference(String cn) {
   210         if (references.contains(cn)) {
   211             return false;
   212         }
   213         references.add(cn);
   214         return true;
   215     }
   216 
   217     @Override
   218     protected void requireScript(String resourcePath) {
   219         scripts.add(resourcePath);
   220     }
   221 
   222     @Override
   223     String assignClass(String className) {
   224         return "vm." + className + " = ";
   225     }
   226     
   227     @Override
   228     String accessClass(String className) {
   229         return "vm." + className;
   230     }
   231 }