Search in sources :

Example 6 with PolyglotException

use of org.graalvm.polyglot.PolyglotException in project graal by oracle.

the class ProxyAPITest method testProxyExecutable.

@Test
public void testProxyExecutable() {
    ProxyExecutableTest proxy = new ProxyExecutableTest();
    Value value = context.asValue(proxy);
    assertTrue(value.canExecute());
    assertSame(proxy, value.asProxyObject());
    assertEquals(0, proxy.executeCounter);
    proxy.execute = (args) -> {
        assertEquals(2, args.length);
        assertEquals("a", args[0].asString());
        assertEquals('a', args[0].as(Object.class));
        ValueAssert.assertValue(context, args[0], Trait.STRING);
        assertTrue(args[1].isNumber());
        assertEquals((byte) 42, args[1].asByte());
        assertEquals((short) 42, args[1].asShort());
        assertEquals(42, args[1].asInt());
        assertEquals(42L, args[1].asLong());
        assertEquals(42, args[1].as(Object.class));
        ValueAssert.assertValue(context, args[1], Trait.NUMBER);
        return 42;
    };
    assertEquals(42, value.execute('a', 42).asInt());
    assertEquals(1, proxy.executeCounter);
    final RuntimeException ex = new RuntimeException();
    proxy.execute = (args) -> {
        throw ex;
    };
    try {
        value.execute();
        Assert.fail();
    } catch (PolyglotException e) {
        assertTrue(e.isHostException());
        assertSame(ex, e.asHostException());
        assertEquals(2, proxy.executeCounter);
    }
    assertValue(context, value, Trait.PROXY_OBJECT, Trait.EXECUTABLE);
}
Also used : ValueAssert.assertValue(com.oracle.truffle.api.test.polyglot.ValueAssert.assertValue) Value(org.graalvm.polyglot.Value) ProxyObject(org.graalvm.polyglot.proxy.ProxyObject) PolyglotException(org.graalvm.polyglot.PolyglotException) Test(org.junit.Test)

Example 7 with PolyglotException

use of org.graalvm.polyglot.PolyglotException in project graal by oracle.

the class ValueHostConversionTest method testExceptionFrames2.

@Test
public void testExceptionFrames2() {
    Value value = context.asValue(new TestExceptionFrames2());
    try {
        value.getMember("foo").execute();
        Assert.fail();
    } catch (PolyglotException e) {
        assertTrue(e.isHostException());
        assertTrue(e.asHostException() instanceof RuntimeException);
        assertEquals("foo", e.getMessage());
        Iterator<StackFrame> frameIterator = e.getPolyglotStackTrace().iterator();
        StackFrame frame;
        frame = frameIterator.next();
        assertTrue(frame.isHostFrame());
        assertEquals("foo", frame.toHostFrame().getMethodName());
        frame = frameIterator.next();
        assertTrue(frame.isHostFrame());
        assertEquals("execute", frame.toHostFrame().getMethodName());
        frame = frameIterator.next();
        assertTrue(frame.isHostFrame());
        assertEquals("testExceptionFrames2", frame.toHostFrame().getMethodName());
    }
}
Also used : StackFrame(org.graalvm.polyglot.PolyglotException.StackFrame) ValueAssert.assertValue(com.oracle.truffle.api.test.polyglot.ValueAssert.assertValue) Value(org.graalvm.polyglot.Value) Iterator(java.util.Iterator) PolyglotException(org.graalvm.polyglot.PolyglotException) Test(org.junit.Test)

Example 8 with PolyglotException

use of org.graalvm.polyglot.PolyglotException in project graal by oracle.

the class ValueHostInteropTest method testException2.

@Test
public void testException2() {
    Value hashMapClass = context.asValue(HashMap.class);
    try {
        hashMapClass.newInstance(-1);
        fail("expected an exception but none was thrown");
    } catch (PolyglotException ex) {
        assertTrue("expected HostException but was: " + ex.getClass(), ex.isHostException());
        assertThat(ex.asHostException(), CoreMatchers.instanceOf(IllegalArgumentException.class));
    }
    try {
        hashMapClass.newInstance("");
        fail("expected an exception but none was thrown");
    } catch (IllegalArgumentException ex) {
    }
}
Also used : ValueAssert.assertValue(com.oracle.truffle.api.test.polyglot.ValueAssert.assertValue) Value(org.graalvm.polyglot.Value) PolyglotException(org.graalvm.polyglot.PolyglotException) Test(org.junit.Test)

Example 9 with PolyglotException

use of org.graalvm.polyglot.PolyglotException in project graal by oracle.

the class MultiLanguageShell method readEvalPrint.

public int readEvalPrint() throws IOException {
    ConsoleReader console = new ConsoleReader(in, out);
    console.setHandleUserInterrupt(true);
    console.setExpandEvents(false);
    console.setCopyPasteDetection(true);
    console.println("GraalVM MultiLanguage Shell " + context.getEngine().getVersion());
    console.println("Copyright (c) 2013-2018, Oracle and/or its affiliates");
    List<Language> languages = new ArrayList<>();
    Set<Language> uniqueValues = new HashSet<>();
    for (Language language : context.getEngine().getLanguages().values()) {
        if (language.isInteractive()) {
            if (uniqueValues.add(language)) {
                languages.add(language);
            }
        }
    }
    languages.sort(Comparator.comparing(Language::getName));
    Map<String, Language> prompts = new HashMap<>();
    StringBuilder promptsString = new StringBuilder();
    for (Language language : languages) {
        String prompt = createPrompt(language).trim();
        promptsString.append(prompt).append(" ");
        prompts.put(prompt, language);
        console.println("  " + language.getName() + " version " + language.getVersion());
    }
    if (languages.isEmpty()) {
        throw new Launcher.AbortException("Error: No Graal languages installed. Exiting shell.", 1);
    }
    printUsage(console, promptsString, false);
    int maxNameLength = 0;
    for (Language language : languages) {
        maxNameLength = Math.max(maxNameLength, language.getName().length());
    }
    String startLanguage = defaultStartLanguage;
    if (startLanguage == null) {
        startLanguage = languages.get(0).getId();
    }
    Language currentLanguage = context.getEngine().getLanguages().get(startLanguage);
    if (currentLanguage == null) {
        throw new Launcher.AbortException("Error: could not find language '" + startLanguage + "'", 1);
    }
    assert languages.indexOf(currentLanguage) >= 0;
    Source bufferSource = null;
    String id = currentLanguage.getId();
    // console.println("initialize time: " + (System.currentTimeMillis() - start));
    String prompt = createPrompt(currentLanguage);
    console.getKeys().bind(String.valueOf((char) 12), new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            throw new ChangeLanguageException(null);
        }
    });
    console.getKeys().bind(String.valueOf((char) 10), new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            throw new RuntimeIncompleteSourceException();
        }
    });
    // initializes the language
    context.initialize(currentLanguage.getId());
    boolean verboseErrors = false;
    for (; ; ) {
        String input = null;
        Source source = null;
        try {
            input = console.readLine(bufferSource == null ? prompt : createBufferPrompt(prompt));
            if (input == null) {
                break;
            } else if (input.trim().equals("")) {
                continue;
            }
            Language switchedLanguage = null;
            String trimmedInput = input.trim();
            if (trimmedInput.equals("-usage")) {
                printUsage(console, promptsString, true);
                input = "";
            } else if (trimmedInput.equals("-verboseErrors")) {
                verboseErrors = !verboseErrors;
                if (verboseErrors) {
                    console.println("Verbose errors is now on.");
                } else {
                    console.println("Verbose errors is now off.");
                }
                input = "";
            } else if (prompts.containsKey(trimmedInput)) {
                switchedLanguage = prompts.get(input);
                input = "";
            }
            NonBlockingInputStream nonBlockIn = ((NonBlockingInputStream) console.getInput());
            while (nonBlockIn.isNonBlockingEnabled() && nonBlockIn.peek(10) != -2 && switchedLanguage == null) {
                String line = console.readLine(createBufferPrompt(prompt));
                String trimmedLine = line.trim();
                if (prompts.containsKey(trimmedLine)) {
                    switchedLanguage = prompts.get(trimmedLine);
                    break;
                } else {
                    input += "\n" + line;
                }
            }
            if (!input.trim().equals("")) {
                source = Source.newBuilder(currentLanguage.getId(), input, "<shell>").interactive(true).build();
                context.eval(source);
                bufferSource = null;
                console.getHistory().replace(source.getCharacters());
            }
            if (switchedLanguage != null) {
                throw new ChangeLanguageException(switchedLanguage);
            }
        } catch (UserInterruptException | EOFException e) {
            // interrupted by ctrl-c
            break;
        } catch (ChangeLanguageException e) {
            bufferSource = null;
            histories.put(currentLanguage, console.getHistory());
            currentLanguage = e.getLanguage() == null ? languages.get((languages.indexOf(currentLanguage) + 1) % languages.size()) : e.getLanguage();
            History history = histories.computeIfAbsent(currentLanguage, k -> new MemoryHistory());
            console.setHistory(history);
            id = currentLanguage.getId();
            prompt = createPrompt(currentLanguage);
            console.resetPromptLine("", "", 0);
            context.initialize(id);
        } catch (ThreadDeath e) {
            console.println("Execution killed!");
            continue;
        } catch (RuntimeIncompleteSourceException e) {
            console.println();
            input += "\n";
            bufferSource = source;
        } catch (PolyglotException e) {
            input += "\n";
            bufferSource = source;
            if (e.isExit()) {
                return e.getExitStatus();
            } else if (e.isIncompleteSource()) {
                input += "\n";
                bufferSource = source;
            } else if (!e.isInternalError()) {
                if (e.getMessage() != null && e.getMessage().isEmpty()) {
                    console.println(e.toString());
                } else {
                    if (verboseErrors) {
                        e.printStackTrace(new PrintWriter(console.getOutput()));
                    }
                }
            } else {
                e.printStackTrace(new PrintWriter(console.getOutput()));
            }
        } catch (Throwable e) {
            e.printStackTrace(new PrintWriter(console.getOutput()));
        }
    }
    return 0;
}
Also used : OutputStream(java.io.OutputStream) PrintWriter(java.io.PrintWriter) History(jline.console.history.History) ActionListener(java.awt.event.ActionListener) PolyglotException(org.graalvm.polyglot.PolyglotException) MemoryHistory(jline.console.history.MemoryHistory) UserInterruptException(jline.console.UserInterruptException) Set(java.util.Set) IOException(java.io.IOException) HashMap(java.util.HashMap) ActionEvent(java.awt.event.ActionEvent) EOFException(java.io.EOFException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) ConsoleReader(jline.console.ConsoleReader) Language(org.graalvm.polyglot.Language) Map(java.util.Map) Source(org.graalvm.polyglot.Source) Context(org.graalvm.polyglot.Context) Comparator(java.util.Comparator) NonBlockingInputStream(jline.internal.NonBlockingInputStream) InputStream(java.io.InputStream) HashMap(java.util.HashMap) ActionEvent(java.awt.event.ActionEvent) ArrayList(java.util.ArrayList) NonBlockingInputStream(jline.internal.NonBlockingInputStream) UserInterruptException(jline.console.UserInterruptException) History(jline.console.history.History) MemoryHistory(jline.console.history.MemoryHistory) Source(org.graalvm.polyglot.Source) Language(org.graalvm.polyglot.Language) EOFException(java.io.EOFException) HashSet(java.util.HashSet) PrintWriter(java.io.PrintWriter) ConsoleReader(jline.console.ConsoleReader) MemoryHistory(jline.console.history.MemoryHistory) PolyglotException(org.graalvm.polyglot.PolyglotException) ActionListener(java.awt.event.ActionListener)

Example 10 with PolyglotException

use of org.graalvm.polyglot.PolyglotException in project graal by oracle.

the class PolyglotLauncher method runScripts.

private void runScripts(List<Script> scripts, Context.Builder contextBuilder, String[] programArgs) {
    Script mainScript = scripts.get(scripts.size() - 1);
    try (Context context = contextBuilder.arguments(mainScript.getLanguage(), programArgs).build()) {
        Engine engine = context.getEngine();
        checkLanguage(mainLanguage, engine);
        for (Script script : scripts) {
            checkLanguage(script.languageId, engine);
        }
        for (Script script : scripts) {
            try {
                Value result = context.eval(script.getSource());
                if (script.isPrintResult()) {
                    System.out.println(result);
                }
            } catch (PolyglotException e) {
                if (e.isExit()) {
                    throw exit(e.getExitStatus());
                } else if (e.isGuestException()) {
                    e.printStackTrace();
                    throw exit(1);
                } else {
                    throw abort(e);
                }
            } catch (IOException e) {
                throw abort(e);
            } catch (Throwable t) {
                throw abort(t);
            }
        }
    }
}
Also used : Context(org.graalvm.polyglot.Context) Value(org.graalvm.polyglot.Value) IOException(java.io.IOException) PolyglotException(org.graalvm.polyglot.PolyglotException) Engine(org.graalvm.polyglot.Engine)

Aggregations

PolyglotException (org.graalvm.polyglot.PolyglotException)43 Value (org.graalvm.polyglot.Value)32 Test (org.junit.Test)32 Context (org.graalvm.polyglot.Context)19 ValueAssert.assertValue (com.oracle.truffle.api.test.polyglot.ValueAssert.assertValue)9 Source (org.graalvm.polyglot.Source)9 ArrayList (java.util.ArrayList)7 Iterator (java.util.Iterator)6 StackFrame (org.graalvm.polyglot.PolyglotException.StackFrame)6 AbstractMap (java.util.AbstractMap)5 TruffleContext (com.oracle.truffle.api.TruffleContext)4 TruffleObject (com.oracle.truffle.api.interop.TruffleObject)4 Engine (org.graalvm.polyglot.Engine)4 ProxyExecutable (org.graalvm.polyglot.proxy.ProxyExecutable)4 Env (com.oracle.truffle.api.TruffleLanguage.Env)3 LanguageContext (com.oracle.truffle.api.test.polyglot.LanguageSPITestLanguage.LanguageContext)3 IOException (java.io.IOException)3 ProxyObject (org.graalvm.polyglot.proxy.ProxyObject)3 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)3 CodeAction (com.oracle.truffle.api.instrumentation.test.UnwindReenterReturnTest.TestControlFlow.CodeAction)2