4 stable releases

1.0.3 Mar 19, 2024
1.0.2 Mar 6, 2024
1.0.1 Mar 5, 2024

#919 in Programming languages

Download history 327/week @ 2024-03-01 66/week @ 2024-03-08 155/week @ 2024-03-15 22/week @ 2024-03-22 16/week @ 2024-03-29

309 downloads per month
Used in sap-cli

MIT/Apache

165KB
3K SLoC

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

Values 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.

Dependencies

~0.7–1.5MB
~34K SLoC