blob: cb3b8227bdd9d81a2e59edddbf3b45a9c7019aa0 [file] [log] [blame]
Akron8ef408b2021-08-02 22:11:04 +02001package datokenizer
2
3/**
4 * The file reader is basically a port of foma2js,
5 * licensed under the Apache License, version 2,
6 * and written by Mans Hulden.
7 */
8
Akronb4bbb472021-08-09 11:49:38 +02009// The maximum number of states is 1.073.741.823 (30bit),
Akron83e75a22021-08-04 13:14:06 +020010// with a loadfactor of ~70, this means roughly 70 million
11// states in the FSA, which is sufficient for the current
12// job.
Akron03c92fe2021-08-09 14:07:57 +020013//
14// Serialization is little endian.
Akron83e75a22021-08-04 13:14:06 +020015
Akron740f3d72021-08-03 12:12:34 +020016// TODO:
Akrone61380b2021-08-16 10:10:46 +020017// - Turn sigma into an array instead of using a map
18// and improve the mapping beforehand so that ASCII
19// is mapped directly and only non-ASCII needs to be
20// looked up in a map or similar.
Akron740f3d72021-08-03 12:12:34 +020021// - replace maxSize with the check value
Akron3a063ef2021-08-05 19:36:35 +020022// - Add checksum to serialization.
Akron03c92fe2021-08-09 14:07:57 +020023// - Instead of memoizing the loadFactor, better remember
24// the number of set transitions
Akrone61380b2021-08-16 10:10:46 +020025// - Replace/Enhance table with a map
26// - Provide a bufio.Scanner compatible interface.
Akron8e1d69b2021-08-12 17:38:49 +020027// - Mark epsilon transitions in bytes
Akron740f3d72021-08-03 12:12:34 +020028
Akron8ef408b2021-08-02 22:11:04 +020029import (
30 "bufio"
31 "compress/gzip"
Akron6247a5d2021-08-03 19:18:28 +020032 "encoding/binary"
Akron8ef408b2021-08-02 22:11:04 +020033 "fmt"
34 "io"
35 "os"
Akronc9d84a62021-08-03 15:56:03 +020036 "sort"
Akron8ef408b2021-08-02 22:11:04 +020037 "strconv"
38 "strings"
39 "unicode/utf8"
Akron740f3d72021-08-03 12:12:34 +020040
Akron527c10c2021-08-13 01:45:18 +020041 "log"
Akron8ef408b2021-08-02 22:11:04 +020042)
43
44const (
Akron2a4b9292021-08-04 15:35:22 +020045 PROPS = 1
46 SIGMA = 2
47 STATES = 3
48 NONE = 4
Akron2a4b9292021-08-04 15:35:22 +020049 DEBUG = false
50 MAGIC = "DATOK"
51 VERSION = uint16(1)
Akron03c92fe2021-08-09 14:07:57 +020052 FIRSTBIT uint32 = 1 << 31
53 SECONDBIT uint32 = 1 << 30
54 RESTBIT uint32 = ^uint32(0) &^ (FIRSTBIT | SECONDBIT)
Akron8ef408b2021-08-02 22:11:04 +020055)
56
Akron03c92fe2021-08-09 14:07:57 +020057// Serialization is always little endian
Akron6247a5d2021-08-03 19:18:28 +020058var bo binary.ByteOrder = binary.LittleEndian
59
Akron8ef408b2021-08-02 22:11:04 +020060type mapping struct {
61 source int
Akron3fdfec62021-08-04 11:40:10 +020062 target uint32
Akron8ef408b2021-08-02 22:11:04 +020063}
64
65type edge struct {
Akron83e75a22021-08-04 13:14:06 +020066 inSym int
67 outSym int
68 end int
69 nontoken bool
70 tokenend bool
Akron8ef408b2021-08-02 22:11:04 +020071}
72
Akron03c92fe2021-08-09 14:07:57 +020073// Tokenizer is the intermediate representation
74// of the tokenizer.
Akron8ef408b2021-08-02 22:11:04 +020075type Tokenizer struct {
Akron740f3d72021-08-03 12:12:34 +020076 sigmaRev map[int]rune
77 arcCount int
Akron740f3d72021-08-03 12:12:34 +020078 sigmaCount int
Akron8ef408b2021-08-02 22:11:04 +020079 transitions []map[int]*edge
Akronc17f1ca2021-08-03 19:47:27 +020080
81 // Special symbols in sigma
82 epsilon int
83 unknown int
84 identity int
85 final int
Akron03c92fe2021-08-09 14:07:57 +020086 tokenend int
Akron8ef408b2021-08-02 22:11:04 +020087}
88
Akronf1a16502021-08-16 15:24:38 +020089type bc struct {
90 base uint32
91 check uint32
92}
93
Akron03c92fe2021-08-09 14:07:57 +020094// DaTokenizer represents a tokenizer implemented as a
95// Double Array FSA.
Akronf2120ca2021-08-03 16:26:41 +020096type DaTokenizer struct {
Akronea46e8a2021-08-17 00:36:31 +020097 sigma map[rune]int
98 sigmaASCII [256]int
Akron03a3c612021-08-04 11:51:27 +020099 maxSize int
100 loadFactor float64
Akronf1a16502021-08-16 15:24:38 +0200101 array []bc
Akronc17f1ca2021-08-03 19:47:27 +0200102
103 // Special symbols in sigma
104 epsilon int
105 unknown int
106 identity int
107 final int
Akron03c92fe2021-08-09 14:07:57 +0200108 tokenend int
Akronf2120ca2021-08-03 16:26:41 +0200109}
110
Akron03c92fe2021-08-09 14:07:57 +0200111// ParseFoma reads the FST from a foma file
112// and creates an internal representation,
113// in case it follows the tokenizer's convention.
Akron64ffd9a2021-08-03 19:55:21 +0200114func LoadFomaFile(file string) *Tokenizer {
Akron8ef408b2021-08-02 22:11:04 +0200115 f, err := os.Open(file)
116 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200117 log.Print(err)
Akron4db3ecf2021-08-11 18:49:03 +0200118 return nil
Akron8ef408b2021-08-02 22:11:04 +0200119 }
120 defer f.Close()
121
122 gz, err := gzip.NewReader(f)
123 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200124 log.Print(err)
Akron4db3ecf2021-08-11 18:49:03 +0200125 return nil
Akron8ef408b2021-08-02 22:11:04 +0200126 }
127 defer gz.Close()
128
Akron3fdfec62021-08-04 11:40:10 +0200129 return ParseFoma(gz)
Akron8ef408b2021-08-02 22:11:04 +0200130}
131
Akron03c92fe2021-08-09 14:07:57 +0200132// ParseFoma reads the FST from a foma file reader
133// and creates an internal representation,
134// in case it follows the tokenizer's convention.
Akron3fdfec62021-08-04 11:40:10 +0200135func ParseFoma(ior io.Reader) *Tokenizer {
Akron8ef408b2021-08-02 22:11:04 +0200136 r := bufio.NewReader(ior)
137
138 tok := &Tokenizer{
Akron740f3d72021-08-03 12:12:34 +0200139 sigmaRev: make(map[int]rune),
Akronc17f1ca2021-08-03 19:47:27 +0200140 epsilon: -1,
141 unknown: -1,
142 identity: -1,
143 final: -1,
Akron03c92fe2021-08-09 14:07:57 +0200144 tokenend: -1,
Akron8ef408b2021-08-02 22:11:04 +0200145 }
146
Akron740f3d72021-08-03 12:12:34 +0200147 var state, inSym, outSym, end, final int
Akron8ef408b2021-08-02 22:11:04 +0200148
149 mode := 0
150 var elem []string
151 var elemint [5]int
152
Akron03c92fe2021-08-09 14:07:57 +0200153 // Iterate over all lines of the file.
154 // This is mainly based on foma2js,
155 // licensed under the Apache License, version 2,
156 // and written by Mans Hulden.
Akron8ef408b2021-08-02 22:11:04 +0200157 for {
158 line, err := r.ReadString('\n')
159 if err != nil {
160 if err == io.EOF {
161 break
162 }
Akron527c10c2021-08-13 01:45:18 +0200163 log.Print(err)
Akron4db3ecf2021-08-11 18:49:03 +0200164 return nil
Akron8ef408b2021-08-02 22:11:04 +0200165 }
Akron8ef408b2021-08-02 22:11:04 +0200166
Akron439f4ec2021-08-09 15:45:38 +0200167 // Read parser mode for the following lines
168 if strings.HasPrefix(line, "##") {
169 if strings.HasPrefix(line, "##props##") {
170 mode = PROPS
171
172 } else if strings.HasPrefix(line, "##states##") {
173 mode = STATES
174
175 // Adds a final transition symbol to sigma
176 // written as '#' in Mizobuchi et al (2000)
177 tok.sigmaCount++
178 tok.final = tok.sigmaCount
179
180 } else if strings.HasPrefix(line, "##sigma##") {
181
182 mode = SIGMA
183
184 } else if strings.HasPrefix(line, "##end##") {
185
186 mode = NONE
187
188 } else if !strings.HasPrefix(line, "##foma-net") {
Akron527c10c2021-08-13 01:45:18 +0200189 log.Print("Unknown input line")
Akron439f4ec2021-08-09 15:45:38 +0200190 break
191 }
Akron8ef408b2021-08-02 22:11:04 +0200192 continue
193 }
194
Akron439f4ec2021-08-09 15:45:38 +0200195 // Based on the current parser mode, interpret the lines
Akron8ef408b2021-08-02 22:11:04 +0200196 switch mode {
197 case PROPS:
198 {
199 elem = strings.Split(line, " ")
200 /*
201 fmt.Println("arity: " + elem[0])
202 fmt.Println("arccount: " + elem[1])
203 fmt.Println("statecount: " + elem[2])
204 fmt.Println("linecount: " + elem[3])
205 fmt.Println("finalcount: " + elem[4])
206 fmt.Println("pathcount: " + elem[5])
207 fmt.Println("is_deterministic: " + elem[6])
208 fmt.Println("is_pruned: " + elem[7])
209 fmt.Println("is_minimized: " + elem[8])
210 fmt.Println("is_epsilon_free: " + elem[9])
211 fmt.Println("is_loop_free: " + elem[10])
212 fmt.Println("extras: " + elem[11])
213 fmt.Println("name: " + elem[12])
214 */
215 if elem[6] != "1" {
Akron527c10c2021-08-13 01:45:18 +0200216 log.Print("The FST needs to be deterministic")
Akron4db3ecf2021-08-11 18:49:03 +0200217 return nil
Akron8ef408b2021-08-02 22:11:04 +0200218 }
Akron439f4ec2021-08-09 15:45:38 +0200219
Akron8ef408b2021-08-02 22:11:04 +0200220 if elem[9] != "1" {
Akron527c10c2021-08-13 01:45:18 +0200221 log.Print("The FST needs to be epsilon free")
Akron4db3ecf2021-08-11 18:49:03 +0200222 return nil
Akron8ef408b2021-08-02 22:11:04 +0200223 }
224
225 elemint[0], err = strconv.Atoi(elem[1])
226 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200227 log.Print("Can't read arccount")
Akron4db3ecf2021-08-11 18:49:03 +0200228 return nil
Akron8ef408b2021-08-02 22:11:04 +0200229 }
Akron740f3d72021-08-03 12:12:34 +0200230 tok.arcCount = elemint[0]
Akron8ef408b2021-08-02 22:11:04 +0200231
Akron8ef408b2021-08-02 22:11:04 +0200232 elemint[0], err = strconv.Atoi(elem[2])
233 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200234 log.Print("Can't read statecount")
Akron4db3ecf2021-08-11 18:49:03 +0200235 return nil
Akron8ef408b2021-08-02 22:11:04 +0200236 }
Akron439f4ec2021-08-09 15:45:38 +0200237
238 // States start at 1 in Mizobuchi et al (2000),
239 // as the state 0 is associated with a fail.
240 // Initialize states and transitions
Akron8ef408b2021-08-02 22:11:04 +0200241 tok.transitions = make([]map[int]*edge, elemint[0]+1)
242 continue
243 }
244 case STATES:
245 {
246 elem = strings.Split(line[0:len(line)-1], " ")
247 if elem[0] == "-1" {
Akron3610f102021-08-08 14:13:25 +0200248 if DEBUG {
249 fmt.Println("Skip", elem)
250 }
Akron8ef408b2021-08-02 22:11:04 +0200251 continue
252 }
253 elemint[0], err = strconv.Atoi(elem[0])
Akron75ebe7f2021-08-03 10:34:10 +0200254 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200255 fmt.Println("Unable to translate", elem[0])
Akron75ebe7f2021-08-03 10:34:10 +0200256 break
257 }
Akron8ef408b2021-08-02 22:11:04 +0200258
259 if len(elem) > 1 {
260 elemint[1], err = strconv.Atoi(elem[1])
261 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200262 fmt.Println("Unable to translate", elem[1])
Akron8ef408b2021-08-02 22:11:04 +0200263 break
264 }
265 if len(elem) > 2 {
266 elemint[2], err = strconv.Atoi(elem[2])
267 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200268 fmt.Println("Unable to translate", elem[2])
Akron8ef408b2021-08-02 22:11:04 +0200269 break
270 }
271 if len(elem) > 3 {
272 elemint[3], err = strconv.Atoi(elem[3])
273 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200274 fmt.Println("Unable to translate", elem[3])
Akron8ef408b2021-08-02 22:11:04 +0200275 break
276 }
277 if len(elem) > 4 {
278 elemint[4], err = strconv.Atoi(elem[4])
279 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200280 fmt.Println("Unable to translate", elem[4])
Akron8ef408b2021-08-02 22:11:04 +0200281 break
282 }
283 }
284 }
285 }
286 }
287
288 switch len(elem) {
289 case 5:
290 {
Akron740f3d72021-08-03 12:12:34 +0200291 state = elemint[0]
292 inSym = elemint[1]
293 outSym = elemint[2]
294 end = elemint[3]
295 final = elemint[4]
Akron8ef408b2021-08-02 22:11:04 +0200296 }
297 case 4:
298 {
299 if elemint[1] == -1 {
Akron740f3d72021-08-03 12:12:34 +0200300 state = elemint[0]
301 final = elemint[3]
Akron8ef408b2021-08-02 22:11:04 +0200302 } else {
Akron740f3d72021-08-03 12:12:34 +0200303 state = elemint[0]
304 inSym = elemint[1]
305 end = elemint[2]
306 final = elemint[3]
307 outSym = inSym
Akron8ef408b2021-08-02 22:11:04 +0200308 }
309 }
310 case 3:
311 {
Akron740f3d72021-08-03 12:12:34 +0200312 inSym = elemint[0]
313 outSym = elemint[1]
314 end = elemint[2]
Akron8ef408b2021-08-02 22:11:04 +0200315 }
316 case 2:
317 {
Akron740f3d72021-08-03 12:12:34 +0200318 inSym = elemint[0]
319 end = elemint[1]
320 outSym = inSym
Akron8ef408b2021-08-02 22:11:04 +0200321 }
322 }
323
Akron83e75a22021-08-04 13:14:06 +0200324 nontoken := false
325 tokenend := false
326
Akron439f4ec2021-08-09 15:45:38 +0200327 // While the states in foma start with 0, the states in the
328 // Mizobuchi FSA start with one - so we increase every state by 1.
329 // We also increase sigma by 1, so there are no 0 transitions.
Akron524c5432021-08-05 14:14:27 +0200330 inSym++
331 outSym++
332
Akron439f4ec2021-08-09 15:45:38 +0200333 // Only a limited list of transitions are allowed
Akron740f3d72021-08-03 12:12:34 +0200334 if inSym != outSym {
Akron01912fc2021-08-12 11:41:58 +0200335 if outSym == tok.tokenend && inSym == tok.epsilon {
Akron83e75a22021-08-04 13:14:06 +0200336 tokenend = true
337 } else if outSym == tok.epsilon {
338 nontoken = true
339 } else {
Akron527c10c2021-08-13 01:45:18 +0200340 log.Println(
Akron740f3d72021-08-03 12:12:34 +0200341 "Unsupported transition: " +
342 strconv.Itoa(state) +
343 " -> " + strconv.Itoa(end) +
Akron75ebe7f2021-08-03 10:34:10 +0200344 " (" +
Akron740f3d72021-08-03 12:12:34 +0200345 strconv.Itoa(inSym) +
Akron75ebe7f2021-08-03 10:34:10 +0200346 ":" +
Akron740f3d72021-08-03 12:12:34 +0200347 strconv.Itoa(outSym) +
Akron75ebe7f2021-08-03 10:34:10 +0200348 ") (" +
Akron740f3d72021-08-03 12:12:34 +0200349 string(tok.sigmaRev[inSym]) +
Akron75ebe7f2021-08-03 10:34:10 +0200350 ":" +
Akron740f3d72021-08-03 12:12:34 +0200351 string(tok.sigmaRev[outSym]) +
Akron75ebe7f2021-08-03 10:34:10 +0200352 ")")
Akron4db3ecf2021-08-11 18:49:03 +0200353 return nil
Akron75ebe7f2021-08-03 10:34:10 +0200354 }
Akron83e75a22021-08-04 13:14:06 +0200355
Akron83e75a22021-08-04 13:14:06 +0200356 } else if inSym == tok.epsilon {
Akron527c10c2021-08-13 01:45:18 +0200357 log.Println("General epsilon transitions are not supported")
Akron4db3ecf2021-08-11 18:49:03 +0200358 return nil
Akron8ef408b2021-08-02 22:11:04 +0200359 }
360
Akron03c92fe2021-08-09 14:07:57 +0200361 // Create an edge based on the collected information
Akron8ef408b2021-08-02 22:11:04 +0200362 targetObj := &edge{
Akron83e75a22021-08-04 13:14:06 +0200363 inSym: inSym,
364 outSym: outSym,
365 end: end + 1,
366 tokenend: tokenend,
367 nontoken: nontoken,
Akron8ef408b2021-08-02 22:11:04 +0200368 }
369
Akron740f3d72021-08-03 12:12:34 +0200370 // Initialize outgoing states
371 if tok.transitions[state+1] == nil {
372 tok.transitions[state+1] = make(map[int]*edge)
Akron8ef408b2021-08-02 22:11:04 +0200373 }
374
Akron740f3d72021-08-03 12:12:34 +0200375 // Ignore transitions with invalid symbols
376 if inSym >= 0 {
377 tok.transitions[state+1][inSym] = targetObj
Akron75ebe7f2021-08-03 10:34:10 +0200378 }
Akron8ef408b2021-08-02 22:11:04 +0200379
Akron740f3d72021-08-03 12:12:34 +0200380 // Add final transition
381 if final == 1 {
Akron03c92fe2021-08-09 14:07:57 +0200382 // TODO:
383 // Maybe this is less relevant for tokenizers
Akronc17f1ca2021-08-03 19:47:27 +0200384 tok.transitions[state+1][tok.final] = &edge{}
Akron8ef408b2021-08-02 22:11:04 +0200385 }
386
Akronb4bbb472021-08-09 11:49:38 +0200387 if DEBUG {
Akron740f3d72021-08-03 12:12:34 +0200388 fmt.Println("Add",
389 state+1, "->", end+1,
390 "(",
391 inSym,
392 ":",
393 outSym,
394 ") (",
395 string(tok.sigmaRev[inSym]),
396 ":",
397 string(tok.sigmaRev[outSym]),
Akron524c5432021-08-05 14:14:27 +0200398 ")",
399 ";",
400 "TE:", tokenend,
Akron3610f102021-08-08 14:13:25 +0200401 "NT:", nontoken,
402 "FIN:", final)
Akron740f3d72021-08-03 12:12:34 +0200403 }
Akron75ebe7f2021-08-03 10:34:10 +0200404
Akron8ef408b2021-08-02 22:11:04 +0200405 continue
406 }
407 case SIGMA:
408 {
409 elem = strings.SplitN(line[0:len(line)-1], " ", 2)
410
411 // Turn string into sigma id
412 number, err := strconv.Atoi(elem[0])
413
Akron524c5432021-08-05 14:14:27 +0200414 // ID needs to be > 1
415 number++
416
Akron8ef408b2021-08-02 22:11:04 +0200417 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200418 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200419 return nil
Akron8ef408b2021-08-02 22:11:04 +0200420 }
421
Akron740f3d72021-08-03 12:12:34 +0200422 tok.sigmaCount = number
Akron8ef408b2021-08-02 22:11:04 +0200423
424 var symbol rune
425
426 // Read rune
427 if utf8.RuneCountInString(elem[1]) == 1 {
428 symbol = []rune(elem[1])[0]
429
Akron8ef408b2021-08-02 22:11:04 +0200430 } else if utf8.RuneCountInString(elem[1]) > 1 {
Akron439f4ec2021-08-09 15:45:38 +0200431
432 // Probably a MCS
Akron8ef408b2021-08-02 22:11:04 +0200433 switch elem[1] {
434 case "@_EPSILON_SYMBOL_@":
435 {
Akronc17f1ca2021-08-03 19:47:27 +0200436 tok.epsilon = number
Akron8ef408b2021-08-02 22:11:04 +0200437 }
438 case "@_UNKNOWN_SYMBOL_@":
439 {
Akronc17f1ca2021-08-03 19:47:27 +0200440 tok.unknown = number
Akron8ef408b2021-08-02 22:11:04 +0200441 }
442
443 case "@_IDENTITY_SYMBOL_@":
444 {
Akronc17f1ca2021-08-03 19:47:27 +0200445 tok.identity = number
Akron8ef408b2021-08-02 22:11:04 +0200446 }
Akron03c92fe2021-08-09 14:07:57 +0200447
448 case "@_TOKEN_SYMBOL_@":
449 {
450 tok.tokenend = number
Akron03c92fe2021-08-09 14:07:57 +0200451 }
Akron8ef408b2021-08-02 22:11:04 +0200452 default:
Akron740f3d72021-08-03 12:12:34 +0200453 {
Akron527c10c2021-08-13 01:45:18 +0200454 log.Println("MCS not supported: " + line)
Akron4db3ecf2021-08-11 18:49:03 +0200455 return nil
Akron740f3d72021-08-03 12:12:34 +0200456 }
Akron8ef408b2021-08-02 22:11:04 +0200457 }
Akron439f4ec2021-08-09 15:45:38 +0200458 continue
Akron8ef408b2021-08-02 22:11:04 +0200459
Akron740f3d72021-08-03 12:12:34 +0200460 } else { // Probably a new line symbol
Akron8ef408b2021-08-02 22:11:04 +0200461 line, err = r.ReadString('\n')
462 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200463 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200464 return nil
Akron8ef408b2021-08-02 22:11:04 +0200465 }
466 if len(line) != 1 {
Akron527c10c2021-08-13 01:45:18 +0200467 log.Println("MCS not supported:" + line)
Akron4db3ecf2021-08-11 18:49:03 +0200468 return nil
Akron8ef408b2021-08-02 22:11:04 +0200469 }
Akron03c92fe2021-08-09 14:07:57 +0200470 symbol = rune('\n')
Akron8ef408b2021-08-02 22:11:04 +0200471 }
472
Akron740f3d72021-08-03 12:12:34 +0200473 tok.sigmaRev[number] = symbol
Akron8ef408b2021-08-02 22:11:04 +0200474 }
475 }
476 }
477
478 return tok
479}
480
Akron64ffd9a2021-08-03 19:55:21 +0200481// Set alphabet A to the list of all symbols
482// outgoing from s
Akron439f4ec2021-08-09 15:45:38 +0200483func (tok *Tokenizer) getSet(s int, A *[]int) {
Akron64ffd9a2021-08-03 19:55:21 +0200484 for a := range tok.transitions[s] {
485 *A = append(*A, a)
486 }
487
488 // Not required, but simplifies bug hunting
Akron439f4ec2021-08-09 15:45:38 +0200489 // sort.Ints(*A)
Akron64ffd9a2021-08-03 19:55:21 +0200490}
491
Akron439f4ec2021-08-09 15:45:38 +0200492// ToDoubleArray turns the intermediate tokenizer representation
493// into a double array representation.
494//
495// This is based on Mizobuchi et al (2000), p.128
Akronf2120ca2021-08-03 16:26:41 +0200496func (tok *Tokenizer) ToDoubleArray() *DaTokenizer {
497
498 dat := &DaTokenizer{
Akron03a3c612021-08-04 11:51:27 +0200499 sigma: make(map[rune]int),
500 loadFactor: -1,
501 final: tok.final,
502 unknown: tok.unknown,
503 identity: tok.identity,
504 epsilon: tok.epsilon,
Akron03c92fe2021-08-09 14:07:57 +0200505 tokenend: tok.tokenend,
Akronf2120ca2021-08-03 16:26:41 +0200506 }
507
Akronf1a16502021-08-16 15:24:38 +0200508 dat.resize(dat.final)
509
Akronf2120ca2021-08-03 16:26:41 +0200510 for num, sym := range tok.sigmaRev {
Akronea46e8a2021-08-17 00:36:31 +0200511 if int(sym) < 256 {
512 dat.sigmaASCII[int(sym)] = num
513 }
Akronf2120ca2021-08-03 16:26:41 +0200514 dat.sigma[sym] = num
515 }
Akron8ef408b2021-08-02 22:11:04 +0200516
517 mark := 0
518 size := 0
Akron6f1c16c2021-08-17 10:45:42 +0200519 var base uint32
Akron8ef408b2021-08-02 22:11:04 +0200520
Akron439f4ec2021-08-09 15:45:38 +0200521 // Create a mapping from s (in Ms aka Intermediate FSA)
522 // to t (in Mt aka Double Array FSA)
Akron740f3d72021-08-03 12:12:34 +0200523 table := make([]*mapping, tok.arcCount+1)
Akron8ef408b2021-08-02 22:11:04 +0200524
Akron439f4ec2021-08-09 15:45:38 +0200525 // Initialize with the start state
Akron8ef408b2021-08-02 22:11:04 +0200526 table[size] = &mapping{source: 1, target: 1}
527 size++
528
Akron740f3d72021-08-03 12:12:34 +0200529 // Allocate space for the outgoing symbol range
530 A := make([]int, 0, tok.sigmaCount)
Akron8ef408b2021-08-02 22:11:04 +0200531
532 for mark < size {
533 s := table[mark].source // This is a state in Ms
534 t := table[mark].target // This is a state in Mt
535 mark++
Akron740f3d72021-08-03 12:12:34 +0200536
537 // Following the paper, here the state t can be remembered
538 // in the set of states St
Akron8ef408b2021-08-02 22:11:04 +0200539 A = A[:0]
Akron439f4ec2021-08-09 15:45:38 +0200540 tok.getSet(s, &A)
Akron8ef408b2021-08-02 22:11:04 +0200541
Akron740f3d72021-08-03 12:12:34 +0200542 // Set base to the first free slot in the double array
Akron6f1c16c2021-08-17 10:45:42 +0200543 base = dat.xCheck(A)
544 dat.array[t].setBase(base)
Akron8ef408b2021-08-02 22:11:04 +0200545
Akron773b1ef2021-08-03 17:37:20 +0200546 // TODO:
Akron068874c2021-08-04 15:19:56 +0200547 // Sort the outgoing transitions based on the
Akron773b1ef2021-08-03 17:37:20 +0200548 // outdegree of .end
549
Akron740f3d72021-08-03 12:12:34 +0200550 // Iterate over all outgoing symbols
Akron8ef408b2021-08-02 22:11:04 +0200551 for _, a := range A {
552
Akronc17f1ca2021-08-03 19:47:27 +0200553 if a != tok.final {
Akron8ef408b2021-08-02 22:11:04 +0200554
Akron740f3d72021-08-03 12:12:34 +0200555 // Aka g(s, a)
556 s1 := tok.transitions[s][a].end
Akron8ef408b2021-08-02 22:11:04 +0200557
Akron740f3d72021-08-03 12:12:34 +0200558 // Store the transition
Akron6f1c16c2021-08-17 10:45:42 +0200559 t1 := base + uint32(a)
Akronf1a16502021-08-16 15:24:38 +0200560 dat.array[t1].setCheck(t)
561
562 // Set maxSize
563 if dat.maxSize < int(t1) {
564 dat.maxSize = int(t1)
565 }
Akron8ef408b2021-08-02 22:11:04 +0200566
Akron439f4ec2021-08-09 15:45:38 +0200567 if DEBUG {
Akron524c5432021-08-05 14:14:27 +0200568 fmt.Println("Translate transition",
569 s, "->", s1, "(", a, ")", "to", t, "->", t1)
570 }
571
Akron83e75a22021-08-04 13:14:06 +0200572 // Mark the state as being the target of a nontoken transition
573 if tok.transitions[s][a].nontoken {
Akronf1a16502021-08-16 15:24:38 +0200574 dat.array[t1].setNonToken(true)
Akron524c5432021-08-05 14:14:27 +0200575 if DEBUG {
576 fmt.Println("Set", t1, "to nontoken")
577 }
Akron83e75a22021-08-04 13:14:06 +0200578 }
579
Akron84d68e62021-08-04 17:06:52 +0200580 // Mark the state as being the target of a tokenend transition
581 if tok.transitions[s][a].tokenend {
Akronf1a16502021-08-16 15:24:38 +0200582 dat.array[t1].setTokenEnd(true)
Akron524c5432021-08-05 14:14:27 +0200583 if DEBUG {
584 fmt.Println("Set", t1, "to tokenend")
585 }
Akron84d68e62021-08-04 17:06:52 +0200586 }
587
Akron740f3d72021-08-03 12:12:34 +0200588 // Check for representative states
Akron439f4ec2021-08-09 15:45:38 +0200589 r := stateAlreadyInTable(s1, table, size)
Akron740f3d72021-08-03 12:12:34 +0200590
Akron439f4ec2021-08-09 15:45:38 +0200591 // No representative found
Akron8ef408b2021-08-02 22:11:04 +0200592 if r == 0 {
Akron740f3d72021-08-03 12:12:34 +0200593 // Remember the mapping
Akron8ef408b2021-08-02 22:11:04 +0200594 table[size] = &mapping{source: s1, target: t1}
595 size++
596 } else {
Akron740f3d72021-08-03 12:12:34 +0200597 // Overwrite with the representative state
Akronf1a16502021-08-16 15:24:38 +0200598 dat.array[t1].setBase(r)
599 dat.array[t1].setSeparate(true)
Akron8ef408b2021-08-02 22:11:04 +0200600 }
601 } else {
Akron740f3d72021-08-03 12:12:34 +0200602 // Store a final transition
Akron6f1c16c2021-08-17 10:45:42 +0200603 dat.array[base+uint32(dat.final)].setCheck(t)
Akronf1a16502021-08-16 15:24:38 +0200604
Akron6f1c16c2021-08-17 10:45:42 +0200605 if dat.maxSize < int(base+uint32(dat.final)) {
606 dat.maxSize = int(base + uint32(dat.final))
Akronf1a16502021-08-16 15:24:38 +0200607 }
Akron8ef408b2021-08-02 22:11:04 +0200608 }
609 }
610 }
611
612 // Following Mizobuchi et al (2000) the size of the
613 // FSA should be stored in check(1).
Akronf1a16502021-08-16 15:24:38 +0200614 // We make the size a bit smaller so we never have to check for boundaries.
Akron3fdfec62021-08-04 11:40:10 +0200615 dat.setSize(dat.maxSize + 1)
Akronf2120ca2021-08-03 16:26:41 +0200616 dat.array = dat.array[:dat.maxSize+1]
617 return dat
Akron8ef408b2021-08-02 22:11:04 +0200618}
619
Akron8ef408b2021-08-02 22:11:04 +0200620// Check the table if a mapping of s
Akron740f3d72021-08-03 12:12:34 +0200621// exists and return this as a representative.
622// Currently iterates through the whole table
623// in a bruteforce manner.
Akron439f4ec2021-08-09 15:45:38 +0200624func stateAlreadyInTable(s int, table []*mapping, size int) uint32 {
Akron8ef408b2021-08-02 22:11:04 +0200625 for x := 0; x < size; x++ {
626 if table[x].source == s {
627 return table[x].target
628 }
629 }
630 return 0
631}
632
Akron64ffd9a2021-08-03 19:55:21 +0200633// Resize double array when necessary
634func (dat *DaTokenizer) resize(l int) {
635 // TODO:
636 // This is a bit too aggressive atm and should be calmed down.
637 if len(dat.array) <= l {
Akronf1a16502021-08-16 15:24:38 +0200638 dat.array = append(dat.array, make([]bc, l)...)
Akron8ef408b2021-08-02 22:11:04 +0200639 }
Akron64ffd9a2021-08-03 19:55:21 +0200640}
Akronc9d84a62021-08-03 15:56:03 +0200641
Akron64ffd9a2021-08-03 19:55:21 +0200642// Set base value in double array
Akronf1a16502021-08-16 15:24:38 +0200643func (bc *bc) setBase(v uint32) {
644 bc.base = v
Akron439f4ec2021-08-09 15:45:38 +0200645}
646
647// Get base value in double array
Akronf1a16502021-08-16 15:24:38 +0200648func (bc *bc) getBase() uint32 {
649 return bc.base & RESTBIT
Akron439f4ec2021-08-09 15:45:38 +0200650}
651
652// Set check value in double array
Akronf1a16502021-08-16 15:24:38 +0200653func (bc *bc) setCheck(v uint32) {
654 bc.check = v
Akron439f4ec2021-08-09 15:45:38 +0200655}
656
657// Get check value in double array
Akronf1a16502021-08-16 15:24:38 +0200658func (bc *bc) getCheck() uint32 {
659 return bc.check & RESTBIT
Akron64ffd9a2021-08-03 19:55:21 +0200660}
661
Akron3fdfec62021-08-04 11:40:10 +0200662// Returns true if a state is separate pointing to a representative
Akronf1a16502021-08-16 15:24:38 +0200663func (bc *bc) isSeparate() bool {
664 return bc.base&FIRSTBIT != 0
Akron3fdfec62021-08-04 11:40:10 +0200665}
666
667// Mark a state as separate pointing to a representative
Akronf1a16502021-08-16 15:24:38 +0200668func (bc *bc) setSeparate(sep bool) {
Akron3fdfec62021-08-04 11:40:10 +0200669 if sep {
Akronf1a16502021-08-16 15:24:38 +0200670 bc.base |= FIRSTBIT
Akron3fdfec62021-08-04 11:40:10 +0200671 } else {
Akronf1a16502021-08-16 15:24:38 +0200672 bc.base &= (RESTBIT | SECONDBIT)
Akron3fdfec62021-08-04 11:40:10 +0200673 }
674}
675
Akron83e75a22021-08-04 13:14:06 +0200676// Returns true if a state is the target of a nontoken transition
Akronf1a16502021-08-16 15:24:38 +0200677func (bc *bc) isNonToken() bool {
678 return bc.check&FIRSTBIT != 0
Akron83e75a22021-08-04 13:14:06 +0200679}
680
681// Mark a state as being the target of a nontoken transition
Akronf1a16502021-08-16 15:24:38 +0200682func (bc *bc) setNonToken(sep bool) {
Akron83e75a22021-08-04 13:14:06 +0200683 if sep {
Akronf1a16502021-08-16 15:24:38 +0200684 bc.check |= FIRSTBIT
Akron83e75a22021-08-04 13:14:06 +0200685 } else {
Akronf1a16502021-08-16 15:24:38 +0200686 bc.check &= (RESTBIT | SECONDBIT)
Akron83e75a22021-08-04 13:14:06 +0200687 }
688}
689
Akron84d68e62021-08-04 17:06:52 +0200690// Returns true if a state is the target of a tokenend transition
Akronf1a16502021-08-16 15:24:38 +0200691func (bc *bc) isTokenEnd() bool {
692 return bc.check&SECONDBIT != 0
Akron84d68e62021-08-04 17:06:52 +0200693}
694
695// Mark a state as being the target of a tokenend transition
Akronf1a16502021-08-16 15:24:38 +0200696func (bc *bc) setTokenEnd(sep bool) {
Akron84d68e62021-08-04 17:06:52 +0200697 if sep {
Akronf1a16502021-08-16 15:24:38 +0200698 bc.check |= SECONDBIT
Akron84d68e62021-08-04 17:06:52 +0200699 } else {
Akronf1a16502021-08-16 15:24:38 +0200700 bc.check &= (RESTBIT | FIRSTBIT)
Akron84d68e62021-08-04 17:06:52 +0200701 }
702}
703
Akron64ffd9a2021-08-03 19:55:21 +0200704// Set size of double array
Akron3fdfec62021-08-04 11:40:10 +0200705func (dat *DaTokenizer) setSize(v int) {
Akronf1a16502021-08-16 15:24:38 +0200706 dat.array[1].setCheck(uint32(v))
Akron64ffd9a2021-08-03 19:55:21 +0200707}
708
709// Get size of double array
Akron3fdfec62021-08-04 11:40:10 +0200710func (dat *DaTokenizer) GetSize() int {
Akronf1a16502021-08-16 15:24:38 +0200711 return int(dat.array[1].getCheck())
Akron8ef408b2021-08-02 22:11:04 +0200712}
713
714// Based on Mizobuchi et al (2000), p. 124
715// This iterates for every state through the complete double array
716// structure until it finds a gap that fits all outgoing transitions
717// of the state. This is extremely slow, but is only necessary in the
718// construction phase of the tokenizer.
Akron3fdfec62021-08-04 11:40:10 +0200719func (dat *DaTokenizer) xCheck(symbols []int) uint32 {
Akron740f3d72021-08-03 12:12:34 +0200720
721 // Start at the first entry of the double array list
Akron6f1c16c2021-08-17 10:45:42 +0200722 base := uint32(1)
723
Akron8ef408b2021-08-02 22:11:04 +0200724OVERLAP:
Akron740f3d72021-08-03 12:12:34 +0200725 // Resize the array if necessary
Akronf1a16502021-08-16 15:24:38 +0200726 dat.resize(int(base) + dat.final)
Akron8ef408b2021-08-02 22:11:04 +0200727 for _, a := range symbols {
Akronf1a16502021-08-16 15:24:38 +0200728 if dat.array[int(base)+a].getCheck() != 0 {
Akron8ef408b2021-08-02 22:11:04 +0200729 base++
730 goto OVERLAP
731 }
732 }
Akron8ef408b2021-08-02 22:11:04 +0200733 return base
734}
735
Akron3610f102021-08-08 14:13:25 +0200736// List all outgoing transitions for a state
737// for testing purposes
738func (dat *DaTokenizer) outgoing(t uint32) []int {
739
740 valid := make([]int, 0, len(dat.sigma))
741
742 for _, a := range dat.sigma {
Akronf1a16502021-08-16 15:24:38 +0200743 t1 := dat.array[t].getBase() + uint32(a)
744 if t1 <= dat.array[1].getCheck() && dat.array[t1].getCheck() == t {
Akron3610f102021-08-08 14:13:25 +0200745 valid = append(valid, a)
746 }
747 }
748
749 for _, a := range []int{dat.epsilon, dat.unknown, dat.identity, dat.final} {
Akronf1a16502021-08-16 15:24:38 +0200750 t1 := dat.array[t].getBase() + uint32(a)
751 if t1 <= dat.array[1].getCheck() && dat.array[t1].getCheck() == t {
Akron3610f102021-08-08 14:13:25 +0200752 valid = append(valid, -1*a)
753 }
754 }
755
756 sort.Ints(valid)
757
758 return valid
759}
760
Akron03a3c612021-08-04 11:51:27 +0200761// LoadFactor as defined in Kanda et al (2018),
762// i.e. the proportion of non-empty elements to all elements.
763func (dat *DaTokenizer) LoadFactor() float64 {
Akrond66a9262021-08-03 17:09:09 +0200764
Akron03a3c612021-08-04 11:51:27 +0200765 // Cache the loadfactor
Akron3f8571a2021-08-05 11:18:10 +0200766 if dat.loadFactor > 0 {
Akron03a3c612021-08-04 11:51:27 +0200767 return dat.loadFactor
Akron773b1ef2021-08-03 17:37:20 +0200768 }
Akrond66a9262021-08-03 17:09:09 +0200769 nonEmpty := 0
770 all := len(dat.array) / 2
Akronf1a16502021-08-16 15:24:38 +0200771 for x := 1; x < len(dat.array); x++ {
772 if dat.array[x].getBase() != 0 {
Akrond66a9262021-08-03 17:09:09 +0200773 nonEmpty++
774 }
775 }
Akron03a3c612021-08-04 11:51:27 +0200776 dat.loadFactor = float64(nonEmpty) / float64(all) * 100
777 return dat.loadFactor
Akrond66a9262021-08-03 17:09:09 +0200778}
779
Akron439f4ec2021-08-09 15:45:38 +0200780// Save stores the double array data in a file
Akron3a063ef2021-08-05 19:36:35 +0200781func (dat *DaTokenizer) Save(file string) (n int64, err error) {
782 f, err := os.Create(file)
783 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200784 log.Println(err)
Akron439f4ec2021-08-09 15:45:38 +0200785 return 0, err
Akron3a063ef2021-08-05 19:36:35 +0200786 }
787 defer f.Close()
788 gz := gzip.NewWriter(f)
789 defer gz.Close()
790 n, err = dat.WriteTo(gz)
791 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200792 log.Println(err)
Akron3a063ef2021-08-05 19:36:35 +0200793 return n, err
794 }
795 gz.Flush()
796 return n, nil
797}
798
799// WriteTo stores the double array data in an io.Writer.
Akron6247a5d2021-08-03 19:18:28 +0200800func (dat *DaTokenizer) WriteTo(w io.Writer) (n int64, err error) {
801
Akron3a063ef2021-08-05 19:36:35 +0200802 wb := bufio.NewWriter(w)
803 defer wb.Flush()
804
Akron6247a5d2021-08-03 19:18:28 +0200805 // Store magical header
Akron3a063ef2021-08-05 19:36:35 +0200806 all, err := wb.Write([]byte(MAGIC))
Akron6247a5d2021-08-03 19:18:28 +0200807 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200808 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200809 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200810 }
811
812 // Get sigma as a list
813 sigmalist := make([]rune, len(dat.sigma)+16)
814 max := 0
815 for sym, num := range dat.sigma {
816 sigmalist[num] = sym
817 if num > max {
818 max = num
819 }
820 }
821
822 sigmalist = sigmalist[:max+1]
823
Akron3f8571a2021-08-05 11:18:10 +0200824 buf := make([]byte, 0, 16)
Akron6247a5d2021-08-03 19:18:28 +0200825 bo.PutUint16(buf[0:2], VERSION)
Akronc17f1ca2021-08-03 19:47:27 +0200826 bo.PutUint16(buf[2:4], uint16(dat.epsilon))
827 bo.PutUint16(buf[4:6], uint16(dat.unknown))
828 bo.PutUint16(buf[6:8], uint16(dat.identity))
829 bo.PutUint16(buf[8:10], uint16(dat.final))
Akron6247a5d2021-08-03 19:18:28 +0200830 bo.PutUint16(buf[10:12], uint16(len(sigmalist)))
Akronf1a16502021-08-16 15:24:38 +0200831 bo.PutUint32(buf[12:16], uint32(len(dat.array)*2)) // Legacy support
Akron3a063ef2021-08-05 19:36:35 +0200832 more, err := wb.Write(buf[0:16])
Akron6247a5d2021-08-03 19:18:28 +0200833 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200834 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200835 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200836 }
837
838 all += more
839
Akron6247a5d2021-08-03 19:18:28 +0200840 // Write sigma
841 for _, sym := range sigmalist {
Akron3f8571a2021-08-05 11:18:10 +0200842
Akron3a063ef2021-08-05 19:36:35 +0200843 more, err = wb.WriteRune(sym)
Akron6247a5d2021-08-03 19:18:28 +0200844 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200845 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200846 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200847 }
848 all += more
849 }
Akron439f4ec2021-08-09 15:45:38 +0200850
Akron6247a5d2021-08-03 19:18:28 +0200851 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200852 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200853 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200854 }
Akron6247a5d2021-08-03 19:18:28 +0200855
856 // Test marker - could be checksum
Akron3a063ef2021-08-05 19:36:35 +0200857 more, err = wb.Write([]byte("T"))
Akron6247a5d2021-08-03 19:18:28 +0200858 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200859 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200860 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200861 }
862 all += more
863
Akronf1a16502021-08-16 15:24:38 +0200864 // for x := 0; x < len(dat.array); x++ {
865 for _, bc := range dat.array {
866 bo.PutUint32(buf[0:4], bc.base)
867 more, err = wb.Write(buf[0:4])
Akron6247a5d2021-08-03 19:18:28 +0200868 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200869 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200870 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200871 }
Akron439f4ec2021-08-09 15:45:38 +0200872 all += more
Akron3a063ef2021-08-05 19:36:35 +0200873 if more != 4 {
Akronf1a16502021-08-16 15:24:38 +0200874 log.Println("Can not write base uint32")
875 return int64(all), err
876 }
877 bo.PutUint32(buf[0:4], bc.check)
878 more, err = wb.Write(buf[0:4])
879 if err != nil {
880 log.Println(err)
881 return int64(all), err
882 }
883 all += more
884 if more != 4 {
885 log.Println("Can not write check uint32")
Akron3a063ef2021-08-05 19:36:35 +0200886 return int64(all), err
887 }
Akron6247a5d2021-08-03 19:18:28 +0200888 }
889
890 return int64(all), err
891}
892
Akron439f4ec2021-08-09 15:45:38 +0200893// LoadDatokFile reads a double array represented tokenizer
894// from a file.
Akron3f8571a2021-08-05 11:18:10 +0200895func LoadDatokFile(file string) *DaTokenizer {
896 f, err := os.Open(file)
897 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200898 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200899 return nil
Akron3f8571a2021-08-05 11:18:10 +0200900 }
901 defer f.Close()
902
903 gz, err := gzip.NewReader(f)
904 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200905 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200906 return nil
Akron3f8571a2021-08-05 11:18:10 +0200907 }
908 defer gz.Close()
909
Akron3a063ef2021-08-05 19:36:35 +0200910 // Todo: Read the whole file!
Akron3f8571a2021-08-05 11:18:10 +0200911 return ParseDatok(gz)
912}
913
Akron439f4ec2021-08-09 15:45:38 +0200914// LoadDatokFile reads a double array represented tokenizer
915// from an io.Reader
Akron3f8571a2021-08-05 11:18:10 +0200916func ParseDatok(ior io.Reader) *DaTokenizer {
917
Akron439f4ec2021-08-09 15:45:38 +0200918 // Initialize tokenizer with default values
Akron3f8571a2021-08-05 11:18:10 +0200919 dat := &DaTokenizer{
920 sigma: make(map[rune]int),
921 epsilon: 0,
922 unknown: 0,
923 identity: 0,
924 final: 0,
925 loadFactor: 0,
926 }
927
928 r := bufio.NewReader(ior)
929
Akron3f8571a2021-08-05 11:18:10 +0200930 buf := make([]byte, 1024)
931 buf = buf[0:len(MAGIC)]
932
Akron439f4ec2021-08-09 15:45:38 +0200933 _, err := r.Read(buf)
Akron3f8571a2021-08-05 11:18:10 +0200934
935 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200936 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200937 return nil
938 }
939
Akron3f8571a2021-08-05 11:18:10 +0200940 if string(MAGIC) != string(buf) {
Akron527c10c2021-08-13 01:45:18 +0200941 log.Println("Not a datok file")
Akron3f8571a2021-08-05 11:18:10 +0200942 return nil
943 }
944
Akron439f4ec2021-08-09 15:45:38 +0200945 more, err := io.ReadFull(r, buf[0:16])
Akron3f8571a2021-08-05 11:18:10 +0200946 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200947 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200948 return nil
949 }
950
Akron439f4ec2021-08-09 15:45:38 +0200951 if more != 16 {
Akron527c10c2021-08-13 01:45:18 +0200952 log.Println("Read bytes do not fit")
Akron439f4ec2021-08-09 15:45:38 +0200953 return nil
954 }
Akron3f8571a2021-08-05 11:18:10 +0200955
Akron3a063ef2021-08-05 19:36:35 +0200956 version := bo.Uint16(buf[0:2])
957
958 if version != VERSION {
Akron527c10c2021-08-13 01:45:18 +0200959 log.Println("Version not compatible")
Akron3a063ef2021-08-05 19:36:35 +0200960 return nil
961 }
962
Akron3f8571a2021-08-05 11:18:10 +0200963 dat.epsilon = int(bo.Uint16(buf[2:4]))
964 dat.unknown = int(bo.Uint16(buf[4:6]))
965 dat.identity = int(bo.Uint16(buf[6:8]))
966 dat.final = int(bo.Uint16(buf[8:10]))
967
968 sigmaCount := int(bo.Uint16(buf[10:12]))
Akronf1a16502021-08-16 15:24:38 +0200969 arraySize := int(bo.Uint32(buf[12:16])) / 2 // Legacy support
Akron3f8571a2021-08-05 11:18:10 +0200970
Akron3a063ef2021-08-05 19:36:35 +0200971 // Shouldn't be relevant though
972 dat.maxSize = arraySize - 1
973
Akron3f8571a2021-08-05 11:18:10 +0200974 for x := 0; x < sigmaCount; x++ {
Akron439f4ec2021-08-09 15:45:38 +0200975 sym, _, err := r.ReadRune()
Akron3f8571a2021-08-05 11:18:10 +0200976 if err == nil && sym != 0 {
Akronea46e8a2021-08-17 00:36:31 +0200977 if int(sym) < 256 {
978 dat.sigmaASCII[int(sym)] = x
979 }
Akron3f8571a2021-08-05 11:18:10 +0200980 dat.sigma[sym] = x
981 }
Akron3f8571a2021-08-05 11:18:10 +0200982 }
983
Akron439f4ec2021-08-09 15:45:38 +0200984 _, err = io.ReadFull(r, buf[0:1])
Akron3f8571a2021-08-05 11:18:10 +0200985
986 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200987 log.Print(err)
Akron3f8571a2021-08-05 11:18:10 +0200988 return nil
989 }
990
Akron3f8571a2021-08-05 11:18:10 +0200991 if string("T") != string(buf[0:1]) {
Akron527c10c2021-08-13 01:45:18 +0200992 log.Println("Not a datok file")
Akron3f8571a2021-08-05 11:18:10 +0200993 return nil
994 }
995
996 // Read based on length
Akronf1a16502021-08-16 15:24:38 +0200997 dat.array = make([]bc, arraySize)
Akron3f8571a2021-08-05 11:18:10 +0200998
Akronbb4aac52021-08-13 00:52:27 +0200999 dataArray, err := io.ReadAll(r)
Akron439f4ec2021-08-09 15:45:38 +02001000
Akronbb4aac52021-08-13 00:52:27 +02001001 if err == io.EOF {
Akron527c10c2021-08-13 01:45:18 +02001002 log.Println(err)
Akronbb4aac52021-08-13 00:52:27 +02001003 return nil
1004 }
1005
Akronf1a16502021-08-16 15:24:38 +02001006 if len(dataArray) < arraySize*8 {
Akron527c10c2021-08-13 01:45:18 +02001007 log.Println("Not enough bytes read")
Akronbb4aac52021-08-13 00:52:27 +02001008 return nil
1009 }
1010
1011 for x := 0; x < arraySize; x++ {
Akronf1a16502021-08-16 15:24:38 +02001012 dat.array[x].base = bo.Uint32(dataArray[x*8 : (x*8)+4])
1013 dat.array[x].check = bo.Uint32(dataArray[(x*8)+4 : (x*8)+8])
Akron3f8571a2021-08-05 11:18:10 +02001014 }
1015
1016 return dat
1017}
1018
Akron439f4ec2021-08-09 15:45:38 +02001019// Show the current state of the buffer,
1020// for testing puroses
Akron3610f102021-08-08 14:13:25 +02001021func showBuffer(buffer []rune, buffo int, buffi int) string {
1022 out := make([]rune, 0, 1024)
1023 for x := 0; x < len(buffer); x++ {
1024 if buffi == x {
1025 out = append(out, '^')
1026 }
1027 if buffo == x {
1028 out = append(out, '[', buffer[x], ']')
1029 } else {
1030 out = append(out, buffer[x])
1031 }
1032 }
1033 return string(out)
1034}
1035
Akron84d68e62021-08-04 17:06:52 +02001036// Transduce an input string against the double array
Akron3610f102021-08-08 14:13:25 +02001037// FSA. The rules are always greedy. If the automaton fails,
1038// it takes the last possible token ending branch.
Akron068874c2021-08-04 15:19:56 +02001039//
Akron4db3ecf2021-08-11 18:49:03 +02001040// Based on Mizobuchi et al (2000), p. 129,
1041// with additional support for IDENTITY, UNKNOWN
1042// and EPSILON transitions and NONTOKEN and TOKENEND handling.
Akron3f8571a2021-08-05 11:18:10 +02001043func (dat *DaTokenizer) Transduce(r io.Reader, w io.Writer) bool {
Akron068874c2021-08-04 15:19:56 +02001044 var a int
Akronb4bbb472021-08-09 11:49:38 +02001045 var t0 uint32
Akronb7e1f132021-08-10 11:52:31 +02001046 t := uint32(1) // Initial state
1047 var ok, rewindBuffer bool
Akron068874c2021-08-04 15:19:56 +02001048
Akron3610f102021-08-08 14:13:25 +02001049 // Remember the last position of a possible tokenend,
1050 // in case the automaton fails.
1051 epsilonState := uint32(0)
1052 epsilonOffset := 0
1053
1054 // Implement a low level buffer for full control,
1055 // however - it is probably better to introduce
1056 // this on a higher level with a io.Reader interface
1057 // The buffer stores a single word and may have white
1058 // space at the end (but not at the beginning).
1059 //
1060 // This is the only backtracking requirement because of
1061 // epsilon transitions, to support tokenizations like:
1062 // "this is an example|.| And it works." vs
1063 // "this is an example.com| application."
Akronb7e1f132021-08-10 11:52:31 +02001064 //
1065 // TODO:
1066 // Store a translation buffer as well, so characters don't
1067 // have to be translated multiple times!
Akron3610f102021-08-08 14:13:25 +02001068 buffer := make([]rune, 1024)
1069 buffo := 0 // Buffer offset
1070 buffi := 0 // Buffer length
1071
Akron3f8571a2021-08-05 11:18:10 +02001072 reader := bufio.NewReader(r)
1073 writer := bufio.NewWriter(w)
1074 defer writer.Flush()
Akron068874c2021-08-04 15:19:56 +02001075
Akron3f8571a2021-08-05 11:18:10 +02001076 var char rune
1077 var err error
1078 eof := false
Akronb7e1f132021-08-10 11:52:31 +02001079 newchar := true
Akron3f8571a2021-08-05 11:18:10 +02001080
Akronc5d8d432021-08-10 16:48:44 +02001081PARSECHAR:
Akron3f8571a2021-08-05 11:18:10 +02001082 for {
1083
Akronb7e1f132021-08-10 11:52:31 +02001084 if newchar {
1085 // Get from reader if buffer is empty
1086 if buffo >= buffi {
Akron1594cb82021-08-11 11:14:56 +02001087 if eof {
1088 break
1089 }
Akronb7e1f132021-08-10 11:52:31 +02001090 char, _, err = reader.ReadRune()
Akron439f4ec2021-08-09 15:45:38 +02001091
Akronb7e1f132021-08-10 11:52:31 +02001092 // No more runes to read
1093 if err != nil {
1094 eof = true
1095 break
1096 }
1097 buffer[buffi] = char
1098 buffi++
Akron3f8571a2021-08-05 11:18:10 +02001099 }
Akronb7e1f132021-08-10 11:52:31 +02001100
1101 char = buffer[buffo]
1102
1103 if DEBUG {
1104 fmt.Println("Current char", string(char), showBuffer(buffer, buffo, buffi))
1105 }
1106
Akron6f1c16c2021-08-17 10:45:42 +02001107 // TODO:
1108 // Better not repeatedly check for a!
1109 // Possibly keep a buffer with a.
Akronea46e8a2021-08-17 00:36:31 +02001110 if int(char) < 256 {
1111 a = dat.sigmaASCII[int(char)]
1112 } else {
1113 a, ok = dat.sigma[char]
1114 if !ok {
1115 a = 0
1116 }
1117 }
Akronb7e1f132021-08-10 11:52:31 +02001118
1119 // Use identity symbol if character is not in sigma
Akronea46e8a2021-08-17 00:36:31 +02001120 if a == 0 && dat.identity != -1 {
Akronb7e1f132021-08-10 11:52:31 +02001121 a = dat.identity
1122 }
1123
1124 t0 = t
1125
1126 // Check for epsilon transitions and remember
Akronf1a16502021-08-16 15:24:38 +02001127 if dat.array[dat.array[t0].getBase()+uint32(dat.epsilon)].getCheck() == t0 {
Akronb7e1f132021-08-10 11:52:31 +02001128 // Remember state for backtracking to last tokenend state
1129 epsilonState = t0
1130 epsilonOffset = buffo
1131 }
Akron3f8571a2021-08-05 11:18:10 +02001132 }
Akron3610f102021-08-08 14:13:25 +02001133
Akronb7e1f132021-08-10 11:52:31 +02001134 // Checks a transition based on t0, a and buffo
Akronf1a16502021-08-16 15:24:38 +02001135 t = dat.array[t0].getBase() + uint32(a)
1136 ta := dat.array[t]
Akron068874c2021-08-04 15:19:56 +02001137
Akron524c5432021-08-05 14:14:27 +02001138 if DEBUG {
Akronb7e1f132021-08-10 11:52:31 +02001139 // Char is only relevant if set
1140 fmt.Println("Check", t0, "-", a, "(", string(char), ")", "->", t)
1141 if false {
1142 fmt.Println(dat.outgoing(t0))
1143 }
Akron524c5432021-08-05 14:14:27 +02001144 }
1145
Akronb7e1f132021-08-10 11:52:31 +02001146 // Check if the transition is invalid according to the double array
Akronf1a16502021-08-16 15:24:38 +02001147 if t > dat.array[1].getCheck() || ta.getCheck() != t0 {
Akron068874c2021-08-04 15:19:56 +02001148
1149 if DEBUG {
Akronf1a16502021-08-16 15:24:38 +02001150 fmt.Println("Match is not fine!", t, "and", ta.getCheck(), "vs", t0)
Akron068874c2021-08-04 15:19:56 +02001151 }
1152
1153 if !ok && a == dat.identity {
Akronb4bbb472021-08-09 11:49:38 +02001154
Akron068874c2021-08-04 15:19:56 +02001155 // Try again with unknown symbol, in case identity failed
Akronb7e1f132021-08-10 11:52:31 +02001156 // Char is only relevant when set
Akron068874c2021-08-04 15:19:56 +02001157 if DEBUG {
Akron3f8571a2021-08-05 11:18:10 +02001158 fmt.Println("UNKNOWN symbol", string(char), "->", dat.unknown)
Akron068874c2021-08-04 15:19:56 +02001159 }
1160 a = dat.unknown
1161
1162 } else if a != dat.epsilon {
Akronb4bbb472021-08-09 11:49:38 +02001163
Akron068874c2021-08-04 15:19:56 +02001164 // Try again with epsilon symbol, in case everything else failed
Akronb4bbb472021-08-09 11:49:38 +02001165 t0 = epsilonState
Akron3610f102021-08-08 14:13:25 +02001166 epsilonState = 0 // reset
1167 buffo = epsilonOffset
Akron439f4ec2021-08-09 15:45:38 +02001168 a = dat.epsilon
1169
Akron3610f102021-08-08 14:13:25 +02001170 if DEBUG {
1171 fmt.Println("Get from epsilon stack and set buffo!", showBuffer(buffer, buffo, buffi))
1172 }
Akronb4bbb472021-08-09 11:49:38 +02001173
Akron068874c2021-08-04 15:19:56 +02001174 } else {
1175 break
1176 }
Akron068874c2021-08-04 15:19:56 +02001177
Akronb7e1f132021-08-10 11:52:31 +02001178 newchar = false
1179 continue
Akronb4bbb472021-08-09 11:49:38 +02001180 }
1181
Akronb7e1f132021-08-10 11:52:31 +02001182 // Transition was successful
1183 rewindBuffer = false
Akron439f4ec2021-08-09 15:45:38 +02001184
1185 // Transition consumes a character
Akronb4bbb472021-08-09 11:49:38 +02001186 if a != dat.epsilon {
1187
Akron3610f102021-08-08 14:13:25 +02001188 buffo++
Akronb4bbb472021-08-09 11:49:38 +02001189
Akron439f4ec2021-08-09 15:45:38 +02001190 // Transition does not produce a character
Akronf1a16502021-08-16 15:24:38 +02001191 if buffo == 1 && ta.isNonToken() {
Akron3610f102021-08-08 14:13:25 +02001192 if DEBUG {
1193 fmt.Println("Nontoken forward", showBuffer(buffer, buffo, buffi))
1194 }
Akron439f4ec2021-08-09 15:45:38 +02001195 rewindBuffer = true
Akron3610f102021-08-08 14:13:25 +02001196 }
Akron3f8571a2021-08-05 11:18:10 +02001197 }
Akron068874c2021-08-04 15:19:56 +02001198
Akronc5d8d432021-08-10 16:48:44 +02001199 // Transition marks the end of a token - so flush the buffer
Akronf1a16502021-08-16 15:24:38 +02001200 if ta.isTokenEnd() {
Akron524c5432021-08-05 14:14:27 +02001201
Akronc5d8d432021-08-10 16:48:44 +02001202 if buffi > 0 {
Akronc5d8d432021-08-10 16:48:44 +02001203 if DEBUG {
Akron01912fc2021-08-12 11:41:58 +02001204 fmt.Println("-> Flush buffer: [", string(buffer[:buffo]), "]", showBuffer(buffer, buffo, buffi))
Akronc5d8d432021-08-10 16:48:44 +02001205 }
Akron01912fc2021-08-12 11:41:58 +02001206 writer.WriteString(string(buffer[:buffo]))
Akronc5d8d432021-08-10 16:48:44 +02001207 rewindBuffer = true
Akron3610f102021-08-08 14:13:25 +02001208 }
Akron1594cb82021-08-11 11:14:56 +02001209 if DEBUG {
1210 fmt.Println("-> Newline")
1211 }
1212 writer.WriteRune('\n')
Akron439f4ec2021-08-09 15:45:38 +02001213 }
Akron3610f102021-08-08 14:13:25 +02001214
Akronc5d8d432021-08-10 16:48:44 +02001215 // Rewind the buffer if necessary
Akron439f4ec2021-08-09 15:45:38 +02001216 if rewindBuffer {
1217
1218 // TODO: Better as a ring buffer
Akron3610f102021-08-08 14:13:25 +02001219 for x, i := range buffer[buffo:buffi] {
1220 buffer[x] = i
1221 }
Akronb4bbb472021-08-09 11:49:38 +02001222
Akron3610f102021-08-08 14:13:25 +02001223 buffi -= buffo
1224 epsilonOffset -= buffo
1225 buffo = 0
1226 if DEBUG {
Akronb4bbb472021-08-09 11:49:38 +02001227 fmt.Println("Remaining:", showBuffer(buffer, buffo, buffi))
Akron3610f102021-08-08 14:13:25 +02001228 }
Akron84d68e62021-08-04 17:06:52 +02001229 }
1230
Akronb7e1f132021-08-10 11:52:31 +02001231 // Move to representative state
Akronf1a16502021-08-16 15:24:38 +02001232 if ta.isSeparate() {
1233 t = ta.getBase()
1234 ta = dat.array[t]
Akronb7e1f132021-08-10 11:52:31 +02001235
1236 if DEBUG {
1237 fmt.Println("Representative pointing to", t)
1238 }
1239 }
1240
Akronc5d8d432021-08-10 16:48:44 +02001241 newchar = true
1242
Akron068874c2021-08-04 15:19:56 +02001243 // TODO:
1244 // Prevent endless epsilon loops!
1245 }
1246
Akron439f4ec2021-08-09 15:45:38 +02001247 // Input reader is not yet finished
Akron3f8571a2021-08-05 11:18:10 +02001248 if !eof {
Akron068874c2021-08-04 15:19:56 +02001249 if DEBUG {
Akronb4bbb472021-08-09 11:49:38 +02001250 fmt.Println("Not at the end - problem", t0, ":", dat.outgoing(t0))
Akron068874c2021-08-04 15:19:56 +02001251 }
1252 return false
1253 }
1254
Akronb7e1f132021-08-10 11:52:31 +02001255 if DEBUG {
1256 fmt.Println("Entering final check")
1257 }
1258
Akronc5d8d432021-08-10 16:48:44 +02001259 // Automaton is in a final state, so flush the buffer and return
Akronf1a16502021-08-16 15:24:38 +02001260 x := dat.array[t].getBase() + uint32(dat.final)
1261
1262 if x < dat.array[1].getCheck() && dat.array[x].getCheck() == t {
Akronb4bbb472021-08-09 11:49:38 +02001263
1264 if buffi > 0 {
Akronb4bbb472021-08-09 11:49:38 +02001265 if DEBUG {
Akron01912fc2021-08-12 11:41:58 +02001266 fmt.Println("-> Flush buffer: [", string(buffer[:buffi]), "]")
Akron3f8571a2021-08-05 11:18:10 +02001267 }
Akron01912fc2021-08-12 11:41:58 +02001268 writer.WriteString(string(buffer[:buffi]))
Akron6e70dc82021-08-11 11:33:18 +02001269
Akronf1a16502021-08-16 15:24:38 +02001270 if dat.array[t].isTokenEnd() {
Akrondf0a3ef2021-08-09 15:53:45 +02001271 writer.WriteRune('\n')
Akronc5d8d432021-08-10 16:48:44 +02001272 if DEBUG {
1273 fmt.Println("-> Newline")
1274 }
Akrondf0a3ef2021-08-09 15:53:45 +02001275 }
Akron84d68e62021-08-04 17:06:52 +02001276 }
1277
Akron6e70dc82021-08-11 11:33:18 +02001278 // Add an additional sentence ending, if the file is over but no explicit
1279 // sentence split was reached. This may be controversial and therefore
1280 // optional via parameter.
Akronf1a16502021-08-16 15:24:38 +02001281 if !dat.array[t0].isTokenEnd() {
Akron6e70dc82021-08-11 11:33:18 +02001282 writer.WriteRune('\n')
1283 if DEBUG {
1284 fmt.Println("-> Newline")
1285 }
1286 }
1287
Akrone61380b2021-08-16 10:10:46 +02001288 // TODO:
1289 // There may be a new line at the end, from an epsilon,
1290 // so we may need to go on!
Akron068874c2021-08-04 15:19:56 +02001291 return true
1292 }
1293
Akronc5d8d432021-08-10 16:48:44 +02001294 // Check epsilon transitions until a final state is reached
1295 t0 = t
Akronf1a16502021-08-16 15:24:38 +02001296 t = dat.array[t0].getBase() + uint32(dat.epsilon)
Akron01912fc2021-08-12 11:41:58 +02001297 a = dat.epsilon
1298 newchar = false
Akronf1a16502021-08-16 15:24:38 +02001299 if dat.array[t].getCheck() == t0 {
Akronc5d8d432021-08-10 16:48:44 +02001300 // Remember state for backtracking to last tokenend state
Akronc5d8d432021-08-10 16:48:44 +02001301 goto PARSECHAR
Akrone61380b2021-08-16 10:10:46 +02001302
Akronc5d8d432021-08-10 16:48:44 +02001303 } else if epsilonState != 0 {
Akronb7e1f132021-08-10 11:52:31 +02001304 t0 = epsilonState
1305 epsilonState = 0 // reset
1306 buffo = epsilonOffset
Akron068874c2021-08-04 15:19:56 +02001307 if DEBUG {
Akronc5d8d432021-08-10 16:48:44 +02001308 fmt.Println("Get from epsilon stack and set buffo!", showBuffer(buffer, buffo, buffi))
Akron068874c2021-08-04 15:19:56 +02001309 }
Akronc5d8d432021-08-10 16:48:44 +02001310 goto PARSECHAR
Akron068874c2021-08-04 15:19:56 +02001311 }
Akronc5d8d432021-08-10 16:48:44 +02001312 return false
Akron068874c2021-08-04 15:19:56 +02001313}