com.oracle.truffle.api.nodes.Node Java Examples

The following examples show how to use com.oracle.truffle.api.nodes.Node. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EventLogger.java    From nodeprof.js with Apache License 2.0 6 votes vote down vote up
InputTypes(Class<? extends Node> instrumentedNode, Object[] inputs) {
    this.nodeClass = instrumentedNode;
    if (inputs == null) {
        types = null;
        this.sample = "";
    } else {
        this.types = new Class<?>[inputs.length];
        String s = "";
        for (int i = 0; i < inputs.length; i++) {
            if (inputs[i] == null) {
                this.types[i] = null;
            } else {
                s += inputs[i];
                this.types[i] = inputs[i].getClass();
            }
            if (i != inputs.length - 1) {
                s += "/";
            }
        }
        this.sample = s;
    }
}
 
Example #2
Source File: HashemLexicalScope.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@SuppressWarnings("all") // The parameter node should not be assigned
public static HashemLexicalScope createScope(Node node) {
    HashemBlockNode block = getParentBlock(node);
    if (block == null) {
        // We're in the root.
        block = findChildrenBlock(node);
        if (block == null) {
            // CorruptedHashemiAST, no block was found
            RootNode root = node.getRootNode();
            assert root instanceof HashemEvalRootNode || root instanceof HashemRootNode : "CorruptedHashemiAST under " + node;
            return new HashemLexicalScope(null, null, (HashemBlockNode) null);
        }
        node = null; // node is above the block
    }
    // Test if there is a parent block. If not, we're in the root scope.
    HashemBlockNode parentBlock = getParentBlock(block);
    if (parentBlock == null) {
        return new HashemLexicalScope(node, block, block.getRootNode());
    } else {
        return new HashemLexicalScope(node, block, parentBlock);
    }
}
 
Example #3
Source File: LiteralFactory.java    From nodeprof.js with Apache License 2.0 6 votes vote down vote up
@Override
public BaseEventHandlerNode create(EventContext context) {
    return new LiteralEventHandler(context) {
        private final boolean skip = !types.contains(LiteralTag.Type.valueOf(getLiteralType()));
        @Node.Child private InteropLibrary postDispatch = (post == null) ? null : createDispatchNode();

        @Override
        public void executePost(VirtualFrame frame, Object result,
                        Object[] inputs) throws InteropException {
            if (post != null && !skip) {
                wrappedDispatchExecution(this, postDispatch, post, getSourceIID(), convertResult(result), Undefined.instance, getLiteralType());
            }
        }

    };
}
 
Example #4
Source File: HashemLexicalScope.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
public HashemLexicalScope findParent() {
    if (parentBlock == null) {
        // This was a root scope.
        return null;
    }
    if (parent == null) {
        Node node = block;
        HashemBlockNode newBlock = parentBlock;
        // Test if there is a next parent block. If not, we're in the root scope.
        HashemBlockNode newParentBlock = getParentBlock(newBlock);
        if (newParentBlock == null) {
            parent = new HashemLexicalScope(node, newBlock, newBlock.getRootNode());
        } else {
            parent = new HashemLexicalScope(node, newBlock, newParentBlock);
        }
    }
    return parent;
}
 
Example #5
Source File: FunctionRootEventHandler.java    From nodeprof.js with Apache License 2.0 6 votes vote down vote up
/**
 * @return the source of the instrumented node (or its closest parent), or null if no source is
 *         available
 */
public Source getSource() {
    if (isRegularExpression() || this.isBuiltin) {
        return null;
    }

    Node n = context.getInstrumentedNode();
    while (n != null && !(n instanceof FunctionBodyNode)) {
        n = n.getParent();
    }

    if (n == null) {
        return null;
    }

    if (n.getSourceSection() == null) {
        return null;
    }

    return n.getSourceSection().getSource();
}
 
Example #6
Source File: DeclareFactory.java    From nodeprof.js with Apache License 2.0 6 votes vote down vote up
@Override
public BaseEventHandlerNode create(EventContext context) {
    return new DeclareEventHandler(context) {
        @Node.Child private InteropLibrary postDispatch = (post == null) ? null : createDispatchNode();

        @Override
        public void executePost(VirtualFrame frame, Object result,
                        Object[] inputs) throws InteropException {
            if (post != null) {
                checkForSymbolicLocation(context.getInstrumentedNode(), frame.getArguments());

                wrappedDispatchExecution(this, postDispatch, post, getSourceIID(), getDeclareName(), getDeclareType());
            }
        }

    };
}
 
Example #7
Source File: HashemTaRepeatingNode.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
private boolean evaluateCondition(VirtualFrame frame) {
    try {
        /*
         * The condition must evaluate to a boolean value, so we call the boolean-specialized
         * execute method.
         */
        return conditionNode.executeBoolean(frame);
    } catch (UnexpectedResultException ex) {
        /*
         * The condition evaluated to a non-boolean result. This is a type error in the SL
         * program. We report it with the same exception that Truffle DSL generated nodes use to
         * report type errors.
         */
        throw new UnsupportedSpecializationException(this, new Node[]{conditionNode}, ex.getResult());
    }
}
 
Example #8
Source File: HashemStatementNode.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
/**
 * Formats a source section of a node in human readable form. If no source section could be
 * found it looks up the parent hierarchy until it finds a source section. Nodes where this was
 * required append a <code>'~'</code> at the end.
 *
 * @param node the node to format.
 * @return a formatted source section string
 */
public static String formatSourceSection(Node node) {
    if (node == null) {
        return "<unknown>";
    }
    SourceSection section = node.getSourceSection();
    boolean estimated = false;
    if (section == null) {
        section = node.getEncapsulatingSourceSection();
        estimated = true;
    }

    if (section == null || section.getSource() == null) {
        return "<unknown source>";
    } else {
        String sourceName = section.getSource().getName();
        int startLine = section.getStartLine();
        return String.format("%s:%d%s", sourceName, startLine, estimated ? "~" : "");
    }
}
 
Example #9
Source File: BaseEventHandlerNode.java    From nodeprof.js with Apache License 2.0 5 votes vote down vote up
protected static void checkForSymbolicLocation(Node node, Object[] args) {
    if (GlobalConfiguration.SYMBOLIC_LOCATIONS) {
        RootNode root = node.getRootNode();
        assert root != null;
        if (":program".equals(root.getName())) {
            SourceMapping.addSyntheticLocation(root.getSourceSection(), ":program");
        } else if (SourceMapping.isModuleOrWrapper(root.getSourceSection()) && isModuleInvocation(args)) {
            SourceMapping.addSyntheticLocation(root.getSourceSection(), "module");
        }
    }
}
 
Example #10
Source File: HashemInstrumentTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
private static void checkBlock(Scope ls) {
    assertEquals("block", ls.getName());
    // Test that ls.getNode() does not return the current root node, it ought to be a block node
    Node node = ls.getNode();
    assertNotNull(node);
    assertFalse(node.getClass().getName(), node instanceof RootNode);
}
 
Example #11
Source File: EventLogger.java    From nodeprof.js with Apache License 2.0 5 votes vote down vote up
@TruffleBoundary
public void addError(ProfiledTagEnum tag, Class<? extends Node> instrumentedNode, Object[] inputs) {
    if (!mapping.containsKey(tag)) {
        mapping.put(tag, new HashSet<EventLogger.EventReport.InputTypes>());
    }
    mapping.get(tag).add(new InputTypes(instrumentedNode, inputs));
}
 
Example #12
Source File: ForObjectFactory.java    From nodeprof.js with Apache License 2.0 5 votes vote down vote up
@Override
public BaseEventHandlerNode create(EventContext context) {
    return new LoopEventHandler(context) {
        @Node.Child private InteropLibrary preDispatch = (pre == null) ? null : createDispatchNode();

        @Override
        public void executePre(VirtualFrame frame,
                        Object[] inputs) throws InteropException {
            if (pre != null && (isForIn() || isForOf())) {
                wrappedDispatchExecution(this, preDispatch, pre, getSourceIID(), isForIn());
            }
        }
    };
}
 
Example #13
Source File: InitialRootFactory.java    From nodeprof.js with Apache License 2.0 5 votes vote down vote up
@Override
public BaseEventHandlerNode create(EventContext context) {
    return new FunctionRootEventHandler(context) {
        @Node.Child private InteropLibrary postDispatch = (post == null) ? null : createDispatchNode();

        @Override
        public int getPriority() {
            return -1;
        }

        @Override
        public BaseEventHandlerNode wantsToUpdateHandler() {
            // remove after initial execution
            return null;
        }

        @Override
        public void executePre(VirtualFrame frame, Object[] inputs) throws InteropException {
            checkForSymbolicLocation(context.getInstrumentedNode(), getArguments(frame));

            if (post == null) {
                return;
            }

            Source source = getSource();
            if (source == null) {
                return;
            }

            if (isNewSource(source)) {
                wrappedDispatchExecution(this, postDispatch, post,
                                SourceMapping.getJSObjectForSource(source), // arg 1: source
                                                                            // object
                                source.getCharacters().toString()); // arg 2: source code
            }
        }
    };
}
 
Example #14
Source File: HashemLanguage.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@Override
public Iterable<Scope> findLocalScopes(HashemContext context, Node node, Frame frame) {
    final HashemLexicalScope scope = HashemLexicalScope.createScope(node);
    return new Iterable<Scope>() {
        @Override
        public Iterator<Scope> iterator() {
            return new Iterator<Scope>() {
                private HashemLexicalScope previousScope;
                private HashemLexicalScope nextScope = scope;

                @Override
                public boolean hasNext() {
                    if (nextScope == null) {
                        nextScope = previousScope.findParent();
                    }
                    return nextScope != null;
                }

                @Override
                public Scope next() {
                    if (!hasNext()) {
                        throw new NoSuchElementException();
                    }
                    Object functionObject = findFunctionObject();
                    Scope vscope = Scope.newBuilder(nextScope.getName(), nextScope.getVariables(frame)).node(nextScope.getNode()).arguments(nextScope.getArguments(frame)).rootInstance(
                            functionObject).build();
                    previousScope = nextScope;
                    nextScope = null;
                    return vscope;
                }

                private Object findFunctionObject() {
                    String name = node.getRootNode().getName();
                    return context.getFunctionRegistry().getFunction(name);
                }
            };
        }
    };
}
 
Example #15
Source File: DebugInstrument.java    From nodeprof.js with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(final Env env) {
    instrumenter = env.getInstrumenter();
    env.registerService(this);
    SourceSectionFilter sourceSectionFilter = SourceSectionFilter.newBuilder().tagIs(JSTags.ALL).build();
    // What generates the input events to track?
    SourceSectionFilter inputGeneratingObjects = SourceSectionFilter.newBuilder().tagIs(
                    StandardTags.ExpressionTag.class,
                    StandardTags.StatementTag.class,
                    InputNodeTag.class).build();
    env.getInstrumenter().attachExecutionEventFactory(sourceSectionFilter, inputGeneratingObjects, new ExecutionEventNodeFactory() {
        public ExecutionEventNode create(EventContext context) {
            // TODO Auto-generated method stub
            return new ExecutionEventNode() {
                @Node.Child private InteropLibrary dispatch = InteropLibrary.getFactory().createDispatched(5);

                @TruffleBoundary
                @Override
                public void onEnter(VirtualFrame frame) {
                    /*
                     * Internal sources are executed at engine startup time. Such sources
                     * include internal code for the registration of builtins like Promise. We
                     * skip all these internal events to ensure that tests are deterministic.
                     */
                    DynamicObject func = (DynamicObject) frame.getArguments()[1];
                    try {
                        dispatch.execute(JSFunction.createEmptyFunction(JSObject.getJSContext(func).getRealm()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
        }
    });
}
 
Example #16
Source File: SqueakLanguage.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Override
protected Iterable<Scope> findLocalScopes(final SqueakImageContext context, final Node node, final Frame frame) {
    // TODO: support access at parse time (frame == null).
    if (!FrameAccess.isTruffleSqueakFrame(frame)) {
        return super.findLocalScopes(context, node, frame);
    }
    final CompiledCodeObject blockOrMethod = FrameAccess.getBlockOrMethod(frame);
    final String name = blockOrMethod.toString();
    final Object receiver = FrameAccess.getReceiver(frame);
    final ContextObjectInfo variables = new ContextObjectInfo(frame);
    final InteropArray arguments = new InteropArray(frame.getArguments());
    return Collections.singletonList(Scope.newBuilder(name, variables).node(node).receiver(receiver.toString(), receiver).arguments(arguments).build());
}
 
Example #17
Source File: MumblerException.java    From mumbler with GNU General Public License v3.0 5 votes vote down vote up
public static Throwable fillInMumblerStackTrace(Throwable t) {
    final List<StackTraceElement> stackTrace = new ArrayList<>();
    Truffle.getRuntime().iterateFrames((FrameInstanceVisitor<Void>) frame -> {
        Node callNode = frame.getCallNode();
        if (callNode == null) {
            return null;
        }
        RootNode root = callNode.getRootNode();

        /*
         * There should be no RootNodes other than SLRootNodes on the stack. Just for the
         * case if this would change.
         */
        String methodName = "$unknownFunction";
        if (root instanceof MumblerRootNode) {
            methodName = ((MumblerRootNode) root).name;
        }

        SourceSection sourceSection = callNode.getEncapsulatingSourceSection();
        Source source = sourceSection != null ? sourceSection.getSource() : null;
        String sourceName = source != null ? source.getName() : null;
        int lineNumber;
        try {
            lineNumber = sourceSection != null ? sourceSection.getStartLine() : -1;
        } catch (UnsupportedOperationException e) {
            /*
             * SourceSection#getLineLocation() may throw an UnsupportedOperationException.
             */
            lineNumber = -1;
        }
        stackTrace.add(new StackTraceElement("mumbler", methodName, sourceName, lineNumber));
        return null;
    });
    t.setStackTrace(stackTrace.toArray(new StackTraceElement[stackTrace.size()]));
    return t;
}
 
Example #18
Source File: UninitializedDispatchNode.java    From mumbler with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Object executeDispatch(VirtualFrame virtualFrame,
        CallTarget callTarget, Object[] arguments) {
    CompilerDirectives.transferToInterpreterAndInvalidate();

    Node cur = this;
    int size = 0;
    while (cur.getParent() instanceof DispatchNode) {
        cur = cur.getParent();
        size++;
    }
    InvokeNode invokeNode = (InvokeNode) cur.getParent();

    DispatchNode replacement;
    if (size < INLINE_CACHE_SIZE) {
        // There's still room in the cache. Add a new DirectDispatchNode.
        DispatchNode next = new UninitializedDispatchNode();
        replacement = new DirectDispatchNode(next, callTarget);
        this.replace(replacement);
    } else {
        replacement = new GenericDispatchNode();
        invokeNode.dispatchNode.replace(replacement);
    }

    // Call function with newly created dispatch node.
    return replacement.executeDispatch(virtualFrame, callTarget, arguments);
}
 
Example #19
Source File: InvokeNode.java    From mumbler with GNU General Public License v3.0 5 votes vote down vote up
private MumblerFunction evaluateFunction(VirtualFrame virtualFrame) {
    try {
        return this.functionNode.executeMumblerFunction(virtualFrame);
    } catch (UnexpectedResultException e) {
        throw new UnsupportedSpecializationException(this,
                new Node[] {this.functionNode}, e);
    }
}
 
Example #20
Source File: HashemInstrumentTest.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
private static void checkRootNode(Scope ls, String name, MaterializedFrame frame) {
    assertEquals(name, ls.getName());
    Node node = ls.getNode();
    assertTrue(node.getClass().getName(), node instanceof RootNode);
    assertEquals(name, ((RootNode) node).getName());
    assertEquals(frame.getFrameDescriptor(), ((RootNode) node).getFrameDescriptor());
}
 
Example #21
Source File: HashemLexicalScope.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
private static HashemBlockNode getParentBlock(Node node) {
    HashemBlockNode block;
    Node parent = node.getParent();
    // Find a nearest block node.
    while (parent != null && !(parent instanceof HashemBlockNode)) {
        parent = parent.getParent();
    }
    if (parent != null) {
        block = (HashemBlockNode) parent;
    } else {
        block = null;
    }
    return block;
}
 
Example #22
Source File: HashemLexicalScope.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
private static HashemBlockNode findChildrenBlock(Node node) {
    HashemBlockNode[] blockPtr = new HashemBlockNode[1];
    node.accept(new NodeVisitor() {
        @Override
        public boolean visit(Node n) {
            if (n instanceof HashemBlockNode) {
                blockPtr[0] = (HashemBlockNode) n;
                return false;
            } else {
                return true;
            }
        }
    });
    return blockPtr[0];
}
 
Example #23
Source File: HashemLexicalScope.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
/**
 * @return the node representing the scope, the block node for block scopes and the
 *         {@link RootNode} for functional scope.
 */
public Node getNode() {
    if (root != null) {
        return root;
    } else {
        return block;
    }
}
 
Example #24
Source File: HashemLexicalScope.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
private Map<String, FrameSlot> collectVars(Node varsBlock, Node currentNode) {
    // Variables are slot-based.
    // To collect declared variables, traverse the block's AST and find slots associated
    // with SLWriteLocalVariableNode. The traversal stops when we hit the current node.
    Map<String, FrameSlot> slots = new LinkedHashMap<>(4);
    NodeUtil.forEachChild(varsBlock, new NodeVisitor() {
        @Override
        public boolean visit(Node node) {
            if (node == currentNode) {
                return false;
            }
            // Do not enter any nested blocks.
            if (!(node instanceof HashemBlockNode)) {
                boolean all = NodeUtil.forEachChild(node, this);
                if (!all) {
                    return false;
                }
            }
            // Write to a variable is a declaration unless it exists already in a parent scope.
            if (node instanceof HashemWriteLocalVariableNode) {
                HashemWriteLocalVariableNode wn = (HashemWriteLocalVariableNode) node;
                String name = Objects.toString(wn.getSlot().getIdentifier());
                if (!hasParentVar(name)) {
                    slots.put(name, wn.getSlot());
                }
            }
            return true;
        }
    });
    return slots;
}
 
Example #25
Source File: HashemLexicalScope.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
private static Map<String, FrameSlot> collectArgs(Node block) {
    // Arguments are pushed to frame slots at the beginning of the function block.
    // To collect argument slots, search for SLReadArgumentNode inside of
    // SLWriteLocalVariableNode.
    Map<String, FrameSlot> args = new LinkedHashMap<>(4);
    NodeUtil.forEachChild(block, new NodeVisitor() {

        private HashemWriteLocalVariableNode wn; // The current write node containing a slot

        @Override
        public boolean visit(Node node) {
            // When there is a write node, search for SLReadArgumentNode among its children:
            if (node instanceof HashemWriteLocalVariableNode) {
                wn = (HashemWriteLocalVariableNode) node;
                boolean all = NodeUtil.forEachChild(node, this);
                wn = null;
                return all;
            } else if (wn != null && (node instanceof HashemReadArgumentNode)) {
                FrameSlot slot = wn.getSlot();
                String name = Objects.toString(slot.getIdentifier());
                assert !args.containsKey(name) : name + " argument exists already.";
                args.put(name, slot);
                return true;
            } else if (wn == null && (node instanceof HashemStatementNode)) {
                // A differentHasheminode - we're done.
                return false;
            } else {
                return NodeUtil.forEachChild(node, this);
            }
        }
    });
    return args;
}
 
Example #26
Source File: HashemParseError.java    From mr-hashemi with Universal Permissive License v1.0 4 votes vote down vote up
@Override
public Node getLocation() {
    return null;
}
 
Example #27
Source File: SqueakExceptions.java    From trufflesqueak with MIT License 4 votes vote down vote up
@Override
public Node getLocation() {
    return null;
}
 
Example #28
Source File: SqueakExceptions.java    From trufflesqueak with MIT License 4 votes vote down vote up
@Override
public Node getLocation() {
    return null;
}
 
Example #29
Source File: SqueakExceptions.java    From trufflesqueak with MIT License 4 votes vote down vote up
@Override
public Node getLocation() {
    return null;
}
 
Example #30
Source File: SqueakExceptions.java    From trufflesqueak with MIT License 4 votes vote down vote up
@Override
public Node getLocation() {
    return dummyCodeObjectNode;
}