com.oracle.truffle.api.source.Source Java Examples

The following examples show how to use com.oracle.truffle.api.source.Source. 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: 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 #2
Source File: TruffleMumblerMain.java    From mumbler with GNU General Public License v3.0 6 votes vote down vote up
private static void startREPL() throws IOException {
    Console console = System.console();
    while (true) {
        // READ
        String data = console.readLine(PROMPT);
        if (data == null) {
            // EOF sent
            break;
        }
        MumblerContext context = new MumblerContext();
        Source source = Source.newBuilder(ID, data, "<console>").build();
        ListSyntax sexp = Reader.read(source);
        Converter converter = new Converter(null, flags.tailCallOptimizationEnabled);
        MumblerNode[] nodes = converter.convertSexp(context, sexp);

        // EVAL
        Object result = execute(nodes, context.getGlobalFrame());

        // PRINT
        if (result != MumblerList.EMPTY) {
            System.out.println(result);
        }
    }
}
 
Example #3
Source File: MumblerReadException.java    From mumbler with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Throwable fillInStackTrace() {
    SourceSection sourceSection = this.getSourceSection();
    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;
    }
    StackTraceElement[] traces = new StackTraceElement[] {
            new StackTraceElement(filename(sourceName),
                    this.getMethodName(),
                    sourceName,
                    lineNumber)
    };
    this.setStackTrace(traces);
    return this;
}
 
Example #4
Source File: Main.java    From sieve with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.err.println("Setting up PolyglotEngine");
    PolyglotEngine vm = PolyglotEngine.newBuilder().
        build();

    vm.eval(Source.fromText("", "warmup.R").withMimeType("text/x-r"));

    URL url = Main.class.getProtectionDomain().getCodeSource().getLocation();
    File local = new File(url.toURI());
    for (;;) {
        File sieveInR = new File(local, "sieve.R");
        if (sieveInR.exists()) {
            break;
        }
        local = local.getParentFile();
    }
    System.err.println("engine is ready");

    Source r = Source.fromFileName(new File(local, "sieve.R").getPath());

    vm.eval(r);
}
 
Example #5
Source File: Main.java    From sieve with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.err.println("Setting up PolyglotEngine");
    PolyglotEngine vm = PolyglotEngine.newBuilder().
        build();

    URL url = Main.class.getProtectionDomain().getCodeSource().getLocation();
    File local = new File(url.toURI());
    for (;;) {
        File sieveInRuby = new File(local, "sieve.R");
        if (sieveInRuby.exists()) {
            break;
        }
        local = local.getParentFile();
    }

    Source r = Source.fromFileName(new File(local, "sieve.R").getPath());
    Source js = Source.fromFileName(new File(local, "sieve.js").getPath());

    vm.eval(r);
    vm.eval(js);
}
 
Example #6
Source File: SourceMapping.java    From nodeprof.js with Apache License 2.0 6 votes vote down vote up
@TruffleBoundary
public static DynamicObject getJSObjectForSource(Source source) {
    if (source == null) {
        return Undefined.instance;
    }
    JSContext ctx = GlobalObjectCache.getInstance().getJSContext();
    DynamicObject o = JSUserObject.create(ctx);
    String srcName = source.getName();
    if (isEval(source)) {
        String evalSrc = innerMostEvalSource(source.getName());
        if (evalSrc != null) {
            // strip :line:column from source name
            srcName = evalSrc.split(":")[0];
        } else {
            Logger.error("Failed to parse eval source: " + source.getName());
        }
        // 'eval' property signals the source is an eval-string, it contains the full eval hint
        JSObject.set(o, "eval", source.getName());
    }
    JSObject.set(o, "name", shortPath(srcName));
    JSObject.set(o, "internal", isInternal(source));
    return o;
}
 
Example #7
Source File: HashemParseInContextTest.java    From mr-hashemi with Universal Permissive License v1.0 6 votes vote down vote up
@Override
protected CallTarget parse(ParsingRequest request) throws Exception {
    return Truffle.getRuntime().createCallTarget(new RootNode(this) {

        @CompilationFinal private ContextReference<Env> reference;

        @Override
        public Object execute(VirtualFrame frame) {
            return parseAndEval();
        }

        @TruffleBoundary
        private Object parseAndEval() {
            if (reference == null) {
                CompilerDirectives.transferToInterpreterAndInvalidate();
                this.reference = lookupContextReference(EvalLang.class);
            }
            Source aPlusB = Source.newBuilder("hashemi", "a + b", "plus.hashem").build();
            return reference.get().parsePublic(aPlusB, "a", "b").call(30, 12);
        }
    });
}
 
Example #8
Source File: PolyglotPlugin.java    From trufflesqueak with MIT License 6 votes vote down vote up
private static Object evalString(final SqueakImageContext image, final NativeObject languageIdOrMimeTypeObj, final NativeObject sourceObject) {
    final String languageIdOrMimeType = languageIdOrMimeTypeObj.asStringUnsafe();
    final String sourceText = sourceObject.asStringUnsafe();
    try {
        final boolean mimeType = isMimeType(languageIdOrMimeType);
        final String lang = mimeType ? findLanguageByMimeType(image.env, languageIdOrMimeType) : languageIdOrMimeType;
        LiteralBuilder newBuilder = Source.newBuilder(lang, sourceText, EVAL_SOURCE_NAME);
        if (mimeType) {
            newBuilder = newBuilder.mimeType(languageIdOrMimeType);
        }
        final Source source = newBuilder.build();
        return image.env.parsePublic(source).call();
    } catch (final RuntimeException e) {
        throw primitiveFailedInInterpreterCapturing(e);
    }
}
 
Example #9
Source File: CompiledCodeObject.java    From trufflesqueak with MIT License 6 votes vote down vote up
public final Source getSource() {
    CompilerAsserts.neverPartOfCompilation();
    if (source == null) {
        String name = null;
        String contents;
        try {
            name = toString();
            contents = SqueakBytecodeDecoder.decodeToString(this);
        } catch (final RuntimeException e) {
            if (name == null) {
                name = SOURCE_UNAVAILABLE_NAME;
            }
            contents = SOURCE_UNAVAILABLE_CONTENTS;
        }
        source = Source.newBuilder(SqueakLanguageConfig.ID, contents, name).mimeType("text/plain").build();
    }
    return source;
}
 
Example #10
Source File: CUDARuntime.java    From grcuda with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public CUDARuntime(GrCUDAContext context, Env env) {
    this.context = context;
    try {
        TruffleObject libcudart = (TruffleObject) env.parseInternal(
                        Source.newBuilder("nfi", "load " + "lib" + CUDA_RUNTIME_LIBRARY_NAME + ".so", "cudaruntime").build()).call();
        TruffleObject libcuda = (TruffleObject) env.parseInternal(
                        Source.newBuilder("nfi", "load " + "lib" + CUDA_LIBRARY_NAME + ".so", "cuda").build()).call();
        TruffleObject libnvrtc = (TruffleObject) env.parseInternal(
                        Source.newBuilder("nfi", "load " + "lib" + NVRTC_LIBRARY_NAME + ".so", "nvrtc").build()).call();
        loadedLibraries.put(CUDA_RUNTIME_LIBRARY_NAME, libcudart);
        loadedLibraries.put(CUDA_LIBRARY_NAME, libcuda);
        loadedLibraries.put(NVRTC_LIBRARY_NAME, libnvrtc);
    } catch (UnsatisfiedLinkError e) {
        throw new GrCUDAException(e.getMessage());
    }

    nvrtc = new NVRuntimeCompiler(this);
    context.addDisposable(this::shutdown);
}
 
Example #11
Source File: AnalysisFilterJS.java    From nodeprof.js with Apache License 2.0 5 votes vote down vote up
@Override
@TruffleBoundary
public boolean testTag(final Source source, ProfiledTagEnum tag) {
    EnumSet<ProfiledTagEnum> tags = includedSources.get(source);
    assert (tags != null);
    return tags == allTags || tags.contains(tag);
}
 
Example #12
Source File: HashemParseError.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
public HashemParseError(Source source, int line, int column, int length, String message) {
    super(message);
    this.source = source;
    this.line = line;
    this.column = column;
    this.length = length;
}
 
Example #13
Source File: SourcePosition.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public SourcePosition(SourceSection sourceSection) {
    Source source = sourceSection.getSource();
    this.id = getId(source);
    this.name = source.getName();
    String sourcePath = source.getPath();
    if (sourcePath == null) {
        sourcePath = name;
    }
    this.path = sourcePath;
    this.sourceSection = sourceSection.getStartLine() + "," + sourceSection.getStartColumn() + "," + sourceSection.getEndLine() + "," + sourceSection.getEndColumn();
    this.code = source.getCharacters().toString();
    this.uri = source.getURI();
}
 
Example #14
Source File: SourcePosition.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static synchronized long getId(Source s) {
    Long id = sourceId.get(s);
    if (id == null) {
        id = new Long(nextId++);
        sourceId.put(s, id);
    }
    return id;
}
 
Example #15
Source File: SqueakLanguage.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Override
protected CallTarget parse(final ParsingRequest request) throws Exception {
    final SqueakImageContext image = getContext();
    final Source source = request.getSource();
    if (source.hasBytes()) {
        image.setImagePath(source.getPath());
        return image.getSqueakImage().asCallTarget();
    } else {
        image.ensureLoaded();
        if (source.isInternal()) {
            image.printToStdOut(MiscUtils.format("Evaluating '%s'...", source.getCharacters().toString()));
        }
        return Truffle.getRuntime().createCallTarget(image.getDoItContextNode(source));
    }
}
 
Example #16
Source File: ExecuteContextNode.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Override
public SourceSection getSourceSection() {
    if (section == null) {
        final Source source = code.getSource();
        section = source.createSection(1, 1, source.getLength());
    }
    return section;
}
 
Example #17
Source File: AbstractBytecodeNode.java    From trufflesqueak with MIT License 5 votes vote down vote up
@Override
public final SourceSection getSourceSection() {
    CompilerAsserts.neverPartOfCompilation();
    if (sourceSection == null) {
        final Source source = code.getSource();
        if (CompiledCodeObject.SOURCE_UNAVAILABLE_CONTENTS.equals(source.getCharacters())) {
            sourceSection = source.createUnavailableSection();
        } else {
            final int lineNumber = SqueakBytecodeDecoder.findLineNumber(code, index);
            sourceSection = source.createSection(lineNumber);
        }
    }
    return sourceSection;
}
 
Example #18
Source File: AbstractOSProcessPlugin.java    From trufflesqueak with MIT License 5 votes vote down vote up
protected final Object getSysCallObject() {
    assert supportsNFI;
    if (sysCallObject == null) {
        CompilerDirectives.transferToInterpreterAndInvalidate();
        final Object defaultLibrary = SqueakLanguage.getContext().env.parseInternal(Source.newBuilder("nfi", "default", "native").build()).call();
        final InteropLibrary lib = InteropLibrary.getFactory().getUncached();
        try {
            final Object symbol = lib.readMember(defaultLibrary, getFunctionName());
            sysCallObject = lib.invokeMember(symbol, "bind", getFunctionSignature());
        } catch (UnsupportedMessageException | UnknownIdentifierException | ArityException | UnsupportedTypeException e) {
            throw PrimitiveFailed.andTransferToInterpreterWithError(e);
        }
    }
    return sysCallObject;
}
 
Example #19
Source File: PolyglotPlugin.java    From trufflesqueak with MIT License 5 votes vote down vote up
private static Object evalFile(final SqueakImageContext image, final NativeObject languageIdOrMimeTypeObj, final NativeObject path) {
    final String languageIdOrMimeType = languageIdOrMimeTypeObj.asStringUnsafe();
    final String pathString = path.asStringUnsafe();
    try {
        final boolean mimeType = isMimeType(languageIdOrMimeType);
        final String lang = mimeType ? findLanguageByMimeType(image.env, languageIdOrMimeType) : languageIdOrMimeType;
        SourceBuilder newBuilder = Source.newBuilder(lang, image.env.getPublicTruffleFile(pathString));
        if (mimeType) {
            newBuilder = newBuilder.mimeType(languageIdOrMimeType);
        }
        return image.env.parsePublic(newBuilder.name(pathString).build()).call();
    } catch (IOException | RuntimeException e) {
        throw primitiveFailedInInterpreterCapturing(e);
    }
}
 
Example #20
Source File: SqueakFFIPrims.java    From trufflesqueak with MIT License 5 votes vote down vote up
private static Object calloutToLib(final SqueakImageContext image, final String name, final Object[] argumentsConverted, final String nfiCode)
                throws UnsupportedMessageException, ArityException, UnknownIdentifierException, UnsupportedTypeException {
    final Source source = Source.newBuilder("nfi", nfiCode, "native").build();
    final Object ffiTest = image.env.parseInternal(source).call();
    final InteropLibrary interopLib = InteropLibrary.getFactory().getUncached(ffiTest);
    return interopLib.invokeMember(ffiTest, name, argumentsConverted);
}
 
Example #21
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 #22
Source File: TruffleMumblerMain.java    From mumbler with GNU General Public License v3.0 5 votes vote down vote up
private static void runMumbler(String filename) throws IOException {
    Source source = Source.newBuilder(ID, new FileReader(new File(filename)), filename).build();
    MumblerContext context = new MumblerContext();
    ListSyntax sexp = Reader.read(source);
    Converter converter = new Converter(null, flags.tailCallOptimizationEnabled);
    MumblerNode[] nodes = converter.convertSexp(context, sexp);
    execute(nodes, context.getGlobalFrame());
}
 
Example #23
Source File: ReadBuiltinNode.java    From mumbler with GNU General Public License v3.0 5 votes vote down vote up
@Specialization
public Syntax read(VirtualFrame virtualFrame, String str) {
    try {
    	Source source = Source.newBuilder(ID, str, "<read>").build();
        return Reader.readForm(source);
    } catch (IOException e) {
        throw new MumblerException(e.getMessage());
    }
}
 
Example #24
Source File: AnalyzerTest.java    From mumbler with GNU General Public License v3.0 5 votes vote down vote up
private static ListSyntax read(String str) {
    try {
        return Reader.read(Source.newBuilder(ID, str, "<junit>").build());
    } catch (IOException e) {
        throw new RuntimeException();
    }
}
 
Example #25
Source File: AnalysisFilterBase.java    From nodeprof.js with Apache License 2.0 5 votes vote down vote up
/**
 * check whether beginning of source file contains DO NOT INSTRUMENT
 *
 * @param source the Source to test
 * @return true if DO NOT INSTRUMENT string found in source
 */
static boolean containsDoNotInstrument(final Source source) {
    if (source.getLineCount() > 0) {
        // check if the source code has a special filter string at its beginning
        CharSequence sourceChars = source.getCharacters();
        String sourceHead = sourceChars.subSequence(0, Math.min(sourceChars.length() - 1, 1000)).toString().trim();
        // should be enough
        if (sourceHead.contains("DO NOT INSTRUMENT")) {
            return true;
        }
    }
    return false;
}
 
Example #26
Source File: HashemLanguageParser.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
public static Map<String, RootCallTarget> parseHashemiLang(HashemLanguage language, Source source) {
    HashemLanguageLexer lexer = new HashemLanguageLexer(CharStreams.fromString(source.getCharacters().toString()));
    HashemLanguageParser parser = new HashemLanguageParser(new CommonTokenStream(lexer));
    lexer.removeErrorListeners();
    parser.removeErrorListeners();
    BailoutErrorListener listener = new BailoutErrorListener(source);
    lexer.addErrorListener(listener);
    parser.addErrorListener(listener);
    parser.factory = new HashemNodeFactory(language, source);
    parser.source = source;
    parser.hashemlanguage();
    return parser.factory.getAllFunctions();
}
 
Example #27
Source File: HashemDefineFunctionBuiltin.java    From mr-hashemi with Universal Permissive License v1.0 5 votes vote down vote up
@TruffleBoundary
@Specialization
public String defineFunction(String code, @CachedContext(HashemLanguage.class) HashemContext context) {
    // @formatter:off
    Source source = Source.newBuilder(HashemLanguage.ID, code, "[defineFunction]").
        build();
    // @formatter:on
    /* The same parsing code as for parsing the initial source. */
    context.getFunctionRegistry().register(source);

    return code;
}
 
Example #28
Source File: GrCUDAParserException.java    From grcuda with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public GrCUDAParserException(String message, Source source, int line, int charPositionInLine, int length) {
    super(message);
    this.source = source;
    this.line = line;
    this.column = charPositionInLine;
    this.length = length;
}
 
Example #29
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 #30
Source File: InitialRootFactory.java    From nodeprof.js with Apache License 2.0 5 votes vote down vote up
@TruffleBoundary
private boolean isNewSource(Source source) {
    if (source == null) {
        return false;
    }
    return seenSources.add(source);
}