vm/src/main/java/org/apidesign/vm4brwsr/VM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 15 Dec 2012 08:17:45 +0100
changeset 322 3884815c0629
parent 300 39695cc9a54f
child 399 1679cdfe4172
child 407 b2f68438b0e2
permissions -rw-r--r--
Class.forName can load new classes
     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             + "      if (!args[0]) throw 'bck2brwsr initialized without loader function, cannot load ' + name;\n"
   119             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   120             + "        load___3Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   121             + "    }\n"
   122             + "    if (args[0]) vm.loadClass = loader.loadClass;\n"
   123             + "    return loader;\n"
   124             + "  };\n");
   125         out.append("}(this));");
   126     }
   127     private static void readResource(InputStream emul, Appendable out) throws IOException {
   128         try {
   129             int state = 0;
   130             for (;;) {
   131                 int ch = emul.read();
   132                 if (ch == -1) {
   133                     break;
   134                 }
   135                 if (ch < 0 || ch > 255) {
   136                     throw new IOException("Invalid char in emulation " + ch);
   137                 }
   138                 switch (state) {
   139                     case 0: 
   140                         if (ch == '/') {
   141                             state = 1;
   142                         } else {
   143                             out.append((char)ch);
   144                         }
   145                         break;
   146                     case 1:
   147                         if (ch == '*') {
   148                             state = 2;
   149                         } else {
   150                             out.append('/').append((char)ch);
   151                             state = 0;
   152                         }
   153                         break;
   154                     case 2:
   155                         if (ch == '*') {
   156                             state = 3;
   157                         }
   158                         break;
   159                     case 3:
   160                         if (ch == '/') {
   161                             state = 0;
   162                         } else {
   163                             state = 2;
   164                         }
   165                         break;
   166                 }
   167             }
   168         } finally {
   169             emul.close();
   170         }
   171     }
   172 
   173     private static InputStream loadClass(Bck2Brwsr.Resources l, String name) throws IOException {
   174         return l.get(name + ".class"); // NOI18N
   175     }
   176 
   177     static String toString(String name) throws IOException {
   178         StringBuilder sb = new StringBuilder();
   179 //        compile(sb, name);
   180         return sb.toString().toString();
   181     }
   182 
   183     private StringArray scripts = new StringArray();
   184     private StringArray references = new StringArray();
   185     
   186     @Override
   187     protected boolean requireReference(String cn) {
   188         if (references.contains(cn)) {
   189             return false;
   190         }
   191         references.add(cn);
   192         return true;
   193     }
   194 
   195     @Override
   196     protected void requireScript(String resourcePath) {
   197         scripts.add(resourcePath);
   198     }
   199 
   200     @Override
   201     String assignClass(String className) {
   202         return "vm." + className + " = ";
   203     }
   204     
   205     @Override
   206     String accessClass(String className) {
   207         return "vm." + className;
   208     }
   209 }