使用此命令:
go tool yacc -p Verb -o verb.go boilerplate.y
Run Code Online (Sandbox Code Playgroud)
试图构建这个yacc文件:
// boilerplate.y
%{
package main
import (
"bufio"
"fmt"
"os"
"unicode"
)
%}
%%
.|\n ECHO;
%%
func main() {
fi := bufio.NewReader(os.NewFile(0, "stdin"))
s, err := fi.ReadString('\n')
if err != nil {
fmt.Println('error', err)
}
VerbParse(&VerbLex{s: s})
}
Run Code Online (Sandbox Code Playgroud)
错误: bad syntax on first rule: boilerplate.y:16
成功地让这个例子起作用:
https://github.com/golang-samples/yacc/blob/master/simple/calc.y
试图建立自己的,并通过lex&yacc书.资源似乎仅限于不存在.
您rule
的规格不正确.
规范文件具有以下声明:
declarations
%%
rules
%%
programs
Run Code Online (Sandbox Code Playgroud)
其中a rule
定义为:
A : BODY ;
Run Code Online (Sandbox Code Playgroud)
其中A是非终端符号,而BODY由令牌(终端符号),非终端和文字组成.在:
和;
需要规则声明的语法成分.
因此规则:
.|\n ECHO;
Run Code Online (Sandbox Code Playgroud)
在语法上是不正确的.
由于您只是尝试回显输入,因此基于的非常简单的实现calc.y
将遵循(文件echo.y):
规则
%%
in : /* empty */
| in input '\n'
{ fmt.Printf("Read character: %s\n", $2) }
;
input : CHARACTER
| input CHARACTER
{ $$ = $1 + $2 }
;
Run Code Online (Sandbox Code Playgroud)
程序
%%
type InputLex struct {
// contains one complete input string (with the trailing \n)
s string
// used to keep track of parser position along the above imput string
pos int
}
func (l *InputLex) Lex(lval *InputSymType) int {
var c rune = ' '
// skip through all the spaces, both at the ends and in between
for c == ' ' {
if l.pos == len(l.s) {
return 0
}
c = rune(l.s[l.pos])
l.pos += 1
}
// only look for input characters that are either digits or lower case
// to do more specific parsing, you'll define more tokens and have a
// more complex parsing logic here, choosing which token to return
// based on parsed input
if unicode.IsDigit(c) || unicode.IsLower(c) {
lval.val = string(c)
return CHARACTER
}
// do not return any token in case of unrecognized grammer
// this results in syntax error
return int(c)
}
func (l *InputLex) Error(s string) {
fmt.Printf("syntax error: %s\n", s)
}
func main() {
// same as in calc.y
}
func readline(fi *bufio.Reader) (string, bool) {
// same as in calc.y
}
Run Code Online (Sandbox Code Playgroud)
要编译并运行此程序,请在命令提示符处执行以下操作:
go tool yacc -o echo.go -p Input echo.y
go run echo.go
Run Code Online (Sandbox Code Playgroud)
如您所见,您必须在Lex
方法中定义自己的解析规则.该结构InputLex
旨在在解析输入时保存值.InputSymType
是自动生成的,由规范部分%union
声明的declaration
.
据我所知,没有办法直接使用JISON或正则表达式使用go的yacc
工具进行匹配.您可能需要查看其他一些库.
更多细节可以在这里找到:http://dinosaur.compilertools.net/yacc/
完整的工作代码:https://play.golang.org/p/u1QxwRKLCl
归档时间: |
|
查看次数: |
1706 次 |
最近记录: |