繁体   English   中英

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

[英]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));
}

这是在一个循环内迭代代码中的每个空格分隔的操作。

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

define TEST 10 end

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

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

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

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

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

(推送伪代码)

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

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

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

  • 您是否允许(重新)定义运算符?

  • 你会允许一个定义引用其他定义吗?

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM