解释器输入 C
我正在开发一个解释器,我对此有一些疑问。
我最近看到一个小型 C 解释器,它使用如下所示的非常简单的结构来表示该语言中的所有对象/值:
struct Object
{
ubyte type;
ubyte value;
};
该结构可以保存解释器正在使用的语言中使用的字符串、整数、布尔值和列表(我认为) 。
- 如何让这个对象结构保存所有这些类型?
I'm developing an interpreter and I have some questions to it.
I recently saw a small C interpreter that used a very simple struct like the below for all its objects/values in the language:
struct Object
{
ubyte type;
ubyte value;
};
This struct can hold strings, integers, bools and lists (I think) used in the language the interpreter is working with.
- How can you get this Object struct to hold all these types?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不保存值,它只保存对存储在其他地方的值的 ID/引用。
It doesn't hold the value it just holds IDs/references to the values which are stored somewhere else.
最有可能的是,它是按照 sbi 建议的方式完成的,因此解释器的结构看起来更像是:
实际值将分配在堆上的某个位置,并且当构造对象时,解释器会记下 ubyte 类型中的类型.稍后,函数会使用
object.type
记录类型,并将值别名为该类型,或者只是假设它是正确的类型,如下所示:如果您只想实现几种类型,您也可以尝试使用联合。
Most likely, it's done like sbi suggests, so the interpreter's struct would look more like:
The actual value would be allocated somewhere on the heap, and when the object was constructed, the interpreter would note the type in
ubyte type
. Later, functions would note the type usingobject.type
and alias the value to that type, or just assume that it was the correct type, like this:If you just have a few types you want to implement, you could also try using a union.