-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
116 lines (106 loc) · 2.33 KB
/
utils.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package main
import (
"crypto/rand"
"fmt"
)
func randString(n int, charset string) (string, error) {
s, r := make([]rune, n), []rune(charset)
for i := range s {
p, err := rand.Prime(rand.Reader, len(r))
if err != nil {
return "", fmt.Errorf("random string n %d: %w", n, err)
}
x, y := p.Uint64(), uint64(len(r))
// fmt.Printf("x: %d y: %d\tx %% y = %d\trandom[%d] = %q\n", x, y, x%y, x%y, string(r[x%y]))
s[i] = r[x%y]
}
return string(s), nil
}
func randChar(charset string) (rune, error) {
str, err := randString(1, charset)
if err != nil {
return 0, err
}
return rune(str[0]), nil
}
func walk(n *node, visitor func(n *node)) {
visitor(n)
for _, child := range n.children {
walk(child, visitor)
}
}
func transformSeeTheRules(n *node) {
toRemove := []*node{}
for _, child := range n.children {
if child.kind == seeTheRulesKind {
toRemove = append(toRemove, child)
} else {
transformSeeTheRules(child)
}
}
for _, child := range toRemove {
removeChild(n, child)
}
}
func transformRepeat(n *node) {
var prev *node
toRemove := []*node{}
for _, child := range n.children {
if child.kind == repeatKind {
child.children = append(child.children, prev)
prev.parent = child
toRemove = append(toRemove, prev)
} else {
transformRepeat(child)
}
prev = child
}
for _, child := range toRemove {
removeChild(n, child)
}
}
func transformAlt(n *node) {
for _, child := range n.children {
transformAlt(child)
}
if len(n.children) > 1 && n.children[0].kind == altKind {
alt := &node{kind: altKind, parent: n}
for _, child := range n.children {
if child.kind == altKind {
if len(child.children) > 1 {
alt.children = append(alt.children, child)
child.kind = groupKind
} else {
child.children[0].parent = alt
alt.children = append(alt.children, child.children[0])
}
} else {
panic("alt mixed with other nodes")
}
}
n.children = []*node{alt}
}
}
func assignId(root *node) {
var nextId int
walk(root, func(n *node) {
n.id = nextId
nextId++
})
}
func nameRhs(root *node) {
walk(root, func(n *node) {
if n.kind == bnfDefKind {
n.children[0].name = n.name
}
})
}
func removeChild(n, childToRemove *node) {
c := []*node{}
for _, child := range n.children {
if child.kind != childToRemove.kind {
c = append(c, child)
}
}
n.children = c
}