【发布时间】:2020-07-31 17:09:24
【问题描述】:
我目前正在编写(为了好玩)一门深受数学启发的编程语言。
运算符(及其优先级/关联性)在语言中定义,例如:
let factorial be an operator[int <- int!]
with precedence of 2
and left-to-right associativity;
let factorial(n) = ...;
let abs be an operator[number <- |number|]
with precedence of 2
and no associativity;
let abs(x) = ...;
let not be an operator[bool <- !bool]
with precedence of 2
and right-to-left associativity;
这适用于更常见的运算符(+、-、*、/,...)。
注意:语法不是确定的
为了生成有用的 AST,我决定进行多个解析步骤。 第一步,表达式只是术语和符号的列表(支持括号分组),例如:
m! / (n! * (m - n)!)
将被解析为(这里是简化的 AST):
["m", "!", "/", ["n", "!", "*", ["m", "-", "n"], "!"]]
在第一步之后,我知道定义了哪些运算符,我知道它们的优先顺序以及它们的关联性。
我在执行第二步时遇到了困难,该步骤应该为表达式生成树(而不是列表)。
第一步是使用library 以EBNF 语法作为输入来实现的。 第二步,我试图在表达式中“找到”运算符的模式(使用自制的Parser Combinator):
let factorial be an operator[int <- int!] ...;
# here the pattern is ["int", "!"]
但是这种方法不尊重优先级和关联性。
如果有人有关于如何从这里开始的建议,或者有关该主题的论文的链接,我将非常欢迎,因为我已经没有毛可拉了 :)
【问题讨论】: