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
printandrange.
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
Exprnode by dispatching to the appropriatevisitmethod. 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
visitmethod. -
executeBlock(
List< Stmt> statements, Environment environment) → void -
Executes a block of
statementswithin a specificenvironment. 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. HandlesNone. 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(). HandlesNone,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 sidevalue, then assigns it to the variablenamein the current environment chain using_environment.assign. Returns the assigned value. -
visitAttributeGetExpr(
AttributeGetExpr expr) → Object? -
Visits a
AttributeGetExprnode (e.g.,obj.attr). -
visitAttributeSetExpr(
AttributeSetExpr expr) → Object? -
Visits a
AttributeSetExprnode (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_BreakExceptionif inside a loop, otherwise throwsRuntimeError. -
visitCallExpr(
CallExpr expr) → Object? -
Visitor method for evaluating a
CallExpr. Evaluates thecalleeexpression. If it's aPyCallable, evaluates all arguments (positional and keyword), then invokes the callable'scallmethod. ThrowsRuntimeErrorif 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_ContinueExceptionif inside a loop, otherwise throwsRuntimeError. -
visitDictComprehensionExpr(
DictComprehensionExpr expr) → Object? -
Visits a
DictComprehensionExprnode (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. ThrowsRuntimeErrorfor 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 theiterableexpression. If it's a Dart Iterable or String, iterates through its elements. In each iteration, defines the loopvariablein the current environment and executes thebody. Handles_BreakExceptionand_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 thethenBranchif truthy. If falsey, evaluateselifconditions sequentially, executing the first truthy one. ExecuteselseBranchif 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 likeobj[key]). Evaluates theobjectand theindexexpressions. Performs list, string, or dictionary lookup based on the object's type. ThrowsRuntimeErrorfor invalid types, index out of bounds, or key errors. -
visitIndexSetExpr(
IndexSetExpr expr) → Object? -
Visitor method for evaluating a
IndexSetExpr(item assignment likeobj[key] = value). Evaluates the object, index/key, and value. Performs assignment on lists or dictionaries. ThrowsRuntimeErrorfor invalid types (e.g., string assignment), index errors, or unhashable keys. -
visitLambdaExpr(
LambdaExpr expr) → Object? -
Visits a
LambdaExprnode (e.g.,lambda x: x**2). -
visitListComprehensionExpr(
ListComprehensionExpr expr) → Object? -
Visits a
ListComprehensionExprnode (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
NonlocalStmtnode (nonlocalstatement). -
visitPassStmt(
PassStmt stmt) → void -
Visitor method for executing a
PassStmt. Does nothing. -
visitRaiseStmt(
RaiseStmt stmt) → void -
Visits a
RaiseStmtnode (e.g.raise Exception()). -
visitReturnStmt(
ReturnStmt stmt) → void -
Visitor method for executing a
ReturnStmt. Evaluates the optional return value and throws aReturnValueexception to unwind the stack to the function call site. -
visitSetComprehensionExpr(
SetComprehensionExpr expr) → Object? -
Visits a
ListComprehensionExprnode (e.g.,{i for i in range(5)]). -
visitSetLiteralExpr(
SetLiteralExpr expr) → Object? -
Visits a
SetLiteralExprnode (e.g.,{1,'a'}). -
visitSliceExpr(
SliceExpr expr) → Object? - Builds a list, string or tuple slice
-
visitSuperExpr(
SuperExpr expr) → Object? -
Visits a
SuperExprnode (e.g., insuper().__init__()). -
visitTernaryExpr(
TernaryExpr expr) → dynamic -
Visits a
TernaryExprnode (e.g.,"x" if 2==3 else "y"). -
visitTryStmt(
TryStmt stmt) → void -
Visits a
TryStmtnode (try:). -
visitTupleLiteralExpr(
TupleLiteralExpr expr) → Object? -
Visits a
TupleLiteralExprnode (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. ThrowsRuntimeErrorif 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_BreakExceptionand_ContinueExceptionto control loop flow. Sets/resets the_isInLoopflag. 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).