vm/src/main/java/org/apidesign/vm4brwsr/VM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 11 Dec 2012 09:36:44 +0100
branchlazyvm
changeset 298 885acca2fa0b
parent 277 vm/src/main/java/org/apidesign/vm4brwsr/GenJS.java@e4b9eee9be83
child 300 39695cc9a54f
permissions -rw-r--r--
Creating Bck2Brwsr entrypoint to for those who wish to generate their JavaScript based Java VM
     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     }
    36     
    37     static void compile(Bck2Brwsr.Resources l, Appendable out, StringArray names) throws IOException {
    38         new VM(out).doCompile(l, names);
    39     }
    40     protected void doCompile(Bck2Brwsr.Resources l, StringArray names) throws IOException {
    41         out.append("(function VM(global) {");
    42         out.append("\n  var vm = {};");
    43         StringArray processed = new StringArray();
    44         StringArray initCode = new StringArray();
    45         for (String baseClass : names.toArray()) {
    46             references.add(baseClass);
    47             for (;;) {
    48                 String name = null;
    49                 for (String n : references.toArray()) {
    50                     if (processed.contains(n)) {
    51                         continue;
    52                     }
    53                     name = n;
    54                 }
    55                 if (name == null) {
    56                     break;
    57                 }
    58                 InputStream is = loadClass(l, name);
    59                 if (is == null) {
    60                     throw new IOException("Can't find class " + name); 
    61                 }
    62                 try {
    63                     String ic = compile(is);
    64                     processed.add(name);
    65                     initCode.add(ic == null ? "" : ic);
    66                 } catch (RuntimeException ex) {
    67                     if (out instanceof CharSequence) {
    68                         CharSequence seq = (CharSequence)out;
    69                         int lastBlock = seq.length();
    70                         while (lastBlock-- > 0) {
    71                             if (seq.charAt(lastBlock) == '{') {
    72                                 break;
    73                             }
    74                         }
    75                         throw new IOException("Error while compiling " + name + "\n" 
    76                             + seq.subSequence(lastBlock + 1, seq.length()), ex
    77                         );
    78                     } else {
    79                         throw new IOException("Error while compiling " + name + "\n" 
    80                             + out, ex
    81                         );
    82                     }
    83                 }
    84             }
    85 
    86             for (String resource : scripts.toArray()) {
    87                 while (resource.startsWith("/")) {
    88                     resource = resource.substring(1);
    89                 }
    90                 InputStream emul = l.get(resource);
    91                 if (emul == null) {
    92                     throw new IOException("Can't find " + resource);
    93                 }
    94                 readResource(emul, out);
    95             }
    96             scripts = new StringArray();
    97             
    98             StringArray toInit = StringArray.asList(references.toArray());
    99             toInit.reverse();
   100 
   101             for (String ic : toInit.toArray()) {
   102                 int indx = processed.indexOf(ic);
   103                 if (indx >= 0) {
   104                     out.append(initCode.toArray()[indx]).append("\n");
   105                     initCode.toArray()[indx] = "";
   106                 }
   107             }
   108         }
   109         out.append(
   110               "  global.bck2brwsr = function() {\n"
   111             + "    var args = arguments;\n"
   112             + "    var loader = {};\n"
   113             + "    loader.vm = vm;\n"
   114             + "    loader.loadClass = function(name) {\n"
   115             + "      var attr = name.replace__Ljava_lang_String_2CC(name, '.','_');\n"
   116             + "      var fn = vm[attr];\n"
   117             + "      if (fn) return fn(false);\n"
   118             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   119             + "        load___3Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   120             + "    }\n"
   121             + "    return loader;\n"
   122             + "  };\n");
   123         out.append("}(this));");
   124     }
   125     private static void readResource(InputStream emul, Appendable out) throws IOException {
   126         try {
   127             int state = 0;
   128             for (;;) {
   129                 int ch = emul.read();
   130                 if (ch == -1) {
   131                     break;
   132                 }
   133                 if (ch < 0 || ch > 255) {
   134                     throw new IOException("Invalid char in emulation " + ch);
   135                 }
   136                 switch (state) {
   137                     case 0: 
   138                         if (ch == '/') {
   139                             state = 1;
   140                         } else {
   141                             out.append((char)ch);
   142                         }
   143                         break;
   144                     case 1:
   145                         if (ch == '*') {
   146                             state = 2;
   147                         } else {
   148                             out.append('/').append((char)ch);
   149                             state = 0;
   150                         }
   151                         break;
   152                     case 2:
   153                         if (ch == '*') {
   154                             state = 3;
   155                         }
   156                         break;
   157                     case 3:
   158                         if (ch == '/') {
   159                             state = 0;
   160                         } else {
   161                             state = 2;
   162                         }
   163                         break;
   164                 }
   165             }
   166         } finally {
   167             emul.close();
   168         }
   169     }
   170 
   171     private static InputStream loadClass(Bck2Brwsr.Resources l, String name) throws IOException {
   172         return l.get(name + ".class"); // NOI18N
   173     }
   174 
   175     static String toString(String name) throws IOException {
   176         StringBuilder sb = new StringBuilder();
   177 //        compile(sb, name);
   178         return sb.toString().toString();
   179     }
   180 
   181     private StringArray scripts = new StringArray();
   182     private StringArray references = new StringArray();
   183     
   184     @Override
   185     protected boolean requireReference(String cn) {
   186         if (references.contains(cn)) {
   187             return false;
   188         }
   189         references.add(cn);
   190         return true;
   191     }
   192 
   193     @Override
   194     protected void requireScript(String resourcePath) {
   195         scripts.add(resourcePath);
   196     }
   197 
   198     @Override
   199     String assignClass(String className) {
   200         return "vm." + className + " = ";
   201     }
   202     
   203     @Override
   204     String accessClass(String className) {
   205         return "vm." + className;
   206     }
   207 }