[英]Building AST in OCaml
I'm using OCaml to build a recursive descent parser for a subset of Scheme. 我正在使用OCaml为Scheme的子集构建递归下降解析器。 Here's the grammar: 这是语法:
S -> a|b|c|(T)
T -> ST | Epsilon
So say I have: 所以说我有:
type expr =
Num of int | String of string | Tuple of expr * expr
Pseudocode 伪代码
These functions have to return expr type to build the AST 这些函数必须返回expr类型来构建AST
parseS lr =
if head matches '(' then
parseL lr
else
match tokens a, b, or c
Using First Set of S which are tokens and '(': 使用第一组S作为标记和'(':
parseL lr =
if head matches '(' or the tokens then
Tuple (parseS lr, parseL lr)
else
match Epsilon
My question is "How do I return for the Epsilon part since I just can't return ()?". 我的问题是“我怎么回到Epsilon部分,因为我无法返回()?”。 An OCaml function requires same return type and even if I leave blank for Epsilon part, OCaml still assumes unit type. OCaml函数需要相同的返回类型,即使我为Epsilon部分留空,OCaml仍然采用单元类型。
As far as I can see, your AST doesn't match your grammar. 据我所知,你的AST与你的语法不符。
You can solve the problem by having a specifically empty node in your AST type to represent the Epsilon in your grammar. 您可以通过在AST类型中使用特定空节点来表示语法中的Epsilon来解决问题。
Or, you can change your grammar to factor out the Epsilon. 或者,您可以更改语法以分解Epsilon。
Here's an equivalent grammar with no Epsilon: 这是一个没有Epsilon的等效语法:
S -> a|b|c|()|(T)
T -> S | S T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.