rt/vm/src/main/java/org/apidesign/vm4brwsr/VM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 10 Mar 2013 21:27:06 +0100
changeset 833 32de22658040
parent 772 d382dacfd73f
child 869 151f4ccd7673
permissions -rw-r--r--
Don't generate too much empty lines
     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                     final String theCode = initCode.toArray()[indx];
   114                     if (!theCode.isEmpty()) {
   115                         out.append(theCode).append("\n");
   116                     }
   117                     initCode.toArray()[indx] = "";
   118                 }
   119             }
   120         }
   121         out.append(
   122               "  return vm;\n"
   123             + "  };\n"
   124             + "  global.bck2brwsr = function() {\n"
   125             + "    var args = Array.prototype.slice.apply(arguments);\n"
   126             + "    var vm = fillInVMSkeleton({});\n"
   127             + "    var loader = {};\n"
   128             + "    loader.vm = vm;\n"
   129             + "    loader.loadClass = function(name) {\n"
   130             + "      var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
   131             + "      var fn = vm[attr];\n"
   132             + "      if (fn) return fn(false);\n"
   133             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   134             + "        load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   135             + "    }\n"
   136             + "    if (vm.loadClass) {\n"
   137             + "      throw 'Cannot initialize the bck2brwsr VM twice!';\n"
   138             + "    }\n"
   139             + "    vm.loadClass = loader.loadClass;\n"
   140             + "    vm.loadBytes = function(name) {\n"
   141             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   142             + "        loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   143             + "    }\n"
   144             + "    vm.java_lang_reflect_Array(false);\n"
   145             + "    vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   146             + "      loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\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 }