gpt4 book ai didi

compiler-construction - 为什么使用整数作为标记?

转载 作者:行者123 更新时间:2023-12-04 00:15:35 25 4
gpt4 key购买 nike

现在有什么好的理由使用数字来识别 token 吗?我正在关注制作编译器

作者给出的代码在这里:

public class Token {
public final static int ID = 0, FLTDCL = 1, INTDCL = 2, PRINT = 3,
ASSIGN = 4, PLUS = 5, MINUS = 6, EOF = 7, INUM = 8, FNUM = 9;

public final static String[] token2str = new String[] { "id", "fltdcl",
"intdcl", "print", "assign", "plus", "minus", "$", "inum", "fnum" };

public final int type;
public final String val;

public Token(int type) {
this(type, "");
}

public Token(int type, String val) {
this.type = type;
this.val = val;
}

public String toString() {
return "Token type\t" + token2str[type] + "\tval\t" + val;
}
}

与其使用丑陋的数组,不如修改构造函数以接受 type 变量的字符串而不是整数,这不是更聪明吗?然后我们可以摆脱

    public final static int ID = 0, FLTDCL = 1, INTDCL = 2, PRINT = 3,
ASSIGN = 4, PLUS = 5, MINUS = 6, EOF = 7, INUM = 8, FNUM = 9;

还是以后需要,因为使用字符串会更糟?

最佳答案

有几个好处:

  • 速度更快,因为比较两个整数(在您的普通编译语言中)只需要几条指令,而比较字符串需要 O(n) 时间,其中 n 是较大 token 的长度。 Compilers need this extra bit of speed .
  • 在 C、C++ 和 Java 中,您可以在 int切换,但不能在字符串上切换。
  • 输入错误的 token 名称将是编译时错误,而不是难以调试的运行时错误。

关于compiler-construction - 为什么使用整数作为标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5172729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com