tsoding / porth

It's like Forth but in Python
629 stars 50 forks source link

Add switch blocks #119

Open mosswg opened 2 years ago

mosswg commented 2 years ago

Added switch blocks using integers for comparison. This also adds the switch, case, and break keywords.

In compilation a list is created in the switch's operand. The last 2 elements contain the default case location and the end location. The other elements of the list are the case conditions.

In simulation mode the list is looped through to find the matching case. If no match if found it will jump to either the default case if it exists or the end of the switch block.

In compilation mode all the conditions are checked consecutively until a match is found. If no matching one is found there is a non conditional jump to either the default case or the end of the switch block.

If a case is found without anything on the stack it will be treated as the default case. Since only one default case is possible having more will cause a compile error. A default keyword could be easily added but I wanted to minimize the amount of new keywords added.