blob: f455ec3629a7b98254e43ed196f9b0ca6fb96f88 [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:
17// - replace maxSize with the check value
Akron3a063ef2021-08-05 19:36:35 +020018// - Add checksum to serialization.
Akrone61380b2021-08-16 10:10:46 +020019// - Replace/Enhance table with a map
20// - Provide a bufio.Scanner compatible interface.
Akron8e1d69b2021-08-12 17:38:49 +020021// - Mark epsilon transitions in bytes
Akron740f3d72021-08-03 12:12:34 +020022
Akron8ef408b2021-08-02 22:11:04 +020023import (
24 "bufio"
25 "compress/gzip"
Akron6247a5d2021-08-03 19:18:28 +020026 "encoding/binary"
Akron8ef408b2021-08-02 22:11:04 +020027 "fmt"
28 "io"
29 "os"
Akronc9d84a62021-08-03 15:56:03 +020030 "sort"
Akron8ef408b2021-08-02 22:11:04 +020031 "strconv"
32 "strings"
33 "unicode/utf8"
Akron740f3d72021-08-03 12:12:34 +020034
Akron527c10c2021-08-13 01:45:18 +020035 "log"
Akron8ef408b2021-08-02 22:11:04 +020036)
37
38const (
Akron2a4b9292021-08-04 15:35:22 +020039 PROPS = 1
40 SIGMA = 2
41 STATES = 3
42 NONE = 4
Akron2a4b9292021-08-04 15:35:22 +020043 DEBUG = false
44 MAGIC = "DATOK"
45 VERSION = uint16(1)
Akron03c92fe2021-08-09 14:07:57 +020046 FIRSTBIT uint32 = 1 << 31
47 SECONDBIT uint32 = 1 << 30
48 RESTBIT uint32 = ^uint32(0) &^ (FIRSTBIT | SECONDBIT)
Akron8ef408b2021-08-02 22:11:04 +020049)
50
Akron03c92fe2021-08-09 14:07:57 +020051// Serialization is always little endian
Akron6247a5d2021-08-03 19:18:28 +020052var bo binary.ByteOrder = binary.LittleEndian
53
Akron8ef408b2021-08-02 22:11:04 +020054type mapping struct {
55 source int
Akron3fdfec62021-08-04 11:40:10 +020056 target uint32
Akron8ef408b2021-08-02 22:11:04 +020057}
58
59type edge struct {
Akron83e75a22021-08-04 13:14:06 +020060 inSym int
61 outSym int
62 end int
63 nontoken bool
64 tokenend bool
Akron8ef408b2021-08-02 22:11:04 +020065}
66
Akron03c92fe2021-08-09 14:07:57 +020067// Tokenizer is the intermediate representation
68// of the tokenizer.
Akron8ef408b2021-08-02 22:11:04 +020069type Tokenizer struct {
Akron740f3d72021-08-03 12:12:34 +020070 sigmaRev map[int]rune
Akron31f3c062021-08-27 10:15:13 +020071 sigmaMCS map[int]string
Akron740f3d72021-08-03 12:12:34 +020072 arcCount int
Akron740f3d72021-08-03 12:12:34 +020073 sigmaCount int
Akron8ef408b2021-08-02 22:11:04 +020074 transitions []map[int]*edge
Akronc17f1ca2021-08-03 19:47:27 +020075
76 // Special symbols in sigma
77 epsilon int
78 unknown int
79 identity int
80 final int
Akron03c92fe2021-08-09 14:07:57 +020081 tokenend int
Akron8ef408b2021-08-02 22:11:04 +020082}
83
Akronf1a16502021-08-16 15:24:38 +020084type bc struct {
85 base uint32
86 check uint32
87}
88
Akron03c92fe2021-08-09 14:07:57 +020089// DaTokenizer represents a tokenizer implemented as a
90// Double Array FSA.
Akronf2120ca2021-08-03 16:26:41 +020091type DaTokenizer struct {
Akronea46e8a2021-08-17 00:36:31 +020092 sigma map[rune]int
93 sigmaASCII [256]int
Akron03a3c612021-08-04 11:51:27 +020094 maxSize int
Akron4fa28b32021-08-27 10:55:41 +020095 transCount int
Akronf1a16502021-08-16 15:24:38 +020096 array []bc
Akronc17f1ca2021-08-03 19:47:27 +020097
98 // Special symbols in sigma
99 epsilon int
100 unknown int
101 identity int
102 final int
Akron03c92fe2021-08-09 14:07:57 +0200103 tokenend int
Akronf2120ca2021-08-03 16:26:41 +0200104}
105
Akron03c92fe2021-08-09 14:07:57 +0200106// ParseFoma reads the FST from a foma file
107// and creates an internal representation,
108// in case it follows the tokenizer's convention.
Akron64ffd9a2021-08-03 19:55:21 +0200109func LoadFomaFile(file string) *Tokenizer {
Akron8ef408b2021-08-02 22:11:04 +0200110 f, err := os.Open(file)
111 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200112 log.Print(err)
Akron4db3ecf2021-08-11 18:49:03 +0200113 return nil
Akron8ef408b2021-08-02 22:11:04 +0200114 }
115 defer f.Close()
116
117 gz, err := gzip.NewReader(f)
118 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200119 log.Print(err)
Akron4db3ecf2021-08-11 18:49:03 +0200120 return nil
Akron8ef408b2021-08-02 22:11:04 +0200121 }
122 defer gz.Close()
123
Akron3fdfec62021-08-04 11:40:10 +0200124 return ParseFoma(gz)
Akron8ef408b2021-08-02 22:11:04 +0200125}
126
Akron03c92fe2021-08-09 14:07:57 +0200127// ParseFoma reads the FST from a foma file reader
128// and creates an internal representation,
129// in case it follows the tokenizer's convention.
Akron3fdfec62021-08-04 11:40:10 +0200130func ParseFoma(ior io.Reader) *Tokenizer {
Akron8ef408b2021-08-02 22:11:04 +0200131 r := bufio.NewReader(ior)
132
133 tok := &Tokenizer{
Akron740f3d72021-08-03 12:12:34 +0200134 sigmaRev: make(map[int]rune),
Akron31f3c062021-08-27 10:15:13 +0200135 sigmaMCS: make(map[int]string),
Akronc17f1ca2021-08-03 19:47:27 +0200136 epsilon: -1,
137 unknown: -1,
138 identity: -1,
139 final: -1,
Akron03c92fe2021-08-09 14:07:57 +0200140 tokenend: -1,
Akron8ef408b2021-08-02 22:11:04 +0200141 }
142
Akron740f3d72021-08-03 12:12:34 +0200143 var state, inSym, outSym, end, final int
Akron8ef408b2021-08-02 22:11:04 +0200144
145 mode := 0
146 var elem []string
147 var elemint [5]int
148
Akron03c92fe2021-08-09 14:07:57 +0200149 // Iterate over all lines of the file.
150 // This is mainly based on foma2js,
151 // licensed under the Apache License, version 2,
152 // and written by Mans Hulden.
Akron8ef408b2021-08-02 22:11:04 +0200153 for {
154 line, err := r.ReadString('\n')
155 if err != nil {
156 if err == io.EOF {
157 break
158 }
Akron527c10c2021-08-13 01:45:18 +0200159 log.Print(err)
Akron4db3ecf2021-08-11 18:49:03 +0200160 return nil
Akron8ef408b2021-08-02 22:11:04 +0200161 }
Akron8ef408b2021-08-02 22:11:04 +0200162
Akron439f4ec2021-08-09 15:45:38 +0200163 // Read parser mode for the following lines
164 if strings.HasPrefix(line, "##") {
165 if strings.HasPrefix(line, "##props##") {
166 mode = PROPS
167
168 } else if strings.HasPrefix(line, "##states##") {
169 mode = STATES
170
171 // Adds a final transition symbol to sigma
172 // written as '#' in Mizobuchi et al (2000)
173 tok.sigmaCount++
174 tok.final = tok.sigmaCount
175
176 } else if strings.HasPrefix(line, "##sigma##") {
177
178 mode = SIGMA
179
180 } else if strings.HasPrefix(line, "##end##") {
181
182 mode = NONE
183
184 } else if !strings.HasPrefix(line, "##foma-net") {
Akron527c10c2021-08-13 01:45:18 +0200185 log.Print("Unknown input line")
Akron439f4ec2021-08-09 15:45:38 +0200186 break
187 }
Akron8ef408b2021-08-02 22:11:04 +0200188 continue
189 }
190
Akron439f4ec2021-08-09 15:45:38 +0200191 // Based on the current parser mode, interpret the lines
Akron8ef408b2021-08-02 22:11:04 +0200192 switch mode {
193 case PROPS:
194 {
195 elem = strings.Split(line, " ")
196 /*
197 fmt.Println("arity: " + elem[0])
198 fmt.Println("arccount: " + elem[1])
199 fmt.Println("statecount: " + elem[2])
200 fmt.Println("linecount: " + elem[3])
201 fmt.Println("finalcount: " + elem[4])
202 fmt.Println("pathcount: " + elem[5])
203 fmt.Println("is_deterministic: " + elem[6])
204 fmt.Println("is_pruned: " + elem[7])
205 fmt.Println("is_minimized: " + elem[8])
206 fmt.Println("is_epsilon_free: " + elem[9])
207 fmt.Println("is_loop_free: " + elem[10])
208 fmt.Println("extras: " + elem[11])
209 fmt.Println("name: " + elem[12])
210 */
211 if elem[6] != "1" {
Akron527c10c2021-08-13 01:45:18 +0200212 log.Print("The FST needs to be deterministic")
Akron4db3ecf2021-08-11 18:49:03 +0200213 return nil
Akron8ef408b2021-08-02 22:11:04 +0200214 }
Akron439f4ec2021-08-09 15:45:38 +0200215
Akron8ef408b2021-08-02 22:11:04 +0200216 if elem[9] != "1" {
Akron527c10c2021-08-13 01:45:18 +0200217 log.Print("The FST needs to be epsilon free")
Akron4db3ecf2021-08-11 18:49:03 +0200218 return nil
Akron8ef408b2021-08-02 22:11:04 +0200219 }
220
221 elemint[0], err = strconv.Atoi(elem[1])
222 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200223 log.Print("Can't read arccount")
Akron4db3ecf2021-08-11 18:49:03 +0200224 return nil
Akron8ef408b2021-08-02 22:11:04 +0200225 }
Akron740f3d72021-08-03 12:12:34 +0200226 tok.arcCount = elemint[0]
Akron8ef408b2021-08-02 22:11:04 +0200227
Akron8ef408b2021-08-02 22:11:04 +0200228 elemint[0], err = strconv.Atoi(elem[2])
229 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200230 log.Print("Can't read statecount")
Akron4db3ecf2021-08-11 18:49:03 +0200231 return nil
Akron8ef408b2021-08-02 22:11:04 +0200232 }
Akron439f4ec2021-08-09 15:45:38 +0200233
234 // States start at 1 in Mizobuchi et al (2000),
235 // as the state 0 is associated with a fail.
236 // Initialize states and transitions
Akron8ef408b2021-08-02 22:11:04 +0200237 tok.transitions = make([]map[int]*edge, elemint[0]+1)
238 continue
239 }
240 case STATES:
241 {
242 elem = strings.Split(line[0:len(line)-1], " ")
243 if elem[0] == "-1" {
Akron3610f102021-08-08 14:13:25 +0200244 if DEBUG {
245 fmt.Println("Skip", elem)
246 }
Akron8ef408b2021-08-02 22:11:04 +0200247 continue
248 }
249 elemint[0], err = strconv.Atoi(elem[0])
Akron75ebe7f2021-08-03 10:34:10 +0200250 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200251 fmt.Println("Unable to translate", elem[0])
Akron75ebe7f2021-08-03 10:34:10 +0200252 break
253 }
Akron8ef408b2021-08-02 22:11:04 +0200254
255 if len(elem) > 1 {
256 elemint[1], err = strconv.Atoi(elem[1])
257 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200258 fmt.Println("Unable to translate", elem[1])
Akron8ef408b2021-08-02 22:11:04 +0200259 break
260 }
261 if len(elem) > 2 {
262 elemint[2], err = strconv.Atoi(elem[2])
263 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200264 fmt.Println("Unable to translate", elem[2])
Akron8ef408b2021-08-02 22:11:04 +0200265 break
266 }
267 if len(elem) > 3 {
268 elemint[3], err = strconv.Atoi(elem[3])
269 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200270 fmt.Println("Unable to translate", elem[3])
Akron8ef408b2021-08-02 22:11:04 +0200271 break
272 }
273 if len(elem) > 4 {
274 elemint[4], err = strconv.Atoi(elem[4])
275 if err != nil {
Akron3610f102021-08-08 14:13:25 +0200276 fmt.Println("Unable to translate", elem[4])
Akron8ef408b2021-08-02 22:11:04 +0200277 break
278 }
279 }
280 }
281 }
282 }
283
284 switch len(elem) {
285 case 5:
286 {
Akron740f3d72021-08-03 12:12:34 +0200287 state = elemint[0]
288 inSym = elemint[1]
289 outSym = elemint[2]
290 end = elemint[3]
291 final = elemint[4]
Akron8ef408b2021-08-02 22:11:04 +0200292 }
293 case 4:
294 {
295 if elemint[1] == -1 {
Akron740f3d72021-08-03 12:12:34 +0200296 state = elemint[0]
297 final = elemint[3]
Akron8ef408b2021-08-02 22:11:04 +0200298 } else {
Akron740f3d72021-08-03 12:12:34 +0200299 state = elemint[0]
300 inSym = elemint[1]
301 end = elemint[2]
302 final = elemint[3]
303 outSym = inSym
Akron8ef408b2021-08-02 22:11:04 +0200304 }
305 }
306 case 3:
307 {
Akron740f3d72021-08-03 12:12:34 +0200308 inSym = elemint[0]
309 outSym = elemint[1]
310 end = elemint[2]
Akron8ef408b2021-08-02 22:11:04 +0200311 }
312 case 2:
313 {
Akron740f3d72021-08-03 12:12:34 +0200314 inSym = elemint[0]
315 end = elemint[1]
316 outSym = inSym
Akron8ef408b2021-08-02 22:11:04 +0200317 }
318 }
319
Akron83e75a22021-08-04 13:14:06 +0200320 nontoken := false
321 tokenend := false
322
Akron439f4ec2021-08-09 15:45:38 +0200323 // While the states in foma start with 0, the states in the
324 // Mizobuchi FSA start with one - so we increase every state by 1.
325 // We also increase sigma by 1, so there are no 0 transitions.
Akron524c5432021-08-05 14:14:27 +0200326 inSym++
327 outSym++
328
Akron439f4ec2021-08-09 15:45:38 +0200329 // Only a limited list of transitions are allowed
Akron740f3d72021-08-03 12:12:34 +0200330 if inSym != outSym {
Akron01912fc2021-08-12 11:41:58 +0200331 if outSym == tok.tokenend && inSym == tok.epsilon {
Akron83e75a22021-08-04 13:14:06 +0200332 tokenend = true
333 } else if outSym == tok.epsilon {
334 nontoken = true
335 } else {
Akron527c10c2021-08-13 01:45:18 +0200336 log.Println(
Akron740f3d72021-08-03 12:12:34 +0200337 "Unsupported transition: " +
338 strconv.Itoa(state) +
339 " -> " + strconv.Itoa(end) +
Akron75ebe7f2021-08-03 10:34:10 +0200340 " (" +
Akron740f3d72021-08-03 12:12:34 +0200341 strconv.Itoa(inSym) +
Akron75ebe7f2021-08-03 10:34:10 +0200342 ":" +
Akron740f3d72021-08-03 12:12:34 +0200343 strconv.Itoa(outSym) +
Akron75ebe7f2021-08-03 10:34:10 +0200344 ") (" +
Akron740f3d72021-08-03 12:12:34 +0200345 string(tok.sigmaRev[inSym]) +
Akron75ebe7f2021-08-03 10:34:10 +0200346 ":" +
Akron740f3d72021-08-03 12:12:34 +0200347 string(tok.sigmaRev[outSym]) +
Akron75ebe7f2021-08-03 10:34:10 +0200348 ")")
Akron4db3ecf2021-08-11 18:49:03 +0200349 return nil
Akron75ebe7f2021-08-03 10:34:10 +0200350 }
Akron92704eb2021-08-27 10:59:46 +0200351 } else if inSym == tok.tokenend {
352 // Ignore tokenend accepting arcs
353 continue
Akron83e75a22021-08-04 13:14:06 +0200354 } else if inSym == tok.epsilon {
Akron527c10c2021-08-13 01:45:18 +0200355 log.Println("General epsilon transitions are not supported")
Akron4db3ecf2021-08-11 18:49:03 +0200356 return nil
Akron31f3c062021-08-27 10:15:13 +0200357 } else if tok.sigmaMCS[inSym] != "" {
358 log.Fatalln("Non supported character", tok.sigmaMCS[inSym])
359 } else if tok.sigmaMCS[outSym] != "" {
360 log.Fatalln("Non supported character", tok.sigmaMCS[outSym])
Akron8ef408b2021-08-02 22:11:04 +0200361 }
362
Akron03c92fe2021-08-09 14:07:57 +0200363 // Create an edge based on the collected information
Akron8ef408b2021-08-02 22:11:04 +0200364 targetObj := &edge{
Akron83e75a22021-08-04 13:14:06 +0200365 inSym: inSym,
366 outSym: outSym,
367 end: end + 1,
368 tokenend: tokenend,
369 nontoken: nontoken,
Akron8ef408b2021-08-02 22:11:04 +0200370 }
371
Akron740f3d72021-08-03 12:12:34 +0200372 // Initialize outgoing states
373 if tok.transitions[state+1] == nil {
374 tok.transitions[state+1] = make(map[int]*edge)
Akron8ef408b2021-08-02 22:11:04 +0200375 }
376
Akron740f3d72021-08-03 12:12:34 +0200377 // Ignore transitions with invalid symbols
378 if inSym >= 0 {
379 tok.transitions[state+1][inSym] = targetObj
Akron75ebe7f2021-08-03 10:34:10 +0200380 }
Akron8ef408b2021-08-02 22:11:04 +0200381
Akron740f3d72021-08-03 12:12:34 +0200382 // Add final transition
383 if final == 1 {
Akron03c92fe2021-08-09 14:07:57 +0200384 // TODO:
385 // Maybe this is less relevant for tokenizers
Akronc17f1ca2021-08-03 19:47:27 +0200386 tok.transitions[state+1][tok.final] = &edge{}
Akron8ef408b2021-08-02 22:11:04 +0200387 }
388
Akronb4bbb472021-08-09 11:49:38 +0200389 if DEBUG {
Akron740f3d72021-08-03 12:12:34 +0200390 fmt.Println("Add",
391 state+1, "->", end+1,
392 "(",
393 inSym,
394 ":",
395 outSym,
396 ") (",
397 string(tok.sigmaRev[inSym]),
398 ":",
399 string(tok.sigmaRev[outSym]),
Akron524c5432021-08-05 14:14:27 +0200400 ")",
401 ";",
402 "TE:", tokenend,
Akron3610f102021-08-08 14:13:25 +0200403 "NT:", nontoken,
404 "FIN:", final)
Akron740f3d72021-08-03 12:12:34 +0200405 }
Akron75ebe7f2021-08-03 10:34:10 +0200406
Akron8ef408b2021-08-02 22:11:04 +0200407 continue
408 }
409 case SIGMA:
410 {
411 elem = strings.SplitN(line[0:len(line)-1], " ", 2)
412
413 // Turn string into sigma id
414 number, err := strconv.Atoi(elem[0])
415
Akron524c5432021-08-05 14:14:27 +0200416 // ID needs to be > 1
417 number++
418
Akron8ef408b2021-08-02 22:11:04 +0200419 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200420 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200421 return nil
Akron8ef408b2021-08-02 22:11:04 +0200422 }
423
Akron740f3d72021-08-03 12:12:34 +0200424 tok.sigmaCount = number
Akron8ef408b2021-08-02 22:11:04 +0200425
426 var symbol rune
427
428 // Read rune
429 if utf8.RuneCountInString(elem[1]) == 1 {
430 symbol = []rune(elem[1])[0]
431
Akron8ef408b2021-08-02 22:11:04 +0200432 } else if utf8.RuneCountInString(elem[1]) > 1 {
Akron439f4ec2021-08-09 15:45:38 +0200433
434 // Probably a MCS
Akron8ef408b2021-08-02 22:11:04 +0200435 switch elem[1] {
436 case "@_EPSILON_SYMBOL_@":
437 {
Akronc17f1ca2021-08-03 19:47:27 +0200438 tok.epsilon = number
Akron8ef408b2021-08-02 22:11:04 +0200439 }
440 case "@_UNKNOWN_SYMBOL_@":
441 {
Akronc17f1ca2021-08-03 19:47:27 +0200442 tok.unknown = number
Akron8ef408b2021-08-02 22:11:04 +0200443 }
444
445 case "@_IDENTITY_SYMBOL_@":
446 {
Akronc17f1ca2021-08-03 19:47:27 +0200447 tok.identity = number
Akron8ef408b2021-08-02 22:11:04 +0200448 }
Akron03c92fe2021-08-09 14:07:57 +0200449
450 case "@_TOKEN_SYMBOL_@":
451 {
452 tok.tokenend = number
Akron03c92fe2021-08-09 14:07:57 +0200453 }
Akron8ef408b2021-08-02 22:11:04 +0200454 default:
Akron740f3d72021-08-03 12:12:34 +0200455 {
Akron31f3c062021-08-27 10:15:13 +0200456 // MCS not supported
457 tok.sigmaMCS[number] = line
Akron740f3d72021-08-03 12:12:34 +0200458 }
Akron8ef408b2021-08-02 22:11:04 +0200459 }
Akron439f4ec2021-08-09 15:45:38 +0200460 continue
Akron8ef408b2021-08-02 22:11:04 +0200461
Akron740f3d72021-08-03 12:12:34 +0200462 } else { // Probably a new line symbol
Akron8ef408b2021-08-02 22:11:04 +0200463 line, err = r.ReadString('\n')
464 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200465 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200466 return nil
Akron8ef408b2021-08-02 22:11:04 +0200467 }
468 if len(line) != 1 {
Akron31f3c062021-08-27 10:15:13 +0200469 // MCS not supported
470 tok.sigmaMCS[number] = line
471 continue
Akron8ef408b2021-08-02 22:11:04 +0200472 }
Akron03c92fe2021-08-09 14:07:57 +0200473 symbol = rune('\n')
Akron8ef408b2021-08-02 22:11:04 +0200474 }
475
Akron740f3d72021-08-03 12:12:34 +0200476 tok.sigmaRev[number] = symbol
Akron8ef408b2021-08-02 22:11:04 +0200477 }
478 }
479 }
Akron31f3c062021-08-27 10:15:13 +0200480 tok.sigmaMCS = nil
Akron8ef408b2021-08-02 22:11:04 +0200481 return tok
482}
483
Akron64ffd9a2021-08-03 19:55:21 +0200484// Set alphabet A to the list of all symbols
485// outgoing from s
Akron439f4ec2021-08-09 15:45:38 +0200486func (tok *Tokenizer) getSet(s int, A *[]int) {
Akron64ffd9a2021-08-03 19:55:21 +0200487 for a := range tok.transitions[s] {
488 *A = append(*A, a)
489 }
490
491 // Not required, but simplifies bug hunting
Akron439f4ec2021-08-09 15:45:38 +0200492 // sort.Ints(*A)
Akron64ffd9a2021-08-03 19:55:21 +0200493}
494
Akron439f4ec2021-08-09 15:45:38 +0200495// ToDoubleArray turns the intermediate tokenizer representation
496// into a double array representation.
497//
498// This is based on Mizobuchi et al (2000), p.128
Akronf2120ca2021-08-03 16:26:41 +0200499func (tok *Tokenizer) ToDoubleArray() *DaTokenizer {
500
501 dat := &DaTokenizer{
Akron03a3c612021-08-04 11:51:27 +0200502 sigma: make(map[rune]int),
Akron4fa28b32021-08-27 10:55:41 +0200503 transCount: -1,
Akron03a3c612021-08-04 11:51:27 +0200504 final: tok.final,
505 unknown: tok.unknown,
506 identity: tok.identity,
507 epsilon: tok.epsilon,
Akron03c92fe2021-08-09 14:07:57 +0200508 tokenend: tok.tokenend,
Akronf2120ca2021-08-03 16:26:41 +0200509 }
510
Akronf1a16502021-08-16 15:24:38 +0200511 dat.resize(dat.final)
512
Akronf2120ca2021-08-03 16:26:41 +0200513 for num, sym := range tok.sigmaRev {
Akronea46e8a2021-08-17 00:36:31 +0200514 if int(sym) < 256 {
515 dat.sigmaASCII[int(sym)] = num
516 }
Akronf2120ca2021-08-03 16:26:41 +0200517 dat.sigma[sym] = num
518 }
Akron8ef408b2021-08-02 22:11:04 +0200519
520 mark := 0
521 size := 0
Akron6f1c16c2021-08-17 10:45:42 +0200522 var base uint32
Akronde18e902021-08-27 09:34:12 +0200523 var atrans *edge
524 var s, s1 int
525 var t, t1 uint32
Akron8ef408b2021-08-02 22:11:04 +0200526
Akron439f4ec2021-08-09 15:45:38 +0200527 // Create a mapping from s (in Ms aka Intermediate FSA)
528 // to t (in Mt aka Double Array FSA)
Akron740f3d72021-08-03 12:12:34 +0200529 table := make([]*mapping, tok.arcCount+1)
Akron8ef408b2021-08-02 22:11:04 +0200530
Akron439f4ec2021-08-09 15:45:38 +0200531 // Initialize with the start state
Akron8ef408b2021-08-02 22:11:04 +0200532 table[size] = &mapping{source: 1, target: 1}
533 size++
534
Akron740f3d72021-08-03 12:12:34 +0200535 // Allocate space for the outgoing symbol range
536 A := make([]int, 0, tok.sigmaCount)
Akron8ef408b2021-08-02 22:11:04 +0200537
Akronde18e902021-08-27 09:34:12 +0200538 // TODO:
539 // Table lookup for the moment
540 // only gives a minor performance benefit.
541 // should be rewritten and should preplace the
542 // table all together.
543 // tableLookup := make(map[int]uint32)
544 // tableLookup[1] = 1
545
Akron8ef408b2021-08-02 22:11:04 +0200546 for mark < size {
Akronde18e902021-08-27 09:34:12 +0200547 s = table[mark].source // This is a state in Ms
548 t = table[mark].target // This is a state in Mt
Akron8ef408b2021-08-02 22:11:04 +0200549 mark++
Akron740f3d72021-08-03 12:12:34 +0200550
551 // Following the paper, here the state t can be remembered
552 // in the set of states St
Akron8ef408b2021-08-02 22:11:04 +0200553 A = A[:0]
Akron439f4ec2021-08-09 15:45:38 +0200554 tok.getSet(s, &A)
Akron8ef408b2021-08-02 22:11:04 +0200555
Akron740f3d72021-08-03 12:12:34 +0200556 // Set base to the first free slot in the double array
Akron6f1c16c2021-08-17 10:45:42 +0200557 base = dat.xCheck(A)
558 dat.array[t].setBase(base)
Akron8ef408b2021-08-02 22:11:04 +0200559
Akron773b1ef2021-08-03 17:37:20 +0200560 // TODO:
Akron068874c2021-08-04 15:19:56 +0200561 // Sort the outgoing transitions based on the
Akron773b1ef2021-08-03 17:37:20 +0200562 // outdegree of .end
563
Akron740f3d72021-08-03 12:12:34 +0200564 // Iterate over all outgoing symbols
Akron8ef408b2021-08-02 22:11:04 +0200565 for _, a := range A {
566
Akronc17f1ca2021-08-03 19:47:27 +0200567 if a != tok.final {
Akron8ef408b2021-08-02 22:11:04 +0200568
Akronde18e902021-08-27 09:34:12 +0200569 atrans = tok.transitions[s][a]
570
Akron740f3d72021-08-03 12:12:34 +0200571 // Aka g(s, a)
Akronde18e902021-08-27 09:34:12 +0200572 s1 = atrans.end
Akron8ef408b2021-08-02 22:11:04 +0200573
Akron740f3d72021-08-03 12:12:34 +0200574 // Store the transition
Akronde18e902021-08-27 09:34:12 +0200575 t1 = base + uint32(a)
Akronf1a16502021-08-16 15:24:38 +0200576 dat.array[t1].setCheck(t)
577
578 // Set maxSize
579 if dat.maxSize < int(t1) {
580 dat.maxSize = int(t1)
581 }
Akron8ef408b2021-08-02 22:11:04 +0200582
Akron439f4ec2021-08-09 15:45:38 +0200583 if DEBUG {
Akron524c5432021-08-05 14:14:27 +0200584 fmt.Println("Translate transition",
585 s, "->", s1, "(", a, ")", "to", t, "->", t1)
586 }
587
Akron83e75a22021-08-04 13:14:06 +0200588 // Mark the state as being the target of a nontoken transition
Akronde18e902021-08-27 09:34:12 +0200589 if atrans.nontoken {
Akronf1a16502021-08-16 15:24:38 +0200590 dat.array[t1].setNonToken(true)
Akron524c5432021-08-05 14:14:27 +0200591 if DEBUG {
592 fmt.Println("Set", t1, "to nontoken")
593 }
Akron83e75a22021-08-04 13:14:06 +0200594 }
595
Akron84d68e62021-08-04 17:06:52 +0200596 // Mark the state as being the target of a tokenend transition
Akronde18e902021-08-27 09:34:12 +0200597 if atrans.tokenend {
Akronf1a16502021-08-16 15:24:38 +0200598 dat.array[t1].setTokenEnd(true)
Akron524c5432021-08-05 14:14:27 +0200599 if DEBUG {
600 fmt.Println("Set", t1, "to tokenend")
601 }
Akron84d68e62021-08-04 17:06:52 +0200602 }
603
Akron740f3d72021-08-03 12:12:34 +0200604 // Check for representative states
Akron439f4ec2021-08-09 15:45:38 +0200605 r := stateAlreadyInTable(s1, table, size)
Akronde18e902021-08-27 09:34:12 +0200606 // r := tableLookup[s1]
Akron740f3d72021-08-03 12:12:34 +0200607
Akron439f4ec2021-08-09 15:45:38 +0200608 // No representative found
Akron8ef408b2021-08-02 22:11:04 +0200609 if r == 0 {
Akron740f3d72021-08-03 12:12:34 +0200610 // Remember the mapping
Akron8ef408b2021-08-02 22:11:04 +0200611 table[size] = &mapping{source: s1, target: t1}
Akronde18e902021-08-27 09:34:12 +0200612 // tableLookup[s1] = t1
Akron8ef408b2021-08-02 22:11:04 +0200613 size++
614 } else {
Akron740f3d72021-08-03 12:12:34 +0200615 // Overwrite with the representative state
Akronf1a16502021-08-16 15:24:38 +0200616 dat.array[t1].setBase(r)
617 dat.array[t1].setSeparate(true)
Akron8ef408b2021-08-02 22:11:04 +0200618 }
619 } else {
Akron740f3d72021-08-03 12:12:34 +0200620 // Store a final transition
Akron6f1c16c2021-08-17 10:45:42 +0200621 dat.array[base+uint32(dat.final)].setCheck(t)
Akronf1a16502021-08-16 15:24:38 +0200622
Akronde18e902021-08-27 09:34:12 +0200623 if dat.maxSize < int(base)+dat.final {
624 dat.maxSize = int(base) + dat.final
Akronf1a16502021-08-16 15:24:38 +0200625 }
Akron8ef408b2021-08-02 22:11:04 +0200626 }
627 }
628 }
629
630 // Following Mizobuchi et al (2000) the size of the
631 // FSA should be stored in check(1).
Akronf1a16502021-08-16 15:24:38 +0200632 // We make the size a bit smaller so we never have to check for boundaries.
Akron3fdfec62021-08-04 11:40:10 +0200633 dat.setSize(dat.maxSize + 1)
Akronf2120ca2021-08-03 16:26:41 +0200634 dat.array = dat.array[:dat.maxSize+1]
635 return dat
Akron8ef408b2021-08-02 22:11:04 +0200636}
637
Akron8ef408b2021-08-02 22:11:04 +0200638// Check the table if a mapping of s
Akron740f3d72021-08-03 12:12:34 +0200639// exists and return this as a representative.
640// Currently iterates through the whole table
641// in a bruteforce manner.
Akron439f4ec2021-08-09 15:45:38 +0200642func stateAlreadyInTable(s int, table []*mapping, size int) uint32 {
Akron8ef408b2021-08-02 22:11:04 +0200643 for x := 0; x < size; x++ {
644 if table[x].source == s {
645 return table[x].target
646 }
647 }
648 return 0
649}
650
Akron64ffd9a2021-08-03 19:55:21 +0200651// Resize double array when necessary
652func (dat *DaTokenizer) resize(l int) {
653 // TODO:
654 // This is a bit too aggressive atm and should be calmed down.
655 if len(dat.array) <= l {
Akronf1a16502021-08-16 15:24:38 +0200656 dat.array = append(dat.array, make([]bc, l)...)
Akron8ef408b2021-08-02 22:11:04 +0200657 }
Akron64ffd9a2021-08-03 19:55:21 +0200658}
Akronc9d84a62021-08-03 15:56:03 +0200659
Akron64ffd9a2021-08-03 19:55:21 +0200660// Set base value in double array
Akronf1a16502021-08-16 15:24:38 +0200661func (bc *bc) setBase(v uint32) {
662 bc.base = v
Akron439f4ec2021-08-09 15:45:38 +0200663}
664
665// Get base value in double array
Akronf1a16502021-08-16 15:24:38 +0200666func (bc *bc) getBase() uint32 {
667 return bc.base & RESTBIT
Akron439f4ec2021-08-09 15:45:38 +0200668}
669
670// Set check value in double array
Akronf1a16502021-08-16 15:24:38 +0200671func (bc *bc) setCheck(v uint32) {
672 bc.check = v
Akron439f4ec2021-08-09 15:45:38 +0200673}
674
675// Get check value in double array
Akronf1a16502021-08-16 15:24:38 +0200676func (bc *bc) getCheck() uint32 {
677 return bc.check & RESTBIT
Akron64ffd9a2021-08-03 19:55:21 +0200678}
679
Akron3fdfec62021-08-04 11:40:10 +0200680// Returns true if a state is separate pointing to a representative
Akronf1a16502021-08-16 15:24:38 +0200681func (bc *bc) isSeparate() bool {
682 return bc.base&FIRSTBIT != 0
Akron3fdfec62021-08-04 11:40:10 +0200683}
684
685// Mark a state as separate pointing to a representative
Akronf1a16502021-08-16 15:24:38 +0200686func (bc *bc) setSeparate(sep bool) {
Akron3fdfec62021-08-04 11:40:10 +0200687 if sep {
Akronf1a16502021-08-16 15:24:38 +0200688 bc.base |= FIRSTBIT
Akron3fdfec62021-08-04 11:40:10 +0200689 } else {
Akronf1a16502021-08-16 15:24:38 +0200690 bc.base &= (RESTBIT | SECONDBIT)
Akron3fdfec62021-08-04 11:40:10 +0200691 }
692}
693
Akron83e75a22021-08-04 13:14:06 +0200694// Returns true if a state is the target of a nontoken transition
Akronf1a16502021-08-16 15:24:38 +0200695func (bc *bc) isNonToken() bool {
696 return bc.check&FIRSTBIT != 0
Akron83e75a22021-08-04 13:14:06 +0200697}
698
699// Mark a state as being the target of a nontoken transition
Akronf1a16502021-08-16 15:24:38 +0200700func (bc *bc) setNonToken(sep bool) {
Akron83e75a22021-08-04 13:14:06 +0200701 if sep {
Akronf1a16502021-08-16 15:24:38 +0200702 bc.check |= FIRSTBIT
Akron83e75a22021-08-04 13:14:06 +0200703 } else {
Akronf1a16502021-08-16 15:24:38 +0200704 bc.check &= (RESTBIT | SECONDBIT)
Akron83e75a22021-08-04 13:14:06 +0200705 }
706}
707
Akron84d68e62021-08-04 17:06:52 +0200708// Returns true if a state is the target of a tokenend transition
Akronf1a16502021-08-16 15:24:38 +0200709func (bc *bc) isTokenEnd() bool {
710 return bc.check&SECONDBIT != 0
Akron84d68e62021-08-04 17:06:52 +0200711}
712
713// Mark a state as being the target of a tokenend transition
Akronf1a16502021-08-16 15:24:38 +0200714func (bc *bc) setTokenEnd(sep bool) {
Akron84d68e62021-08-04 17:06:52 +0200715 if sep {
Akronf1a16502021-08-16 15:24:38 +0200716 bc.check |= SECONDBIT
Akron84d68e62021-08-04 17:06:52 +0200717 } else {
Akronf1a16502021-08-16 15:24:38 +0200718 bc.check &= (RESTBIT | FIRSTBIT)
Akron84d68e62021-08-04 17:06:52 +0200719 }
720}
721
Akron64ffd9a2021-08-03 19:55:21 +0200722// Set size of double array
Akron3fdfec62021-08-04 11:40:10 +0200723func (dat *DaTokenizer) setSize(v int) {
Akronf1a16502021-08-16 15:24:38 +0200724 dat.array[1].setCheck(uint32(v))
Akron64ffd9a2021-08-03 19:55:21 +0200725}
726
727// Get size of double array
Akron3fdfec62021-08-04 11:40:10 +0200728func (dat *DaTokenizer) GetSize() int {
Akronf1a16502021-08-16 15:24:38 +0200729 return int(dat.array[1].getCheck())
Akron8ef408b2021-08-02 22:11:04 +0200730}
731
732// Based on Mizobuchi et al (2000), p. 124
733// This iterates for every state through the complete double array
734// structure until it finds a gap that fits all outgoing transitions
735// of the state. This is extremely slow, but is only necessary in the
736// construction phase of the tokenizer.
Akron3fdfec62021-08-04 11:40:10 +0200737func (dat *DaTokenizer) xCheck(symbols []int) uint32 {
Akron740f3d72021-08-03 12:12:34 +0200738
739 // Start at the first entry of the double array list
Akron6f1c16c2021-08-17 10:45:42 +0200740 base := uint32(1)
741
Akron8ef408b2021-08-02 22:11:04 +0200742OVERLAP:
Akron740f3d72021-08-03 12:12:34 +0200743 // Resize the array if necessary
Akronf1a16502021-08-16 15:24:38 +0200744 dat.resize(int(base) + dat.final)
Akron8ef408b2021-08-02 22:11:04 +0200745 for _, a := range symbols {
Akronf1a16502021-08-16 15:24:38 +0200746 if dat.array[int(base)+a].getCheck() != 0 {
Akron8ef408b2021-08-02 22:11:04 +0200747 base++
748 goto OVERLAP
749 }
750 }
Akron8ef408b2021-08-02 22:11:04 +0200751 return base
752}
753
Akron3610f102021-08-08 14:13:25 +0200754// List all outgoing transitions for a state
755// for testing purposes
756func (dat *DaTokenizer) outgoing(t uint32) []int {
757
758 valid := make([]int, 0, len(dat.sigma))
759
760 for _, a := range dat.sigma {
Akronf1a16502021-08-16 15:24:38 +0200761 t1 := dat.array[t].getBase() + uint32(a)
762 if t1 <= dat.array[1].getCheck() && dat.array[t1].getCheck() == t {
Akron3610f102021-08-08 14:13:25 +0200763 valid = append(valid, a)
764 }
765 }
766
767 for _, a := range []int{dat.epsilon, dat.unknown, dat.identity, dat.final} {
Akronf1a16502021-08-16 15:24:38 +0200768 t1 := dat.array[t].getBase() + uint32(a)
769 if t1 <= dat.array[1].getCheck() && dat.array[t1].getCheck() == t {
Akron3610f102021-08-08 14:13:25 +0200770 valid = append(valid, -1*a)
771 }
772 }
773
774 sort.Ints(valid)
775
776 return valid
777}
778
Akron4fa28b32021-08-27 10:55:41 +0200779// TransCount as the number of transitions aka arcs in the
780// finite state automaton
781func (dat *DaTokenizer) TransCount() int {
782 // Cache the transCount
783 if dat.transCount > 0 {
784 return dat.transCount
785 }
786
787 dat.transCount = 0
788 for x := 1; x < len(dat.array); x++ {
789 if dat.array[x].getBase() != 0 {
790 dat.transCount++
791 }
792 }
793
794 return dat.transCount
795}
796
Akron03a3c612021-08-04 11:51:27 +0200797// LoadFactor as defined in Kanda et al (2018),
798// i.e. the proportion of non-empty elements to all elements.
799func (dat *DaTokenizer) LoadFactor() float64 {
Akron4fa28b32021-08-27 10:55:41 +0200800 return float64(dat.TransCount()) / float64(len(dat.array)) * 100
Akrond66a9262021-08-03 17:09:09 +0200801}
802
Akron439f4ec2021-08-09 15:45:38 +0200803// Save stores the double array data in a file
Akron3a063ef2021-08-05 19:36:35 +0200804func (dat *DaTokenizer) Save(file string) (n int64, err error) {
805 f, err := os.Create(file)
806 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200807 log.Println(err)
Akron439f4ec2021-08-09 15:45:38 +0200808 return 0, err
Akron3a063ef2021-08-05 19:36:35 +0200809 }
810 defer f.Close()
811 gz := gzip.NewWriter(f)
812 defer gz.Close()
813 n, err = dat.WriteTo(gz)
814 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200815 log.Println(err)
Akron3a063ef2021-08-05 19:36:35 +0200816 return n, err
817 }
818 gz.Flush()
819 return n, nil
820}
821
822// WriteTo stores the double array data in an io.Writer.
Akron6247a5d2021-08-03 19:18:28 +0200823func (dat *DaTokenizer) WriteTo(w io.Writer) (n int64, err error) {
824
Akron3a063ef2021-08-05 19:36:35 +0200825 wb := bufio.NewWriter(w)
826 defer wb.Flush()
827
Akron6247a5d2021-08-03 19:18:28 +0200828 // Store magical header
Akron3a063ef2021-08-05 19:36:35 +0200829 all, err := wb.Write([]byte(MAGIC))
Akron6247a5d2021-08-03 19:18:28 +0200830 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200831 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200832 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200833 }
834
835 // Get sigma as a list
836 sigmalist := make([]rune, len(dat.sigma)+16)
837 max := 0
838 for sym, num := range dat.sigma {
839 sigmalist[num] = sym
840 if num > max {
841 max = num
842 }
843 }
844
845 sigmalist = sigmalist[:max+1]
846
Akron3f8571a2021-08-05 11:18:10 +0200847 buf := make([]byte, 0, 16)
Akron6247a5d2021-08-03 19:18:28 +0200848 bo.PutUint16(buf[0:2], VERSION)
Akronc17f1ca2021-08-03 19:47:27 +0200849 bo.PutUint16(buf[2:4], uint16(dat.epsilon))
850 bo.PutUint16(buf[4:6], uint16(dat.unknown))
851 bo.PutUint16(buf[6:8], uint16(dat.identity))
852 bo.PutUint16(buf[8:10], uint16(dat.final))
Akron6247a5d2021-08-03 19:18:28 +0200853 bo.PutUint16(buf[10:12], uint16(len(sigmalist)))
Akronf1a16502021-08-16 15:24:38 +0200854 bo.PutUint32(buf[12:16], uint32(len(dat.array)*2)) // Legacy support
Akron3a063ef2021-08-05 19:36:35 +0200855 more, err := wb.Write(buf[0:16])
Akron6247a5d2021-08-03 19:18:28 +0200856 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200857 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200858 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200859 }
860
861 all += more
862
Akron6247a5d2021-08-03 19:18:28 +0200863 // Write sigma
864 for _, sym := range sigmalist {
Akron3f8571a2021-08-05 11:18:10 +0200865
Akron3a063ef2021-08-05 19:36:35 +0200866 more, err = wb.WriteRune(sym)
Akron6247a5d2021-08-03 19:18:28 +0200867 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200868 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200869 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200870 }
871 all += more
872 }
Akron439f4ec2021-08-09 15:45:38 +0200873
Akron6247a5d2021-08-03 19:18:28 +0200874 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200875 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200876 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200877 }
Akron6247a5d2021-08-03 19:18:28 +0200878
879 // Test marker - could be checksum
Akron3a063ef2021-08-05 19:36:35 +0200880 more, err = wb.Write([]byte("T"))
Akron6247a5d2021-08-03 19:18:28 +0200881 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200882 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200883 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200884 }
885 all += more
886
Akronf1a16502021-08-16 15:24:38 +0200887 // for x := 0; x < len(dat.array); x++ {
888 for _, bc := range dat.array {
889 bo.PutUint32(buf[0:4], bc.base)
890 more, err = wb.Write(buf[0:4])
Akron6247a5d2021-08-03 19:18:28 +0200891 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200892 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200893 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200894 }
Akron439f4ec2021-08-09 15:45:38 +0200895 all += more
Akron3a063ef2021-08-05 19:36:35 +0200896 if more != 4 {
Akronf1a16502021-08-16 15:24:38 +0200897 log.Println("Can not write base uint32")
898 return int64(all), err
899 }
900 bo.PutUint32(buf[0:4], bc.check)
901 more, err = wb.Write(buf[0:4])
902 if err != nil {
903 log.Println(err)
904 return int64(all), err
905 }
906 all += more
907 if more != 4 {
908 log.Println("Can not write check uint32")
Akron3a063ef2021-08-05 19:36:35 +0200909 return int64(all), err
910 }
Akron6247a5d2021-08-03 19:18:28 +0200911 }
912
913 return int64(all), err
914}
915
Akron439f4ec2021-08-09 15:45:38 +0200916// LoadDatokFile reads a double array represented tokenizer
917// from a file.
Akron3f8571a2021-08-05 11:18:10 +0200918func LoadDatokFile(file string) *DaTokenizer {
919 f, err := os.Open(file)
920 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200921 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200922 return nil
Akron3f8571a2021-08-05 11:18:10 +0200923 }
924 defer f.Close()
925
926 gz, err := gzip.NewReader(f)
927 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200928 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200929 return nil
Akron3f8571a2021-08-05 11:18:10 +0200930 }
931 defer gz.Close()
932
Akron3a063ef2021-08-05 19:36:35 +0200933 // Todo: Read the whole file!
Akron3f8571a2021-08-05 11:18:10 +0200934 return ParseDatok(gz)
935}
936
Akron439f4ec2021-08-09 15:45:38 +0200937// LoadDatokFile reads a double array represented tokenizer
938// from an io.Reader
Akron3f8571a2021-08-05 11:18:10 +0200939func ParseDatok(ior io.Reader) *DaTokenizer {
940
Akron439f4ec2021-08-09 15:45:38 +0200941 // Initialize tokenizer with default values
Akron3f8571a2021-08-05 11:18:10 +0200942 dat := &DaTokenizer{
943 sigma: make(map[rune]int),
944 epsilon: 0,
945 unknown: 0,
946 identity: 0,
947 final: 0,
Akron4fa28b32021-08-27 10:55:41 +0200948 transCount: 0,
Akron3f8571a2021-08-05 11:18:10 +0200949 }
950
951 r := bufio.NewReader(ior)
952
Akron3f8571a2021-08-05 11:18:10 +0200953 buf := make([]byte, 1024)
954 buf = buf[0:len(MAGIC)]
955
Akron439f4ec2021-08-09 15:45:38 +0200956 _, err := r.Read(buf)
Akron3f8571a2021-08-05 11:18:10 +0200957
958 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200959 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200960 return nil
961 }
962
Akron3f8571a2021-08-05 11:18:10 +0200963 if string(MAGIC) != string(buf) {
Akron527c10c2021-08-13 01:45:18 +0200964 log.Println("Not a datok file")
Akron3f8571a2021-08-05 11:18:10 +0200965 return nil
966 }
967
Akron439f4ec2021-08-09 15:45:38 +0200968 more, err := io.ReadFull(r, buf[0:16])
Akron3f8571a2021-08-05 11:18:10 +0200969 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200970 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200971 return nil
972 }
973
Akron439f4ec2021-08-09 15:45:38 +0200974 if more != 16 {
Akron527c10c2021-08-13 01:45:18 +0200975 log.Println("Read bytes do not fit")
Akron439f4ec2021-08-09 15:45:38 +0200976 return nil
977 }
Akron3f8571a2021-08-05 11:18:10 +0200978
Akron3a063ef2021-08-05 19:36:35 +0200979 version := bo.Uint16(buf[0:2])
980
981 if version != VERSION {
Akron527c10c2021-08-13 01:45:18 +0200982 log.Println("Version not compatible")
Akron3a063ef2021-08-05 19:36:35 +0200983 return nil
984 }
985
Akron3f8571a2021-08-05 11:18:10 +0200986 dat.epsilon = int(bo.Uint16(buf[2:4]))
987 dat.unknown = int(bo.Uint16(buf[4:6]))
988 dat.identity = int(bo.Uint16(buf[6:8]))
989 dat.final = int(bo.Uint16(buf[8:10]))
990
991 sigmaCount := int(bo.Uint16(buf[10:12]))
Akronf1a16502021-08-16 15:24:38 +0200992 arraySize := int(bo.Uint32(buf[12:16])) / 2 // Legacy support
Akron3f8571a2021-08-05 11:18:10 +0200993
Akron3a063ef2021-08-05 19:36:35 +0200994 // Shouldn't be relevant though
995 dat.maxSize = arraySize - 1
996
Akron3f8571a2021-08-05 11:18:10 +0200997 for x := 0; x < sigmaCount; x++ {
Akron439f4ec2021-08-09 15:45:38 +0200998 sym, _, err := r.ReadRune()
Akron3f8571a2021-08-05 11:18:10 +0200999 if err == nil && sym != 0 {
Akronea46e8a2021-08-17 00:36:31 +02001000 if int(sym) < 256 {
1001 dat.sigmaASCII[int(sym)] = x
1002 }
Akron3f8571a2021-08-05 11:18:10 +02001003 dat.sigma[sym] = x
1004 }
Akron3f8571a2021-08-05 11:18:10 +02001005 }
1006
Akron439f4ec2021-08-09 15:45:38 +02001007 _, err = io.ReadFull(r, buf[0:1])
Akron3f8571a2021-08-05 11:18:10 +02001008
1009 if err != nil {
Akron527c10c2021-08-13 01:45:18 +02001010 log.Print(err)
Akron3f8571a2021-08-05 11:18:10 +02001011 return nil
1012 }
1013
Akron3f8571a2021-08-05 11:18:10 +02001014 if string("T") != string(buf[0:1]) {
Akron527c10c2021-08-13 01:45:18 +02001015 log.Println("Not a datok file")
Akron3f8571a2021-08-05 11:18:10 +02001016 return nil
1017 }
1018
1019 // Read based on length
Akronf1a16502021-08-16 15:24:38 +02001020 dat.array = make([]bc, arraySize)
Akron3f8571a2021-08-05 11:18:10 +02001021
Akronbb4aac52021-08-13 00:52:27 +02001022 dataArray, err := io.ReadAll(r)
Akron439f4ec2021-08-09 15:45:38 +02001023
Akronbb4aac52021-08-13 00:52:27 +02001024 if err == io.EOF {
Akron527c10c2021-08-13 01:45:18 +02001025 log.Println(err)
Akronbb4aac52021-08-13 00:52:27 +02001026 return nil
1027 }
1028
Akronf1a16502021-08-16 15:24:38 +02001029 if len(dataArray) < arraySize*8 {
Akron527c10c2021-08-13 01:45:18 +02001030 log.Println("Not enough bytes read")
Akronbb4aac52021-08-13 00:52:27 +02001031 return nil
1032 }
1033
1034 for x := 0; x < arraySize; x++ {
Akronf1a16502021-08-16 15:24:38 +02001035 dat.array[x].base = bo.Uint32(dataArray[x*8 : (x*8)+4])
1036 dat.array[x].check = bo.Uint32(dataArray[(x*8)+4 : (x*8)+8])
Akron3f8571a2021-08-05 11:18:10 +02001037 }
1038
1039 return dat
1040}
1041
Akron439f4ec2021-08-09 15:45:38 +02001042// Show the current state of the buffer,
1043// for testing puroses
Akron3610f102021-08-08 14:13:25 +02001044func showBuffer(buffer []rune, buffo int, buffi int) string {
1045 out := make([]rune, 0, 1024)
1046 for x := 0; x < len(buffer); x++ {
1047 if buffi == x {
1048 out = append(out, '^')
1049 }
1050 if buffo == x {
1051 out = append(out, '[', buffer[x], ']')
1052 } else {
1053 out = append(out, buffer[x])
1054 }
1055 }
1056 return string(out)
1057}
1058
Akron84d68e62021-08-04 17:06:52 +02001059// Transduce an input string against the double array
Akron3610f102021-08-08 14:13:25 +02001060// FSA. The rules are always greedy. If the automaton fails,
1061// it takes the last possible token ending branch.
Akron068874c2021-08-04 15:19:56 +02001062//
Akron4db3ecf2021-08-11 18:49:03 +02001063// Based on Mizobuchi et al (2000), p. 129,
1064// with additional support for IDENTITY, UNKNOWN
1065// and EPSILON transitions and NONTOKEN and TOKENEND handling.
Akron3f8571a2021-08-05 11:18:10 +02001066func (dat *DaTokenizer) Transduce(r io.Reader, w io.Writer) bool {
Akron068874c2021-08-04 15:19:56 +02001067 var a int
Akronb4bbb472021-08-09 11:49:38 +02001068 var t0 uint32
Akronb7e1f132021-08-10 11:52:31 +02001069 t := uint32(1) // Initial state
1070 var ok, rewindBuffer bool
Akron068874c2021-08-04 15:19:56 +02001071
Akron3610f102021-08-08 14:13:25 +02001072 // Remember the last position of a possible tokenend,
1073 // in case the automaton fails.
1074 epsilonState := uint32(0)
1075 epsilonOffset := 0
1076
1077 // Implement a low level buffer for full control,
1078 // however - it is probably better to introduce
1079 // this on a higher level with a io.Reader interface
1080 // The buffer stores a single word and may have white
1081 // space at the end (but not at the beginning).
1082 //
1083 // This is the only backtracking requirement because of
1084 // epsilon transitions, to support tokenizations like:
1085 // "this is an example|.| And it works." vs
1086 // "this is an example.com| application."
Akronb7e1f132021-08-10 11:52:31 +02001087 //
1088 // TODO:
1089 // Store a translation buffer as well, so characters don't
1090 // have to be translated multiple times!
Akron3610f102021-08-08 14:13:25 +02001091 buffer := make([]rune, 1024)
1092 buffo := 0 // Buffer offset
1093 buffi := 0 // Buffer length
1094
Akron3f8571a2021-08-05 11:18:10 +02001095 reader := bufio.NewReader(r)
1096 writer := bufio.NewWriter(w)
1097 defer writer.Flush()
Akron068874c2021-08-04 15:19:56 +02001098
Akron3f8571a2021-08-05 11:18:10 +02001099 var char rune
1100 var err error
1101 eof := false
Akronb7e1f132021-08-10 11:52:31 +02001102 newchar := true
Akron3f8571a2021-08-05 11:18:10 +02001103
Akronc5d8d432021-08-10 16:48:44 +02001104PARSECHAR:
Akron3f8571a2021-08-05 11:18:10 +02001105 for {
1106
Akronb7e1f132021-08-10 11:52:31 +02001107 if newchar {
1108 // Get from reader if buffer is empty
1109 if buffo >= buffi {
Akron1594cb82021-08-11 11:14:56 +02001110 if eof {
1111 break
1112 }
Akronb7e1f132021-08-10 11:52:31 +02001113 char, _, err = reader.ReadRune()
Akron439f4ec2021-08-09 15:45:38 +02001114
Akronb7e1f132021-08-10 11:52:31 +02001115 // No more runes to read
1116 if err != nil {
1117 eof = true
1118 break
1119 }
1120 buffer[buffi] = char
1121 buffi++
Akron3f8571a2021-08-05 11:18:10 +02001122 }
Akronb7e1f132021-08-10 11:52:31 +02001123
1124 char = buffer[buffo]
1125
1126 if DEBUG {
1127 fmt.Println("Current char", string(char), showBuffer(buffer, buffo, buffi))
1128 }
1129
Akron6f1c16c2021-08-17 10:45:42 +02001130 // TODO:
1131 // Better not repeatedly check for a!
1132 // Possibly keep a buffer with a.
Akronea46e8a2021-08-17 00:36:31 +02001133 if int(char) < 256 {
1134 a = dat.sigmaASCII[int(char)]
1135 } else {
1136 a, ok = dat.sigma[char]
1137 if !ok {
1138 a = 0
1139 }
1140 }
Akronb7e1f132021-08-10 11:52:31 +02001141
1142 // Use identity symbol if character is not in sigma
Akronea46e8a2021-08-17 00:36:31 +02001143 if a == 0 && dat.identity != -1 {
Akronb7e1f132021-08-10 11:52:31 +02001144 a = dat.identity
1145 }
1146
1147 t0 = t
1148
1149 // Check for epsilon transitions and remember
Akronf1a16502021-08-16 15:24:38 +02001150 if dat.array[dat.array[t0].getBase()+uint32(dat.epsilon)].getCheck() == t0 {
Akronb7e1f132021-08-10 11:52:31 +02001151 // Remember state for backtracking to last tokenend state
1152 epsilonState = t0
1153 epsilonOffset = buffo
1154 }
Akron3f8571a2021-08-05 11:18:10 +02001155 }
Akron3610f102021-08-08 14:13:25 +02001156
Akronb7e1f132021-08-10 11:52:31 +02001157 // Checks a transition based on t0, a and buffo
Akronf1a16502021-08-16 15:24:38 +02001158 t = dat.array[t0].getBase() + uint32(a)
1159 ta := dat.array[t]
Akron068874c2021-08-04 15:19:56 +02001160
Akron524c5432021-08-05 14:14:27 +02001161 if DEBUG {
Akronb7e1f132021-08-10 11:52:31 +02001162 // Char is only relevant if set
1163 fmt.Println("Check", t0, "-", a, "(", string(char), ")", "->", t)
1164 if false {
1165 fmt.Println(dat.outgoing(t0))
1166 }
Akron524c5432021-08-05 14:14:27 +02001167 }
1168
Akronb7e1f132021-08-10 11:52:31 +02001169 // Check if the transition is invalid according to the double array
Akronf1a16502021-08-16 15:24:38 +02001170 if t > dat.array[1].getCheck() || ta.getCheck() != t0 {
Akron068874c2021-08-04 15:19:56 +02001171
1172 if DEBUG {
Akronf1a16502021-08-16 15:24:38 +02001173 fmt.Println("Match is not fine!", t, "and", ta.getCheck(), "vs", t0)
Akron068874c2021-08-04 15:19:56 +02001174 }
1175
1176 if !ok && a == dat.identity {
Akronb4bbb472021-08-09 11:49:38 +02001177
Akron068874c2021-08-04 15:19:56 +02001178 // Try again with unknown symbol, in case identity failed
Akronb7e1f132021-08-10 11:52:31 +02001179 // Char is only relevant when set
Akron068874c2021-08-04 15:19:56 +02001180 if DEBUG {
Akron3f8571a2021-08-05 11:18:10 +02001181 fmt.Println("UNKNOWN symbol", string(char), "->", dat.unknown)
Akron068874c2021-08-04 15:19:56 +02001182 }
1183 a = dat.unknown
1184
1185 } else if a != dat.epsilon {
Akronb4bbb472021-08-09 11:49:38 +02001186
Akron068874c2021-08-04 15:19:56 +02001187 // Try again with epsilon symbol, in case everything else failed
Akronb4bbb472021-08-09 11:49:38 +02001188 t0 = epsilonState
Akron3610f102021-08-08 14:13:25 +02001189 epsilonState = 0 // reset
1190 buffo = epsilonOffset
Akron439f4ec2021-08-09 15:45:38 +02001191 a = dat.epsilon
1192
Akron3610f102021-08-08 14:13:25 +02001193 if DEBUG {
1194 fmt.Println("Get from epsilon stack and set buffo!", showBuffer(buffer, buffo, buffi))
1195 }
Akronb4bbb472021-08-09 11:49:38 +02001196
Akron068874c2021-08-04 15:19:56 +02001197 } else {
1198 break
1199 }
Akron068874c2021-08-04 15:19:56 +02001200
Akronb7e1f132021-08-10 11:52:31 +02001201 newchar = false
1202 continue
Akronb4bbb472021-08-09 11:49:38 +02001203 }
1204
Akronb7e1f132021-08-10 11:52:31 +02001205 // Transition was successful
1206 rewindBuffer = false
Akron439f4ec2021-08-09 15:45:38 +02001207
1208 // Transition consumes a character
Akronb4bbb472021-08-09 11:49:38 +02001209 if a != dat.epsilon {
1210
Akron3610f102021-08-08 14:13:25 +02001211 buffo++
Akronb4bbb472021-08-09 11:49:38 +02001212
Akron439f4ec2021-08-09 15:45:38 +02001213 // Transition does not produce a character
Akronf1a16502021-08-16 15:24:38 +02001214 if buffo == 1 && ta.isNonToken() {
Akron3610f102021-08-08 14:13:25 +02001215 if DEBUG {
1216 fmt.Println("Nontoken forward", showBuffer(buffer, buffo, buffi))
1217 }
Akron439f4ec2021-08-09 15:45:38 +02001218 rewindBuffer = true
Akron3610f102021-08-08 14:13:25 +02001219 }
Akron3f8571a2021-08-05 11:18:10 +02001220 }
Akron068874c2021-08-04 15:19:56 +02001221
Akronc5d8d432021-08-10 16:48:44 +02001222 // Transition marks the end of a token - so flush the buffer
Akronf1a16502021-08-16 15:24:38 +02001223 if ta.isTokenEnd() {
Akron524c5432021-08-05 14:14:27 +02001224
Akronc5d8d432021-08-10 16:48:44 +02001225 if buffi > 0 {
Akronc5d8d432021-08-10 16:48:44 +02001226 if DEBUG {
Akron01912fc2021-08-12 11:41:58 +02001227 fmt.Println("-> Flush buffer: [", string(buffer[:buffo]), "]", showBuffer(buffer, buffo, buffi))
Akronc5d8d432021-08-10 16:48:44 +02001228 }
Akron01912fc2021-08-12 11:41:58 +02001229 writer.WriteString(string(buffer[:buffo]))
Akronc5d8d432021-08-10 16:48:44 +02001230 rewindBuffer = true
Akron3610f102021-08-08 14:13:25 +02001231 }
Akron1594cb82021-08-11 11:14:56 +02001232 if DEBUG {
1233 fmt.Println("-> Newline")
1234 }
1235 writer.WriteRune('\n')
Akron439f4ec2021-08-09 15:45:38 +02001236 }
Akron3610f102021-08-08 14:13:25 +02001237
Akronc5d8d432021-08-10 16:48:44 +02001238 // Rewind the buffer if necessary
Akron439f4ec2021-08-09 15:45:38 +02001239 if rewindBuffer {
1240
1241 // TODO: Better as a ring buffer
Akron3610f102021-08-08 14:13:25 +02001242 for x, i := range buffer[buffo:buffi] {
1243 buffer[x] = i
1244 }
Akronb4bbb472021-08-09 11:49:38 +02001245
Akron3610f102021-08-08 14:13:25 +02001246 buffi -= buffo
1247 epsilonOffset -= buffo
1248 buffo = 0
1249 if DEBUG {
Akronb4bbb472021-08-09 11:49:38 +02001250 fmt.Println("Remaining:", showBuffer(buffer, buffo, buffi))
Akron3610f102021-08-08 14:13:25 +02001251 }
Akron84d68e62021-08-04 17:06:52 +02001252 }
1253
Akronb7e1f132021-08-10 11:52:31 +02001254 // Move to representative state
Akronf1a16502021-08-16 15:24:38 +02001255 if ta.isSeparate() {
1256 t = ta.getBase()
1257 ta = dat.array[t]
Akronb7e1f132021-08-10 11:52:31 +02001258
1259 if DEBUG {
1260 fmt.Println("Representative pointing to", t)
1261 }
1262 }
1263
Akronc5d8d432021-08-10 16:48:44 +02001264 newchar = true
1265
Akron068874c2021-08-04 15:19:56 +02001266 // TODO:
1267 // Prevent endless epsilon loops!
1268 }
1269
Akron439f4ec2021-08-09 15:45:38 +02001270 // Input reader is not yet finished
Akron3f8571a2021-08-05 11:18:10 +02001271 if !eof {
Akron068874c2021-08-04 15:19:56 +02001272 if DEBUG {
Akronb4bbb472021-08-09 11:49:38 +02001273 fmt.Println("Not at the end - problem", t0, ":", dat.outgoing(t0))
Akron068874c2021-08-04 15:19:56 +02001274 }
1275 return false
1276 }
1277
Akronb7e1f132021-08-10 11:52:31 +02001278 if DEBUG {
1279 fmt.Println("Entering final check")
1280 }
1281
Akronc5d8d432021-08-10 16:48:44 +02001282 // Automaton is in a final state, so flush the buffer and return
Akronf1a16502021-08-16 15:24:38 +02001283 x := dat.array[t].getBase() + uint32(dat.final)
1284
1285 if x < dat.array[1].getCheck() && dat.array[x].getCheck() == t {
Akronb4bbb472021-08-09 11:49:38 +02001286
1287 if buffi > 0 {
Akronb4bbb472021-08-09 11:49:38 +02001288 if DEBUG {
Akron01912fc2021-08-12 11:41:58 +02001289 fmt.Println("-> Flush buffer: [", string(buffer[:buffi]), "]")
Akron3f8571a2021-08-05 11:18:10 +02001290 }
Akron01912fc2021-08-12 11:41:58 +02001291 writer.WriteString(string(buffer[:buffi]))
Akron6e70dc82021-08-11 11:33:18 +02001292
Akronf1a16502021-08-16 15:24:38 +02001293 if dat.array[t].isTokenEnd() {
Akrondf0a3ef2021-08-09 15:53:45 +02001294 writer.WriteRune('\n')
Akronc5d8d432021-08-10 16:48:44 +02001295 if DEBUG {
1296 fmt.Println("-> Newline")
1297 }
Akrondf0a3ef2021-08-09 15:53:45 +02001298 }
Akron84d68e62021-08-04 17:06:52 +02001299 }
1300
Akron6e70dc82021-08-11 11:33:18 +02001301 // Add an additional sentence ending, if the file is over but no explicit
1302 // sentence split was reached. This may be controversial and therefore
1303 // optional via parameter.
Akronf1a16502021-08-16 15:24:38 +02001304 if !dat.array[t0].isTokenEnd() {
Akron6e70dc82021-08-11 11:33:18 +02001305 writer.WriteRune('\n')
1306 if DEBUG {
1307 fmt.Println("-> Newline")
1308 }
1309 }
1310
Akrone61380b2021-08-16 10:10:46 +02001311 // TODO:
1312 // There may be a new line at the end, from an epsilon,
1313 // so we may need to go on!
Akron068874c2021-08-04 15:19:56 +02001314 return true
1315 }
1316
Akronc5d8d432021-08-10 16:48:44 +02001317 // Check epsilon transitions until a final state is reached
1318 t0 = t
Akronf1a16502021-08-16 15:24:38 +02001319 t = dat.array[t0].getBase() + uint32(dat.epsilon)
Akron01912fc2021-08-12 11:41:58 +02001320 a = dat.epsilon
1321 newchar = false
Akronf1a16502021-08-16 15:24:38 +02001322 if dat.array[t].getCheck() == t0 {
Akronc5d8d432021-08-10 16:48:44 +02001323 // Remember state for backtracking to last tokenend state
Akronc5d8d432021-08-10 16:48:44 +02001324 goto PARSECHAR
Akrone61380b2021-08-16 10:10:46 +02001325
Akronc5d8d432021-08-10 16:48:44 +02001326 } else if epsilonState != 0 {
Akronb7e1f132021-08-10 11:52:31 +02001327 t0 = epsilonState
1328 epsilonState = 0 // reset
1329 buffo = epsilonOffset
Akron068874c2021-08-04 15:19:56 +02001330 if DEBUG {
Akronc5d8d432021-08-10 16:48:44 +02001331 fmt.Println("Get from epsilon stack and set buffo!", showBuffer(buffer, buffo, buffi))
Akron068874c2021-08-04 15:19:56 +02001332 }
Akronc5d8d432021-08-10 16:48:44 +02001333 goto PARSECHAR
Akron068874c2021-08-04 15:19:56 +02001334 }
Akronc5d8d432021-08-10 16:48:44 +02001335 return false
Akron068874c2021-08-04 15:19:56 +02001336}