rt/flow/src/test/java/org/apidesign/bck2brwsr/flow/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Thu, 12 Mar 2015 12:07:54 +0100
branchflow
changeset 1815 fbe883b5a793
parent 1812 4fef6b767f61
child 1817 c1fd23f4e0ae
permissions -rw-r--r--
Optimize only simpleLoopTest... method and first check the generated code before compiling it as JavaScript
jaroslav@708
     1
/**
jaroslav@708
     2
 * Back 2 Browser Bytecode Translator
jaroslav@1787
     3
 * Copyright (C) 2012-2015 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
jaroslav@708
     4
 *
jaroslav@708
     5
 * This program is free software: you can redistribute it and/or modify
jaroslav@708
     6
 * it under the terms of the GNU General Public License as published by
jaroslav@708
     7
 * the Free Software Foundation, version 2 of the License.
jaroslav@708
     8
 *
jaroslav@708
     9
 * This program is distributed in the hope that it will be useful,
jaroslav@708
    10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
jaroslav@708
    11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
jaroslav@708
    12
 * GNU General Public License for more details.
jaroslav@708
    13
 *
jaroslav@708
    14
 * You should have received a copy of the GNU General Public License
jaroslav@708
    15
 * along with this program. Look for COPYING file in the top folder.
jaroslav@708
    16
 * If not, see http://opensource.org/licenses/GPL-2.0.
jaroslav@708
    17
 */
jaroslav@1812
    18
package org.apidesign.bck2brwsr.flow;
jaroslav@708
    19
jaroslav@1497
    20
import java.io.ByteArrayInputStream;
jaroslav@708
    21
import java.io.File;
jaroslav@1762
    22
import java.io.FileOutputStream;
jaroslav@708
    23
import java.io.IOException;
jaroslav@708
    24
import java.io.InputStream;
jaroslav@1762
    25
import java.io.OutputStreamWriter;
jaroslav@1762
    26
import java.io.Writer;
jaroslav@708
    27
import java.net.URL;
jaroslav@1609
    28
import java.util.ArrayList;
jaroslav@1609
    29
import java.util.Arrays;
jaroslav@708
    30
import java.util.Enumeration;
jaroslav@1611
    31
import java.util.HashSet;
jaroslav@1609
    32
import java.util.List;
jaroslav@1611
    33
import java.util.Set;
jaroslav@708
    34
import javax.script.Invocable;
jaroslav@1367
    35
import javax.script.ScriptContext;
jaroslav@708
    36
import javax.script.ScriptEngine;
jaroslav@708
    37
import javax.script.ScriptEngineManager;
jaroslav@708
    38
import javax.script.ScriptException;
jaroslav@1812
    39
import org.apidesign.vm4brwsr.Bck2Brwsr;
jaroslav@1812
    40
import org.apidesign.vm4brwsr.Bck2Brwsr.Flow;
jaroslav@1812
    41
import org.apidesign.vm4brwsr.ObfuscationLevel;
jaroslav@708
    42
import static org.testng.Assert.*;
jaroslav@708
    43
jaroslav@1367
    44
public final class TestVM {
jaroslav@1815
    45
    private final ScriptEngine js;
jaroslav@1815
    46
    private Invocable code;
jaroslav@708
    47
    private final CharSequence codeSeq;
jaroslav@1815
    48
    private Object bck2brwsr;
jaroslav@708
    49
    
jaroslav@708
    50
    
jaroslav@1815
    51
    private TestVM(ScriptEngine js, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
jaroslav@1815
    52
        this.js = js;
jaroslav@708
    53
        this.codeSeq = codeSeq;
jaroslav@708
    54
    }
jaroslav@708
    55
    
jaroslav@708
    56
    public Object execCode(
jaroslav@708
    57
        String msg, Class<?> clazz, String method, 
jaroslav@708
    58
        Object expRes, Object... args
jaroslav@708
    59
    ) throws Exception {
jaroslav@708
    60
        Object ret = null;
jaroslav@708
    61
        try {
jaroslav@1815
    62
            ret = getCode().invokeMethod(bck2brwsr, "loadClass", clazz.getName());
jaroslav@1812
    63
            List<Object> ma = new ArrayList<Object>();
jaroslav@1609
    64
            ma.add(method);
jaroslav@1609
    65
            ma.addAll(Arrays.asList(args));
jaroslav@1815
    66
            ret = getCode().invokeMethod(ret, "invoke", ma.toArray());
jaroslav@708
    67
        } catch (ScriptException ex) {
jaroslav@782
    68
            fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
jaroslav@708
    69
        } catch (NoSuchMethodException ex) {
jaroslav@708
    70
            fail("Cannot find method in " + dumpJS(codeSeq), ex);
jaroslav@708
    71
        }
jaroslav@708
    72
        if (ret == null && expRes == null) {
jaroslav@708
    73
            return null;
jaroslav@708
    74
        }
jaroslav@747
    75
        if (expRes != null && expRes.equals(ret)) {
jaroslav@708
    76
            return null;
jaroslav@708
    77
        }
jaroslav@708
    78
        if (expRes instanceof Number) {
jaroslav@708
    79
            // in case of Long it is necessary convert it to number
jaroslav@708
    80
            // since the Long is represented by two numbers in JavaScript
jaroslav@708
    81
            try {
jaroslav@1815
    82
                final Object toFP = ((ScriptEngine)getCode()).eval("Number.prototype.toFP");
jaroslav@1392
    83
                if (ret instanceof Long) {
jaroslav@1815
    84
                    ret = getCode().invokeMethod(toFP, "call", ret);
jaroslav@1392
    85
                }
jaroslav@1815
    86
                ret = getCode().invokeFunction("Number", ret);
jaroslav@708
    87
            } catch (ScriptException ex) {
jaroslav@784
    88
                fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
jaroslav@708
    89
            } catch (NoSuchMethodException ex) {
jaroslav@784
    90
                fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
jaroslav@708
    91
            }
jaroslav@708
    92
        }
jaroslav@708
    93
        return ret;
jaroslav@708
    94
    }
jaroslav@708
    95
    
jaroslav@708
    96
    void assertExec(
jaroslav@708
    97
        String msg, Class clazz, String method, Object expRes, Object... args
jaroslav@708
    98
    ) throws Exception {
jaroslav@708
    99
        Object ret = execCode(msg, clazz, method, expRes, args);
jaroslav@708
   100
        if (ret == null) {
jaroslav@708
   101
            return;
jaroslav@708
   102
        }
jaroslav@1392
   103
        if (expRes instanceof Integer && ret instanceof Double) {
jaroslav@1392
   104
            expRes = ((Integer)expRes).doubleValue();
jaroslav@1392
   105
        }
jaroslav@708
   106
        if (expRes != null && expRes.equals(ret)) {
jaroslav@708
   107
            return;
jaroslav@708
   108
        }
jaroslav@708
   109
        assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
jaroslav@708
   110
    }    
jaroslav@708
   111
jaroslav@708
   112
    static TestVM compileClass(String... names) throws ScriptException, IOException {
jaroslav@1812
   113
        return compileClass(null, GraalFlowAnalyzer.getDefault(), names);
jaroslav@708
   114
    }
jaroslav@708
   115
    
jaroslav@1812
   116
    static TestVM compileClass(StringBuilder sb, Flow.Analyzer flow, String... names) throws ScriptException, IOException {
jaroslav@1812
   117
        return compileClass(sb, null, flow, names);
jaroslav@708
   118
    }
jaroslav@708
   119
jaroslav@1812
   120
    static TestVM compileClass(StringBuilder sb, 
jaroslav@1812
   121
        ScriptEngine[] eng, Flow.Analyzer flow, String... names
jaroslav@1812
   122
    ) throws ScriptException, IOException {
jaroslav@1812
   123
        return compileClass(sb, eng, flow, new EmulationResources(), names);
jaroslav@1645
   124
    }
jaroslav@1645
   125
    static TestVM compileClass(
jaroslav@1645
   126
        StringBuilder sb, 
jaroslav@1645
   127
        ScriptEngine[] eng, 
jaroslav@1812
   128
        Flow.Analyzer flow,
jaroslav@1645
   129
        Bck2Brwsr.Resources resources, 
jaroslav@1645
   130
        String... names
jaroslav@1645
   131
    ) throws ScriptException, IOException {
jaroslav@708
   132
        if (sb == null) {
jaroslav@708
   133
            sb = new StringBuilder();
jaroslav@708
   134
        }
jaroslav@1812
   135
        Bck2Brwsr.newCompiler()
jaroslav@1812
   136
            .resources(resources)
jaroslav@1812
   137
            .addClasses(names)
jaroslav@1812
   138
            .flowAnalyzer(flow)
jaroslav@1812
   139
            .generate(sb);
jaroslav@708
   140
        ScriptEngineManager sem = new ScriptEngineManager();
jaroslav@708
   141
        ScriptEngine js = sem.getEngineByExtension("js");
jaroslav@708
   142
        if (eng != null) {
jaroslav@708
   143
            eng[0] = js;
jaroslav@708
   144
        }
jaroslav@708
   145
        try {
jaroslav@1815
   146
            return new TestVM(js, sb);
jaroslav@1493
   147
        } catch (Exception ex) {
jaroslav@1493
   148
            if (sb.length() > 2000) {
jaroslav@1493
   149
                sb = dumpJS(sb);
jaroslav@1493
   150
            }
jaroslav@1493
   151
            fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
jaroslav@1493
   152
            return null;
jaroslav@1493
   153
        }
jaroslav@1493
   154
    }
jaroslav@840
   155
jaroslav@708
   156
    Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
jaroslav@1815
   157
        return getCode().invokeMethod(bck2brwsr, "loadClass", LoopControl.class.getName());
jaroslav@708
   158
    }
jaroslav@708
   159
    
jaroslav@708
   160
    Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
jaroslav@1815
   161
        return getCode().invokeMethod(obj, method, params);
jaroslav@708
   162
    }
jaroslav@708
   163
jaroslav@708
   164
    Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
jaroslav@1815
   165
        return getCode().invokeFunction(methodName, args);
jaroslav@708
   166
    }
jaroslav@708
   167
jaroslav@708
   168
    static StringBuilder dumpJS(CharSequence sb) throws IOException {
jaroslav@708
   169
        File f = File.createTempFile("execution", ".js");
jaroslav@1762
   170
        Writer w = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
jaroslav@708
   171
        w.append(sb);
jaroslav@708
   172
        w.close();
jaroslav@708
   173
        return new StringBuilder(f.getPath());
jaroslav@708
   174
    }
jaroslav@708
   175
jaroslav@708
   176
    @Override
jaroslav@708
   177
    public String toString() {
jaroslav@708
   178
        try {
jaroslav@708
   179
            return dumpJS(codeSeq).toString();
jaroslav@708
   180
        } catch (IOException ex) {
jaroslav@708
   181
            return ex.toString();
jaroslav@708
   182
        }
jaroslav@708
   183
    }
jaroslav@1453
   184
jaroslav@1453
   185
    final CharSequence codeSeq() {
jaroslav@1453
   186
        return codeSeq;
jaroslav@1453
   187
    }
jaroslav@1815
   188
jaroslav@1815
   189
    /**
jaroslav@1815
   190
     * @return the code
jaroslav@1815
   191
     */
jaroslav@1815
   192
    private Invocable getCode() throws ScriptException {
jaroslav@1815
   193
        if (code == null) {
jaroslav@1815
   194
            Object res = js.eval(code.toString());
jaroslav@1815
   195
            code = (Invocable) js;
jaroslav@1815
   196
            this.bck2brwsr = ((ScriptEngine)code).eval("bck2brwsr(function(n) { return loader.get(n); })");
jaroslav@1815
   197
            ((ScriptEngine)code).getContext().setAttribute("loader", this, ScriptContext.ENGINE_SCOPE);
jaroslav@1815
   198
        }
jaroslav@1815
   199
        return (Invocable)code;
jaroslav@1815
   200
    }
jaroslav@708
   201
    
jaroslav@708
   202
    private static class EmulationResources implements Bck2Brwsr.Resources {
jaroslav@708
   203
        @Override
jaroslav@708
   204
        public InputStream get(String name) throws IOException {
jaroslav@1344
   205
            if ("java/net/URI.class".equals(name)) {
jaroslav@1344
   206
                // skip
jaroslav@1344
   207
                return null;
jaroslav@1344
   208
            }
jaroslav@1404
   209
            if ("java/net/URLConnection.class".equals(name)) {
jaroslav@1404
   210
                // skip
jaroslav@1404
   211
                return null;
jaroslav@1404
   212
            }
jaroslav@1344
   213
            if ("java/lang/System.class".equals(name)) {
jaroslav@1344
   214
                // skip
jaroslav@1344
   215
                return null;
jaroslav@1344
   216
            }
jaroslav@1812
   217
            if ("java/io/PrintStream.class".equals(name)) {
jaroslav@1812
   218
                // skip
jaroslav@1812
   219
                return null;
jaroslav@1812
   220
            }
jaroslav@1812
   221
            if ("java/io/PrintWriter.class".equals(name)) {
jaroslav@1812
   222
                // skip
jaroslav@1812
   223
                return null;
jaroslav@1812
   224
            }
jaroslav@1812
   225
            Enumeration<URL> en = LoopControlTest.class.getClassLoader().getResources(name);
jaroslav@708
   226
            URL u = null;
jaroslav@708
   227
            while (en.hasMoreElements()) {
jaroslav@708
   228
                u = en.nextElement();
jaroslav@708
   229
            }
jaroslav@708
   230
            if (u == null) {
jaroslav@708
   231
                throw new IOException("Can't find " + name);
jaroslav@708
   232
            }
jaroslav@708
   233
            if (u.toExternalForm().contains("rt.jar!")) {
jaroslav@708
   234
                throw new IOException("No emulation for " + u);
jaroslav@708
   235
            }
jaroslav@708
   236
            return u.openStream();
jaroslav@708
   237
        }
jaroslav@708
   238
    }
jaroslav@708
   239
}