PScript Interpreter – Part 2 – Expressions

I must admit that PScript is a nice break from the larger BSA task. Sadly BSA is written in C# and PScript in C++ because PScript is perfect for extending BSA. But, I can actually use C++ from C#, so lets see.

I have created a stack that I use while I interpret and I am very happy with how that worked out, but I have so far only interpreted the core language and I need expressions. I have done several expression parsers both interpreters and parsers in the past, so what I want goes hand in hand with the existing stack. Let’s annotate an example:

uint32 d
d = 3 + 4 * 5
print(d)

This is a classic mathematical expression test that should print out 23. Let’s interpret this step by step:

  1. “uint32 d” will set up an entry on the stack for the variable d.
  2. Next line “d” tells me that this is a variable and as such an assign operation.
  3. “=” confirms that this is an assign operation.
  4. “3+” get added on the stack.
  5. “4*” get added on the stack. As we now have two or more expression components we evaluate if we should calculate and since * have higher priority than + we just continue.
  6. “5 eol” is added to the stack.
  7. As eol (end of line) is the lowest priority we now calculate “4 * 5” and replace the two last stack entries with “20 eol”
  8. We now evaluate the two remaining expression entries and calculate “3 + 20” replacing the two last entries with “23 eol”
  9. With only one entry left, nothing more to parse and “eol” tagged we are finished. The result is 23. So we assign 23 to the variable d.
  10. “print (d)” is parsed. A call to print and d is pushed on the stack and 23 get printed out.

I have only used a very simple example as we also need to support parentheses and variables in addition to constants. We also need to support functions that return values, but it is all pretty much straight forward.

Once expressions and return functions are supported we pretty much have our own math script where we can combine math expressions and logic for more complex calculations. My experience with expressions tells me that 10 stack entries are a very complex expression. This is no limit, but it is an estimate that we need ca 10 entries (120 bytes) in spare while interpreting an expression. After an expression is interpreted we release the stack.

 

Leave a Reply