0
# Truffle API
1
2
Truffle is a multi-language framework for executing dynamic languages that achieves high performance when combined with Graal. It provides a comprehensive API for implementing dynamic language runtimes on the JVM with advanced optimization features including JIT compilation, profiling, debugging, and cross-language interoperability.
3
4
## Package Information
5
6
- **Package Name**: org.graalvm.truffle:truffle-api
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: `<dependency><groupId>org.graalvm.truffle</groupId><artifactId>truffle-api</artifactId><version>23.1.3</version></dependency>`
10
- **Java Compliance**: 17+
11
12
## Core Imports
13
14
```java
15
import com.oracle.truffle.api.TruffleLanguage;
16
import com.oracle.truffle.api.nodes.Node;
17
import com.oracle.truffle.api.nodes.RootNode;
18
import com.oracle.truffle.api.frame.VirtualFrame;
19
import com.oracle.truffle.api.interop.InteropLibrary;
20
```
21
22
## Basic Usage
23
24
```java
25
import com.oracle.truffle.api.TruffleLanguage;
26
import com.oracle.truffle.api.nodes.RootNode;
27
import com.oracle.truffle.api.frame.VirtualFrame;
28
29
@TruffleLanguage.Registration(id = "mylang", name = "MyLanguage")
30
public final class MyLanguage extends TruffleLanguage<MyContext> {
31
32
@Override
33
protected MyContext createContext(Env env) {
34
return new MyContext(env);
35
}
36
37
@Override
38
protected CallTarget parse(ParsingRequest request) throws Exception {
39
// Parse source and create AST
40
RootNode rootNode = new MyRootNode(this);
41
return rootNode.getCallTarget();
42
}
43
}
44
45
// Example AST node
46
public class MyRootNode extends RootNode {
47
48
protected MyRootNode(TruffleLanguage<?> language) {
49
super(language);
50
}
51
52
@Override
53
public Object execute(VirtualFrame frame) {
54
// Execute language logic
55
return "Hello, Truffle!";
56
}
57
}
58
```
59
60
## Architecture
61
62
Truffle is built around several key architectural components:
63
64
- **Language Implementation Framework**: Core abstractions for implementing dynamic languages (`TruffleLanguage`, contexts, environments)
65
- **Abstract Syntax Tree (AST) System**: Node-based tree structures for representing and executing code (`Node`, `RootNode`, execution frames)
66
- **Domain-Specific Language (DSL)**: Annotation-driven code generation for optimized node implementations and specializations
67
- **Interoperability System**: Cross-language integration enabling seamless interaction between different Truffle languages
68
- **Instrumentation Framework**: Debugging, profiling, and tooling infrastructure for language development and runtime analysis
69
- **Optimization Infrastructure**: Profiling, assumption management, and compiler integration for high-performance execution
70
71
## Capabilities
72
73
### Core Language Implementation
74
75
Essential classes and interfaces for implementing Truffle-based dynamic languages, including language registration, context management, and basic execution infrastructure.
76
77
```java { .api }
78
@TruffleLanguage.Registration(id = "mylang", name = "MyLanguage")
79
public abstract class TruffleLanguage<C> {
80
protected abstract C createContext(Env env);
81
82
protected abstract CallTarget parse(ParsingRequest request) throws Exception;
83
84
public static final class Env {
85
public TruffleFile getInternalTruffleFile(String path);
86
public TruffleLogger getLogger(String loggerName);
87
public void registerService(Object service);
88
}
89
}
90
91
public abstract class RootNode extends Node {
92
public abstract Object execute(VirtualFrame frame);
93
94
public final CallTarget getCallTarget();
95
public final String getName();
96
}
97
98
public interface CallTarget {
99
Object call(Object... arguments);
100
}
101
```
102
103
[Core API](./core-api.md)
104
105
### AST Nodes and Execution Framework
106
107
Node-based abstract syntax tree system with execution frames, source location tracking, and tree manipulation utilities.
108
109
```java { .api }
110
public abstract class Node implements NodeInterface, Cloneable {
111
public final <T extends Node> T replace(T newNode);
112
public final NodeCost getCost();
113
114
protected final void notifyInserted(Node newChild);
115
116
public final SourceSection getSourceSection();
117
}
118
119
public interface VirtualFrame extends Frame {
120
Object[] getArguments();
121
122
FrameDescriptor getFrameDescriptor();
123
124
Object getObject(FrameSlot slot) throws FrameSlotTypeException;
125
void setObject(FrameSlot slot, Object value);
126
}
127
128
public final class FrameDescriptor {
129
public FrameSlot addFrameSlot(Object identifier);
130
public FrameSlot findFrameSlot(Object identifier);
131
}
132
```
133
134
[Core API](./core-api.md)
135
136
### Domain-Specific Language (DSL)
137
138
Annotation-driven system for generating optimized node implementations with automatic specialization, caching, and fallback handling.
139
140
```java { .api }
141
@NodeChild("leftNode")
142
@NodeChild("rightNode")
143
public abstract class AddNode extends BinaryNode {
144
145
@Specialization
146
protected int doInteger(int left, int right) {
147
return left + right;
148
}
149
150
@Specialization
151
protected double doDouble(double left, double right) {
152
return left + right;
153
}
154
155
@Fallback
156
protected Object doGeneric(Object left, Object right) {
157
// Handle other types
158
return InteropLibrary.getFactory().getUncached().execute(left, "+", right);
159
}
160
}
161
162
@GenerateNodeFactory
163
@NodeChild("arguments")
164
public abstract class CallNode extends Node {
165
166
@Specialization(guards = "function.getCallTarget() == cachedTarget")
167
protected Object doDirect(VirtualFrame frame, TruffleObject function,
168
@Cached("function.getCallTarget()") CallTarget cachedTarget,
169
@Cached DirectCallNode callNode) {
170
return callNode.call(frame.getArguments());
171
}
172
}
173
```
174
175
[Domain-Specific Language](./dsl.md)
176
177
### Cross-Language Interoperability
178
179
Comprehensive interoperability system enabling seamless integration between different Truffle languages through message-based protocols and shared object representations.
180
181
```java { .api }
182
public abstract class InteropLibrary extends Library {
183
public abstract boolean hasArrayElements(Object receiver);
184
public abstract Object readArrayElement(Object receiver, long index) throws UnsupportedMessageException, InvalidArrayIndexException;
185
public abstract void writeArrayElement(Object receiver, long index, Object value) throws UnsupportedMessageException, UnsupportedTypeException, InvalidArrayIndexException;
186
187
public abstract boolean hasMembers(Object receiver);
188
public abstract Object getMembers(Object receiver, boolean includeInternal) throws UnsupportedMessageException;
189
public abstract Object readMember(Object receiver, String member) throws UnsupportedMessageException, UnknownIdentifierException;
190
191
public abstract boolean isExecutable(Object receiver);
192
public abstract Object execute(Object receiver, Object... arguments) throws UnsupportedTypeException, ArityException, UnsupportedMessageException;
193
}
194
195
public interface TruffleObject {
196
// Marker interface for interoperable objects
197
}
198
199
@ExportLibrary(InteropLibrary.class)
200
public class MyObject implements TruffleObject {
201
202
@ExportMessage
203
boolean hasMembers() {
204
return true;
205
}
206
207
@ExportMessage
208
Object readMember(String member) throws UnknownIdentifierException {
209
// Return member value
210
return getMember(member);
211
}
212
}
213
```
214
215
[Interoperability](./interop.md)
216
217
### Instrumentation and Debugging
218
219
Comprehensive debugging and profiling infrastructure for language development, runtime analysis, and tooling integration.
220
221
```java { .api }
222
public abstract class TruffleInstrument {
223
224
protected abstract void onCreate(Env env);
225
226
public static final class Env {
227
public Instrumenter getInstrumenter();
228
public TruffleLogger getLogger(String loggerName);
229
public void registerService(Object service);
230
}
231
}
232
233
public abstract class Instrumenter {
234
public <T extends ExecutionEventNodeFactory> EventBinding<T> attachExecutionEventFactory(
235
SourceSectionFilter filter, T factory);
236
237
public EventBinding<ExecutionEventListener> attachExecutionEventListener(
238
SourceSectionFilter filter, ExecutionEventListener listener);
239
240
public AllocationReporter getAllocationReporter();
241
}
242
243
public abstract class ExecutionEventNode extends Node {
244
protected void onEnter(VirtualFrame frame) {}
245
protected void onReturnValue(VirtualFrame frame, Object result) {}
246
protected void onReturnExceptional(VirtualFrame frame, Throwable exception) {}
247
}
248
```
249
250
[Instrumentation and Debugging](./instrumentation.md)
251
252
### Data Types and Performance
253
254
Specialized data types, profiling utilities, and performance optimization features for high-performance language implementations.
255
256
```java { .api }
257
public final class TruffleString extends AbstractTruffleString {
258
public static TruffleString fromJavaStringUncached(String javaString, Encoding encoding);
259
260
public String toJavaStringUncached();
261
public int codePointLengthUncached(Encoding encoding);
262
263
public TruffleString concatUncached(TruffleString other, Encoding encoding, boolean lazy);
264
public TruffleString substringUncached(int fromIndex, int length, Encoding encoding, boolean lazy);
265
}
266
267
public abstract class ValueProfile extends Profile {
268
public abstract <T> T profile(T value);
269
270
public static ValueProfile createIdentityProfile();
271
public static ValueProfile createClassProfile();
272
}
273
274
public abstract class ConditionProfile extends Profile {
275
public abstract boolean profile(boolean value);
276
277
public static ConditionProfile createBinaryProfile();
278
public static ConditionProfile createCountingProfile();
279
}
280
```
281
282
[Data Types and Performance](./data-types.md)
283
284
### Advanced Features
285
286
Advanced capabilities including library-based dispatch, static object layouts, and runtime utilities for sophisticated language implementations.
287
288
```java { .api }
289
@GenerateLibrary
290
public abstract class MyLibrary extends Library {
291
292
public boolean accepts(Object receiver) {
293
return receiver instanceof MyObject;
294
}
295
296
public abstract Object executeMethod(Object receiver, String methodName, Object[] args);
297
}
298
299
public abstract class StaticShape<T> {
300
public abstract StaticProperty getProperty(Object propertyName);
301
public abstract T newInstance();
302
303
public static <T> Builder<T> newBuilder(TruffleLanguage<?> language);
304
305
public static final class Builder<T> {
306
public Builder<T> property(StaticProperty property, Class<?> type, boolean isFinal);
307
public StaticShape<T> build();
308
}
309
}
310
311
public final class AssumedValue<T> {
312
public AssumedValue(String name, T initialValue);
313
314
public T get();
315
public void set(T newValue);
316
317
public Assumption getAssumption();
318
}
319
```
320
321
[Advanced Features](./advanced.md)
322
323
## Types
324
325
### Core Framework Types
326
327
```java { .api }
328
public final class TruffleContext {
329
public Object eval(Source source);
330
public void close();
331
public boolean isClosed();
332
}
333
334
public final class Source {
335
public static Source newBuilder(String language, String text, String name).build();
336
337
public String getCharacters();
338
public String getName();
339
public String getLanguage();
340
}
341
342
public final class SourceSection {
343
public Source getSource();
344
public int getStartLine();
345
public int getStartColumn();
346
public int getEndLine();
347
public int getEndColumn();
348
}
349
```
350
351
### Exception Handling Types
352
353
```java { .api }
354
public abstract class AbstractTruffleException extends RuntimeException implements TruffleObject {
355
protected AbstractTruffleException();
356
protected AbstractTruffleException(String message);
357
protected AbstractTruffleException(String message, Throwable cause);
358
359
public final int getStackTraceElementLimit();
360
}
361
362
public class InteropException extends AbstractTruffleException {
363
// Base class for interop exceptions
364
}
365
366
public final class UnsupportedMessageException extends InteropException {
367
public static UnsupportedMessageException create();
368
}
369
```