我将如何为我的语言添加定义?

How would I go about adding definitions to my language?

我用 C 编写了一种基于堆栈的解释型语言。解释器的工作方式是逐行读取文件并根据操作执行该行。 python 中的 print(1 + 1) 将变为 1 1 + print

这是检查操作是什么并将其压入堆栈或对其进行操作的函数:

if (strncmp(op, "+", 1) == 0 && is_definition == 0)
{
    float a = pop(stack);
    float b = pop(stack);
    push(stack, a + b);
}
else if (strncmp(op, "-", 1) == 0 && is_definition == 0)
{
    float a = pop(stack);
    float b = pop(stack);
    push(stack, b - a);
}
else if (strncmp(op, "*", 1) == 0 && is_definition == 0)
{
    float a = pop(stack);
    float b = pop(stack);
    push(stack, a * b);
}
else if (strncmp(op, "/", 1) == 0 && is_definition == 0)
{
    float a = pop(stack);
    float b = pop(stack);
    push(stack, b / a);
}
else if (strncmp(op, "print", 5) == 0 && is_definition == 0)
{
    float a = pop(stack);
    if(a == (int)a)
        printf("%d\n", (int)a);
    else
        printf("%f\n", a);
}
else if (strncmp(op, "define", 6) == 0 && is_definition == 0)
{
    is_definition = 1;
}
else if (is_definition == 1)
{
}
else if (strncmp(op, "end", 3) == 0 && is_definition == 1)
{
    is_definition = 0;
}
else
{
    push(stack, atoi(op));
}

这是一个循环,循环遍历代码中的每个 space 分隔操作。

我想添加一个有点像C语言的定义系统。 这是我想要的语法

define TEST 10 end

我想像使用可变系统一样使用它,您可以在其中使用 TEST

在伪代码中,您应该执行以下操作:

  1. 读取一行源码
  2. 如果是定义,则解析+存储并跳过其余部分
  3. (这不是定义)执行,很像你发布的代码

关于“解析+存储”定义,您需要 - 例如 - 几个数组,或一个结构数组。您需要存储每个“名称”(别名,或定义的名称)及其值。

然后,在您发布的代码中,您应该实现 push() 指令(您只提到 pop())。 push() 指令读取操作数并确定它是否是别名(定义):

(推送伪代码)

  1. 获取操作数
  2. 判断是否为定义。基本上,您迭代所有存储的定义以找到对应关系
  3. 得到最终值,入栈

有几件事可以说...其中一些,顺序很稀疏:

  • 压入的操作数是数字?在这种情况下,您可以跳过定义检查,假设说“define 10 20”

    是非法的
  • 您允许(重新)定义运算符吗?

  • 您是否允许一个定义引用其他定义?

...