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