gpt4 book ai didi

assembly - 如何避免解析器中出现大量 if-else 语句

转载 作者:行者123 更新时间:2023-12-03 05:05:31 25 4
gpt4 key购买 nike

我是汇编器设计领域的新手。我正在为机器设计自己的汇编器。目前,我的汇编器采用第一个标记(假设它是一条指令),然后尝试生成相应的目标代码。现在我需要将 token 与助记符池进行匹配,然后生成相应的 obj 代码。问题是我目前使用 if-else 结构,即

if(strcmp(mnemonic_read, "mov")==0)
// generate code for mov instr
else if(strcmp(mnemonic_read,"cmp")==0)
// generate code for cmp

我可以在不使用大量 if-else 语句的情况下完成这一切吗?我可以通过 mnemonic_read 字符串变量调用函数吗?

最佳答案

这是一个常见问题,有一个常见的解决方案(哈罗德建议)。

您可能需要研究 lex/yacc 或 flex/bison,它们在 *nix 环境中运行良好。 Antlr 做了类似的事情,但使用 Java。

例如,您可以使用 lex(来自 http://dinosaur.compilertools.net/ ):

Lex source is a table of regular expressions and corresponding program fragments. The table is translated to a program which reads an input stream, copying it to an output stream and partitioning the input into strings which match the given expressions. As each such string is recognized the corresponding program fragment is executed.

因此在 lex 中您可以指定标记(由正则表达式匹配)以及要生成的相应代码。您还可以将标记输入 yacc(另一个编译器编译器),您可以使用它为您的新语言生成编译器。

这是一个有用的指南和示例:http://ds9a.nl/lex-yacc/cvs/lex-yacc-howto.html

关于assembly - 如何避免解析器中出现大量 if-else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12318809/

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