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