具有单寄存器虚拟机的解释器 - 可以评估所有数学。表达式?
我正在写一个解释器。我以前曾这样做过,但从未尝试过可以与 3 + 4 * 2 / ( 1 − 5 ) ^ 2 ^ 3 等表达式一起使用的方法。
我在解析过程中没有遇到问题,实际上这是关于我的虚拟机然后执行代码的问题。
我的目标是一个快速解释器,所以我决定不使用基于堆栈的虚拟机,在这种情况下,您需要多个指令来进行乘法,例如(push、push、mul)
由解析器如下所示:
3 + 4 * 2 / ( 1 − 5 ) ^ 2 ^ 3
变为
sub 1 5
pow result 2
pow result 3
div 2 result
mul 4 result
add 3 result
(结果正确)
- 如您所见: 每条指令都没有参数,只有一个或两个参数。结果寄存器保存最后一条指令的结果。就是这样。
具有这种结构的语言且只有一个寄存器的虚拟机是否可以计算每个数学表达式(例如Python或PHP)?
如果没有堆栈就不可能,我会立即重新开始!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于 (1 + 2) * (3 + 4) 或任何其他需要计算多个中间结果的情况,您会怎么做?
What do you do about (1 + 2) * (3 + 4), or any other that would require you to calculate more than one intermediate result?