tcl/tcl.go

92 lines
2.1 KiB
Go
Raw Normal View History

2019-06-16 20:45:30 +02:00
package tcl
import (
"log"
"os"
"github.com/davecgh/go-spew/spew"
. "github.com/oec/goparsify"
)
// Tcl parser, using combinators
// Based on the grammer in:
// https://wiki.tcl-lang.org/page/BNF+for+Tcl
var (
2019-06-17 06:27:17 +02:00
word Parser
words Parser
command Parser
script Parser
2019-06-16 20:45:30 +02:00
)
var (
2019-06-17 06:27:17 +02:00
comment = NewParser("comment", Merge(Seq("#", NotChars("\r\n")))).Map(drop)
wordExp = NewParser("{*}word", Seq("{*}", &word)).Map(resultchild(1))
wordSub = NewParser("[*]word", Seq("[*]", &word)).Map(resultchild(1))
wordBrc = NewParser("{command}", Seq("{", Many(&command), "}")).Map(func(r *Result) { collectchildren(&r.Child[1]); r.Result = r.Child[1].Result })
wordQtd = NewParser(`"word"`, StringLit(`"`)).Map(token)
wordSmp = NewParser("simple", NotChars("{}[]* ;\t\r\n")).Map(token)
2019-06-16 20:45:30 +02:00
)
func init() {
2019-06-17 06:27:17 +02:00
word = NewParser("word", Any(&wordSmp, &wordQtd, &wordBrc, &wordSub, &wordExp))
words = NewParser("words", Many(&word)).Map(collectchildren)
command = NewParser("command", Seq(&words, Maybe(";"))).Map(resultchild(0))
script = NewParser("script", Many(Any(&comment, &command))).Map(collectchildren)
2019-06-16 20:45:30 +02:00
}
func Parse(input string) (data interface{}, e error) {
data, e = Run(&script, input, ASCIIWhitespace)
return
}
func ParseDebug(input string) (data interface{}, e error) {
EnableLogging(os.Stdout)
data, e = Run(&script, input, ASCIIWhitespace)
return
}
func found(typ string) func(*Result) {
return func(r *Result) {
2019-06-17 06:27:17 +02:00
log.Printf("found a %s: %q (r.R: %v)\n", typ, r.Token, r.Result)
r.Result = r.Token
}
}
func drop(r *Result) {
r.Token = ""
r.Result = nil
}
func token(r *Result) {
r.Result = r.Token
// log.Println("token:", r.Token)
}
2019-06-16 20:45:30 +02:00
2019-06-17 06:27:17 +02:00
func collectchildren(r *Result) {
data := []string{}
for _, ch := range r.Child {
switch v := ch.Result.(type) {
case string:
data = append(data, v)
case []string:
data = append(data, v...)
default:
// log.Println("oops:", r)
}
2019-06-16 20:45:30 +02:00
}
2019-06-17 06:27:17 +02:00
// log.Println("data: ", data)
r.Result = data
2019-06-16 20:45:30 +02:00
}
2019-06-17 06:27:17 +02:00
func resultchild(c int) func(*Result) {
return func(r *Result) {
r.Result = r.Child[c].Result
// log.Printf("child[%d]: %v\n", c, r.Result)
}
}
2019-06-16 20:45:30 +02:00
func dump(r *Result) {
spew.Dump(r)
}