-
Notifications
You must be signed in to change notification settings - Fork 0
/
dag.go
294 lines (270 loc) · 6.83 KB
/
dag.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package goabnf
import (
"fmt"
"strings"
)
type node struct {
Rulename string
index, lowlink int
onStack bool
Dependencies []string
}
// Depgraph contains for each rule the rules it depends on.
// Notice it does not differentiate between a mandatory dependency
// or an avoidable one.
type Depgraph map[string]*node
// DependencyGraph creates a dependency graph for a whole grammar.
// It includes core rules only if necessary.
func (g *Grammar) DependencyGraph() Depgraph {
graph := Depgraph{}
for _, corerule := range coreRules {
graph[corerule.Name] = &node{
Rulename: corerule.Name,
Dependencies: getDependencies(corerule.Alternation),
}
}
for _, rule := range g.Rulemap {
graph[rule.Name] = &node{
Rulename: rule.Name,
Dependencies: getDependencies(rule.Alternation),
}
}
return graph
}
func getDependencies(alt Alternation) []string {
deps := []string{}
for _, conc := range alt.Concatenations {
for _, rep := range conc.Repetitions {
switch v := rep.Element.(type) {
case ElemGroup:
deps = appendDeps(deps, getDependencies(v.Alternation)...)
case ElemOption:
deps = appendDeps(deps, getDependencies(v.Alternation)...)
case ElemRulename:
deps = appendDeps(deps, v.Name)
}
}
}
return deps
}
func appendDeps(deps []string, ndeps ...string) []string {
for _, ndep := range ndeps {
already := false
for _, dep := range deps {
if ndep == dep {
already = true
break
}
}
if !already {
deps = append(deps, ndep)
}
}
return deps
}
// Mermaid returns a flowchart of the dependency graph.
func (dg Depgraph) Mermaid() string {
out := "flowchart TD\n"
for _, node := range dg {
for _, dep := range node.Dependencies {
out += fmt.Sprintf("\t%s --> %s\n", node.Rulename, dep)
}
out += "\n"
}
return out
}
// IsDag find Strongly Connected Components using Tarjan's algorithm
// and returns whether it contains cycle or not.
// Could be improved by Nuutila's or Pearce's algorithms, or replaced
// by Kosaraju's algorithm.
func (g *Grammar) IsDAG() bool {
scc := &cycle{
index: 0,
stack: []*node{},
dg: g.DependencyGraph(),
}
scc.find()
for _, sccs := range scc.sccs {
if len(sccs) > 1 {
return false
}
}
return true
}
// RuleContainsCycle returns whether the rule contains a cycle or not.
// It travels through the whole rule dependency graph, such that
// it checks if the rule is cyclic AND if one of its dependency is too.
//
// WARNING: it is different than IsLeftTerminating, refer to its doc.
func (g *Grammar) RuleContainsCycle(rulename string) (bool, error) {
// Check the rule exists
rule := GetRule(rulename, g.Rulemap)
if rule == nil {
return false, &ErrRuleNotFound{
Rulename: rulename,
}
}
// Get all SCCs
scc := &cycle{
index: 0,
stack: []*node{},
dg: g.DependencyGraph(),
}
scc.find()
return ruleContainsCycle(scc.sccs, rulename), nil
}
// IsLeftTerminating returns whether the rule is not left terminating.
// It travels through the whole rule dependency graph, such that
// it checks if the rule has a way to left terminate.
//
// Notice that it depends on the ordering your grammar, which could be
// illustrated by the ABNF rule "element" that begins with the alternation
// of a "rulename", which is terminating, and not by "option" or "group"
// which are not.
//
// WARNING: it is different than RuleContainsCycle, refer to its doc.
func (g *Grammar) IsLeftTerminating(rulename string) (bool, error) {
// Check the rule exists
rule := GetRule(rulename, g.Rulemap)
if rule == nil {
return false, &ErrRuleNotFound{
Rulename: rulename,
}
}
// Stack has the same signature as a rulemap in order to use getRuleIn for simplicity
stack := map[string]*Rule{
rulename: rule,
}
return isAltLeftTerminating(g, stack, rule.Alternation), nil
}
func isAltLeftTerminating(g *Grammar, stack map[string]*Rule, alt Alternation) bool {
for _, con := range alt.Concatenations {
for _, rep := range con.Repetitions {
_, subIsOption := rep.Element.(ElemOption)
if rep.Min == 0 || subIsOption {
if !isElemLeftTerminating(g, stack, rep.Element) {
return false
}
continue
}
if !isElemLeftTerminating(g, stack, rep.Element) {
return false
}
break
}
}
return true
}
func isElemLeftTerminating(g *Grammar, stack map[string]*Rule, elem ElemItf) bool {
switch v := elem.(type) {
case ElemRulename:
ruleInStack := (getRuleIn(v.Name, stack) != nil)
if ruleInStack {
return false
}
rule := GetRule(v.Name, g.Rulemap)
return isAltLeftTerminating(g, stack, rule.Alternation)
case ElemOption:
return isAltLeftTerminating(g, stack, v.Alternation)
case ElemGroup:
return isAltLeftTerminating(g, stack, v.Alternation)
case ElemCharVal:
return len(v.Values) != 0
case ElemProseVal:
return len(v.values) != 0
}
return true
}
func ruleContainsCycle(sccs [][]*node, rulename string) bool {
// Find rulename's SCC
scc := ([]*node)(nil)
rulenode := (*node)(nil)
for _, s := range sccs {
if scc != nil {
break
}
for _, ss := range s {
if strings.EqualFold(ss.Rulename, rulename) {
rulenode = ss
scc = s
break
}
}
}
// Check if cyclic
dependsOn := false
for _, dep := range rulenode.Dependencies {
if strings.EqualFold(dep, rulename) {
dependsOn = true
break
}
}
if dependsOn || len(scc) != 1 {
// If it depends on itself or is part of an SCC, then is cylic
return true
}
// Propagate to deps
for _, dep := range rulenode.Dependencies {
if strings.EqualFold(dep, rulename) {
continue
}
if ruleContainsCycle(sccs, dep) {
return true
}
}
return false
}
type cycle struct {
index int
stack []*node
sccs [][]*node
dg Depgraph
}
func (c *cycle) find() {
for _, v := range c.dg {
if v.index == 0 {
c.strongconnect(v)
}
}
}
func (c *cycle) strongconnect(v *node) {
// Set the depth index for v to the smallest unused index
v.index = c.index
v.lowlink = c.index
c.index++
c.stack = append(c.stack, v)
v.onStack = true
// Consider successors of v
for _, dep := range v.Dependencies {
w, ok := c.dg[dep]
if !ok {
// core rules, as we know they won't have a cycle thus
// no SCC, we don't need to recurse.
continue
}
if w.index == 0 {
// Successor w has not yet been visited; recurse on it
c.strongconnect(w)
v.lowlink = min(v.lowlink, w.lowlink)
} else {
if w.onStack {
// Successor w is in stack S and hence in the current SCC
// If w is not on stack, then (v, w) is an edge pointing
// to an SCC already found and must be ignored.
v.lowlink = min(v.lowlink, w.index)
}
}
}
// If v is a root node, pop the stack and generate an SCC
if v.lowlink == v.index {
scc := []*node{}
w := (*node)(nil)
for w == nil || v.Rulename != w.Rulename {
w = c.stack[len(c.stack)-1]
c.stack = c.stack[:len(c.stack)-1]
w.onStack = false
scc = append(scc, w)
}
c.sccs = append(c.sccs, scc)
}
}