分配语法与λ微积分应用语法 问题1 问题2 可能的解决方案

问题描述

我正在使用ANTLR4及其C ++目标实现扩展的λ演算解释器。这是语言语法:

grammar lambda;

program: expression|;

expression:
    (Int | Bool)                                # literal
    | Identifier                                # variable
    | expression expression                     # application
    | Lambda Identifier '.' expression          # abstraction
    | Identifier '=' expression                 # assign
    | condition                                 # conditional
    | Operator expression expression            # binaryExpression
    | 'print' expression                        # printInstruction
    | '(' expression ')'                        # brackets;

body: expression;
condition: 'if' expression 'then' body 'else' body
    | '(' expression '->' body '|' body;

Lambda: '\\' | 'λ';
Bool : 'tru' | 'fls' | 'true' | 'false';
Int: [0-9]+;
Identifier: ('a' ..'z') ('a' ..'z' | '0' ..'9')*;
Operator:
    '+'
    | '-'
    | '*'
    | '/'
    | '<'
    | '>'
    | '<='
    | '>='
    | '==';

WS: [ \n\t\r]+ -> skip;

我正在使用访问者模型构建AST,该模型将单独进行评估。我在ANTLR解析输入的方式时遇到了一个问题,我甚至都不知道该怎么称呼。

问题1

// incorrect_association.lambda

y = 1
x = 1

Assignment ( y = ( Application ( Literal ( 1 ) ) ( Assignment ( x = ( Literal ( 1 ) ) ) ) ) )

AST应该是

Assignment ( y = ( Literal ( 1 ) )
Assignment ( x = ( Literal ( 1 ) )

Grouping (
    Assignment ( y = ( Literal ( 1 ) ),Assignment ( x = ( Literal ( 1 ) )
)

问题2

我想这可能与第一个问题有关:跨多行的表达式被读为Application表达式。

// incorrect_application.lambda

x = 1
print x

Assignment ( x = ( Application ( Literal ( 1 ) ) ( PrintInstruction ( Identifier ( "x" ) ) ) ) )

AST应该是

Assignment ( x = ( Literal ( 1 ) )
PrintInstruction ( Identifier ( "x" ) )

Grouping (
    Assignment ( x = ( Literal ( 1 ) ),PrintInstruction ( Identifier ( "x" ) )
)

我试图拥有类似命令式的常量分配,并具有类似函数的执行方式。最终,该程序应该是任何main = ...(例如Haskell)。是否有可能阻止Application规则匹配不同行上的两个表达式,但继续允许任何其他空格和括号?

可能的解决方案

我正在考虑编写一个预处理器,该预处理器只会在每行结束处抛出分号。无论如何,我可能仍需要这样做,因为我打算添加

imports: 'import' Identifier | '(' imports ')';

作为语法规则,还没有找到使用ANTLR处理导入的好方法。如果我要走这条路线,我该如何在语法中加入;行尾?

PS:我是ANTLR的新手,所以任何指导都将非常有帮助。

解决方法

如果您希望换行很重要,请让它们通过词法扫描器。

WS: [ \t\r]+ -> skip;
NL: [\n];

然后,您可以将程序定义为以换行符结尾的一系列表达式:

program: ( expression NL )*;

如果您希望分号也能正常工作,只需更改NL的定义:

NL: [\n;];

您还希望更改body以接受多个表达式,尽管我尚不清楚您要使用哪种标点符号。

body: expression (NL expression)*;

将为您工作,但可能会产生意外的结果。

您的应用程序语法非常含糊。我不知道Antlr将如何处理它,但我无法解释。如果有

+ a b c

那必须是以下之一:

(+ a b) (c)
(+ a (b c))
(+ (a b) c)

但是我看不出应该优先选择这三个中的哪个。我认为您需要提出一种具有更精确优先级的语法。

(Lisp和Scheme使用括号的原因是:-))

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...