Class TruffleInstrument

java.lang.Object
com.oracle.truffle.api.instrumentation.TruffleInstrument

public abstract class TruffleInstrument extends Object
The service provider interface (SPI) for Truffle instruments: clients of Truffle instrumentation that may observe and inject behavior into interpreters written using the Truffle framework.

Instrument implementation classes must use the TruffleInstrument.Registration annotation to provide required metadata and to enable automatic discovery of the implementation.

An instrument is created if at least one instrument option was specified or if a service was looked up. The Instrumenter available in the provided environment allows the instrument instance to bind listeners for execution and source events, as well as node factories for code injection at guest language code locations.

An instrument is disposed when the associated polyglot engine is disposed. All active bindings created by a disposed instrument become disposed automatically. The Instrumenter instance available in the provided environment may not be used after disposal.

Example for a simple expression coverage instrument:

@Registration(id = CoverageExample.ID, services = Object.class)
public final class CoverageExample extends TruffleInstrument {

    public static final String ID = "test-coverage";

    private final Set<SourceSection> coverage = new HashSet<>();

    @Override
    protected void onCreate(final Env env) {
        SourceSectionFilter.Builder builder = SourceSectionFilter.newBuilder();
        SourceSectionFilter filter = builder.tagIs(ExpressionTag.class).build();
        Instrumenter instrumenter = env.getInstrumenter();
        instrumenter.attachExecutionEventFactory(filter,
                        new CoverageExampleEventFactory(env));
    }

    private class CoverageExampleEventFactory
                    implements ExecutionEventNodeFactory {

        private final Env env;

        CoverageExampleEventFactory(final Env env) {
            this.env = env;
        }

        public ExecutionEventNode create(final EventContext ec) {
            final PrintStream out = new PrintStream(env.out());
            return new ExecutionEventNode() {
                @CompilationFinal private boolean visited;

                @Override
                public void onReturnValue(VirtualFrame vFrame, Object result) {
                    if (!visited) {
                        CompilerDirectives.transferToInterpreterAndInvalidate();
                        visited = true;
                        SourceSection src = ec.getInstrumentedSourceSection();
                        out.print(src.getCharIndex() + " ");
                        coverage.add(src);
                    }
                }
            };
        }
    }

}
Since:
0.12