Expand description
§Interpreter Module
The Interpreter module is responsible for the execution, and runtime management of a
SAP program. Through the eval_program()
function, the AST is traversed, and the
actual runtime logic of each node is applied. For example if a Binary
node is
encountered, it is converted into it’s actual value (i.e. 1+2
becomes 3
).
§Values
Value
s a repsented as enum. The same module also contains all the logic for
manipulating values, such as comparing, adding, subtracting and so on…
§Environment
At runtime, values which aren’t directly stored in the AST (i.e variables) are stored
in an Environment
. An environment is made up of 2 things: A hashmap binding the
variable names to the data they store, and a reference to the outer/parent
environment.
§Execution
As previosuly mentioned, a SAP program is executed by traversing it’s AST, and applying the runtime logic of each node. This can be evaluating numerical expression, retrieving/storing variables, repetition or displaying to the console.
Before understanding traversal interrupts, it is important to note that the call stack is reflective of where in the tree the code has traversed, as each AST node has it’s own dedicated function.
There are two things which can interrupt the traversal of the tree:
- Runtime errors
- Return statements
When a runtime error is encountered, traversal stops completely and
the error is returned to the caller of the eval_program()
function.
When a return statement in encountered, the code backtracks up the tree until reaching
a FunctionCall
node, or the root (Program
) node. If the root node is reached,
this indicates the return statement was used outside of a function, which is treated
as an error.
If a FunctionCall
node is reached, this indicates the return statement was used
inside a function, which was invoked by this function call. The return value is
unwrapped into a normal value, and can be used as normal in the place of the function
call.
For example, take the expression set x = 1+add(1, 3)
, the function add(1, 3)
might
produce a Return(Value(4))
which is then unwrapped into a Value(4)
. The resulting
statement now looks like set x = 1+4
.
Modules§
- runtime
- This module contains the
Environment
struct, which is used to store and lookup SAP variables and functions. It also contains a type alias for a sharedEnvironment
reference. - value
- This module contains the
Value
struct, which represents a variable or function stored within anEnvironment
. It also contains all the logic for manipulating values (such as addition, comparison or conversion between types).
Enums§
- Traversal
Interrupt - Represents an interruption in traversal of the AST.
Constants§
Functions§
- create_
env - Shorthand function for creating a new empty
EnvRef
- eval_
program - Probably the most important function in the whole program, the main entry point of the SAP interpreter. It performs the actual execution of a program, returning a final result.