嘿,对于一个学校项目, 目标是构建一个编译器 ,虽然我完成了所有其他要求, 我似乎无法忍受让比较运算符为字符串工作 。它适用于整数,浮点数,字符和布尔值,但在处理字符串时踌躇不前。如果不发布我的整个代码,我会告诉你变量的参数输出正确的值。
对于前。这是在我自己的编译器中:
var test:=“hello”==“hi”;
我函数中的参数是分别具有hello和hi值的标记。
if(type == type.STRING) {
if(operator == Punctuator.Equal) { // the operator checks which operator is used which in this case is "==", that is what Punctuator.Equal is equal to.
code.add(JumpTrue);
code.add(Jump);
}
// operator for when '!='
}
所以这段代码正在做的是查看参数是否为字符串并且运算符等于'=='。然后它使用编译器代码转换为机器语言,我将在下面发布一个片段。
Jump, // takes a string operand, branches to statement with that label.
JumpFalse, // takes a string operand. Pops top value (integer) from stack, does Jump if value=0
JumpTrue, // takes a string operand. Pops the top (integer) and Jumps if it is not 0.
JumpNeg, // takes a string operand. Pops the top (integer) and Jumps if it is negative.
JumpPos, // takes a string operand. Pops the top (integer) and Jumps if it is positive.
JumpFNeg, // takes a string operand. Pops the top (floating) and Jumps if it is negative.
JumpFPos, // takes a string operand. Pops the top (floating) and Jumps if it is positive.
JumpFZero, // takes a string operand. Pops the top (floating) and Jumps if it is zero.
Call, // takes a string operand. Jumps to that location, and pushes return instruction location.
JumpV, // [... addr] -> [...] Branches to addr.
CallV, // [... addr] -> [...] Jumps to addr, and pushes return instruction location.
如果有人能看出我的错误可能存在的地方,请给我一些提示,以便我可以修补它。
我认为“code.add(JumpTrue)”可能不起作用,因为我正在处理字符串,但我不知道还有什么可以使用。
编辑:我不使用 Java编译器编译我的代码。这是由我自己的编译器编译的,允许通过字符串进行“==”比较。