rt/flow/src/test/java/org/apidesign/bck2brwsr/flow/TestVM.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Wed, 11 Mar 2015 18:58:39 +0100
branchflow
changeset 1812 4fef6b767f61
parent 1787 rt/vm/src/test/java/org/apidesign/vm4brwsr/TestVM.java@ea12a3bb4b33
child 1815 fbe883b5a793
permissions -rw-r--r--
Defining API for registration of a Flow.Analyzer and getting ready for use the one from Graal
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012-2015 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.bck2brwsr.flow;
    19 
    20 import java.io.ByteArrayInputStream;
    21 import java.io.File;
    22 import java.io.FileOutputStream;
    23 import java.io.IOException;
    24 import java.io.InputStream;
    25 import java.io.OutputStreamWriter;
    26 import java.io.Writer;
    27 import java.net.URL;
    28 import java.util.ArrayList;
    29 import java.util.Arrays;
    30 import java.util.Enumeration;
    31 import java.util.HashSet;
    32 import java.util.List;
    33 import java.util.Set;
    34 import javax.script.Invocable;
    35 import javax.script.ScriptContext;
    36 import javax.script.ScriptEngine;
    37 import javax.script.ScriptEngineManager;
    38 import javax.script.ScriptException;
    39 import org.apidesign.vm4brwsr.Bck2Brwsr;
    40 import org.apidesign.vm4brwsr.Bck2Brwsr.Flow;
    41 import org.apidesign.vm4brwsr.ObfuscationLevel;
    42 import static org.testng.Assert.*;
    43 
    44 public final class TestVM {
    45     private final Invocable code;
    46     private final CharSequence codeSeq;
    47     private final Object bck2brwsr;
    48     
    49     
    50     private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
    51         this.code = code;
    52         this.codeSeq = codeSeq;
    53         this.bck2brwsr = ((ScriptEngine)code).eval("bck2brwsr(function(n) { return loader.get(n); })");
    54         ((ScriptEngine)code).getContext().setAttribute("loader", this, ScriptContext.ENGINE_SCOPE);
    55     }
    56     
    57     public Object execCode(
    58         String msg, Class<?> clazz, String method, 
    59         Object expRes, Object... args
    60     ) throws Exception {
    61         Object ret = null;
    62         try {
    63             ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
    64             List<Object> ma = new ArrayList<Object>();
    65             ma.add(method);
    66             ma.addAll(Arrays.asList(args));
    67             ret = code.invokeMethod(ret, "invoke", ma.toArray());
    68         } catch (ScriptException ex) {
    69             fail("Execution failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    70         } catch (NoSuchMethodException ex) {
    71             fail("Cannot find method in " + dumpJS(codeSeq), ex);
    72         }
    73         if (ret == null && expRes == null) {
    74             return null;
    75         }
    76         if (expRes != null && expRes.equals(ret)) {
    77             return null;
    78         }
    79         if (expRes instanceof Number) {
    80             // in case of Long it is necessary convert it to number
    81             // since the Long is represented by two numbers in JavaScript
    82             try {
    83                 final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
    84                 if (ret instanceof Long) {
    85                     ret = code.invokeMethod(toFP, "call", ret);
    86                 }
    87                 ret = code.invokeFunction("Number", ret);
    88             } catch (ScriptException ex) {
    89                 fail("Conversion to number failed in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    90             } catch (NoSuchMethodException ex) {
    91                 fail("Cannot find global Number(x) function in " + dumpJS(codeSeq) + ": " + ex.getMessage(), ex);
    92             }
    93         }
    94         return ret;
    95     }
    96     
    97     void assertExec(
    98         String msg, Class clazz, String method, Object expRes, Object... args
    99     ) throws Exception {
   100         Object ret = execCode(msg, clazz, method, expRes, args);
   101         if (ret == null) {
   102             return;
   103         }
   104         if (expRes instanceof Integer && ret instanceof Double) {
   105             expRes = ((Integer)expRes).doubleValue();
   106         }
   107         if (expRes != null && expRes.equals(ret)) {
   108             return;
   109         }
   110         assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
   111     }    
   112 
   113     static TestVM compileClass(String... names) throws ScriptException, IOException {
   114         return compileClass(null, GraalFlowAnalyzer.getDefault(), names);
   115     }
   116     
   117     static TestVM compileClass(StringBuilder sb, Flow.Analyzer flow, String... names) throws ScriptException, IOException {
   118         return compileClass(sb, null, flow, names);
   119     }
   120 
   121     static TestVM compileClass(StringBuilder sb, 
   122         ScriptEngine[] eng, Flow.Analyzer flow, String... names
   123     ) throws ScriptException, IOException {
   124         return compileClass(sb, eng, flow, new EmulationResources(), names);
   125     }
   126     static TestVM compileClass(
   127         StringBuilder sb, 
   128         ScriptEngine[] eng, 
   129         Flow.Analyzer flow,
   130         Bck2Brwsr.Resources resources, 
   131         String... names
   132     ) throws ScriptException, IOException {
   133         if (sb == null) {
   134             sb = new StringBuilder();
   135         }
   136         Bck2Brwsr.newCompiler()
   137             .resources(resources)
   138             .addClasses(names)
   139             .flowAnalyzer(flow)
   140             .generate(sb);
   141         ScriptEngineManager sem = new ScriptEngineManager();
   142         ScriptEngine js = sem.getEngineByExtension("js");
   143         if (eng != null) {
   144             eng[0] = js;
   145         }
   146         try {
   147             Object res = js.eval(sb.toString());
   148             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   149             return new TestVM((Invocable) js, sb);
   150         } catch (Exception ex) {
   151             if (sb.length() > 2000) {
   152                 sb = dumpJS(sb);
   153             }
   154             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   155             return null;
   156         }
   157     }
   158     
   159     static TestVM compileClassAsExtension(
   160         StringBuilder sb, ScriptEngine[] eng, 
   161         String name, final String resourceName, final String resourceContent
   162     ) throws ScriptException, IOException {
   163         return compileClassesAsExtension(sb, eng, resourceName, resourceContent, name);
   164     }
   165     static TestVM compileClassesAsExtension(
   166         StringBuilder sb, ScriptEngine[] eng, 
   167         final String resourceName, final String resourceContent, String... names
   168     ) throws ScriptException, IOException {
   169         if (sb == null) {
   170             sb = new StringBuilder();
   171         }
   172         if (eng[0] == null) {
   173             ScriptEngineManager sem = new ScriptEngineManager();
   174             ScriptEngine js = sem.getEngineByExtension("js");
   175             eng[0] = js;
   176             Bck2Brwsr.newCompiler().resources(new EmulationResources())
   177                 .obfuscation(ObfuscationLevel.NONE).generate(sb);
   178         }
   179         Set<String> exp = new HashSet<String>();
   180         for (String n : names) {
   181             int last = n.lastIndexOf('/');
   182             exp.add(n.substring(0, last + 1));
   183         }
   184         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   185             resources(new EmulationResources() {
   186                 @Override
   187                 public InputStream get(String name) throws IOException {
   188                     if (name.equals(resourceName)) {
   189                         return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
   190                     }
   191                     return super.get(name);
   192                 }
   193             }).
   194             addClasses(names).
   195             addResources("org/apidesign/vm4brwsr/obj.js").
   196             addExported(exp.toArray(new String[0])).
   197             obfuscation(ObfuscationLevel.FULL).
   198             library();
   199         if (resourceName != null) {
   200             b2b = b2b.addResources(resourceName);
   201         }
   202         b2b.generate(sb);
   203         try {
   204             defineAtoB(eng[0]);
   205             Object res = eng[0].eval(sb.toString());
   206             assertTrue(eng[0] instanceof Invocable, "It is invocable object: " + res);
   207             return new TestVM((Invocable) eng[0], sb);
   208         } catch (Exception ex) {
   209             if (sb.length() > 2000) {
   210                 sb = dumpJS(sb);
   211             }
   212             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   213             return null;
   214         }
   215     }
   216     
   217     static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
   218         if (sb == null) {
   219             sb = new StringBuilder();
   220         }
   221         Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
   222             resources(new EmulationResources()).
   223             addRootClasses(name).
   224             addResources(resources);
   225         b2b.generate(sb);
   226         ScriptEngineManager sem = new ScriptEngineManager();
   227         ScriptEngine js = sem.getEngineByExtension("js");
   228         if (eng != null) {
   229             eng[0] = js;
   230         }
   231         try {
   232             defineAtoB(js);
   233             
   234             Object res = js.eval(sb.toString());
   235             assertTrue(js instanceof Invocable, "It is invocable object: " + res);
   236             return new TestVM((Invocable) js, sb);
   237         } catch (Exception ex) {
   238             if (sb.length() > 2000) {
   239                 sb = dumpJS(sb);
   240             }
   241             fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
   242             return null;
   243         }
   244     }
   245 
   246     private static void defineAtoB(ScriptEngine js) throws ScriptException {
   247         js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
   248     }
   249 
   250     Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
   251         return code.invokeMethod(bck2brwsr, "loadClass", LoopControl.class.getName());
   252     }
   253     
   254     Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
   255         return code.invokeMethod(obj, method, params);
   256     }
   257 
   258     Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
   259         return code.invokeFunction(methodName, args);
   260     }
   261 
   262     static StringBuilder dumpJS(CharSequence sb) throws IOException {
   263         File f = File.createTempFile("execution", ".js");
   264         Writer w = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
   265         w.append(sb);
   266         w.close();
   267         return new StringBuilder(f.getPath());
   268     }
   269 
   270     @Override
   271     public String toString() {
   272         try {
   273             return dumpJS(codeSeq).toString();
   274         } catch (IOException ex) {
   275             return ex.toString();
   276         }
   277     }
   278 
   279     final CharSequence codeSeq() {
   280         return codeSeq;
   281     }
   282     
   283     private static class EmulationResources implements Bck2Brwsr.Resources {
   284         @Override
   285         public InputStream get(String name) throws IOException {
   286             if ("java/net/URI.class".equals(name)) {
   287                 // skip
   288                 return null;
   289             }
   290             if ("java/net/URLConnection.class".equals(name)) {
   291                 // skip
   292                 return null;
   293             }
   294             if ("java/lang/System.class".equals(name)) {
   295                 // skip
   296                 return null;
   297             }
   298             if ("java/io/PrintStream.class".equals(name)) {
   299                 // skip
   300                 return null;
   301             }
   302             if ("java/io/PrintWriter.class".equals(name)) {
   303                 // skip
   304                 return null;
   305             }
   306             Enumeration<URL> en = LoopControlTest.class.getClassLoader().getResources(name);
   307             URL u = null;
   308             while (en.hasMoreElements()) {
   309                 u = en.nextElement();
   310             }
   311             if (u == null) {
   312                 throw new IOException("Can't find " + name);
   313             }
   314             if (u.toExternalForm().contains("rt.jar!")) {
   315                 throw new IOException("No emulation for " + u);
   316             }
   317             return u.openStream();
   318         }
   319     }
   320 }