Defining API for registration of a Flow.Analyzer and getting ready for use the one from Graal
2 * Back 2 Browser Bytecode Translator
3 * Copyright (C) 2012-2015 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
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.
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.
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.
18 package org.apidesign.bck2brwsr.flow;
20 import java.io.ByteArrayInputStream;
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;
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;
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.*;
44 public final class TestVM {
45 private final Invocable code;
46 private final CharSequence codeSeq;
47 private final Object bck2brwsr;
50 private TestVM(Invocable code, CharSequence codeSeq) throws ScriptException, NoSuchMethodException {
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);
57 public Object execCode(
58 String msg, Class<?> clazz, String method,
59 Object expRes, Object... args
63 ret = code.invokeMethod(bck2brwsr, "loadClass", clazz.getName());
64 List<Object> ma = new ArrayList<Object>();
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);
73 if (ret == null && expRes == null) {
76 if (expRes != null && expRes.equals(ret)) {
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
83 final Object toFP = ((ScriptEngine)code).eval("Number.prototype.toFP");
84 if (ret instanceof Long) {
85 ret = code.invokeMethod(toFP, "call", ret);
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);
98 String msg, Class clazz, String method, Object expRes, Object... args
100 Object ret = execCode(msg, clazz, method, expRes, args);
104 if (expRes instanceof Integer && ret instanceof Double) {
105 expRes = ((Integer)expRes).doubleValue();
107 if (expRes != null && expRes.equals(ret)) {
110 assertEquals(ret, expRes, msg + "was: " + ret + "\n" + dumpJS(codeSeq));
113 static TestVM compileClass(String... names) throws ScriptException, IOException {
114 return compileClass(null, GraalFlowAnalyzer.getDefault(), names);
117 static TestVM compileClass(StringBuilder sb, Flow.Analyzer flow, String... names) throws ScriptException, IOException {
118 return compileClass(sb, null, flow, names);
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);
126 static TestVM compileClass(
130 Bck2Brwsr.Resources resources,
132 ) throws ScriptException, IOException {
134 sb = new StringBuilder();
136 Bck2Brwsr.newCompiler()
137 .resources(resources)
141 ScriptEngineManager sem = new ScriptEngineManager();
142 ScriptEngine js = sem.getEngineByExtension("js");
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) {
154 fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
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);
165 static TestVM compileClassesAsExtension(
166 StringBuilder sb, ScriptEngine[] eng,
167 final String resourceName, final String resourceContent, String... names
168 ) throws ScriptException, IOException {
170 sb = new StringBuilder();
172 if (eng[0] == null) {
173 ScriptEngineManager sem = new ScriptEngineManager();
174 ScriptEngine js = sem.getEngineByExtension("js");
176 Bck2Brwsr.newCompiler().resources(new EmulationResources())
177 .obfuscation(ObfuscationLevel.NONE).generate(sb);
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));
184 Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
185 resources(new EmulationResources() {
187 public InputStream get(String name) throws IOException {
188 if (name.equals(resourceName)) {
189 return new ByteArrayInputStream(resourceContent.getBytes("UTF-8"));
191 return super.get(name);
195 addResources("org/apidesign/vm4brwsr/obj.js").
196 addExported(exp.toArray(new String[0])).
197 obfuscation(ObfuscationLevel.FULL).
199 if (resourceName != null) {
200 b2b = b2b.addResources(resourceName);
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) {
212 fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
217 static TestVM compileClassAndResources(StringBuilder sb, ScriptEngine[] eng, String name, String... resources) throws ScriptException, IOException {
219 sb = new StringBuilder();
221 Bck2Brwsr b2b = Bck2Brwsr.newCompiler().
222 resources(new EmulationResources()).
223 addRootClasses(name).
224 addResources(resources);
226 ScriptEngineManager sem = new ScriptEngineManager();
227 ScriptEngine js = sem.getEngineByExtension("js");
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) {
241 fail("Could not evaluate:" + ex.getClass() + ":" + ex.getMessage() + "\n" + sb, ex);
246 private static void defineAtoB(ScriptEngine js) throws ScriptException {
247 js.eval("atob = function(s) { return new String(org.apidesign.vm4brwsr.ResourcesTest.parseBase64Binary(s)); }");
250 Object loadClass(String loadClass, String name) throws ScriptException, NoSuchMethodException {
251 return code.invokeMethod(bck2brwsr, "loadClass", LoopControl.class.getName());
254 Object invokeMethod(Object obj, String method, Object... params) throws ScriptException, NoSuchMethodException {
255 return code.invokeMethod(obj, method, params);
258 Object invokeFunction(String methodName, Object... args) throws ScriptException, NoSuchMethodException {
259 return code.invokeFunction(methodName, args);
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");
267 return new StringBuilder(f.getPath());
271 public String toString() {
273 return dumpJS(codeSeq).toString();
274 } catch (IOException ex) {
275 return ex.toString();
279 final CharSequence codeSeq() {
283 private static class EmulationResources implements Bck2Brwsr.Resources {
285 public InputStream get(String name) throws IOException {
286 if ("java/net/URI.class".equals(name)) {
290 if ("java/net/URLConnection.class".equals(name)) {
294 if ("java/lang/System.class".equals(name)) {
298 if ("java/io/PrintStream.class".equals(name)) {
302 if ("java/io/PrintWriter.class".equals(name)) {
306 Enumeration<URL> en = LoopControlTest.class.getClassLoader().getResources(name);
308 while (en.hasMoreElements()) {
309 u = en.nextElement();
312 throw new IOException("Can't find " + name);
314 if (u.toExternalForm().contains("rt.jar!")) {
315 throw new IOException("No emulation for " + u);
317 return u.openStream();