c - 编写编译器时,如何检查标记?

标签 c compiler-construction lexical-analysis

如果遇到某个关键字,编译器在决定做什么时是否使用 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/

相关文章:

c - C中密码中的字符数

c - Microsoft Visual Studios 2010 - 在常规 C 中创建一个新项目

compiler-construction - 不清楚链接器的工作

compiler-construction - 是什么让值不安全地存储在寄存器中?

objective-c - 如何在没有解析器生成器的情况下用 C 或 Objective-C 编写解析器?

parsing - 耶尔瓦尔和联盟

c# - 创建词流的最佳方式

c - 将分配函数导出到导致段错误的子例程。

c - "Resetting"链表的"Head"指针

compiler-construction - wxwidgets setup.h“没有这样的文件”