-
Notifications
You must be signed in to change notification settings - Fork 1
/
location_path.go
75 lines (62 loc) · 1.41 KB
/
location_path.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
71
72
73
74
75
package schema
import (
"github.com/alecthomas/participle/v2"
"strings"
)
var (
pathParser = participle.MustBuild[PathAst](
participle.Unquote("String", "Char", "RawString"),
)
)
func MustParseLocation(input string) []Location {
result, err := ParseLocation(input)
if err != nil {
panic(err)
}
return result
}
func ParseLocation(input string) ([]Location, error) {
// Parse the input and build a Predicate value
ast, err := pathParser.ParseString("", strings.TrimSpace(input))
if err != nil {
return nil, err
}
// Convert the AST to a Predicate value
return ast.ToLocation()
}
type PathAst struct {
Parts []Part `@@ ( "." @@ )*`
}
func (ast PathAst) ToLocation() ([]Location, error) {
var parts []Location
for _, part := range ast.Parts {
parts = append(parts, part.ToLocation()...)
}
return parts, nil
}
type Part struct {
Location string `@Ident`
Acc []Acc `("[" @@ "]")*`
}
type Acc struct {
Name *string `@(String|Char|RawString)`
Index *int `| @Int`
Any bool `| @("*") `
}
func (p Part) ToLocation() []Location {
var result []Location
result = append(result, &LocationField{Name: p.Location})
for _, a := range p.Acc {
result = append(result, a.ToAccessor())
}
return result
}
func (a Acc) ToAccessor() Location {
if a.Name != nil {
return &LocationField{Name: *a.Name}
}
if a.Index != nil {
return &LocationIndex{Index: *a.Index}
}
return &LocationAnything{}
}