1 package org.apidesign.vm4brwsr;
3 import java.io.BufferedWriter;
4 import java.io.FileWriter;
5 import java.io.IOException;
6 import java.io.InputStream;
8 import java.util.Arrays;
9 import java.util.HashSet;
10 import java.util.LinkedList;
11 import java.util.List;
14 /** Generator of JavaScript from bytecode of classes on classpath of the VM.
16 * @author Jaroslav Tulach <jtulach@netbeans.org>
21 public static void main(String... args) throws IOException {
22 if (args.length < 2) {
23 System.err.println("Usage: java -cp ... -jar ... <file_to_generate_js_code_to> java/lang/Class org/your/App ...");
27 Writer w = new BufferedWriter(new FileWriter(args[0]));
28 List<String> classes = Arrays.asList(args).subList(1, args.length);
33 static void compile(Appendable out, String... names) throws IOException {
34 compile(out, Arrays.asList(names));
36 static void compile(Appendable out, List<String> names) throws IOException {
37 Set<String> processed = new HashSet<String>();
38 LinkedList<String> toProcess = new LinkedList<String>(names);
40 toProcess.removeAll(processed);
41 if (toProcess.isEmpty()) {
44 String name = toProcess.getFirst();
46 if (name.startsWith("sun/")) {
49 if (name.startsWith("java/")
50 && !name.equals("java/lang/Object")
51 && !name.equals("java/lang/StringBuilder")
52 && !name.equals("java/lang/AbstractStringBuilder")
56 InputStream is = GenJS.class.getClassLoader().getResourceAsStream(name + ".class");
58 throw new IOException("Can't find class " + name);
60 LinkedList<String> scripts = new LinkedList<String>();
62 ByteCodeToJavaScript.compile(is, out, toProcess, scripts);
63 } catch (RuntimeException ex) {
64 if (out instanceof CharSequence) {
65 CharSequence seq = (CharSequence)out;
66 int lastBlock = seq.length();
67 while (lastBlock-- >= 0) {
68 if (seq.charAt(lastBlock) == '{') {
72 throw new IOException("Error while compiling " + name + "\n"
73 + seq.subSequence(lastBlock + 1, seq.length()), ex
76 throw new IOException("Error while compiling " + name + "\n"
81 for (String resource : scripts) {
82 InputStream emul = GenJS.class.getResourceAsStream(resource);
84 throw new IOException("Can't find " + resource);
86 readResource(emul, out);
90 private static void readResource(InputStream emul, Appendable out) throws IOException {
98 if (ch < 0 || ch > 255) {
99 throw new IOException("Invalid char in emulation " + ch);
106 out.append((char)ch);
113 out.append('/').append((char)ch);