vm/src/main/java/org/apidesign/vm4brwsr/GenJS.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 06 Dec 2012 21:31:09 +0100
branchlazyvm
changeset 274 81f6e7778135
parent 272 a6a23aa7a546
child 276 aeb9fe11cd60
permissions -rw-r--r--
Hiding all generated class methods from sight of external users. Exposing only bck2brwsr entry point function
     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 import java.net.URL;
    23 import java.util.Enumeration;
    24 
    25 /** Generator of JavaScript from bytecode of classes on classpath of the VM.
    26  *
    27  * @author Jaroslav Tulach <jtulach@netbeans.org>
    28  */
    29 class GenJS extends ByteCodeToJavaScript {
    30     public GenJS(Appendable out) {
    31         super(out);
    32     }
    33     
    34     static void compile(Appendable out, String... names) throws IOException {
    35         compile(out, StringArray.asList(names));
    36     }
    37     static void compile(ClassLoader l, Appendable out, String... names) throws IOException {
    38         compile(l, out, StringArray.asList(names));
    39     }
    40     static void compile(Appendable out, StringArray names) throws IOException {
    41         compile(GenJS.class.getClassLoader(), out, names);
    42     }
    43     static void compile(ClassLoader l, Appendable out, StringArray names) throws IOException {
    44         new GenJS(out).doCompile(l, names);
    45     }
    46     protected void doCompile(ClassLoader l, StringArray names) throws IOException {
    47         out.append("(function VM(global) {");
    48         out.append("\n  var vm = {};");
    49         StringArray processed = new StringArray();
    50         StringArray initCode = new StringArray();
    51         for (String baseClass : names.toArray()) {
    52             references.add(baseClass);
    53             for (;;) {
    54                 String name = null;
    55                 for (String n : references.toArray()) {
    56                     if (processed.contains(n)) {
    57                         continue;
    58                     }
    59                     name = n;
    60                 }
    61                 if (name == null) {
    62                     break;
    63                 }
    64                 InputStream is = loadClass(l, name);
    65                 if (is == null) {
    66                     throw new IOException("Can't find class " + name); 
    67                 }
    68                 try {
    69                     String ic = compile(is);
    70                     processed.add(name);
    71                     initCode.add(ic == null ? "" : ic);
    72                 } catch (RuntimeException ex) {
    73                     if (out instanceof CharSequence) {
    74                         CharSequence seq = (CharSequence)out;
    75                         int lastBlock = seq.length();
    76                         while (lastBlock-- > 0) {
    77                             if (seq.charAt(lastBlock) == '{') {
    78                                 break;
    79                             }
    80                         }
    81                         throw new IOException("Error while compiling " + name + "\n" 
    82                             + seq.subSequence(lastBlock + 1, seq.length()), ex
    83                         );
    84                     } else {
    85                         throw new IOException("Error while compiling " + name + "\n" 
    86                             + out, ex
    87                         );
    88                     }
    89                 }
    90             }
    91 
    92             for (String resource : scripts.toArray()) {
    93                 while (resource.startsWith("/")) {
    94                     resource = resource.substring(1);
    95                 }
    96                 InputStream emul = l.getResourceAsStream(resource);
    97                 if (emul == null) {
    98                     throw new IOException("Can't find " + resource);
    99                 }
   100                 readResource(emul, out);
   101             }
   102             scripts = new StringArray();
   103             
   104             StringArray toInit = StringArray.asList(references.toArray());
   105             toInit.reverse();
   106 
   107             for (String ic : toInit.toArray()) {
   108                 int indx = processed.indexOf(ic);
   109                 if (indx >= 0) {
   110                     out.append(initCode.toArray()[indx]).append("\n");
   111                     initCode.toArray()[indx] = "";
   112                 }
   113             }
   114         }
   115         out.append(
   116               "  global.bck2brwsr = function() { return {\n"
   117             + "    loadClass : function(name) { return vm[name](true); }\n"
   118             + "  };\n};\n");
   119         out.append("}(this));");
   120     }
   121     private static void readResource(InputStream emul, Appendable out) throws IOException {
   122         try {
   123             int state = 0;
   124             for (;;) {
   125                 int ch = emul.read();
   126                 if (ch == -1) {
   127                     break;
   128                 }
   129                 if (ch < 0 || ch > 255) {
   130                     throw new IOException("Invalid char in emulation " + ch);
   131                 }
   132                 switch (state) {
   133                     case 0: 
   134                         if (ch == '/') {
   135                             state = 1;
   136                         } else {
   137                             out.append((char)ch);
   138                         }
   139                         break;
   140                     case 1:
   141                         if (ch == '*') {
   142                             state = 2;
   143                         } else {
   144                             out.append('/').append((char)ch);
   145                             state = 0;
   146                         }
   147                         break;
   148                     case 2:
   149                         if (ch == '*') {
   150                             state = 3;
   151                         }
   152                         break;
   153                     case 3:
   154                         if (ch == '/') {
   155                             state = 0;
   156                         } else {
   157                             state = 2;
   158                         }
   159                         break;
   160                 }
   161             }
   162         } finally {
   163             emul.close();
   164         }
   165     }
   166 
   167     private static InputStream loadClass(ClassLoader l, String name) throws IOException {
   168         Enumeration<URL> en = l.getResources(name + ".class");
   169         URL u = null;
   170         while (en.hasMoreElements()) {
   171             u = en.nextElement();
   172         }
   173         if (u == null) {
   174             throw new IOException("Can't find " + name);
   175         }
   176         if (u.toExternalForm().contains("rt.jar!")) {
   177             throw new IOException("No emulation for " + u);
   178         }
   179         return u.openStream();
   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 }