Interpreter class

Executes the Abstract Syntax Tree (AST) representing the script.

It walks the AST using the Visitor pattern (ExprVisitor, StmtVisitor), evaluating expressions and executing statements according to the language semantics. It manages the program's state (variables, functions) using an Environment stack. Handles runtime errors and control flow constructs.

Constructors

Interpreter()
Creates a new Interpreter instance. Initializes the global environment and defines built-in functions like print and range.

Properties

globals → Environment
The top-level global environment. Holds built-ins and global variables.
final
hashCode → int
The hash code for this object.
no setterinherited
runtimeType → Type
A representation of the runtime type of the object.
no setterinherited
vfs ↔ Map<String, String>
Virtual file system
getter/setter pair

Methods

evaluate(Expr expr) → Object?
Evaluates a single Expr node by dispatching to the appropriate visit method. Returns the result of the expression evaluation.
evaluateInEnvironment(Expr expr, Environment environment) → Object?
Helper to evaluate an expression within a specific environment. Used primarily for evaluating default parameter values in the correct closure scope.
execute(Stmt stmt) → void
Executes a single Stmt node by dispatching to the appropriate visit method.
executeBlock(List<Stmt> statements, Environment environment) → void
Executes a block of statements within a specific environment. Sets the interpreter's current environment to the given one for the duration of the block's execution and restores the previous environment afterwards. Crucial for function calls and potentially other scoped constructs.
interpret(List<Stmt> statements, [void printCallback(String)?, void errorCallback(String)?]) → Object?
Interprets a list of top-level statements (the AST).
isEqual(Object? a, Object? b) → bool
Compares two objects for equality using Python's == semantics. Handles None. Performs deep comparison for lists and maps. Falls back to Dart's == for other types.
isInt(dynamic arg) → bool
isNum(dynamic arg) → bool
isTruthy(Object? object) → bool
Determines the truthiness of an object according to Python rules. False, None, numeric zero, empty strings/lists/maps are falsey. Everything else is truthy.
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
pyThrow(String excType, Token token, [String? message]) → void
registerFunction(String name, dynamic function(List args, Map kwargs)) → void
repr(Object? object) → String
stringify(Object? object) → String
Converts a runtime object into its string representation, similar to Python's str(). Handles None, True, False, numbers, strings, lists, maps, and callables.
toInt(dynamic arg, Token token) → int
toString() → String
A string representation of this object.
inherited
visitAssignExpr(AssignExpr expr) → Object?
Visitor method for evaluating an AssignExpr. Evaluates the right-hand side value, then assigns it to the variable name in the current environment chain using _environment.assign. Returns the assigned value.
visitAttributeGetExpr(AttributeGetExpr expr) → Object?
Visits a AttributeGetExpr node (e.g., obj.attr).
visitAttributeSetExpr(AttributeSetExpr expr) → Object?
Visits a AttributeSetExpr node (e.g., obj.attr = value).
visitAugAssignExpr(AugAssignExpr expr) → Object?
Visitor method for evaluating an AugAssignExpr (e.g., +=, *=). Evaluates the target (variable or index/key) to get the current value, evaluates the right-hand side value, performs the operation, and assigns the result back to the target. Handles both variable and index targets.
visitBinaryExpr(BinaryExpr expr) → Object?
Visitor method for evaluating a BinaryExpr (arithmetic, comparison, bitwise).
visitBlockStmt(BlockStmt stmt) → void
Visitor method for executing a BlockStmt. Simply executes the statements within the current environment. Note: Scope creation is handled by the calling context (e.g., executeBlock).
visitBreakStmt(BreakStmt stmt) → void
Visitor method for executing a BreakStmt. Throws _BreakException if inside a loop, otherwise throws RuntimeError.
visitCallExpr(CallExpr expr) → Object?
Visitor method for evaluating a CallExpr. Evaluates the callee expression. If it's a PyCallable, evaluates all arguments (positional and keyword), then invokes the callable's call method. Throws RuntimeError if the callee is not callable or if errors occur during the call.
visitClassStmt(ClassStmt stmt) → void
Defines a class.
visitContinueStmt(ContinueStmt stmt) → void
Visitor method for executing a ContinueStmt. Throws _ContinueException if inside a loop, otherwise throws RuntimeError.
visitDictComprehensionExpr(DictComprehensionExpr expr) → Object?
Visits a DictComprehensionExpr node (e.g., {[}i: i*i for i in range(5)}).
visitDictLiteralExpr(DictLiteralExpr expr) → Object?
Visitor method for evaluating a DictLiteralExpr ({...}). Evaluates each key and value expression, checks key hashability, and returns a new Dart Map. Throws RuntimeError for unhashable keys.
visitExpressionStmt(ExpressionStmt stmt) → void
Visitor method for executing an ExpressionStmt. Evaluates the expression and discards the result.
visitForStmt(ForStmt stmt) → void
Visitor method for executing a ForStmt. Evaluates the iterableexpression. If it's a Dart Iterable or String, iterates through its elements. In each iteration, defines the loop variable in the current environment and executes the body. Handles _BreakException and _ContinueException. Sets/resets _isInLoop.
visitFromImportStmt(FromImportStmt stmt) → void
Visitor method for executing an ImportStmt.
visitFStringExpr(FStringExpr expr) → Object?
Visitor method for evaluating an FStringExpr (f"..."). Evaluates each part expression and returns the combined string.
visitFunctionStmt(FunctionStmt stmt) → void
Visitor method for handling a FunctionStmt (function definition). Creates a PyFunction object, capturing the current environment as its closure, and defines it in the current environment.
visitGlobalStmt(GlobalStmt stmt) → void
Visitor method for handling a GlobalStmt (global variables definition).
visitGroupingExpr(GroupingExpr expr) → Object?
Visitor method for evaluating a GroupingExpr ((...)). Simply evaluates the inner expression.
visitIfStmt(IfStmt stmt) → void
Visitor method for executing an IfStmt. Evaluates the condition, executes the thenBranch if truthy. If falsey, evaluates elif conditions sequentially, executing the first truthy one. Executes elseBranch if no previous condition was met.
visitImportStmt(ImportStmt stmt) → void
Visitor method for executing an ImportStmt. Loads the specified module(s) and adds them to the environment
visitIndexGetExpr(IndexGetExpr expr) → Object?
Visitor method for evaluating a IndexGetExpr (indexing like obj[key]). Evaluates the object and the index expressions. Performs list, string, or dictionary lookup based on the object's type. Throws RuntimeError for invalid types, index out of bounds, or key errors.
visitIndexSetExpr(IndexSetExpr expr) → Object?
Visitor method for evaluating a IndexSetExpr (item assignment like obj[key] = value). Evaluates the object, index/key, and value. Performs assignment on lists or dictionaries. Throws RuntimeError for invalid types (e.g., string assignment), index errors, or unhashable keys.
visitLambdaExpr(LambdaExpr expr) → Object?
Visits a LambdaExpr node (e.g., lambda x: x**2).
visitListComprehensionExpr(ListComprehensionExpr expr) → Object?
Visits a ListComprehensionExpr node (e.g., [i for i in range(5)]).
visitListLiteralExpr(ListLiteralExpr expr) → Object?
Visitor method for evaluating a ListLiteralExpr ([...]). Evaluates each element expression and returns a new Dart List.
visitLiteralExpr(LiteralExpr expr) → Object?
Visitor method for evaluating a LiteralExpr (numbers, strings, True, False, None). Returns the literal value directly.
visitLogicalExpr(LogicalExpr expr) → Object?
Visitor method for evaluating a LogicalExpr (and, or). Implements short-circuiting evaluation:
visitNonlocalStmt(NonlocalStmt stmt) → void
Visits a NonlocalStmt node (nonlocal statement).
visitPassStmt(PassStmt stmt) → void
Visitor method for executing a PassStmt. Does nothing.
visitRaiseStmt(RaiseStmt stmt) → void
Visits a RaiseStmt node (e.g. raise Exception()).
visitReturnStmt(ReturnStmt stmt) → void
Visitor method for executing a ReturnStmt. Evaluates the optional return value and throws a ReturnValue exception to unwind the stack to the function call site.
visitSetComprehensionExpr(SetComprehensionExpr expr) → Object?
Visits a ListComprehensionExpr node (e.g., {i for i in range(5)]).
visitSetLiteralExpr(SetLiteralExpr expr) → Object?
Visits a SetLiteralExpr node (e.g., {1,'a'}).
visitSliceExpr(SliceExpr expr) → Object?
Builds a list, string or tuple slice
visitSuperExpr(SuperExpr expr) → Object?
Visits a SuperExpr node (e.g., in super().__init__()).
visitTernaryExpr(TernaryExpr expr) → dynamic
Visits a TernaryExpr node (e.g., "x" if 2==3 else "y").
visitTryStmt(TryStmt stmt) → void
Visits a TryStmt node (try:).
visitTupleLiteralExpr(TupleLiteralExpr expr) → Object?
Visits a TupleLiteralExpr node (e.g., (1,'a')).
visitUnaryExpr(UnaryExpr expr) → Object?
Visitor method for evaluating a UnaryExpr (-, +, ~, not). Evaluates the operand, performs the unary operation, and returns the result. Includes type checking.
visitVariableExpr(VariableExpr expr) → Object?
Visitor method for evaluating a VariableExpr. Looks up the variable's value in the current environment chain using _environment.get. Throws RuntimeError if the variable is not defined.
visitWhileStmt(WhileStmt stmt) → void
Visitor method for executing a WhileStmt. Repeatedly evaluates the condition; if truthy, executes the body. Handles _BreakException and _ContinueException to control loop flow. Sets/resets the _isInLoop flag. Includes basic infinite loop protection.
withEnvironment<T>(Environment env, T callback()) → T

Operators

operator ==(Object other) → bool
The equality operator.
inherited

Static Methods

builtInToken(String name) → Token
Creates a dummy token for error reporting within built-ins.
getTypeString(Object? obj) → String
Helper to get a predictable type name string used by type() and error messages.
internalIsEqual(Object? a, Object? b) → bool
Performs deep equality comparison between two runtime objects. Handles primitives, None, and recursively compares containers. Designed to be called internally or from type overrides (like PyTuple.==). Does NOT handle cross-type numeric comparison (e.g., 1 == 1.0) directly, relies on Dart's == for primitives which does handle it.
isHashable(Object? key) → bool
Helper to check if an object is suitable as a dictionary key (hashable). Mimics Python's rules (numbers, strings, booleans, None are hashable; lists, dicts are not).