aboutsummaryrefslogtreecommitdiff
path: root/spec/spec.go
blob: 829008ab3bfaadf8119060a89cbebb27b1343df0 (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
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
package spec

import (
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

const lexKindPattern = "[A-Za-z_][0-9A-Za-z_]*"

var lexKindRE = regexp.MustCompile(lexKindPattern)

type LexKind string

const LexKindNil = LexKind("")

func (k LexKind) String() string {
	return string(k)
}

func (k LexKind) validate() error {
	if k == "" {
		return fmt.Errorf("kind doesn't allow to be the empty string")
	}
	if !lexKindRE.Match([]byte(k)) {
		return fmt.Errorf("kind must be %v", lexKindPattern)
	}
	return nil
}

type LexPattern string

func (p LexPattern) validate() error {
	if p == "" {
		return fmt.Errorf("pattern doesn't allow to be the empty string")
	}
	return nil
}

const lexModePattern = "[A-Za-z_][0-9A-Za-z_]*"

var lexModeRE = regexp.MustCompile(lexKindPattern)

type LexModeName string

const (
	LexModeNameNil     = LexModeName("")
	LexModeNameDefault = LexModeName("default")
)

func (m LexModeName) String() string {
	return string(m)
}

func (m LexModeName) validate() error {
	if m.isNil() || !lexModeRE.Match([]byte(m)) {
		return fmt.Errorf("mode must be %v", lexModePattern)
	}
	return nil
}

func (m LexModeName) isNil() bool {
	return m == LexModeNameNil
}

type LexModeNum int

const (
	LexModeNumNil     = LexModeNum(0)
	LexModeNumDefault = LexModeNum(1)
)

func (n LexModeNum) String() string {
	return strconv.Itoa(int(n))
}

func (n LexModeNum) Int() int {
	return int(n)
}

func (n LexModeNum) Succ() LexModeNum {
	return n + 1
}

func (n LexModeNum) IsNil() bool {
	return n == LexModeNumNil
}

type LexEntry struct {
	Kind     LexKind       `json:"kind"`
	Pattern  LexPattern    `json:"pattern"`
	Modes    []LexModeName `json:"modes"`
	Push     LexModeName   `json:"push"`
	Pop      bool          `json:"pop"`
	Fragment bool          `json:"fragment"`
}

func (e *LexEntry) validate() error {
	err := e.Kind.validate()
	if err != nil {
		return err
	}
	err = e.Pattern.validate()
	if err != nil {
		return err
	}
	if len(e.Modes) > 0 {
		for _, mode := range e.Modes {
			err = mode.validate()
			if err != nil {
				return err
			}
		}
	}
	return nil
}

type LexSpec struct {
	Entries []*LexEntry `json:"entries"`
}

func (s *LexSpec) Validate() error {
	if len(s.Entries) <= 0 {
		return fmt.Errorf("the lexical specification must have at least one entry")
	}
	{
		var errs []error
		for i, e := range s.Entries {
			err := e.validate()
			if err != nil {
				errs = append(errs, fmt.Errorf("entry #%v: %w", i+1, err))
			}
		}
		if len(errs) > 0 {
			var b strings.Builder
			fmt.Fprintf(&b, "%v", errs[0])
			for _, err := range errs[1:] {
				fmt.Fprintf(&b, "\n%v", err)
			}
			return fmt.Errorf(b.String())
		}
	}
	{
		ks := map[string]struct{}{}
		fks := map[string]struct{}{}
		for _, e := range s.Entries {
			// Allow duplicate names between fragments and non-fragments.
			if e.Fragment {
				if _, exist := fks[e.Kind.String()]; exist {
					return fmt.Errorf("kinds `%v` are duplicates", e.Kind)
				}
				fks[e.Kind.String()] = struct{}{}
			} else {
				if _, exist := ks[e.Kind.String()]; exist {
					return fmt.Errorf("kinds `%v` are duplicates", e.Kind)
				}
				ks[e.Kind.String()] = struct{}{}
			}
		}
	}
	return nil
}

type RowDisplacementTable struct {
	OriginalRowCount int   `json:"original_row_count"`
	OriginalColCount int   `json:"original_col_count"`
	EmptyValue       int   `json:"empty_value"`
	Entries          []int `json:"entries"`
	Bounds           []int `json:"bounds"`
	RowDisplacement  []int `json:"row_displacement"`
}

type UniqueEntriesTable struct {
	UniqueEntries             *RowDisplacementTable `json:"unique_entries,omitempty"`
	UncompressedUniqueEntries []int                 `json:"uncompressed_unique_entries,omitempty"`
	RowNums                   []int                 `json:"row_nums"`
	OriginalRowCount          int                   `json:"original_row_count"`
	OriginalColCount          int                   `json:"original_col_count"`
	EmptyValue                int                   `json:"empty_value"`
}

type TransitionTable struct {
	InitialState           int                 `json:"initial_state"`
	AcceptingStates        []int               `json:"accepting_states"`
	RowCount               int                 `json:"row_count"`
	ColCount               int                 `json:"col_count"`
	Transition             *UniqueEntriesTable `json:"transition,omitempty"`
	UncompressedTransition []int               `json:"uncompressed_transition,omitempty"`
}

type CompiledLexModeSpec struct {
	Kinds []LexKind        `json:"kinds"`
	Push  []LexModeNum     `json:"push"`
	Pop   []int            `json:"pop"`
	DFA   *TransitionTable `json:"dfa"`
}

type CompiledLexSpec struct {
	InitialMode      LexModeNum             `json:"initial_mode"`
	Modes            []LexModeName          `json:"modes"`
	CompressionLevel int                    `json:"compression_level"`
	Specs            []*CompiledLexModeSpec `json:"specs"`
}