Goal: follow the boundary where syntax changes state
A syntax tree describes operations but does not change variables or the DOM by itself. The runtime evaluates expressions, updates bindings, and invokes supported operations. Follow eval_expr, execute_stmt, and call_function to identify which state each statement changes. The goal is to explain a displayed result from the previous environment and the operation that executed, rather than accepting the final number as self-explanatory.
This educational JavaScript subset is implemented in Rust. Its values are represented explicitly instead of being delegated to host eval. Compare values, diagnostics, and DOM changes for the same input in the CLI and WASM interface. Distinguishing computation in Rust from presentation in the browser makes the architecture observable and prevents the interface from becoming an accidental second interpreter.
An environment records more than names and values
let count = 0; creates a binding that can be updated. const limit = 2; also records a restriction on reassignment. A dictionary containing only names and numbers would lose this distinction. Separate reading a binding from writing one, and inspect where the runtime checks the binding's mutability before changing its value. A rejected assignment should leave the previous binding available for diagnosis.
A function call evaluates arguments, binds them to parameters, and creates a local naming context. The supported model has top-level named functions and local bindings, rather than arbitrary stored closures. Investigate parameter names that overlap outer names and the environment visible after return. Read the implementation's scope rules directly instead of assuming the complete ECMAScript environment model has been reproduced. Ordinary function calls also check argument count against their declared parameter count.
Represent values separately from control flow
Expression evaluation produces a value. Statement execution also determines whether execution continues normally or returns to a caller. Treating return 3; as merely the number three would let subsequent statements in the function execute incorrectly. Follow the separate path for return completion, including a return nested inside an if. Correct value representation does not by itself establish correct control flow.
Operator behavior also deserves explicit tests. The subset implements arithmetic, comparisons, and negation, but that does not justify assuming every ECMAScript conversion rule. Compare numeric addition, addition involving a string, and an unknown-name read as separate inputs. If a result differs from a prediction, distinguish tree structure, value conversion, and environment lookup before changing the evaluator. Here == and != use the same bounded strict primitive comparisons as === and !==. Numbers must remain finite and division by zero is diagnosed.
Worked trace: one function call
Consider function next(x) { return x + 1; } let count = next(2);. The function definition becomes available, the argument two is associated with parameter x, the body computes three, and return transfers that value to the caller. The declaration then initializes count. Do not treat the parameter and the receiving global binding as the same storage location; identify the environment consulted at every stage.
This table is a reasoning trace, not a promise about an exact number of recorded frames. Change the call to next(5) and distinguish changed argument values from newly created call state. Add a statement after return and verify that it does not execute. That extra observation tests control flow rather than merely checking the arithmetic result.
| Stage | State | Next check |
|---|---|---|
| Define | next → function body | Do not evaluate the body yet |
| Call | local x = 2 | Bind argument to parameter |
| Evaluate | x + 1 → 3 | Produce a value |
| Return | return 3 → count = 3 | Skip following body statements |
Use Rust node identifiers for DOM references
document.getElementById searches the DOM owned by the Rust lesson engine. A subsequent textContent assignment mutates a node in that same arena. The host browser does not find a real page element and copy its result back. This distinction connects variable evaluation to the rendering pipeline: visually similar elements can belong to different trees, so identify which tree owns a handle.
A missing ID or an invalid method receiver cannot be treated as a valid node handle. Begin with a working lookup, change one character in the ID, and compare the resulting diagnostic. setAttribute is also restricted to the implemented surface rather than being an arbitrary Web API bridge. Follow the Rust value variants and receiver checks to distinguish node references, strings, and function references.
Runnable Rust: mutation and execution budgets
The standalone host program checks mutable bindings, rejected reassignment to a constant, and consumption of an execution budget. It does not reproduce the entire interpreter or its conversion rules. Reducing the state makes it easy to assert that a failed operation preserves the existing value. Keep this invariant test separate from tests that parse and execute JavaScript source.
The actual interpreter limits execution to 2048 steps and accepts at most sixteen input events. Recursion can consume substantial work even without loop syntax. A budget is an implementation contract about which operations consume resources, not simply a timeout attached afterward. First observe the success and failure at a budget of one in the snippet, then investigate boundary inputs in the distributed interpreter.
use std::collections::BTreeMap;
#[derive(Clone)]
struct Binding { value: i64, writable: bool }
fn assign(env: &mut BTreeMap<String, Binding>, name: &str, value: i64)
-> Result<(), &'static str> {
let b = env.get_mut(name).ok_or("unknown binding")?;
if !b.writable { return Err("constant assignment"); }
b.value = value;
Ok(())
}
fn tick(remaining: &mut usize) -> Result<(), &'static str> {
if *remaining == 0 { return Err("step budget"); }
*remaining -= 1; Ok(())
}
fn main() {
let mut env = BTreeMap::new();
env.insert("count".into(), Binding { value: 0, writable: true });
env.insert("limit".into(), Binding { value: 2, writable: false });
assert!(assign(&mut env, "count", 1).is_ok());
assert_eq!(assign(&mut env, "limit", 3), Err("constant assignment"));
assert_eq!(env["limit"].value, 2);
let mut budget = 1;
assert_eq!(tick(&mut budget), Ok(()));
assert_eq!(tick(&mut budget), Err("step budget"));
println!("count={} limit={} budget={}", env["count"].value, env["limit"].value, budget);
}Use one state model for normal, boundary, and failure cases
For a normal case, update a let binding once and pass its value to a function. Boundaries include empty argument lists, returns inside branches, deep calls, and the end of the step budget. Failures include constant reassignment, unknown names, and unsupported calls. Record the initial environment, the last completed operation, and the diagnostic instead of assuming that an error means nothing executed.
In a sequence of statements, earlier mutations may complete before a later statement fails. Do not assume the interpreter provides automatic transactional rollback. Inspect the returned DOM and trace to establish progress. Also distinguish resetting and repeating the whole input from adding another event within one execution; these operations may begin from different environments and therefore test different contracts.
Exercise: write the environments before the result
Write a short program with a top-level count, a function parameter x, and a local variable. Record the environment before the call, after binding arguments, immediately before return, and after returning. Rename a local binding to match an outer name and predict which binding each read selects. Explain disagreements as scope assumptions rather than reporting only incorrect final values.
Add a constant assignment at the end and identify mutations completed before failure. Submit one normal, one boundary, and one failure case with the relevant Rust branch supporting each explanation. As an extension, try a small recursive call and inspect the budget diagnostic. Explain how the stopping condition remains observable before proposing to increase or remove the resource limit.