vm/src/main/java/org/apidesign/vm4brwsr/GenJS.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 09 Oct 2012 18:47:42 -0700
branchemul
changeset 97 437df2a719e7
parent 93 a236a9f137ac
child 104 1376481f15e7
permissions -rw-r--r--
Better order of static initializers
     1 package org.apidesign.vm4brwsr;
     2 
     3 import java.io.BufferedWriter;
     4 import java.io.FileWriter;
     5 import java.io.IOException;
     6 import java.io.InputStream;
     7 import java.io.Writer;
     8 import java.net.URL;
     9 import java.util.Arrays;
    10 import java.util.Collections;
    11 import java.util.Enumeration;
    12 import java.util.HashMap;
    13 import java.util.Iterator;
    14 import java.util.LinkedList;
    15 import java.util.List;
    16 import java.util.Map;
    17 
    18 /** Generator of JavaScript from bytecode of classes on classpath of the VM.
    19  *
    20  * @author Jaroslav Tulach <jtulach@netbeans.org>
    21  */
    22 final class GenJS {
    23     private GenJS() {}
    24     
    25     public static void main(String... args) throws IOException {
    26         if (args.length < 2) {
    27             System.err.println("Usage: java -cp ... -jar ... <file_to_generate_js_code_to> java/lang/Class org/your/App ...");
    28             return;
    29         }
    30         
    31         Writer w = new BufferedWriter(new FileWriter(args[0]));
    32         List<String> classes = Arrays.asList(args).subList(1, args.length);
    33         compile(w, classes);
    34         w.close();
    35     }
    36     
    37     static void compile(Appendable out, String... names) throws IOException {
    38         compile(out, Arrays.asList(names));
    39     }
    40     static void compile(Appendable out, List<String> names) throws IOException {
    41         for (String baseClass : names) {
    42             Map<String,String> processed = new HashMap<String, String>();
    43             LinkedList<String> toProcess = new LinkedList<String>();
    44             toProcess.add(baseClass);
    45             for (;;) {
    46                 String name = null;
    47                 Iterator<String> it = toProcess.iterator();
    48                 while (it.hasNext() && name == null) {
    49                     String n = it.next();
    50                     if (processed.get(n) != null) {
    51                         continue;
    52                     }
    53                     name = n;
    54                 }
    55                 if (name == null) {
    56                     break;
    57                 }
    58                 if (name.startsWith("java/")
    59                     && !name.equals("java/lang/Object")
    60                     && !name.equals("java/lang/Class")
    61                     && !name.equals("java/lang/Number")
    62                     && !name.equals("java/lang/Integer")
    63                     && !name.equals("java/lang/Throwable")
    64                     && !name.equals("java/lang/Exception")
    65                     && !name.equals("java/lang/RuntimeException")
    66                     && !name.equals("java/lang/UnsupportedOperationException")
    67                     && !name.equals("java/lang/String")
    68                     && !name.equals("java/lang/String$CaseInsensitiveComparator")
    69                     && !name.equals("java/lang/StringBuilder")
    70                     && !name.equals("java/lang/AbstractStringBuilder")
    71                 ) {
    72                     processed.put(name, "");
    73                     continue;
    74                 }            
    75                 InputStream is = loadClass(name);
    76                 if (is == null) {
    77                     throw new IOException("Can't find class " + name); 
    78                 }
    79                 LinkedList<String> scripts = new LinkedList<String>();
    80                 try {
    81                     String initCode = ByteCodeToJavaScript.compile(is, out, toProcess, scripts);
    82                     processed.put(name, initCode == null ? "" : initCode);
    83                 } catch (RuntimeException ex) {
    84                     if (out instanceof CharSequence) {
    85                         CharSequence seq = (CharSequence)out;
    86                         int lastBlock = seq.length();
    87                         while (lastBlock-- >= 0) {
    88                             if (seq.charAt(lastBlock) == '{') {
    89                                 break;
    90                             }
    91                         }
    92                         throw new IOException("Error while compiling " + name + "\n" 
    93                             + seq.subSequence(lastBlock + 1, seq.length()), ex
    94                         );
    95                     } else {
    96                         throw new IOException("Error while compiling " + name + "\n" 
    97                             + out, ex
    98                         );
    99                     }
   100                 }
   101                 for (String resource : scripts) {
   102                     InputStream emul = GenJS.class.getResourceAsStream(resource);
   103                     if (emul == null) {
   104                         throw new IOException("Can't find " + resource);
   105                     }
   106                     readResource(emul, out);
   107                 }
   108             }
   109             
   110             Collections.reverse(toProcess);
   111 
   112             for (String clazz : toProcess) {
   113                 String initCode = processed.remove(clazz);
   114                 if (initCode != null) {
   115                     out.append(initCode).append("\n");
   116                 }
   117             }
   118         }
   119         
   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(String name) throws IOException {
   168         Enumeration<URL> en = ClassLoader.getSystemClassLoader().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         return u.openStream();
   177     }
   178     
   179 }