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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
|
package grammar
import (
"fmt"
"io"
"strings"
)
type ActionType string
const (
ActionTypeShift = ActionType("shift")
ActionTypeReduce = ActionType("reduce")
ActionTypeError = ActionType("error")
)
type actionEntry int
const actionEntryEmpty = actionEntry(0)
func newShiftActionEntry(state stateNum) actionEntry {
return actionEntry(state * -1)
}
func newReduceActionEntry(prod productionNum) actionEntry {
return actionEntry(prod)
}
func (e actionEntry) isEmpty() bool {
return e == actionEntryEmpty
}
func (e actionEntry) describe() (ActionType, stateNum, productionNum) {
if e == actionEntryEmpty {
return ActionTypeError, stateNumInitial, productionNumNil
}
if e < 0 {
return ActionTypeShift, stateNum(e * -1), productionNumNil
}
return ActionTypeReduce, stateNumInitial, productionNum(e)
}
type GoToType string
const (
GoToTypeRegistered = GoToType("registered")
GoToTypeError = GoToType("error")
)
type goToEntry uint
const goToEntryEmpty = goToEntry(0)
func newGoToEntry(state stateNum) goToEntry {
return goToEntry(state)
}
func (e goToEntry) isEmpty() bool {
return e == goToEntryEmpty
}
func (e goToEntry) describe() (GoToType, stateNum) {
if e == goToEntryEmpty {
return GoToTypeError, stateNumInitial
}
return GoToTypeRegistered, stateNum(e)
}
type conflict interface {
conflict()
}
type shiftReduceConflict struct {
state stateNum
sym symbol
nextState stateNum
prodNum productionNum
}
func (c *shiftReduceConflict) conflict() {
}
type reduceReduceConflict struct {
state stateNum
sym symbol
prodNum1 productionNum
prodNum2 productionNum
}
func (c *reduceReduceConflict) conflict() {
}
var (
_ conflict = &shiftReduceConflict{}
_ conflict = &reduceReduceConflict{}
)
type ParsingTable struct {
actionTable []actionEntry
goToTable []goToEntry
stateCount int
terminalCount int
nonTerminalCount int
expectedTerminals [][]int
InitialState stateNum
}
func (t *ParsingTable) getAction(state stateNum, sym symbolNum) (ActionType, stateNum, productionNum) {
pos := state.Int()*t.terminalCount + sym.Int()
return t.actionTable[pos].describe()
}
func (t *ParsingTable) getGoTo(state stateNum, sym symbolNum) (GoToType, stateNum) {
pos := state.Int()*t.nonTerminalCount + sym.Int()
return t.goToTable[pos].describe()
}
func (t *ParsingTable) writeShiftAction(state stateNum, sym symbol, nextState stateNum) conflict {
pos := state.Int()*t.terminalCount + sym.num().Int()
act := t.actionTable[pos]
if !act.isEmpty() {
ty, _, p := act.describe()
if ty == ActionTypeReduce {
return &shiftReduceConflict{
state: state,
sym: sym,
nextState: nextState,
prodNum: p,
}
}
}
t.actionTable[pos] = newShiftActionEntry(nextState)
return nil
}
func (t *ParsingTable) writeReduceAction(state stateNum, sym symbol, prod productionNum) conflict {
pos := state.Int()*t.terminalCount + sym.num().Int()
act := t.actionTable[pos]
if !act.isEmpty() {
ty, s, p := act.describe()
if ty == ActionTypeReduce && p != prod {
return &reduceReduceConflict{
state: state,
sym: sym,
prodNum1: p,
prodNum2: prod,
}
}
return &shiftReduceConflict{
state: state,
sym: sym,
nextState: s,
prodNum: prod,
}
}
t.actionTable[pos] = newReduceActionEntry(prod)
return nil
}
func (t *ParsingTable) writeGoTo(state stateNum, sym symbol, nextState stateNum) {
pos := state.Int()*t.nonTerminalCount + sym.num().Int()
t.goToTable[pos] = newGoToEntry(nextState)
}
type lrTableBuilder struct {
automaton *lr0Automaton
prods *productionSet
termCount int
nonTermCount int
symTab *symbolTable
sym2AnonPat map[symbol]string
conflicts []conflict
}
func (b *lrTableBuilder) build() (*ParsingTable, error) {
var ptab *ParsingTable
{
initialState := b.automaton.states[b.automaton.initialState]
ptab = &ParsingTable{
actionTable: make([]actionEntry, len(b.automaton.states)*b.termCount),
goToTable: make([]goToEntry, len(b.automaton.states)*b.nonTermCount),
stateCount: len(b.automaton.states),
terminalCount: b.termCount,
nonTerminalCount: b.nonTermCount,
expectedTerminals: make([][]int, len(b.automaton.states)),
InitialState: initialState.num,
}
}
var conflicts []conflict
for _, state := range b.automaton.states {
var eTerms []int
for sym, kID := range state.next {
nextState := b.automaton.states[kID]
if sym.isTerminal() {
eTerms = append(eTerms, sym.num().Int())
c := ptab.writeShiftAction(state.num, sym, nextState.num)
if c != nil {
conflicts = append(conflicts, c)
continue
}
} else {
ptab.writeGoTo(state.num, sym, nextState.num)
}
}
for prodID := range state.reducible {
reducibleProd, ok := b.prods.findByID(prodID)
if !ok {
return nil, fmt.Errorf("reducible production not found: %v", prodID)
}
var reducibleItem *lrItem
for _, item := range state.items {
if item.prod != reducibleProd.id {
continue
}
reducibleItem = item
break
}
if reducibleItem == nil {
for _, item := range state.emptyProdItems {
if item.prod != reducibleProd.id {
continue
}
reducibleItem = item
break
}
if reducibleItem == nil {
return nil, fmt.Errorf("reducible item not found; state: %v, production: %v", state.num, reducibleProd.num)
}
}
for a := range reducibleItem.lookAhead.symbols {
eTerms = append(eTerms, a.num().Int())
c := ptab.writeReduceAction(state.num, a, reducibleProd.num)
if c != nil {
conflicts = append(conflicts, c)
continue
}
}
}
ptab.expectedTerminals[state.num] = eTerms
}
b.conflicts = conflicts
if len(conflicts) > 0 {
return nil, fmt.Errorf("%v conflicts", len(conflicts))
}
return ptab, nil
}
func (b *lrTableBuilder) write(w io.Writer) {
conflicts := map[stateNum][]conflict{}
for _, con := range b.conflicts {
switch c := con.(type) {
case *shiftReduceConflict:
conflicts[c.state] = append(conflicts[c.state], c)
case *reduceReduceConflict:
conflicts[c.state] = append(conflicts[c.state], c)
}
}
fmt.Fprintf(w, "# Conflicts\n\n")
if len(b.conflicts) > 0 {
fmt.Fprintf(w, "%v conflics:\n\n", len(b.conflicts))
for _, conflict := range b.conflicts {
switch c := conflict.(type) {
case *shiftReduceConflict:
fmt.Fprintf(w, "%v: shift/reduce conflict (shift %v, reduce %v) on %v\n", c.state, c.nextState, c.prodNum, b.symbolToText(c.sym))
case *reduceReduceConflict:
fmt.Fprintf(w, "%v: reduce/reduce conflict (reduce %v and %v) on %v\n", c.state, c.prodNum1, c.prodNum2, b.symbolToText(c.sym))
}
}
fmt.Fprintf(w, "\n")
} else {
fmt.Fprintf(w, "no conflicts\n\n")
}
fmt.Fprintf(w, "# Terminals\n\n")
termSyms := b.symTab.terminalSymbols()
fmt.Fprintf(w, "%v symbols:\n\n", len(termSyms))
for _, sym := range termSyms {
text, ok := b.symTab.toText(sym)
if !ok {
text = fmt.Sprintf("<symbol not found: %v>", sym)
}
if strings.HasPrefix(text, "_") {
fmt.Fprintf(w, "%4v %v: \"%v\"\n", sym.num(), text, b.sym2AnonPat[sym])
} else {
fmt.Fprintf(w, "%4v %v\n", sym.num(), text)
}
}
fmt.Fprintf(w, "\n")
fmt.Fprintf(w, "# Productions\n\n")
fmt.Fprintf(w, "%v productions:\n\n", len(b.prods.getAllProductions()))
for _, prod := range b.prods.getAllProductions() {
fmt.Fprintf(w, "%4v %v\n", prod.num, b.productionToString(prod, -1))
}
fmt.Fprintf(w, "\n# States\n\n")
fmt.Fprintf(w, "%v states:\n\n", len(b.automaton.states))
for _, state := range b.automaton.states {
fmt.Fprintf(w, "state %v\n", state.num)
for _, item := range state.items {
prod, ok := b.prods.findByID(item.prod)
if !ok {
fmt.Fprintf(w, "<production not found>\n")
continue
}
fmt.Fprintf(w, " %v\n", b.productionToString(prod, item.dot))
}
fmt.Fprintf(w, "\n")
var shiftRecs []string
var reduceRecs []string
var gotoRecs []string
var accRec string
{
for sym, kID := range state.next {
nextState := b.automaton.states[kID]
if sym.isTerminal() {
shiftRecs = append(shiftRecs, fmt.Sprintf("shift %4v on %v", nextState.num, b.symbolToText(sym)))
} else {
gotoRecs = append(gotoRecs, fmt.Sprintf("goto %4v on %v", nextState.num, b.symbolToText(sym)))
}
}
for prodID := range state.reducible {
prod, ok := b.prods.findByID(prodID)
if !ok {
reduceRecs = append(reduceRecs, "<production not found>")
continue
}
if prod.lhs.isStart() {
accRec = "accept on <EOF>"
continue
}
var reducibleItem *lrItem
for _, item := range state.items {
if item.prod != prodID {
continue
}
reducibleItem = item
break
}
if reducibleItem == nil {
for _, item := range state.emptyProdItems {
if item.prod != prodID {
continue
}
reducibleItem = item
break
}
if reducibleItem == nil {
reduceRecs = append(reduceRecs, "<item not found>")
continue
}
}
for a := range reducibleItem.lookAhead.symbols {
reduceRecs = append(reduceRecs, fmt.Sprintf("reduce %4v on %v", prod.num, b.symbolToText(a)))
}
}
}
if len(shiftRecs) > 0 || len(reduceRecs) > 0 {
for _, rec := range shiftRecs {
fmt.Fprintf(w, " %v\n", rec)
}
for _, rec := range reduceRecs {
fmt.Fprintf(w, " %v\n", rec)
}
fmt.Fprintf(w, "\n")
}
if len(gotoRecs) > 0 {
for _, rec := range gotoRecs {
fmt.Fprintf(w, " %v\n", rec)
}
fmt.Fprintf(w, "\n")
}
if accRec != "" {
fmt.Fprintf(w, " %v\n\n", accRec)
}
cons, ok := conflicts[state.num]
if ok {
for _, con := range cons {
switch c := con.(type) {
case *shiftReduceConflict:
fmt.Fprintf(w, " shift/reduce conflict (shift %v, reduce %v) on %v\n", c.nextState, c.prodNum, b.symbolToText(c.sym))
case *reduceReduceConflict:
fmt.Fprintf(w, " reduce/reduce conflict (reduce %v and %v) on %v\n", c.prodNum1, c.prodNum2, b.symbolToText(c.sym))
}
}
fmt.Fprintf(w, "\n")
}
}
}
func (b *lrTableBuilder) productionToString(prod *production, dot int) string {
var w strings.Builder
fmt.Fprintf(&w, "%v →", b.symbolToText(prod.lhs))
for n, rhs := range prod.rhs {
if n == dot {
fmt.Fprintf(&w, " ・")
}
fmt.Fprintf(&w, " %v", b.symbolToText(rhs))
}
if dot == len(prod.rhs) {
fmt.Fprintf(&w, " ・")
}
return w.String()
}
func (b *lrTableBuilder) symbolToText(sym symbol) string {
if sym.isNil() {
return "<NULL>"
}
if sym.isEOF() {
return "<EOF>"
}
text, ok := b.symTab.toText(sym)
if !ok {
return fmt.Sprintf("<symbol not found: %v>", sym)
}
if strings.HasPrefix(text, "_") {
pat, ok := b.sym2AnonPat[sym]
if !ok {
return fmt.Sprintf("<pattern not found: %v>", text)
}
return fmt.Sprintf(`"%v"`, pat)
}
return text
}
|