【发布时间】:2014-10-21 10:56:55
【问题描述】:
我正在尝试在 Coco/r 中为 C# 中的算术运算实现一种语言,该语言考虑了运算符优先级。我的 ATG 代码如下所示:
/* Coco/R lexer and parser specification for arithmetic expressions. */
/* 2006-09-14 */
/* Build with:
* Coco.exe -namespace Expressions Ex2.ATG
*/
using System.Collections.Generic;
COMPILER Expressions
public int res;
/*--------------------------------------------------------------------------*/
CHARACTERS
letter = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".
digit = "0123456789".
cr = '\r'.
lf = '\n'.
tab = '\t'.
TOKENS
ident = letter {letter | digit}.
number = digit {digit}.
IGNORE cr + lf + tab
PRODUCTIONS
/*------------------------------------------------------------------------*/
Expr<out int n> (. int n1, n2; .)
= Term<out n1> (. n = n1; .)
{
'+' Term<out n2> (. n = n+n2; .)
|
'-' Term<out n2> (. n = n-n2; .)
|
Factor<out int n>
}
.
Factor<out int n>
=
{
"==" Term<out n2> (. if(n1 == n2){ n = 1; } else { n = 2; } .)
|
'<' Term<out n2> (. if(n1 < n2) { n = 1; } else { n = 0; } .)
|
'>' Term<out n2> (. if(n1 > n2) { n = 1; } else { n = 0; } .)
|
"!=" Term<out n2> (. if(n1 != n2){ n = 1; } else { n = 0; } .)
|
"<=" Term<out n2> (. if(n1 <= n2){ n = 1; } else { n = 0; } .)
|
">=" Term<out n2> (. if(n1 >= n2){ n = 1; } else { n = 0; } .)
|
"|" Term<out n2> (. if(n1 != 0 | n2 != 0) { n = 1; } else { n = 0; } .)
|
"&" Term<out n2> (. if(n1 != 0 & n2 != 0){ n = 1; } else { n = 0; } .)
}
.
Term<out int n>
= number (. n = Convert.ToInt32(t.val); .)
{
'*' number (. n = n*Convert.ToInt32(t.val); .)
}
.
Expressions (. int n; .)
= Expr<out n> (. res = n; .)
.
END Expressions.
'+' 和 '-' 以外的运算符优先级较低。此外,“&”运算符的优先级应低于“|”。
问题是当我尝试测试代码时出现以下错误:
Factor deletable
LL1 warning in Expr: contents of [...] or {...} must not be deletable
LL1 warning in Expr: "+" is start of several alternatives
LL1 warning in Expr: "-" is start of several alternatives
LL1 warning in Factor: "==" is start & successor of deletable structure
LL1 warning in Factor: "<" is start & successor of deletable structure
LL1 warning in Factor: ">" is start & successor of deletable structure
LL1 warning in Factor: "!=" is start & successor of deletable structure
LL1 warning in Factor: "<=" is start & successor of deletable structure
LL1 warning in Factor: ">=" is start & successor of deletable structure
LL1 warning in Factor: "|" is start & successor of deletable structure
LL1 warning in Factor: "&" is start & successor of deletable structure
我是 Coco/r 和 EBNF 的新手。我查看了 Coco\r 的手册,但我真的不明白问题出在哪里;我错过了什么?
提前谢谢你!
【问题讨论】: