Saturday, 10 November 2012

Testing, Operators, and Syntax Checking

Over the last few weeks I have made a big change and added new things to my project. I will start off with the use of unit testing. I had never really tried out the unit testing tools built into visual studio, so I thought this would be the perfect opportunity to do so. It has proven to be a huge help allowing me to check different use cases and tweak code where necessary so that all the tests pass.

The big change I have made is the way operators are handled. I have decided to treat operators as a type of function, sort of like a proxy for another function, so for example the operator "+" can be used like 2+2, but really it is just a function pointing to another function, which in the case of "+" would be "add", which could be also called like add(2 2).

My final thing to report is the implementation of syntax checking. I have designed a simple way to ensure syntax is correct using a process that utilises numbers on a stack and goes as follows: functions set the next number to push based on their amount of arguments, "(" push the next number onto the stack then reset it to 1, operators count for 1, and everything else counts for -1 (the ")" also pops the stack).

For the expression add(2 (4 - 1)), the process would be:

1. nextStart = 1  |  stack = [1]

2. "add" takes two arguments set the next start (nextStart = 2, stack = [1])

3. "(" pushed nextStart value onto the stack and resets it (nextStart = 1, stack = [1 2])

4. "2" counts for -1 decrease stack (nextStart = 1, stack = [1 1])

5. "(" pushed nextStart value onto the stack and resets it (nextStart = 1, stack = [1 1 1])

6. "4" counts for -1 decrease stack (nextStart = 1, stack = [1 1 0])

7. "-" counts for 1 increase stack (nextStart = 1, stack = [1 1 1])

8. "1" counts for -1 decrease stack (nextStart = 1, stack = [1 1 0])

9. ")" pop value off the stack and decrease -1 (nextStart = 1, stack = [1 0])

10. ")" pop value off the stack and decrease -1 (nextStart = 1, stack = [0])

Combining this process with a set of rules I am able to check the last number on the stack to identify bad syntax, an example would be, if the last element on the stack is 0 I know that the last token was not an operator.

No comments:

Post a Comment