views:

50

answers:

1

I'm writing an interpreter. I've done that before but never tried one which can work with expressions like 3 + 4 * 2 / ( 1 − 5 ) ^ 2 ^ 3.

I'm not having a problem with the parsing process, actually it is about my VM which then executes the code.

My goal was a fast interpreter and so I decided not to use a stack-based VM where you would need more than one instruction for a multiplication, for example (push, push, mul)

The "assembly" code for the VM generated by the parser looks as following:

3 + 4 * 2 / ( 1 − 5 ) ^ 2 ^ 3

becomes

sub 1         5
pow result    2
pow result    3
div 2         result 
mul 4         result
add 3         result

(The result is correct)

  • As you can see: Every instruction takes no, one or two arguments. There is the result register which holds the result of the last instruction. And that's it.

Can a VM with a language of this structure and only one register calculate every mathematical expression for example Python or PHP can?

If it is not possible without a stack I'll start over right now!

+3  A: 

What do you do about (1 + 2) * (3 + 4), or any other that would require you to calculate more than one intermediate result?

calmh
Yep, now I and my interpreter have a problem.
mersion
Do you think it would be possible with a two-register machine? So that you have the result of the last *two* operations?
mersion
(1 + 2) * (3 + 4) + (5 + 6) * (7 * 8)
John Kugelman
No, I don't think an "n-register" machine will handle random expressions. You need a stack. For the two-register machine, (1+2)*(3+4)*(5+6) will be a problem.
calmh