Trying out participle
| package main | |
| import ( | |
| "os" | |
| "github.com/alecthomas/participle" | |
| "github.com/alecthomas/participle/lexer" | |
| "github.com/alecthomas/repr" | |
| "github.com/davecgh/go-spew/spew" | |
| ) | |
| var iniLexer = lexer.Must(lexer.Regexp( | |
| `(?m)` + | |
| `(\s+)` + | |
| `|(^[#;].*$)` + | |
| `|(?P<Ident>[a-zA-Z][a-zA-Z_\d]*)` + | |
| `|(?P<String>"(?:\\.|[^"])*")` + | |
| `|(?P<Lparen>[\(])` + | |
| `|(?P<Rparen>[\)])` + | |
| `|(?P<Comma>[,])`, | |
| )) | |
| type Expression struct { | |
| Function *string `@Ident` | |
| Lparen *string `@Lparen` | |
| Args *Args `{ @@ }` | |
| Rparen *string `@Rparen` | |
| } | |
| type Args struct { | |
| Arg *string `@Ident | @String` | |
| Comma *string `{ @Comma }` | |
| More []*Args `{ @@ }` | |
| } | |
| func main() { | |
| parser, err := participle.Build(&Expression{}, participle.Lexer(iniLexer), participle.Unquote(iniLexer, "String")) | |
| if err != nil { | |
| panic(err) | |
| } | |
| myAST := &Expression{} | |
| err = parser.Parse(os.Stdin, myAST) | |
| if err != nil { | |
| panic(err) | |
| } | |
| repr.Println(myAST, repr.Indent(" "), repr.OmitEmpty(true)) | |
| spew.Dump(myAST) | |
| } |
| ➜ $?=0 ➤ echo 'contains()' | go run main_backup_works.go | |
| &main.Expression{ | |
| Function: &"contains", | |
| Lparen: &"(", | |
| Rparen: &")", | |
| } | |
| (*main.Expression)(0xc42008aa00)({ | |
| Function: (*string)(0xc42007e420)((len=8) "contains"), | |
| Lparen: (*string)(0xc42007e450)((len=1) "("), | |
| Args: (*main.Args)(<nil>), | |
| Rparen: (*string)(0xc42007e480)((len=1) ")") | |
| }) | |
| >>> 0s elasped... | |
| ➜ $?=0 ➤ echo 'contains("a", "b")' | go run main_backup_works.go | |
| &main.Expression{ | |
| Function: &"contains", | |
| Lparen: &"(", | |
| Args: &main.Args{ | |
| Arg: &"a", | |
| Comma: &",", | |
| More: []*main.Args{ | |
| &main.Args{ | |
| Arg: &"b", | |
| }, | |
| }, | |
| }, | |
| Rparen: &")", | |
| } | |
| (*main.Expression)(0xc42000aa40)({ | |
| Function: (*string)(0xc42000e5a0)((len=8) "contains"), | |
| Lparen: (*string)(0xc42000e5d0)((len=1) "("), | |
| Args: (*main.Args)(0xc420084c30)({ | |
| Arg: (*string)(0xc42000e600)((len=1) "a"), | |
| Comma: (*string)(0xc42000e630)((len=1) ","), | |
| More: ([]*main.Args) (len=1 cap=1) { | |
| (*main.Args)(0xc420084b70)({ | |
| Arg: (*string)(0xc42000e660)((len=1) "b"), | |
| Comma: (*string)(<nil>), | |
| More: ([]*main.Args) <nil> | |
| }) | |
| } | |
| }), | |
| Rparen: (*string)(0xc42000e690)((len=1) ")") | |
| }) | |
| >>> 1s elasped... | |
| ➜ $?=0 ➤ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment