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