-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar.go
70 lines (59 loc) · 1.73 KB
/
grammar.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package parse
import (
"github.com/alecthomas/participle"
"github.com/alecthomas/participle/lexer"
"github.com/alecthomas/participle/lexer/ebnf"
)
type Generator struct {
Range string `"range" @JSONPath`
SubTemplate Value `"[" @@ "]"`
}
type AnnotatedField struct {
Annotation string `("@" @Ident)?`
Key string `@String ":"`
Value Value `@@`
}
type Object struct {
Fields []AnnotatedField `"{" (@@ ("," @@)* ","?)? "}"`
}
type Function struct {
Name string `@Ident`
Args []Value `"(" (@@ ("," @@)*)? ")"`
}
type Value struct {
// These are standard JSON fields.
String *string ` @String`
Number *float64 `| @Number`
Object *Object `| @@`
Array []Value `| "[" (@@ ("," @@)* ","?)? "]"`
Bool *bool `| (@"true" | "false")`
Null bool `| @"null"`
// These are template elements generating JSON fields.
Generator *Generator `| @@`
Extractor *string `| @JSONPath`
Function *Function `| @@`
}
type Template struct {
Root Value `@@`
}
var lex = lexer.Must(ebnf.New(`
Comment = "#" { "\u0000"…"\uffff"-"\n" } .
Ident = (alpha | "_") { "_" | alpha | digit } .
String = "\"" { "\u0000"…"\uffff"-"\""-"\\" | "\\" any } "\"" .
Number = Int | Float .
Int = [ "-" ] digit { digit } .
Float = [ "-" ] [ digit ] "." digit { digit } .
JSONPath = "$" { "." { "." } JSONPathExpr } .
JSONPathExpr = "*" | (Ident { "[" { "\u0000"…"\uffff"-"]" } "]" }) .
Punct = "!"…"/" | ":"…"@" | "["…` + "\"`\"" + ` | "{"…"~" .
Whitespace = " " | "\t" | "\n" | "\r" .
alpha = "a"…"z" | "A"…"Z" .
digit = "0"…"9" .
any = "\u0000"…"\uffff" .
`))
var Parser = participle.MustBuild(
&Template{},
participle.Lexer(lex),
participle.Unquote("String"),
participle.Elide("Whitespace", "Comment"),
)