-
Notifications
You must be signed in to change notification settings - Fork 2
/
compute.go
131 lines (127 loc) · 2.76 KB
/
compute.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
package main
import (
"fmt"
"os"
)
func computeTable() {
table = make([][]int, len(nonterms))
for i := 0; i < len(nonterms); i++ {
table[i] = make([]int, len(terms))
for j := 0; j < len(terms); j++ {
table[i][j] = -1
}
}
for nonterm, r := range nonterms {
for _, c := range terms {
for prodidx, p := range prods {
prod := p.(*production)
if prod.name != nonterm {
continue
}
switch {
case firsts[prodidx].IndexOf(c) > -1:
if table[r][c] != -1 {
fmt.Println("FIRST/FIRST CONFLICT")
fmt.Println("Error between", prods[table[r][c]], "and", prod)
os.Exit(-4)
}
table[r][c] = prodidx
case firsts[prodidx].HasE() && follows[r].IndexOf(c) > -1:
if table[r][c] != -1 {
fmt.Println("FIRST/FOLLOW CONFLICT")
fmt.Println("Error between", prods[table[r][c]], "and", prod)
os.Exit(-4)
}
table[r][c] = prodidx
}
}
}
}
}
func computeFollows() {
if len(nonterms) == 0 {
return
}
for i := 0; i < len(nonterms); i++ {
follows[i] = &set{}
}
follows[0].Push(-1)
for true {
changed := false
for _, p := range prods {
prod := p.(*production)
for sidx, s := range prod.seq {
word := s.(tok)
if word.ttype != nonterm {
continue
}
wordidx := nonterms[word.text]
after := prod.seq[sidx+1:]
if len(after) == 0 {
fs := followsFor(prod.name)
changed = follows[wordidx].Union(fs.NoE()) || changed
goto NextItem
}
for seqidx, t := range after {
next := t.(tok)
last := seqidx == len(after)-1
switch next.ttype {
case term:
changed = follows[wordidx].Push(terms[next.text]) || changed
goto NextItem
case nonterm:
fs := firstsFor(next.text)
changed = follows[wordidx].Union(fs.NoE()) || changed
if !fs.HasE() {
goto NextItem
}
if last {
fs = followsFor(prod.name)
changed = follows[wordidx].Union(fs.NoE()) || changed
}
}
}
NextItem:
}
}
if !changed {
break
}
}
}
func computeFirsts() {
for i := 0; i < len(prods); i++ {
firsts[i] = &set{}
}
for true {
changed := false
for prodidx, p := range prods {
prod := p.(*production)
if len(prod.seq) == 0 {
changed = firsts[prodidx].Push(terms[""]) || changed
goto NextProd
}
for wordidx, w := range prod.seq {
word := w.(tok)
switch word.ttype {
case term:
changed = firsts[prodidx].Push(terms[word.text]) || changed
goto NextProd
case nonterm:
fs := firstsFor(word.text)
changed = firsts[prodidx].Union(fs.NoE()) || changed
if !fs.HasE() {
goto NextProd
}
if wordidx == len(prod.seq)-1 {
changed = firsts[prodidx].Push(0) || changed
}
}
}
NextProd:
}
if !changed {
break
}
}
}