rt/vm/src/main/java/org/apidesign/vm4brwsr/VM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 05 Oct 2013 07:23:48 +0200
changeset 1344 bb1e59f5cff3
parent 869 151f4ccd7673
child 1367 6193e735f4d1
permissions -rw-r--r--
Need to skip URI and System references, as they are not part of minimal API profile
     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     private VM(Appendable out, ObfuscationDelegate obfuscationDelegate) {
    33         super(out, obfuscationDelegate);
    34     }
    35 
    36     static {
    37         // uses VMLazy to load dynamic classes
    38         boolean assertsOn = false;
    39         assert assertsOn = true;
    40         if (assertsOn) {
    41             VMLazy.init();
    42             Zips.init();
    43         }
    44     }
    45 
    46     @Override
    47     boolean debug(String msg) throws IOException {
    48         return false;
    49     }
    50     
    51     static void compile(Bck2Brwsr.Resources l, Appendable out, StringArray names) throws IOException {
    52         new VM(out).doCompile(l, names);
    53     }
    54 
    55     static void compile(Bck2Brwsr.Resources l, Appendable out, StringArray names,
    56                         ObfuscationDelegate obfuscationDelegate) throws IOException {
    57         new VM(out, obfuscationDelegate).doCompile(l, names);
    58     }
    59 
    60     protected void doCompile(Bck2Brwsr.Resources l, StringArray names) throws IOException {
    61         out.append("(function VM(global) {var fillInVMSkeleton = function(vm) {");
    62         StringArray processed = new StringArray();
    63         StringArray initCode = new StringArray();
    64         StringArray skipClass = new StringArray();
    65         for (String baseClass : names.toArray()) {
    66             references.add(baseClass);
    67             for (;;) {
    68                 String name = null;
    69                 for (String n : references.toArray()) {
    70                     if (skipClass.contains(n)) {
    71                         continue;
    72                     }
    73                     if (processed.contains(n)) {
    74                         continue;
    75                     }
    76                     name = n;
    77                 }
    78                 if (name == null) {
    79                     break;
    80                 }
    81                 InputStream is = loadClass(l, name);
    82                 if (is == null) {
    83                     skipClass.add(name);
    84                     continue;
    85                 }
    86                 try {
    87                     String ic = compile(is);
    88                     processed.add(name);
    89                     initCode.add(ic == null ? "" : ic);
    90                 } catch (RuntimeException ex) {
    91                     if (out instanceof CharSequence) {
    92                         CharSequence seq = (CharSequence)out;
    93                         int lastBlock = seq.length();
    94                         while (lastBlock-- > 0) {
    95                             if (seq.charAt(lastBlock) == '{') {
    96                                 break;
    97                             }
    98                         }
    99                         throw new IOException("Error while compiling " + name + "\n" 
   100                             + seq.subSequence(lastBlock + 1, seq.length()), ex
   101                         );
   102                     } else {
   103                         throw new IOException("Error while compiling " + name + "\n" 
   104                             + out, ex
   105                         );
   106                     }
   107                 }
   108             }
   109 
   110             for (String resource : scripts.toArray()) {
   111                 while (resource.startsWith("/")) {
   112                     resource = resource.substring(1);
   113                 }
   114                 InputStream emul = l.get(resource);
   115                 if (emul == null) {
   116                     throw new IOException("Can't find " + resource);
   117                 }
   118                 readResource(emul, out);
   119             }
   120             scripts = new StringArray();
   121             
   122             StringArray toInit = StringArray.asList(references.toArray());
   123             toInit.reverse();
   124 
   125             for (String ic : toInit.toArray()) {
   126                 int indx = processed.indexOf(ic);
   127                 if (indx >= 0) {
   128                     final String theCode = initCode.toArray()[indx];
   129                     if (!theCode.isEmpty()) {
   130                         out.append(theCode).append("\n");
   131                     }
   132                     initCode.toArray()[indx] = "";
   133                 }
   134             }
   135         }
   136         out.append(
   137               "  return vm;\n"
   138             + "  };\n"
   139             + "  global.bck2brwsr = function() {\n"
   140             + "    var args = Array.prototype.slice.apply(arguments);\n"
   141             + "    var vm = fillInVMSkeleton({});\n"
   142             + "    var loader = {};\n"
   143             + "    loader.vm = vm;\n"
   144             + "    loader.loadClass = function(name) {\n"
   145             + "      var attr = name.replace__Ljava_lang_String_2CC('.','_');\n"
   146             + "      var fn = vm[attr];\n"
   147             + "      if (fn) return fn(false);\n"
   148             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   149             + "        load__Ljava_lang_Object_2Ljava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   150             + "    }\n"
   151             + "    if (vm.loadClass) {\n"
   152             + "      throw 'Cannot initialize the bck2brwsr VM twice!';\n"
   153             + "    }\n"
   154             + "    vm.loadClass = loader.loadClass;\n"
   155             + "    vm.loadBytes = function(name) {\n"
   156             + "      return vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   157             + "        loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, name, args);\n"
   158             + "    }\n"
   159             + "    vm.java_lang_reflect_Array(false);\n"
   160             + "    vm.org_apidesign_vm4brwsr_VMLazy(false).\n"
   161             + "      loadBytes___3BLjava_lang_Object_2Ljava_lang_String_2_3Ljava_lang_Object_2(loader, null, args);\n"
   162             + "    return loader;\n"
   163             + "  };\n");
   164         out.append("}(this));");
   165     }
   166     private static void readResource(InputStream emul, Appendable out) throws IOException {
   167         try {
   168             int state = 0;
   169             for (;;) {
   170                 int ch = emul.read();
   171                 if (ch == -1) {
   172                     break;
   173                 }
   174                 if (ch < 0 || ch > 255) {
   175                     throw new IOException("Invalid char in emulation " + ch);
   176                 }
   177                 switch (state) {
   178                     case 0: 
   179                         if (ch == '/') {
   180                             state = 1;
   181                         } else {
   182                             out.append((char)ch);
   183                         }
   184                         break;
   185                     case 1:
   186                         if (ch == '*') {
   187                             state = 2;
   188                         } else {
   189                             out.append('/').append((char)ch);
   190                             state = 0;
   191                         }
   192                         break;
   193                     case 2:
   194                         if (ch == '*') {
   195                             state = 3;
   196                         }
   197                         break;
   198                     case 3:
   199                         if (ch == '/') {
   200                             state = 0;
   201                         } else {
   202                             state = 2;
   203                         }
   204                         break;
   205                 }
   206             }
   207         } finally {
   208             emul.close();
   209         }
   210     }
   211 
   212     private static InputStream loadClass(Bck2Brwsr.Resources l, String name) throws IOException {
   213         return l.get(name + ".class"); // NOI18N
   214     }
   215 
   216     static String toString(String name) throws IOException {
   217         StringBuilder sb = new StringBuilder();
   218 //        compile(sb, name);
   219         return sb.toString().toString();
   220     }
   221 
   222     private StringArray scripts = new StringArray();
   223     private StringArray references = new StringArray();
   224     
   225     @Override
   226     protected boolean requireReference(String cn) {
   227         if (references.contains(cn)) {
   228             return false;
   229         }
   230         references.add(cn);
   231         return true;
   232     }
   233 
   234     @Override
   235     protected void requireScript(String resourcePath) {
   236         scripts.add(resourcePath);
   237     }
   238 
   239     @Override
   240     String assignClass(String className) {
   241         return "vm." + className + " = ";
   242     }
   243     
   244     @Override
   245     String accessClass(String className) {
   246         return "vm." + className;
   247     }
   248 
   249     @Override
   250     String getVMObject() {
   251         return "vm";
   252     }
   253 }