C宏处理
我正在考虑编写能够处理宏的C定义处理器的最佳方法。不幸的是,我并没有想到任何聪明的事情。 它的行为应该与 C 中的完全一样,因此它处理如下表达式:
#define max(a, b) (a > b ? a : b)
printf("%d\n", max(a, b));
或者这样:
#define F 10
#define max(a, b) (a > b ? a : b)
printf("%d\n", max(a, F));
我知道 K&R2 的安装和查找函数,我还需要什么 替换括号内的文本? 有人有任何建议或一些伪代码吗? 我知道这是一项复杂的任务,但是,最好的方法是什么?
I'm thinking about best way to write C define processor that would be able to handle macros. Unfortunately nothing intelligent comes to my mind.
It should behave exactly like one in C, so it handles expressions like this:
#define max(a, b) (a > b ? a : b)
printf("%d\n", max(a, b));
Or this:
#define F 10
#define max(a, b) (a > b ? a : b)
printf("%d\n", max(a, F));
I know about install and lookup functions from K&R2, what else do I need for
replacing text inside parenthesis?
Does anyone have any advice or some pseudo-code maybe?
I know it's complex task, but still, what would be best possible way to do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
宏处理器非常有趣,但可能成为难以驯服的野兽(例如,考虑递归扩展)。
您可以查看现有宏处理器(例如 M4)的实现(http ://www.scs.stanford.edu/~reddy/links/gnu/m4.pdf)。
一般来说,您将需要:
我认为这是一个非常有趣的练习。处理所有这些的正确数据结构并非易事。
Macro processors are very interesting but can became a difficult beast to tame (think about recursive expansions, for example).
You can look at the implementation of already existing macro processors like M4 (http://www.scs.stanford.edu/~reddy/links/gnu/m4.pdf).
In very general terms you will need:
I think it's a very interesting exercise. The proper data structure to handle all this is not trivial.
这是一个模式匹配问题,你应该先看看正则表达式,然后当您掌握了相关理论后,您可以继续阅读词法分析器。
正则表达式基本上是将字符串与预定义的模式进行匹配。
一些regexp(正则表达式的缩写)软件/库:
- Boost.Regexp
- GNU C 库正则表达式
- PCRE
词法分析器是一款对匹配文本执行某些操作的软件,例如替换该文本一段文字与其他一段文字,基本上就是你似乎需要的。
一些已知的词法分析器:
- flex
- Boost.Wave
This is a pattern matching problem, you should take a look at regular expressions to start with, then when you've grasped the theory on that you could move on to reading about lexers.
A regular expression is basically matching a string to a predefined pattern.
Some regexp (short for regular expression) software/libraries:
- Boost.Regexp
- GNU C library regexp
- PCRE
And a lexer is a piece of software that does something with the matched text, for example, replacing that piece of text with some other piece of text, basically what you seem to need.
Some known lexers:
- flex
- Boost.Wave
2个建议:
,即“不要在家尝试这个”。
2 suggestions:
ie "don't try this at home".