如果遇到某个关键字,编译器在决定做什么时是否使用 if 语句?编写编译器的人是否应该在检查代码时将它们用于大多数操作?或者有没有更有效的方法?例如,当我针对符号表测试一个符号并且它作为有效的“标记”返回时,我是否必须使用 if 语句来确定对每个关键字执行的操作,因为它看起来效率很低,例如伪代码:
/*Each keyword/token in my compiler has a numerical representation which is what the symbol table returns back for example #define IF 0 and so on*/
if(Token == IF){
//This will be done to generate the AST representation for IF statements
}else if(Token == ELSE){
//This will be done to generate the AST representation of an if statement
}else if(Token == INT){
//This will be done to generate the AST represnetation of an integer
}
最佳答案
你指的是哪种编译器? 如果性能很重要,你可能想要像回调这样的东西,这样,使用关键字作为键,回调函数作为值,所以伪代码如下所示:
func *fp = funcTbl.get(Token);
if (fp) { fp(); }
您也可以尝试递归下降。与关键字相关的函数在预期的位置被调用。
最后但同样重要的是,你写的也不错。
关于c - 编写编译器时,如何检查标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33839072/