vm/src/main/java/org/apidesign/vm4brwsr/GenJS.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 11 Nov 2012 13:23:52 +0100
branchjavap
changeset 151 40f95fe90cdc
parent 136 d48a0da4549c
child 162 70e7710a65dc
permissions -rw-r--r--
Almost rewritten to javap: @JavaScriptBody and double/long may not yet be supported
     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.ArrayList;
    24 import java.util.Arrays;
    25 import java.util.Collections;
    26 import java.util.Enumeration;
    27 import java.util.HashMap;
    28 import java.util.Iterator;
    29 import java.util.LinkedHashSet;
    30 import java.util.LinkedList;
    31 import java.util.List;
    32 import java.util.Map;
    33 
    34 /** Generator of JavaScript from bytecode of classes on classpath of the VM.
    35  *
    36  * @author Jaroslav Tulach <jtulach@netbeans.org>
    37  */
    38 final class GenJS {
    39     private GenJS() {}
    40     
    41     static void compile(Appendable out, String... names) throws IOException {
    42         compile(out, Arrays.asList(names));
    43     }
    44     static void compile(Appendable out, List<String> names) throws IOException {
    45         compile(GenJS.class.getClassLoader(), out, names);
    46     }
    47     static void compile(ClassLoader l, Appendable out, List<String> names) throws IOException {
    48         final Map<String,String> processed = new HashMap<String, String>();
    49         for (String baseClass : names) {
    50             LinkedHashSet<String> toProcess = new LinkedHashSet<String>() {
    51                 @Override
    52                 public boolean add(String e) {
    53                     if (processed.containsKey(e)) {
    54                         return false;
    55                     }
    56                     return super.add(e);
    57                 }
    58             };
    59             toProcess.add(baseClass);
    60             for (;;) {
    61                 String name = null;
    62                 Iterator<String> it = toProcess.iterator();
    63                 while (it.hasNext() && name == null) {
    64                     String n = it.next();
    65                     if (processed.get(n) != null) {
    66                         continue;
    67                     }
    68                     name = n;
    69                 }
    70                 if (name == null) {
    71                     break;
    72                 }
    73                 if (name.startsWith("sun/")) {
    74                     processed.put(name, "");
    75                     continue;
    76                 }            
    77                 InputStream is = loadClass(l, name);
    78                 if (is == null) {
    79                     throw new IOException("Can't find class " + name); 
    80                 }
    81                 LinkedList<String> scripts = new LinkedList<String>();
    82                 try {
    83                     String initCode = ByteCodeToJavaScript.compile(is, out, toProcess, scripts);
    84                     processed.put(name, initCode == null ? "" : initCode);
    85                 } catch (RuntimeException ex) {
    86                     if (out instanceof CharSequence) {
    87                         CharSequence seq = (CharSequence)out;
    88                         int lastBlock = seq.length();
    89                         while (lastBlock-- > 0) {
    90                             if (seq.charAt(lastBlock) == '{') {
    91                                 break;
    92                             }
    93                         }
    94                         throw new IOException("Error while compiling " + name + "\n" 
    95                             + seq.subSequence(lastBlock + 1, seq.length()), ex
    96                         );
    97                     } else {
    98                         throw new IOException("Error while compiling " + name + "\n" 
    99                             + out, ex
   100                         );
   101                     }
   102                 }
   103                 for (String resource : scripts) {
   104                     while (resource.startsWith("/")) {
   105                         resource = resource.substring(1);
   106                     }
   107                     InputStream emul = l.getResourceAsStream(resource);
   108                     if (emul == null) {
   109                         throw new IOException("Can't find " + resource);
   110                     }
   111                     readResource(emul, out);
   112                 }
   113             }
   114 
   115             List<String> toInit = new ArrayList<String>(toProcess);
   116             Collections.reverse(toInit);
   117 
   118             for (String clazz : toInit) {
   119                 String initCode = processed.get(clazz);
   120                 if (initCode != null && !initCode.isEmpty()) {
   121                     out.append(initCode).append("\n");
   122                     processed.put(clazz, "");
   123                 }
   124             }
   125 
   126         }
   127     }
   128     private static void readResource(InputStream emul, Appendable out) throws IOException {
   129         try {
   130             int state = 0;
   131             for (;;) {
   132                 int ch = emul.read();
   133                 if (ch == -1) {
   134                     break;
   135                 }
   136                 if (ch < 0 || ch > 255) {
   137                     throw new IOException("Invalid char in emulation " + ch);
   138                 }
   139                 switch (state) {
   140                     case 0: 
   141                         if (ch == '/') {
   142                             state = 1;
   143                         } else {
   144                             out.append((char)ch);
   145                         }
   146                         break;
   147                     case 1:
   148                         if (ch == '*') {
   149                             state = 2;
   150                         } else {
   151                             out.append('/').append((char)ch);
   152                             state = 0;
   153                         }
   154                         break;
   155                     case 2:
   156                         if (ch == '*') {
   157                             state = 3;
   158                         }
   159                         break;
   160                     case 3:
   161                         if (ch == '/') {
   162                             state = 0;
   163                         } else {
   164                             state = 2;
   165                         }
   166                         break;
   167                 }
   168             }
   169         } finally {
   170             emul.close();
   171         }
   172     }
   173 
   174     private static InputStream loadClass(ClassLoader l, String name) throws IOException {
   175         Enumeration<URL> en = l.getResources(name + ".class");
   176         URL u = null;
   177         while (en.hasMoreElements()) {
   178             u = en.nextElement();
   179         }
   180         if (u == null) {
   181             throw new IOException("Can't find " + name);
   182         }
   183         return u.openStream();
   184     }
   185 
   186     static String toString(String name) throws IOException {
   187         StringBuilder sb = new StringBuilder();
   188         compile(sb, name);
   189         return sb.toString().toString();
   190     }
   191 }