首页 > 解决方案 > 将字符串常量转换为虚拟机代码

问题描述

我有一个学校项目,可以将千斤顶程序翻译成 vm 代码。我们得到了一些模糊的指示,让我们自己去做。
我在将字符串常量转换为 vm 代码时遇到问题。
假设程序中有一个命令如下:
do Output.printString("Hello world!")
翻译将是这样的:

push SOMETHING (I don't know what to put here) 
call Output.printString 1

如何将字符串翻译成 vm?

谢谢!

标签: stringcompilationconstants

解决方案


这是我想出的:
有两个函数用于创建字符串。String.newString.appendChar
要创建一个字符串,首先调用String.new字符串的长度作为参数。然后,调用String.appendChar每个字符,将当前字符的 ascii 值作为函数的参数。
因此,例如,要创建字符串"Hello World"

push constant 11 //this is the length of the word
call String.new 1
push constant 72 //ascii of h
call String.appendChar 2
//continue this for each character in the word
...
call Output.printString 1 //prints the string that we created

推荐阅读