您的规格说明中存在错误的规则
。
一个规格说明文件具有以下声明:
declarations
%%
rules
%%
programs
规则的定义如下:
A : BODY ;
其中A是非终结符号,而BODY由令牌(终结符)、非终结符和字面量组成。 :
和;
是规则声明语法的必需组成部分。
因此,规则为:
.|\n ECHO;
语法有误。
由于您只是试图回显输入内容,基于 calc.y
的一个非常简单的实现如下(文件 echo.y):
规则
%%
in :
| in input '\n'
{ fmt.Printf("Read character: %s\n", $2) }
;
input : CHARACTER
| input CHARACTER
{ $$ = $1 + $2 }
;
程序
%%
type InputLex struct {
s string
pos int
}
func (l *InputLex) Lex(lval *InputSymType) int {
var c rune = ' '
for c == ' ' {
if l.pos == len(l.s) {
return 0
}
c = rune(l.s[l.pos])
l.pos += 1
}
if unicode.IsDigit(c) || unicode.IsLower(c) {
lval.val = string(c)
return CHARACTER
}
return int(c)
}
func (l *InputLex) Error(s string) {
fmt.Printf("syntax error: %s\n", s)
}
func main() {
}
func readline(fi *bufio.Reader) (string, bool) {
}
要编译并运行此程序,请在命令提示符下执行以下操作:
go tool yacc -o echo.go -p Input echo.y
go run echo.go
如您所见,您将需要在 Lex
方法中定义自己的解析规则。结构体 InputLex
用于在解析输入时保存值。 InputSymType
是自动生成的,并由规范的 declaration
部分中声明的 %union
定义。
据我所知,没有直接使用 JISON 或正则表达式来使用 Go 的 yacc
工具进行匹配的方法。您可能需要查看其他库。
更多详细信息请参见此处:http://dinosaur.compilertools.net/yacc/
完整可工作的代码在此处:https://play.golang.org/p/u1QxwRKLCl