vm/src/main/java/org/apidesign/vm4brwsr/GenJS.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 16 Oct 2012 17:17:43 +0200
changeset 110 2428122fb24d
parent 109 b19d12a9e6d5
child 114 a0505844750a
permissions -rw-r--r--
Polishing imports, removing debug messages
     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.BufferedWriter;
    21 import java.io.FileWriter;
    22 import java.io.IOException;
    23 import java.io.InputStream;
    24 import java.io.Writer;
    25 import java.net.URL;
    26 import java.util.Arrays;
    27 import java.util.Collections;
    28 import java.util.Enumeration;
    29 import java.util.HashMap;
    30 import java.util.Iterator;
    31 import java.util.LinkedList;
    32 import java.util.List;
    33 import java.util.Map;
    34 
    35 /** Generator of JavaScript from bytecode of classes on classpath of the VM.
    36  *
    37  * @author Jaroslav Tulach <jtulach@netbeans.org>
    38  */
    39 final class GenJS {
    40     private GenJS() {}
    41     
    42     public static void main(String... args) throws IOException {
    43         if (args.length < 2) {
    44             System.err.println("Usage: java -cp ... -jar ... <file_to_generate_js_code_to> java/lang/Class org/your/App ...");
    45             return;
    46         }
    47         
    48         Writer w = new BufferedWriter(new FileWriter(args[0]));
    49         List<String> classes = Arrays.asList(args).subList(1, args.length);
    50         compile(w, classes);
    51         w.close();
    52     }
    53     
    54     static void compile(Appendable out, String... names) throws IOException {
    55         compile(out, Arrays.asList(names));
    56     }
    57     static void compile(Appendable out, List<String> names) throws IOException {
    58         compile(GenJS.class.getClassLoader(), out, names);
    59     }
    60     static void compile(ClassLoader l, Appendable out, List<String> names) throws IOException {
    61         for (String baseClass : names) {
    62             Map<String,String> processed = new HashMap<String, String>();
    63             LinkedList<String> toProcess = new LinkedList<String>();
    64             toProcess.add(baseClass);
    65             for (;;) {
    66                 String name = null;
    67                 Iterator<String> it = toProcess.iterator();
    68                 while (it.hasNext() && name == null) {
    69                     String n = it.next();
    70                     if (processed.get(n) != null) {
    71                         continue;
    72                     }
    73                     name = n;
    74                 }
    75                 if (name == null) {
    76                     break;
    77                 }
    78                 if (name.startsWith("java/")
    79                     && !name.equals("java/lang/Object")
    80                     && !name.equals("java/lang/Class")
    81                     && !name.equals("java/lang/Math")
    82                     && !name.equals("java/lang/Number")
    83                     && !name.equals("java/lang/Integer")
    84                     && !name.equals("java/lang/Float")
    85                     && !name.equals("java/lang/Double")
    86                     && !name.equals("java/lang/Throwable")
    87                     && !name.equals("java/lang/Exception")
    88                     && !name.equals("java/lang/RuntimeException")
    89                     && !name.equals("java/lang/UnsupportedOperationException")
    90                     && !name.equals("java/lang/String")
    91                     && !name.equals("java/lang/String$CaseInsensitiveComparator")
    92                     && !name.equals("java/lang/StringBuilder")
    93                     && !name.equals("java/lang/AbstractStringBuilder")
    94                 ) {
    95                     processed.put(name, "");
    96                     continue;
    97                 }            
    98                 InputStream is = loadClass(l, name);
    99                 if (is == null) {
   100                     throw new IOException("Can't find class " + name); 
   101                 }
   102                 LinkedList<String> scripts = new LinkedList<String>();
   103                 try {
   104                     String initCode = ByteCodeToJavaScript.compile(is, out, toProcess, scripts);
   105                     processed.put(name, initCode == null ? "" : initCode);
   106                 } catch (RuntimeException ex) {
   107                     if (out instanceof CharSequence) {
   108                         CharSequence seq = (CharSequence)out;
   109                         int lastBlock = seq.length();
   110                         while (lastBlock-- >= 0) {
   111                             if (seq.charAt(lastBlock) == '{') {
   112                                 break;
   113                             }
   114                         }
   115                         throw new IOException("Error while compiling " + name + "\n" 
   116                             + seq.subSequence(lastBlock + 1, seq.length()), ex
   117                         );
   118                     } else {
   119                         throw new IOException("Error while compiling " + name + "\n" 
   120                             + out, ex
   121                         );
   122                     }
   123                 }
   124                 for (String resource : scripts) {
   125                     while (resource.startsWith("/")) {
   126                         resource = resource.substring(1);
   127                     }
   128                     InputStream emul = l.getResourceAsStream(resource);
   129                     if (emul == null) {
   130                         throw new IOException("Can't find " + resource);
   131                     }
   132                     readResource(emul, out);
   133                 }
   134             }
   135             
   136             Collections.reverse(toProcess);
   137 
   138             for (String clazz : toProcess) {
   139                 String initCode = processed.remove(clazz);
   140                 if (initCode != null) {
   141                     out.append(initCode).append("\n");
   142                 }
   143             }
   144         }
   145     }
   146     private static void readResource(InputStream emul, Appendable out) throws IOException {
   147         try {
   148             int state = 0;
   149             for (;;) {
   150                 int ch = emul.read();
   151                 if (ch == -1) {
   152                     break;
   153                 }
   154                 if (ch < 0 || ch > 255) {
   155                     throw new IOException("Invalid char in emulation " + ch);
   156                 }
   157                 switch (state) {
   158                     case 0: 
   159                         if (ch == '/') {
   160                             state = 1;
   161                         } else {
   162                             out.append((char)ch);
   163                         }
   164                         break;
   165                     case 1:
   166                         if (ch == '*') {
   167                             state = 2;
   168                         } else {
   169                             out.append('/').append((char)ch);
   170                             state = 0;
   171                         }
   172                         break;
   173                     case 2:
   174                         if (ch == '*') {
   175                             state = 3;
   176                         }
   177                         break;
   178                     case 3:
   179                         if (ch == '/') {
   180                             state = 0;
   181                         } else {
   182                             state = 2;
   183                         }
   184                         break;
   185                 }
   186             }
   187         } finally {
   188             emul.close();
   189         }
   190     }
   191 
   192     private static InputStream loadClass(ClassLoader l, String name) throws IOException {
   193         Enumeration<URL> en = l.getResources(name + ".class");
   194         URL u = null;
   195         while (en.hasMoreElements()) {
   196             u = en.nextElement();
   197         }
   198         if (u == null) {
   199             throw new IOException("Can't find " + name);
   200         }
   201         return u.openStream();
   202     }
   203     
   204 }