vm/src/main/java/org/apidesign/vm4brwsr/GenJS.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Tue, 16 Oct 2012 12:42:00 +0200
changeset 106 346633cd13d6
parent 104 1376481f15e7
child 109 b19d12a9e6d5
permissions -rw-r--r--
Fixing license in all files
     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         for (String baseClass : names) {
    59             Map<String,String> processed = new HashMap<String, String>();
    60             LinkedList<String> toProcess = new LinkedList<String>();
    61             toProcess.add(baseClass);
    62             for (;;) {
    63                 String name = null;
    64                 Iterator<String> it = toProcess.iterator();
    65                 while (it.hasNext() && name == null) {
    66                     String n = it.next();
    67                     if (processed.get(n) != null) {
    68                         continue;
    69                     }
    70                     name = n;
    71                 }
    72                 if (name == null) {
    73                     break;
    74                 }
    75                 if (name.startsWith("java/")
    76                     && !name.equals("java/lang/Object")
    77                     && !name.equals("java/lang/Class")
    78                     && !name.equals("java/lang/Math")
    79                     && !name.equals("java/lang/Number")
    80                     && !name.equals("java/lang/Integer")
    81                     && !name.equals("java/lang/Float")
    82                     && !name.equals("java/lang/Double")
    83                     && !name.equals("java/lang/Throwable")
    84                     && !name.equals("java/lang/Exception")
    85                     && !name.equals("java/lang/RuntimeException")
    86                     && !name.equals("java/lang/UnsupportedOperationException")
    87                     && !name.equals("java/lang/String")
    88                     && !name.equals("java/lang/String$CaseInsensitiveComparator")
    89                     && !name.equals("java/lang/StringBuilder")
    90                     && !name.equals("java/lang/AbstractStringBuilder")
    91                 ) {
    92                     processed.put(name, "");
    93                     continue;
    94                 }            
    95                 InputStream is = loadClass(name);
    96                 if (is == null) {
    97                     throw new IOException("Can't find class " + name); 
    98                 }
    99                 LinkedList<String> scripts = new LinkedList<String>();
   100                 try {
   101                     String initCode = ByteCodeToJavaScript.compile(is, out, toProcess, scripts);
   102                     processed.put(name, initCode == null ? "" : initCode);
   103                 } catch (RuntimeException ex) {
   104                     if (out instanceof CharSequence) {
   105                         CharSequence seq = (CharSequence)out;
   106                         int lastBlock = seq.length();
   107                         while (lastBlock-- >= 0) {
   108                             if (seq.charAt(lastBlock) == '{') {
   109                                 break;
   110                             }
   111                         }
   112                         throw new IOException("Error while compiling " + name + "\n" 
   113                             + seq.subSequence(lastBlock + 1, seq.length()), ex
   114                         );
   115                     } else {
   116                         throw new IOException("Error while compiling " + name + "\n" 
   117                             + out, ex
   118                         );
   119                     }
   120                 }
   121                 for (String resource : scripts) {
   122                     InputStream emul = GenJS.class.getResourceAsStream(resource);
   123                     if (emul == null) {
   124                         throw new IOException("Can't find " + resource);
   125                     }
   126                     readResource(emul, out);
   127                 }
   128             }
   129             
   130             Collections.reverse(toProcess);
   131 
   132             for (String clazz : toProcess) {
   133                 String initCode = processed.remove(clazz);
   134                 if (initCode != null) {
   135                     out.append(initCode).append("\n");
   136                 }
   137             }
   138         }
   139     }
   140     private static void readResource(InputStream emul, Appendable out) throws IOException {
   141         try {
   142             int state = 0;
   143             for (;;) {
   144                 int ch = emul.read();
   145                 if (ch == -1) {
   146                     break;
   147                 }
   148                 if (ch < 0 || ch > 255) {
   149                     throw new IOException("Invalid char in emulation " + ch);
   150                 }
   151                 switch (state) {
   152                     case 0: 
   153                         if (ch == '/') {
   154                             state = 1;
   155                         } else {
   156                             out.append((char)ch);
   157                         }
   158                         break;
   159                     case 1:
   160                         if (ch == '*') {
   161                             state = 2;
   162                         } else {
   163                             out.append('/').append((char)ch);
   164                             state = 0;
   165                         }
   166                         break;
   167                     case 2:
   168                         if (ch == '*') {
   169                             state = 3;
   170                         }
   171                         break;
   172                     case 3:
   173                         if (ch == '/') {
   174                             state = 0;
   175                         } else {
   176                             state = 2;
   177                         }
   178                         break;
   179                 }
   180             }
   181         } finally {
   182             emul.close();
   183         }
   184     }
   185 
   186     private static InputStream loadClass(String name) throws IOException {
   187         Enumeration<URL> en = ClassLoader.getSystemClassLoader().getResources(name + ".class");
   188         URL u = null;
   189         while (en.hasMoreElements()) {
   190             u = en.nextElement();
   191         }
   192         if (u == null) {
   193             throw new IOException("Can't find " + name);
   194         }
   195         return u.openStream();
   196     }
   197     
   198 }