Close

Expression evaluation

A project log for One kilobyte Tiny BASIC for the 8080 and Z80

BASIC for the 8080 and Z80, fits in 1K of memory, runs BASIC games on a 2K system. Features similar to Palo Alto Tiny BASIC.

willstevenswill.stevens 01/26/2024 at 07:340 Comments

When I first wrote the expression evaluator I used Dijkstra’s shunting yard algorithm for handling operator precedence and bracketed subexpressions. I changed approach later on when writing code for the RND, USR and ABS functions because I realised the the evaluator needed to be recursive so that the function parameter can be evaluated. In the new approach recursion is also used to evaluate bracketed subexpressions. Within a bracketed subexpression a stack-based evaluator is used, but the top of the evaluation stack is stored in DE - this means that evaluation of simple expressions (constants, variables) doesn’t need to use the physical stack at all.

To the evaluator, an expression is just an alternating sequence of values and operators (because function calls and bracketed subexpressions are handled recursively, they are just like values to the evaluator).

When an operator is encountered, there will be a value in DE, and the stack will either be empty if this is the first operator, or will contain an operator. An empty stack is detected by looking for a value of zero in the high-order byte of the 16-bit value on the stack (because the evaluator is always called from page zero). If there is an operator on the stack and its precedence is greater than the operator encountered, the function corresponding to the operator on the stack is called (leaving a value in DE) and we loop back to the beginning of this paragraph. Otherwise we push DE and the operator onto the stack and look for the next value. When we reach the end of the expression we evaluate every operator remaining on the stack. 

At the time of writing this, the evaluator occupies addresses 38h to 7Ch and BCh to CFh, a total of 88 bytes. This doesn’t include any of the code called by the evaluator to evaluate operators or RND, USR, ABS, or code getting the location of a variable.

Discussions