d4rt library

D4rt - A powerful Dart code interpreter and runtime environment.

D4rt provides a complete Dart interpreter that can execute Dart code at runtime, with support for bridging between interpreted and native Dart code, async/await, classes, inheritance, enums, and more.

Key Features:

  • Full Dart syntax support including classes, methods, functions
  • Async/await execution with proper state management
  • Bridged types for seamless native-interpreted code integration
  • Standard library implementation
  • Module system with import/export support
  • Extension methods and mixins

Basic Usage:

final interpreter = D4rt();
final result = await interpreter.execute('''
  int add(int a, int b) => a + b;

  void main() {
    print(add(5, 3));
  }
''');

Classes

AppliedRuntimeType
Runtime model of a generic type applied to concrete type arguments, such as Box<int> or List<String>. Preserves the applied type arguments at runtime so is Box<int> and generic/collection return-type checks can compare the arguments element-wise instead of collapsing to the raw base type. Ports the applied-runtime-types half of upstream 1042fff.
AsyncExecutionState
Represents the state of an ongoing asynchronous function execution. This object tracks the progress and context needed for resumption.
AsyncGeneratorGate
The link from an async* body back to its listener (SCF4).
AsyncSuspensionRequest
Represents a request to suspend execution and wait for a Future. This object is returned by visitor methods when an await is encountered.
BarrelMapping
doc-ref: ok — the package: URIs in this example name BRIDGED libraries, the canonical URIs a bridge registers under rather than files here. Mapping from a barrel (re-export file) to its source libraries.
BoundBridgedSuper
Represents 'super' bound to an instance when the direct superclass is bridged.
BoundExtensionCallable
A bound wrapper for any ExtensionMemberCallable.
BoundExtensionMethodCallable
Represents an extension method bound to a target instance.
BoundObjectSuper
Represents 'super' bound to an instance whose class's superclass is Object: no interpreted superclass, no bridged superclass and no bridged mixin. Its members are Object's (InterpretedInstance.objectMember).
BoundSuper
BridgedClass
Represents a natively defined class that is accessible to the interpreter.
BridgedClassInfo
Information about a bridged class.
BridgedEnum
Represents an enum type defined in the host Dart environment and bridged into the interpreter. It holds the definition and provides access to its values.
BridgedEnumDefinition<T extends Enum>
BridgedEnumInfo
Information about a bridged enum.
BridgedEnumMixinMethodCallable
Callable for bridged mixin methods on enum values
BridgedEnumValue
Represents a specific value of a BridgedEnum. It holds the value's name, index, and the original native enum value.
BridgedExtensionDefinition
Definition for a bridged native extension.
BridgedInstance<T extends Object>
Represents an instance of a bridged native class.
BridgedMethodCallable
BridgedMixinMethodCallable
Represents a method call on a bridged mixin applied to an interpreted instance.
BridgedStaticMethodCallable
Represents a static method from a bridged class that can be passed as a value
BridgedSuperMethodCallable
Represents a method call on a bridged superclass object. Stores the specific native super object and the method adapter.
Callable
CertificatePermission
Certificate permissions govern loading X.509 certificates and private keys into a SecurityContext.
ClassInfo
Information about a class declaration.
D4
D4 - Static helper class for D4rt bridge code generation.
D4InterpretedProxy
Marker for native objects produced by an interface-proxy factory that wrap an InterpretedInstance.
D4rt
The main D4rt interpreter class.
D4rtCallStack
The stack itself, one per run.
D4rtConfiguration
Complete configuration snapshot of a D4rt interpreter instance.
D4rtDiag
Lightweight, always-on interpreter instrumentation counters.
D4rtGlobalsUserBridge
Annotation to mark a class as a D4rt globals user bridge override.
D4rtProfiler
Compile-time-gated profiler for D4rt's initialization path.
D4rtProgram
A script parsed once by D4rt.parse, to be run by D4rt.executeProgram.
D4rtStackFrame
One frame of an interpreted call stack.
D4rtUserBridge
Annotation to mark a class as a D4rt user bridge override.
D4rtUserProxy
Annotation marking a class as a D4rt user-defined proxy directive.
D4rtUserRelaxer
Annotation marking a class as a D4rt user-defined relaxer directive.
D4UserBridge
Base class for user-defined bridge overrides.
D4UserProxy
Base class for user-defined proxy-generation directives.
D4UserRelaxer
Base class for user-provided relaxer factories.
DangerousPermission
Dangerous permissions that should be granted with extreme caution.
DeclarationInfo
Represents information about a declaration in the executed code. This is the base class for all introspection results.
DeclarationVisitor
Visitor for the first pass: Declares class and mixin placeholders.
EnumInfo
Information about an enum declaration.
Environment
Represents the execution environment for interpreted code.
EnvironmentState
Represents the current state of the D4rt environment.
EnvironmentVariableInfo
Information about a variable in the environment.
ErrorReporter
Static error reporter that tracks all created D4rtExceptions.
ExtensionInfo
Information about an extension declaration.
ExtensionMemberCallable
Abstract interface for extension member callables.
FilesystemPermission
Filesystem permissions control file and directory operations.
FunctionInfo
Information about a function declaration.
FunctionRuntimeType
Runtime model of a function type such as int Function(String, [double]) or void Function({int count}). Subtyping is structural: return type covariant, parameters contravariant, arities and named-parameter shape must line up.
GeneratorCancelledSignal
SCF4: the unwind that ends an async* body whose subscription was cancelled.
GlobalFunctionInfo
Information about a registered global function.
GlobalGetter
A wrapper for lazy-evaluated global getters with optional setter support.
GlobalGetterInfo
Information about a registered global getter.
GlobalVariableInfo
Information about a registered global variable.
ImportConfiguration
Configuration for a single import library.
InterpretedClass
Represents a class definition at runtime.
InterpretedEnum
Represents an enum definition at runtime.
InterpretedEnumValue
Represents a specific value within an enum at runtime.
InterpretedExtension
InterpretedExtensionMethod
InterpretedExtensionType
Lim-1 FIX: Represents an extension type definition at runtime. Extension types are inline classes that provide a zero-cost abstraction.
InterpretedExtensionTypeInstance
An instance of an extension type
InterpretedFunction
InterpretedInstance
Represents an instance of an InterpretedClass at runtime.
InterpretedRecord
Represents an interpreted record value.
InterpreterVisitor
IntrospectionBuilder
Helper class to build introspection results from an environment.
IntrospectionResult
Result of introspection containing all declarations found in the executed code.
IsolatePermission
Isolate permissions control isolate creation and communication.
LateVariable
Represents a late variable that supports lazy initialization
LazyBridgeRegistry<K>
A key → BridgedClass map whose entries may be stored as deferred thunks rather than pre-built classes.
LibraryBridgeDefinition
Bridges for a single source library.
LibraryClass
Wrapper class for library-scoped bridged classes. Stores a bridged class with its canonical source URI for deduplication.
LibraryEnum
Wrapper class for library-scoped bridged enums. Stores a bridged enum with its canonical source URI for deduplication.
LibraryExtension
Wrapper class for library-scoped bridged extensions. Stores a bridged extension definition with its canonical source URI.
LibraryFunction
Wrapper class for library-scoped functions. Stores a native function with its canonical source URI for deduplication.
LibraryGetter
Wrapper class for library-scoped getters. Stores a getter name, its function, and optionally its canonical source URI for deduplication across re-exports.
LibrarySetter
Wrapper class for library-scoped setters. Stores a setter name, its function, and optionally its canonical source URI for deduplication across re-exports.
LibraryVariable
Wrapper class for library-scoped variables. Stores a variable name, its value, and optionally its canonical source URI for deduplication across re-exports.
LoadedModule
Logger
LoopStackDepths
The depth of each loop stack at the moment a loop was entered; see AsyncExecutionState.loopEntryDepths.
ModuleBridgeInfo
Complete bridge information for a package/module.
ModuleLoader
NamedRuntimeType
A minimal, self-contained RuntimeType identified purely by name. Used as a sentinel for dynamic return/parameter types when a richer type object is unavailable, and as a fallback for parameter types the resolver cannot map to a concrete class.
NativeExtensionCallable
A callable for a native (bridged) extension member.
NativeFunction
NetworkPermission
Network permissions control network operations.
PendingJump
A jump deferred until the finallys between it and its target have run.
Permission
Base class for all permissions in the d4rt security system.
PermissionInfo
Information about a granted permission.
ProcessRunPermission
Process permissions control process execution.
RecordRuntimeType
Runtime model of a record type such as (int, String) or (int, {String label}). Subtyping requires an identical shape (same positional arity, same named keys) with each field compatible.
ResolvedBinding
A binding check with everything that does not depend on the value already resolved — the product of InterpretedFunction.resolveBinding.
RuntimeType
Common interface for types defined at runtime (interpreted or bridged).
RuntimeValue
Common interface for values defined at runtime (interpreted or bridged instances).
ScriptExecutionResult
Result of a script execution.
StaticCoord
Statically-resolved lexical coordinate of an identifier use.
StaticResolver
Static lexical resolver (plan_3 §4.4 / §9 S1).
Stdlib
TypeParameter
Represents a generic type parameter like T, U, etc.
VariableInfo
Information about a variable declaration.
YieldValue
Represents a yield operation in a generator function

Enums

D4LogLevel

Functions

callInterpretedToString(InterpretedFunction method, RuntimeValue target, InterpreterVisitor visitor) → Object?
Calls an interpreted toString and returns what it produced, unwrapping the ReturnException a block-bodied one throws.
executeFile(D4rt d4rt, String filePath, {void log(String)?}) → ScriptExecutionResult
Execute a Dart script file with fresh interpreter state.
executeFileContinued(D4rt d4rt, String filePath, {void log(String)?}) → ScriptExecutionResult
Execute a Dart script file in the current interpreter environment.
executeSource(D4rt d4rt, String source, String basePath, {String scriptName = '__script__.dart', void log(String)?}) → ScriptExecutionResult
Execute a Dart script from source code with a basePath for import resolution.
indexRangeError(int index, int length) → RangeError
The RangeError the platform raises for an out-of-range index.
isInterpreterControlFlowSignal(Object e) → bool
Whether e is one of the exceptions the interpreter uses to unwind its own stack, rather than a failure a script or a native callee produced.
isTopTypeName(String n) → bool
True for the names that denote a TOP TYPE — one every value inhabits.
opensLexicalFrame(AstNode node) → bool
Does node open a new runtime Environment frame?
renderInterpretedToString({required RuntimeValue target, required InterpretedFunction? method, required InterpreterVisitor? visitor, required String fallback()}) → String
Dispatches to a script's toString() when there is one, and falls back to fallback otherwise.
resolveImportsRecursively(String source, String sourceUri, Map<String, String> sources, void log(String)?) → void
Recursively resolves imports from a Dart source file.
rewrapPreservingMemberSignal(RuntimeD4rtException e, String message) → RuntimeD4rtException
Re-wraps e under a new message, keeping the "member absent" signal when e carries one.
throwAsHostFacingError(Object e, StackTrace s) → Never
Rethrows e in the shape a host calling execute() should receive, so that a catch clause outside the interpreter can name the same type a catch clause inside the script can.
unwrapScriptError(Object error) → Object
Recovers the value the script actually threw from the interpreter's internal wrappers — public, because an embedder sometimes has to call it.
wrapDirectiveError(String directiveType, Uri ownerUri, Uri targetUri, D4rtException error) → D4rtException
DFUB13 — names the module that ASKED for a target that failed to load.

Typedefs

BridgedConstructorCallable = Object? Function(InterpreterVisitor visitor, List<Object?> positionalArgs, Map<String, Object?> namedArgs)
Calls a native constructor.
BridgedInstanceGetterAdapter = Object? Function(InterpreterVisitor? visitor, Object target)
Adapter for bridged instance getters. Takes interpreter context, the native target object. Returns the result of the native instance getter.
BridgedInstanceSetterAdapter = void Function(InterpreterVisitor? visitor, Object target, Object? value)
Adapter for bridged instance setters. Takes interpreter context, the native target object, the value to set.
BridgedMethodAdapter = Object? Function(InterpreterVisitor visitor, Object target, List<Object?> positionalArguments, Map<String, Object?> namedArguments, List<RuntimeType>? typeArguments)
BridgedStaticGetterAdapter = Object? Function(InterpreterVisitor visitor)
Adapter for bridged static getters. Takes interpreter context. Returns the result of the native static getter.
BridgedStaticMethodAdapter = Object? Function(InterpreterVisitor visitor, List<Object?> positionalArguments, Map<String, Object?> namedArguments, List<RuntimeType>? typeArguments)
Adapter for bridged static methods. Takes interpreter context, positional args, named args, type args. Returns the result of the native static method call.
BridgedStaticSetterAdapter = void Function(InterpreterVisitor visitor, Object? value)
Adapter for bridged static setters. Takes interpreter context, the value to set.
D4rtFrameLocator = ({int column, int line, Uri? source})? Function(Object statement)
Where a statement is: its line and column, and the library it is in.
GenericConstructorFactory = Object? Function(InterpreterVisitor visitor, List<Object?> positionalArgs, Map<String, Object?> namedArgs, List<RuntimeType>? typeArguments)
RC-2: Factory for constructing generic bridged classes with type arguments.
GenericTypeWrapperFactory = Object? Function(Object value, String innerTypeArg)
GEN-079: Factory callback for creating typed wrappers.
InterfaceProxyFactory = Object? Function(InterpreterVisitor visitor, InterpretedInstance instance)
RC-1: Factory for creating native proxy objects that delegate method calls back to an InterpretedInstance.
NativeFunctionImpl = Object? Function(InterpreterVisitor visitor, List<Object?> arguments, Map<String, Object?> namedArguments, List<RuntimeType>? typeArguments)
TypeCoercionFactory = Object? Function(Object value)
RC-3: Factory for converting one type to another when they represent the same concept but live in different packages.

Exceptions / Errors

AmbiguousBridgedNameException
Thrown when a script names a bridged class by its simple name and two different libraries in scope declare a class under that name.
ArgumentD4rtException
Exception for argument-related errors in D4rt components.
BreakException
Internal exception used to unwind the stack during a 'break' statement.
ContinueException
Internal exception used to unwind the stack during a 'continue' statement.
ContinueSwitchLabel
Internal exception for continue-to-label in switch statements. This is used to signal the switch handler to restart from a specific labeled case.
D4rtException
Base class for all D4rt-specific exceptions that should be tracked.
D4rtNoSuchMethodError
A NoSuchMethodError carrying d4rt's own diagnostic.
D4rtTypeError
A TypeError carrying d4rt's own diagnostic.
D4UnwrapException
Exception thrown by D4.unwrapAs when an interpreter result cannot be converted to the requested native type T.
InternalInterpreterD4rtException
Internal exception wrapper for user-thrown exceptions.
LateInitializationError
Exception thrown when accessing an uninitialized late variable
PatternMatchD4rtException
Exception specifically for pattern matching failures.
Ranged4rtException
Exception for range-related errors in D4rt components.
ReturnException
Internal exception used to unwind the stack during a 'return' statement.
RuntimeD4rtException
Custom exception for runtime errors during interpretation.
SourceCodeD4rtException
Exception thrown when there's an issue with the source code itself, like parsing errors or missing files.
StateD4rtException
Exception for state-related errors in D4rt components.
SyncGeneratorYieldSuspension
Exception used to pause sync* generator execution at a yield point
UndefinedMemberD4rtException
Thrown when a member lookup finds no member of that name on the receiver.
UndefinedNameD4rtException
Thrown when a name a script reads resolves to no declaration at all.
UndefinedStaticMemberD4rtException
Thrown when a STATIC member lookup fails on a class, enum, bridged class or extension.
UnimplementedD4rtException
Exception for unimplemented features in D4rt components.
UnsupportedD4rtException
Exception for unsupported operations in D4rt components.