Debian Codegraph @

gtrie/gtrie.go

raw symbols SCIP
1 //go:generate msgp
2 //msgp:shim rune as:int32 using:int32/rune
3 // Copyright (c) 2013 Mathieu Turcotte
4 // Licensed under the MIT license.
5
6 // Package gtrie provides a trie implementation based on a minimal acyclic
7 // finite-state automaton.
8 package gtrie
9
10 import (
11 "errors"
12 "sort"
13 "strings"
14 "fmt"
15 )
16
17 type NodeId int
18
19 type nodeIdGen struct {
20 id NodeId
21 }
22
23 func (g *nodeIdGen) next() (next NodeId) {
24 next = g.id
25 g.id++
26 return
27 }
28
29 // Represents a transition in the acyclic finite-state automaton. Each
30 // transition has one label and leads to one node.
31 type Transition struct {
32 Child *Node
33 Label rune
34 }
35
36 // Represents a node in the acyclic finite-state automaton.
37 type Node struct {
38 Id NodeId
39 Terminal bool
40 Transitions []Transition
41 }
42
43 // Checks whether the node has children.
44 func (n *Node) HasChildren() bool {
45 return len(n.Transitions) > 0
46 }
47
48 // Checks whether the node has a child for the given letter.
49 func (n *Node) HasChild(letter rune) bool {
50 return n.GetChild(letter) != nil
51 }
52
53 func (n *Node) ChildKeys() []string {
54 if !n.HasChildren() || n.Terminal {
55 return nil
56 }
57 strs := make([]string, 0)
58 for _, c := range n.Transitions {
59 letter := c.Label
60 child_strings := c.Child.ChildKeys()
61 if child_strings != nil {
62 for _, cs := range child_strings {
63 strs = append(strs, fmt.Sprintf("%c%s", letter, cs))
64 }
65 } else {
66 strs = append(strs, fmt.Sprintf("%c", letter))
67 }
68 }
69 return strs
70 }
71
72 // Retrieves the child for the given letter. Returns nil if there is no child
73 // for this letter.
74 func (n *Node) GetChild(letter rune) (child *Node) {
75 transitions := n.Transitions
76 finder := func(i int) bool { return transitions[i].Label >= letter }
77 // It is possible to use a binary search here because we know, by
78 // construction, that the transitions are sorted by their labels.
79 index := sort.Search(len(transitions), finder)
80 if index < len(transitions) && transitions[index].Label == letter {
81 child = transitions[index].Child
82 }
83 return
84 }
85
86 // Whether the node recognizes the given suffix. A suffix is accepted if there
87 // exists a path from the current node to a final node labeled with the suffix
88 // elements.
89 func (n *Node) Accepts(suffix string) bool {
90 letters := []rune(suffix)
91 current := n
92 for i := 0; current != nil && i < len(letters); i++ {
93 current = current.GetChild(letters[i])
94 }
95 return current != nil && current.Terminal
96 }
97
98 // Whether the given prefix is found in the tree. Most useful reading off the
99 // root node.
100 func (n *Node) HasPrefix(prefix string) (*Node, error) {
101 letters := []rune(prefix)
102 current := n
103 for i := 0; current != nil && i < len(letters); i++ {
104 current = current.GetChild(letters[i])
105 }
106 if current == nil {
107 err := fmt.Errorf("%s not found", prefix)
108 return nil, err
109 }
110 return current, nil
111 }
112
113 // Gets the number of nodes in the given automaton.
114 func Size(node *Node) int {
115 ids := make(map[NodeId]bool)
116 queue := []*Node{node}
117 for len(queue) > 0 {
118 node = queue[0]
119 queue = queue[1:]
120 ids[node.Id] = true
121 for _, t := range node.Transitions {
122 queue = append(queue, t.Child)
123 }
124 }
125 return len(ids)
126 }
127
128 func newNode(idGen *nodeIdGen) *Node {
129 return &Node{Id: idGen.next()}
130 }
131
132 func addTransition(node *Node, child *Node, letter rune) {
133 node.Transitions = append(node.Transitions, Transition{child, letter})
134 }
135
136 func addChild(node *Node, letter rune, idGen *nodeIdGen) (child *Node) {
137 child = node.GetChild(letter)
138 if child == nil {
139 child = newNode(idGen)
140 addTransition(node, child, letter)
141 }
142 return
143 }
144
145 func getLastChild(node *Node) *Node {
146 t := node.Transitions
147 return t[len(t)-1].Child
148 }
149
150 func setLastChild(node *Node, last *Node) {
151 t := node.Transitions
152 t[len(t)-1].Child = last
153 }
154
155 type eqClass struct {
156 terminal bool
157 children string
158 }
159
160 // Obtains the equivalence class for this node, knowing that two nodes p and
161 // q belongs to the same class if and only if:
162 // 1. they are either both final or both nonfinal; and
163 // 2. they have the same number of outgoing transitions; and
164 // 3. corresponding outgoing transitions have the same labels; and
165 // 4. corresponding transitions lead to the same states.
166 func getEquivalenceClass(node *Node) (class eqClass) {
167 children := []string{}
168 for _, t := range node.Transitions {
169 children = append(children, string(t.Label)+":"+string(t.Child.Id))
170 }
171 class.children = strings.Join(children, ";")
172 class.terminal = node.Terminal
173 return
174 }
175
176 type registry struct {
177 // Mapping from equivalence class to node.
178 eqv map[eqClass]*Node
179 // Set of nodes that are registered.
180 nodes map[*Node]bool
181 }
182
183 func newRegistery() (reg *registry) {
184 reg = new(registry)
185 reg.eqv = make(map[eqClass]*Node)
186 reg.nodes = make(map[*Node]bool)
187 return
188 }
189
190 func (r *registry) find(class eqClass) *Node {
191 return r.eqv[class]
192 }
193
194 func (r *registry) register(class eqClass, node *Node) {
195 r.eqv[class] = node
196 r.nodes[node] = true
197 }
198
199 func (r *registry) registered(node *Node) bool {
200 return r.nodes[node]
201 }
202
203 // Creates an acyclic finite-state automaton from a sorted list of words and
204 // returns the root node. Words can contain any unicode chararcters. An error
205 // will be returned if the list of words is not lexicographically sorted.
206 func Create(words []string) (automaton *Node, err error) {
207 reg := newRegistery()
208 idGen := new(nodeIdGen)
209 automaton = newNode(idGen)
210
211 if !sort.StringsAreSorted(words) {
212 err = errors.New("the words are not sorted")
213 return
214 }
215
216 for _, word := range words {
217 insertWord(word, automaton, reg, idGen)
218 }
219
220 replaceOrRegister(automaton, reg)
221 return
222 }
223
224 func insertWord(word string, automaton *Node, reg *registry, idGen *nodeIdGen) {
225 letters := []rune(word)
226 var last *Node
227
228 if len(letters) == 0 {
229 return
230 }
231
232 // Find last common state.
233 for current := automaton; current != nil && len(letters) > 0; {
234 last = current
235 current = last.GetChild(letters[0])
236 if current != nil {
237 letters = letters[1:]
238 }
239 }
240
241 // Minimize.
242 if last.HasChildren() {
243 replaceOrRegister(last, reg)
244 }
245
246 // Add suffix.
247 for len(letters) > 0 {
248 last = addChild(last, letters[0], idGen)
249 letters = letters[1:]
250 }
251
252 last.Terminal = true
253 }
254
255 func replaceOrRegister(node *Node, reg *registry) {
256 var child = getLastChild(node)
257
258 if reg.registered(child) {
259 return
260 }
261
262 if child.HasChildren() {
263 replaceOrRegister(child, reg)
264 }
265
266 class := getEquivalenceClass(child)
267
268 if eq := reg.find(class); eq != nil {
269 setLastChild(node, eq)
270 } else {
271 reg.register(class, child)
272 }
273 }