aboutsummaryrefslogtreecommitdiff
path: root/driver/lac_test.go
blob: 6406f95ac62d0df82722e9ba7f743723a0bc6233 (plain) (blame)
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
package driver

import (
	"strings"
	"testing"

	"github.com/nihei9/vartan/grammar"
	"github.com/nihei9/vartan/spec"
)

func TestParserWithLAC(t *testing.T) {
	specSrc := `
S
    : C C
	;
C
    : c C
	| d
	;

c: 'c';
d: 'd';
`

	src := `ccd`

	actLogWithLAC := []string{
		"shift/c",
		"shift/c",
		"shift/d",
		"miss",
	}

	actLogWithoutLAC := []string{
		"shift/c",
		"shift/c",
		"shift/d",
		"reduce/C",
		"reduce/C",
		"reduce/C",
		"miss",
	}

	ast, err := spec.Parse(strings.NewReader(specSrc))
	if err != nil {
		t.Fatal(err)
	}

	b := grammar.GrammarBuilder{
		AST: ast,
	}
	g, err := b.Build()
	if err != nil {
		t.Fatal(err)
	}

	gram, err := grammar.Compile(g, grammar.SpecifyClass(grammar.ClassLALR))
	if err != nil {
		t.Fatal(err)
	}

	t.Run("LAC is enabled", func(t *testing.T) {
		semAct := &testSemAct{
			gram: gram,
		}

		p, err := NewParser(gram, strings.NewReader(src), SemanticAction(semAct))
		if err != nil {
			t.Fatal(err)
		}

		err = p.Parse()
		if err != nil {
			t.Fatal(err)
		}

		if len(semAct.actLog) != len(actLogWithLAC) {
			t.Fatalf("unexpected action log; want: %+v, got: %+v", actLogWithLAC, semAct.actLog)
		}

		for i, e := range actLogWithLAC {
			if semAct.actLog[i] != e {
				t.Fatalf("unexpected action log; want: %+v, got: %+v", actLogWithLAC, semAct.actLog)
			}
		}
	})

	t.Run("LAC is disabled", func(t *testing.T) {
		semAct := &testSemAct{
			gram: gram,
		}

		p, err := NewParser(gram, strings.NewReader(src), SemanticAction(semAct), DisableLAC())
		if err != nil {
			t.Fatal(err)
		}

		err = p.Parse()
		if err != nil {
			t.Fatal(err)
		}

		if len(semAct.actLog) != len(actLogWithoutLAC) {
			t.Fatalf("unexpected action log; want: %+v, got: %+v", actLogWithoutLAC, semAct.actLog)
		}

		for i, e := range actLogWithoutLAC {
			if semAct.actLog[i] != e {
				t.Fatalf("unexpected action log; want: %+v, got: %+v", actLogWithoutLAC, semAct.actLog)
			}
		}
	})
}