blob: 8fb3d19a979efcd4b043020654405c7f86751155 [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 }
Akron83e75a22021-08-04 13:14:06 +0200351 } else if inSym == tok.epsilon {
Akron527c10c2021-08-13 01:45:18 +0200352 log.Println("General epsilon transitions are not supported")
Akron4db3ecf2021-08-11 18:49:03 +0200353 return nil
Akron31f3c062021-08-27 10:15:13 +0200354 } else if tok.sigmaMCS[inSym] != "" {
355 log.Fatalln("Non supported character", tok.sigmaMCS[inSym])
356 } else if tok.sigmaMCS[outSym] != "" {
357 log.Fatalln("Non supported character", tok.sigmaMCS[outSym])
Akron8ef408b2021-08-02 22:11:04 +0200358 }
359
Akron03c92fe2021-08-09 14:07:57 +0200360 // Create an edge based on the collected information
Akron8ef408b2021-08-02 22:11:04 +0200361 targetObj := &edge{
Akron83e75a22021-08-04 13:14:06 +0200362 inSym: inSym,
363 outSym: outSym,
364 end: end + 1,
365 tokenend: tokenend,
366 nontoken: nontoken,
Akron8ef408b2021-08-02 22:11:04 +0200367 }
368
Akron740f3d72021-08-03 12:12:34 +0200369 // Initialize outgoing states
370 if tok.transitions[state+1] == nil {
371 tok.transitions[state+1] = make(map[int]*edge)
Akron8ef408b2021-08-02 22:11:04 +0200372 }
373
Akron740f3d72021-08-03 12:12:34 +0200374 // Ignore transitions with invalid symbols
375 if inSym >= 0 {
376 tok.transitions[state+1][inSym] = targetObj
Akron75ebe7f2021-08-03 10:34:10 +0200377 }
Akron8ef408b2021-08-02 22:11:04 +0200378
Akron740f3d72021-08-03 12:12:34 +0200379 // Add final transition
380 if final == 1 {
Akron03c92fe2021-08-09 14:07:57 +0200381 // TODO:
382 // Maybe this is less relevant for tokenizers
Akronc17f1ca2021-08-03 19:47:27 +0200383 tok.transitions[state+1][tok.final] = &edge{}
Akron8ef408b2021-08-02 22:11:04 +0200384 }
385
Akronb4bbb472021-08-09 11:49:38 +0200386 if DEBUG {
Akron740f3d72021-08-03 12:12:34 +0200387 fmt.Println("Add",
388 state+1, "->", end+1,
389 "(",
390 inSym,
391 ":",
392 outSym,
393 ") (",
394 string(tok.sigmaRev[inSym]),
395 ":",
396 string(tok.sigmaRev[outSym]),
Akron524c5432021-08-05 14:14:27 +0200397 ")",
398 ";",
399 "TE:", tokenend,
Akron3610f102021-08-08 14:13:25 +0200400 "NT:", nontoken,
401 "FIN:", final)
Akron740f3d72021-08-03 12:12:34 +0200402 }
Akron75ebe7f2021-08-03 10:34:10 +0200403
Akron8ef408b2021-08-02 22:11:04 +0200404 continue
405 }
406 case SIGMA:
407 {
408 elem = strings.SplitN(line[0:len(line)-1], " ", 2)
409
410 // Turn string into sigma id
411 number, err := strconv.Atoi(elem[0])
412
Akron524c5432021-08-05 14:14:27 +0200413 // ID needs to be > 1
414 number++
415
Akron8ef408b2021-08-02 22:11:04 +0200416 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200417 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200418 return nil
Akron8ef408b2021-08-02 22:11:04 +0200419 }
420
Akron740f3d72021-08-03 12:12:34 +0200421 tok.sigmaCount = number
Akron8ef408b2021-08-02 22:11:04 +0200422
423 var symbol rune
424
425 // Read rune
426 if utf8.RuneCountInString(elem[1]) == 1 {
427 symbol = []rune(elem[1])[0]
428
Akron8ef408b2021-08-02 22:11:04 +0200429 } else if utf8.RuneCountInString(elem[1]) > 1 {
Akron439f4ec2021-08-09 15:45:38 +0200430
431 // Probably a MCS
Akron8ef408b2021-08-02 22:11:04 +0200432 switch elem[1] {
433 case "@_EPSILON_SYMBOL_@":
434 {
Akronc17f1ca2021-08-03 19:47:27 +0200435 tok.epsilon = number
Akron8ef408b2021-08-02 22:11:04 +0200436 }
437 case "@_UNKNOWN_SYMBOL_@":
438 {
Akronc17f1ca2021-08-03 19:47:27 +0200439 tok.unknown = number
Akron8ef408b2021-08-02 22:11:04 +0200440 }
441
442 case "@_IDENTITY_SYMBOL_@":
443 {
Akronc17f1ca2021-08-03 19:47:27 +0200444 tok.identity = number
Akron8ef408b2021-08-02 22:11:04 +0200445 }
Akron03c92fe2021-08-09 14:07:57 +0200446
447 case "@_TOKEN_SYMBOL_@":
448 {
449 tok.tokenend = number
Akron03c92fe2021-08-09 14:07:57 +0200450 }
Akron8ef408b2021-08-02 22:11:04 +0200451 default:
Akron740f3d72021-08-03 12:12:34 +0200452 {
Akron31f3c062021-08-27 10:15:13 +0200453 // MCS not supported
454 tok.sigmaMCS[number] = line
Akron740f3d72021-08-03 12:12:34 +0200455 }
Akron8ef408b2021-08-02 22:11:04 +0200456 }
Akron439f4ec2021-08-09 15:45:38 +0200457 continue
Akron8ef408b2021-08-02 22:11:04 +0200458
Akron740f3d72021-08-03 12:12:34 +0200459 } else { // Probably a new line symbol
Akron8ef408b2021-08-02 22:11:04 +0200460 line, err = r.ReadString('\n')
461 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200462 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200463 return nil
Akron8ef408b2021-08-02 22:11:04 +0200464 }
465 if len(line) != 1 {
Akron31f3c062021-08-27 10:15:13 +0200466 // MCS not supported
467 tok.sigmaMCS[number] = line
468 continue
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 }
Akron31f3c062021-08-27 10:15:13 +0200477 tok.sigmaMCS = nil
Akron8ef408b2021-08-02 22:11:04 +0200478 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),
Akron4fa28b32021-08-27 10:55:41 +0200500 transCount: -1,
Akron03a3c612021-08-04 11:51:27 +0200501 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
Akronde18e902021-08-27 09:34:12 +0200520 var atrans *edge
521 var s, s1 int
522 var t, t1 uint32
Akron8ef408b2021-08-02 22:11:04 +0200523
Akron439f4ec2021-08-09 15:45:38 +0200524 // Create a mapping from s (in Ms aka Intermediate FSA)
525 // to t (in Mt aka Double Array FSA)
Akron740f3d72021-08-03 12:12:34 +0200526 table := make([]*mapping, tok.arcCount+1)
Akron8ef408b2021-08-02 22:11:04 +0200527
Akron439f4ec2021-08-09 15:45:38 +0200528 // Initialize with the start state
Akron8ef408b2021-08-02 22:11:04 +0200529 table[size] = &mapping{source: 1, target: 1}
530 size++
531
Akron740f3d72021-08-03 12:12:34 +0200532 // Allocate space for the outgoing symbol range
533 A := make([]int, 0, tok.sigmaCount)
Akron8ef408b2021-08-02 22:11:04 +0200534
Akronde18e902021-08-27 09:34:12 +0200535 // TODO:
536 // Table lookup for the moment
537 // only gives a minor performance benefit.
538 // should be rewritten and should preplace the
539 // table all together.
540 // tableLookup := make(map[int]uint32)
541 // tableLookup[1] = 1
542
Akron8ef408b2021-08-02 22:11:04 +0200543 for mark < size {
Akronde18e902021-08-27 09:34:12 +0200544 s = table[mark].source // This is a state in Ms
545 t = table[mark].target // This is a state in Mt
Akron8ef408b2021-08-02 22:11:04 +0200546 mark++
Akron740f3d72021-08-03 12:12:34 +0200547
548 // Following the paper, here the state t can be remembered
549 // in the set of states St
Akron8ef408b2021-08-02 22:11:04 +0200550 A = A[:0]
Akron439f4ec2021-08-09 15:45:38 +0200551 tok.getSet(s, &A)
Akron8ef408b2021-08-02 22:11:04 +0200552
Akron740f3d72021-08-03 12:12:34 +0200553 // Set base to the first free slot in the double array
Akron6f1c16c2021-08-17 10:45:42 +0200554 base = dat.xCheck(A)
555 dat.array[t].setBase(base)
Akron8ef408b2021-08-02 22:11:04 +0200556
Akron773b1ef2021-08-03 17:37:20 +0200557 // TODO:
Akron068874c2021-08-04 15:19:56 +0200558 // Sort the outgoing transitions based on the
Akron773b1ef2021-08-03 17:37:20 +0200559 // outdegree of .end
560
Akron740f3d72021-08-03 12:12:34 +0200561 // Iterate over all outgoing symbols
Akron8ef408b2021-08-02 22:11:04 +0200562 for _, a := range A {
563
Akronc17f1ca2021-08-03 19:47:27 +0200564 if a != tok.final {
Akron8ef408b2021-08-02 22:11:04 +0200565
Akronde18e902021-08-27 09:34:12 +0200566 atrans = tok.transitions[s][a]
567
Akron740f3d72021-08-03 12:12:34 +0200568 // Aka g(s, a)
Akronde18e902021-08-27 09:34:12 +0200569 s1 = atrans.end
Akron8ef408b2021-08-02 22:11:04 +0200570
Akron740f3d72021-08-03 12:12:34 +0200571 // Store the transition
Akronde18e902021-08-27 09:34:12 +0200572 t1 = base + uint32(a)
Akronf1a16502021-08-16 15:24:38 +0200573 dat.array[t1].setCheck(t)
574
575 // Set maxSize
576 if dat.maxSize < int(t1) {
577 dat.maxSize = int(t1)
578 }
Akron8ef408b2021-08-02 22:11:04 +0200579
Akron439f4ec2021-08-09 15:45:38 +0200580 if DEBUG {
Akron524c5432021-08-05 14:14:27 +0200581 fmt.Println("Translate transition",
582 s, "->", s1, "(", a, ")", "to", t, "->", t1)
583 }
584
Akron83e75a22021-08-04 13:14:06 +0200585 // Mark the state as being the target of a nontoken transition
Akronde18e902021-08-27 09:34:12 +0200586 if atrans.nontoken {
Akronf1a16502021-08-16 15:24:38 +0200587 dat.array[t1].setNonToken(true)
Akron524c5432021-08-05 14:14:27 +0200588 if DEBUG {
589 fmt.Println("Set", t1, "to nontoken")
590 }
Akron83e75a22021-08-04 13:14:06 +0200591 }
592
Akron84d68e62021-08-04 17:06:52 +0200593 // Mark the state as being the target of a tokenend transition
Akronde18e902021-08-27 09:34:12 +0200594 if atrans.tokenend {
Akronf1a16502021-08-16 15:24:38 +0200595 dat.array[t1].setTokenEnd(true)
Akron524c5432021-08-05 14:14:27 +0200596 if DEBUG {
597 fmt.Println("Set", t1, "to tokenend")
598 }
Akron84d68e62021-08-04 17:06:52 +0200599 }
600
Akron740f3d72021-08-03 12:12:34 +0200601 // Check for representative states
Akron439f4ec2021-08-09 15:45:38 +0200602 r := stateAlreadyInTable(s1, table, size)
Akronde18e902021-08-27 09:34:12 +0200603 // r := tableLookup[s1]
Akron740f3d72021-08-03 12:12:34 +0200604
Akron439f4ec2021-08-09 15:45:38 +0200605 // No representative found
Akron8ef408b2021-08-02 22:11:04 +0200606 if r == 0 {
Akron740f3d72021-08-03 12:12:34 +0200607 // Remember the mapping
Akron8ef408b2021-08-02 22:11:04 +0200608 table[size] = &mapping{source: s1, target: t1}
Akronde18e902021-08-27 09:34:12 +0200609 // tableLookup[s1] = t1
Akron8ef408b2021-08-02 22:11:04 +0200610 size++
611 } else {
Akron740f3d72021-08-03 12:12:34 +0200612 // Overwrite with the representative state
Akronf1a16502021-08-16 15:24:38 +0200613 dat.array[t1].setBase(r)
614 dat.array[t1].setSeparate(true)
Akron8ef408b2021-08-02 22:11:04 +0200615 }
616 } else {
Akron740f3d72021-08-03 12:12:34 +0200617 // Store a final transition
Akron6f1c16c2021-08-17 10:45:42 +0200618 dat.array[base+uint32(dat.final)].setCheck(t)
Akronf1a16502021-08-16 15:24:38 +0200619
Akronde18e902021-08-27 09:34:12 +0200620 if dat.maxSize < int(base)+dat.final {
621 dat.maxSize = int(base) + dat.final
Akronf1a16502021-08-16 15:24:38 +0200622 }
Akron8ef408b2021-08-02 22:11:04 +0200623 }
624 }
625 }
626
627 // Following Mizobuchi et al (2000) the size of the
628 // FSA should be stored in check(1).
Akronf1a16502021-08-16 15:24:38 +0200629 // We make the size a bit smaller so we never have to check for boundaries.
Akron3fdfec62021-08-04 11:40:10 +0200630 dat.setSize(dat.maxSize + 1)
Akronf2120ca2021-08-03 16:26:41 +0200631 dat.array = dat.array[:dat.maxSize+1]
632 return dat
Akron8ef408b2021-08-02 22:11:04 +0200633}
634
Akron8ef408b2021-08-02 22:11:04 +0200635// Check the table if a mapping of s
Akron740f3d72021-08-03 12:12:34 +0200636// exists and return this as a representative.
637// Currently iterates through the whole table
638// in a bruteforce manner.
Akron439f4ec2021-08-09 15:45:38 +0200639func stateAlreadyInTable(s int, table []*mapping, size int) uint32 {
Akron8ef408b2021-08-02 22:11:04 +0200640 for x := 0; x < size; x++ {
641 if table[x].source == s {
642 return table[x].target
643 }
644 }
645 return 0
646}
647
Akron64ffd9a2021-08-03 19:55:21 +0200648// Resize double array when necessary
649func (dat *DaTokenizer) resize(l int) {
650 // TODO:
651 // This is a bit too aggressive atm and should be calmed down.
652 if len(dat.array) <= l {
Akronf1a16502021-08-16 15:24:38 +0200653 dat.array = append(dat.array, make([]bc, l)...)
Akron8ef408b2021-08-02 22:11:04 +0200654 }
Akron64ffd9a2021-08-03 19:55:21 +0200655}
Akronc9d84a62021-08-03 15:56:03 +0200656
Akron64ffd9a2021-08-03 19:55:21 +0200657// Set base value in double array
Akronf1a16502021-08-16 15:24:38 +0200658func (bc *bc) setBase(v uint32) {
659 bc.base = v
Akron439f4ec2021-08-09 15:45:38 +0200660}
661
662// Get base value in double array
Akronf1a16502021-08-16 15:24:38 +0200663func (bc *bc) getBase() uint32 {
664 return bc.base & RESTBIT
Akron439f4ec2021-08-09 15:45:38 +0200665}
666
667// Set check value in double array
Akronf1a16502021-08-16 15:24:38 +0200668func (bc *bc) setCheck(v uint32) {
669 bc.check = v
Akron439f4ec2021-08-09 15:45:38 +0200670}
671
672// Get check value in double array
Akronf1a16502021-08-16 15:24:38 +0200673func (bc *bc) getCheck() uint32 {
674 return bc.check & RESTBIT
Akron64ffd9a2021-08-03 19:55:21 +0200675}
676
Akron3fdfec62021-08-04 11:40:10 +0200677// Returns true if a state is separate pointing to a representative
Akronf1a16502021-08-16 15:24:38 +0200678func (bc *bc) isSeparate() bool {
679 return bc.base&FIRSTBIT != 0
Akron3fdfec62021-08-04 11:40:10 +0200680}
681
682// Mark a state as separate pointing to a representative
Akronf1a16502021-08-16 15:24:38 +0200683func (bc *bc) setSeparate(sep bool) {
Akron3fdfec62021-08-04 11:40:10 +0200684 if sep {
Akronf1a16502021-08-16 15:24:38 +0200685 bc.base |= FIRSTBIT
Akron3fdfec62021-08-04 11:40:10 +0200686 } else {
Akronf1a16502021-08-16 15:24:38 +0200687 bc.base &= (RESTBIT | SECONDBIT)
Akron3fdfec62021-08-04 11:40:10 +0200688 }
689}
690
Akron83e75a22021-08-04 13:14:06 +0200691// Returns true if a state is the target of a nontoken transition
Akronf1a16502021-08-16 15:24:38 +0200692func (bc *bc) isNonToken() bool {
693 return bc.check&FIRSTBIT != 0
Akron83e75a22021-08-04 13:14:06 +0200694}
695
696// Mark a state as being the target of a nontoken transition
Akronf1a16502021-08-16 15:24:38 +0200697func (bc *bc) setNonToken(sep bool) {
Akron83e75a22021-08-04 13:14:06 +0200698 if sep {
Akronf1a16502021-08-16 15:24:38 +0200699 bc.check |= FIRSTBIT
Akron83e75a22021-08-04 13:14:06 +0200700 } else {
Akronf1a16502021-08-16 15:24:38 +0200701 bc.check &= (RESTBIT | SECONDBIT)
Akron83e75a22021-08-04 13:14:06 +0200702 }
703}
704
Akron84d68e62021-08-04 17:06:52 +0200705// Returns true if a state is the target of a tokenend transition
Akronf1a16502021-08-16 15:24:38 +0200706func (bc *bc) isTokenEnd() bool {
707 return bc.check&SECONDBIT != 0
Akron84d68e62021-08-04 17:06:52 +0200708}
709
710// Mark a state as being the target of a tokenend transition
Akronf1a16502021-08-16 15:24:38 +0200711func (bc *bc) setTokenEnd(sep bool) {
Akron84d68e62021-08-04 17:06:52 +0200712 if sep {
Akronf1a16502021-08-16 15:24:38 +0200713 bc.check |= SECONDBIT
Akron84d68e62021-08-04 17:06:52 +0200714 } else {
Akronf1a16502021-08-16 15:24:38 +0200715 bc.check &= (RESTBIT | FIRSTBIT)
Akron84d68e62021-08-04 17:06:52 +0200716 }
717}
718
Akron64ffd9a2021-08-03 19:55:21 +0200719// Set size of double array
Akron3fdfec62021-08-04 11:40:10 +0200720func (dat *DaTokenizer) setSize(v int) {
Akronf1a16502021-08-16 15:24:38 +0200721 dat.array[1].setCheck(uint32(v))
Akron64ffd9a2021-08-03 19:55:21 +0200722}
723
724// Get size of double array
Akron3fdfec62021-08-04 11:40:10 +0200725func (dat *DaTokenizer) GetSize() int {
Akronf1a16502021-08-16 15:24:38 +0200726 return int(dat.array[1].getCheck())
Akron8ef408b2021-08-02 22:11:04 +0200727}
728
729// Based on Mizobuchi et al (2000), p. 124
730// This iterates for every state through the complete double array
731// structure until it finds a gap that fits all outgoing transitions
732// of the state. This is extremely slow, but is only necessary in the
733// construction phase of the tokenizer.
Akron3fdfec62021-08-04 11:40:10 +0200734func (dat *DaTokenizer) xCheck(symbols []int) uint32 {
Akron740f3d72021-08-03 12:12:34 +0200735
736 // Start at the first entry of the double array list
Akron6f1c16c2021-08-17 10:45:42 +0200737 base := uint32(1)
738
Akron8ef408b2021-08-02 22:11:04 +0200739OVERLAP:
Akron740f3d72021-08-03 12:12:34 +0200740 // Resize the array if necessary
Akronf1a16502021-08-16 15:24:38 +0200741 dat.resize(int(base) + dat.final)
Akron8ef408b2021-08-02 22:11:04 +0200742 for _, a := range symbols {
Akronf1a16502021-08-16 15:24:38 +0200743 if dat.array[int(base)+a].getCheck() != 0 {
Akron8ef408b2021-08-02 22:11:04 +0200744 base++
745 goto OVERLAP
746 }
747 }
Akron8ef408b2021-08-02 22:11:04 +0200748 return base
749}
750
Akron3610f102021-08-08 14:13:25 +0200751// List all outgoing transitions for a state
752// for testing purposes
753func (dat *DaTokenizer) outgoing(t uint32) []int {
754
755 valid := make([]int, 0, len(dat.sigma))
756
757 for _, a := range dat.sigma {
Akronf1a16502021-08-16 15:24:38 +0200758 t1 := dat.array[t].getBase() + uint32(a)
759 if t1 <= dat.array[1].getCheck() && dat.array[t1].getCheck() == t {
Akron3610f102021-08-08 14:13:25 +0200760 valid = append(valid, a)
761 }
762 }
763
764 for _, a := range []int{dat.epsilon, dat.unknown, dat.identity, dat.final} {
Akronf1a16502021-08-16 15:24:38 +0200765 t1 := dat.array[t].getBase() + uint32(a)
766 if t1 <= dat.array[1].getCheck() && dat.array[t1].getCheck() == t {
Akron3610f102021-08-08 14:13:25 +0200767 valid = append(valid, -1*a)
768 }
769 }
770
771 sort.Ints(valid)
772
773 return valid
774}
775
Akron4fa28b32021-08-27 10:55:41 +0200776// TransCount as the number of transitions aka arcs in the
777// finite state automaton
778func (dat *DaTokenizer) TransCount() int {
779 // Cache the transCount
780 if dat.transCount > 0 {
781 return dat.transCount
782 }
783
784 dat.transCount = 0
785 for x := 1; x < len(dat.array); x++ {
786 if dat.array[x].getBase() != 0 {
787 dat.transCount++
788 }
789 }
790
791 return dat.transCount
792}
793
Akron03a3c612021-08-04 11:51:27 +0200794// LoadFactor as defined in Kanda et al (2018),
795// i.e. the proportion of non-empty elements to all elements.
796func (dat *DaTokenizer) LoadFactor() float64 {
Akron4fa28b32021-08-27 10:55:41 +0200797 return float64(dat.TransCount()) / float64(len(dat.array)) * 100
Akrond66a9262021-08-03 17:09:09 +0200798}
799
Akron439f4ec2021-08-09 15:45:38 +0200800// Save stores the double array data in a file
Akron3a063ef2021-08-05 19:36:35 +0200801func (dat *DaTokenizer) Save(file string) (n int64, err error) {
802 f, err := os.Create(file)
803 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200804 log.Println(err)
Akron439f4ec2021-08-09 15:45:38 +0200805 return 0, err
Akron3a063ef2021-08-05 19:36:35 +0200806 }
807 defer f.Close()
808 gz := gzip.NewWriter(f)
809 defer gz.Close()
810 n, err = dat.WriteTo(gz)
811 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200812 log.Println(err)
Akron3a063ef2021-08-05 19:36:35 +0200813 return n, err
814 }
815 gz.Flush()
816 return n, nil
817}
818
819// WriteTo stores the double array data in an io.Writer.
Akron6247a5d2021-08-03 19:18:28 +0200820func (dat *DaTokenizer) WriteTo(w io.Writer) (n int64, err error) {
821
Akron3a063ef2021-08-05 19:36:35 +0200822 wb := bufio.NewWriter(w)
823 defer wb.Flush()
824
Akron6247a5d2021-08-03 19:18:28 +0200825 // Store magical header
Akron3a063ef2021-08-05 19:36:35 +0200826 all, err := wb.Write([]byte(MAGIC))
Akron6247a5d2021-08-03 19:18:28 +0200827 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200828 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200829 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200830 }
831
832 // Get sigma as a list
833 sigmalist := make([]rune, len(dat.sigma)+16)
834 max := 0
835 for sym, num := range dat.sigma {
836 sigmalist[num] = sym
837 if num > max {
838 max = num
839 }
840 }
841
842 sigmalist = sigmalist[:max+1]
843
Akron3f8571a2021-08-05 11:18:10 +0200844 buf := make([]byte, 0, 16)
Akron6247a5d2021-08-03 19:18:28 +0200845 bo.PutUint16(buf[0:2], VERSION)
Akronc17f1ca2021-08-03 19:47:27 +0200846 bo.PutUint16(buf[2:4], uint16(dat.epsilon))
847 bo.PutUint16(buf[4:6], uint16(dat.unknown))
848 bo.PutUint16(buf[6:8], uint16(dat.identity))
849 bo.PutUint16(buf[8:10], uint16(dat.final))
Akron6247a5d2021-08-03 19:18:28 +0200850 bo.PutUint16(buf[10:12], uint16(len(sigmalist)))
Akronf1a16502021-08-16 15:24:38 +0200851 bo.PutUint32(buf[12:16], uint32(len(dat.array)*2)) // Legacy support
Akron3a063ef2021-08-05 19:36:35 +0200852 more, err := wb.Write(buf[0:16])
Akron6247a5d2021-08-03 19:18:28 +0200853 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200854 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200855 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200856 }
857
858 all += more
859
Akron6247a5d2021-08-03 19:18:28 +0200860 // Write sigma
861 for _, sym := range sigmalist {
Akron3f8571a2021-08-05 11:18:10 +0200862
Akron3a063ef2021-08-05 19:36:35 +0200863 more, err = wb.WriteRune(sym)
Akron6247a5d2021-08-03 19:18:28 +0200864 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200865 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200866 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200867 }
868 all += more
869 }
Akron439f4ec2021-08-09 15:45:38 +0200870
Akron6247a5d2021-08-03 19:18:28 +0200871 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200872 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200873 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200874 }
Akron6247a5d2021-08-03 19:18:28 +0200875
876 // Test marker - could be checksum
Akron3a063ef2021-08-05 19:36:35 +0200877 more, err = wb.Write([]byte("T"))
Akron6247a5d2021-08-03 19:18:28 +0200878 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200879 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200880 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200881 }
882 all += more
883
Akronf1a16502021-08-16 15:24:38 +0200884 // for x := 0; x < len(dat.array); x++ {
885 for _, bc := range dat.array {
886 bo.PutUint32(buf[0:4], bc.base)
887 more, err = wb.Write(buf[0:4])
Akron6247a5d2021-08-03 19:18:28 +0200888 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200889 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200890 return int64(all), err
Akron6247a5d2021-08-03 19:18:28 +0200891 }
Akron439f4ec2021-08-09 15:45:38 +0200892 all += more
Akron3a063ef2021-08-05 19:36:35 +0200893 if more != 4 {
Akronf1a16502021-08-16 15:24:38 +0200894 log.Println("Can not write base uint32")
895 return int64(all), err
896 }
897 bo.PutUint32(buf[0:4], bc.check)
898 more, err = wb.Write(buf[0:4])
899 if err != nil {
900 log.Println(err)
901 return int64(all), err
902 }
903 all += more
904 if more != 4 {
905 log.Println("Can not write check uint32")
Akron3a063ef2021-08-05 19:36:35 +0200906 return int64(all), err
907 }
Akron6247a5d2021-08-03 19:18:28 +0200908 }
909
910 return int64(all), err
911}
912
Akron439f4ec2021-08-09 15:45:38 +0200913// LoadDatokFile reads a double array represented tokenizer
914// from a file.
Akron3f8571a2021-08-05 11:18:10 +0200915func LoadDatokFile(file string) *DaTokenizer {
916 f, err := os.Open(file)
917 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200918 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200919 return nil
Akron3f8571a2021-08-05 11:18:10 +0200920 }
921 defer f.Close()
922
923 gz, err := gzip.NewReader(f)
924 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200925 log.Println(err)
Akron4db3ecf2021-08-11 18:49:03 +0200926 return nil
Akron3f8571a2021-08-05 11:18:10 +0200927 }
928 defer gz.Close()
929
Akron3a063ef2021-08-05 19:36:35 +0200930 // Todo: Read the whole file!
Akron3f8571a2021-08-05 11:18:10 +0200931 return ParseDatok(gz)
932}
933
Akron439f4ec2021-08-09 15:45:38 +0200934// LoadDatokFile reads a double array represented tokenizer
935// from an io.Reader
Akron3f8571a2021-08-05 11:18:10 +0200936func ParseDatok(ior io.Reader) *DaTokenizer {
937
Akron439f4ec2021-08-09 15:45:38 +0200938 // Initialize tokenizer with default values
Akron3f8571a2021-08-05 11:18:10 +0200939 dat := &DaTokenizer{
940 sigma: make(map[rune]int),
941 epsilon: 0,
942 unknown: 0,
943 identity: 0,
944 final: 0,
Akron4fa28b32021-08-27 10:55:41 +0200945 transCount: 0,
Akron3f8571a2021-08-05 11:18:10 +0200946 }
947
948 r := bufio.NewReader(ior)
949
Akron3f8571a2021-08-05 11:18:10 +0200950 buf := make([]byte, 1024)
951 buf = buf[0:len(MAGIC)]
952
Akron439f4ec2021-08-09 15:45:38 +0200953 _, err := r.Read(buf)
Akron3f8571a2021-08-05 11:18:10 +0200954
955 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200956 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200957 return nil
958 }
959
Akron3f8571a2021-08-05 11:18:10 +0200960 if string(MAGIC) != string(buf) {
Akron527c10c2021-08-13 01:45:18 +0200961 log.Println("Not a datok file")
Akron3f8571a2021-08-05 11:18:10 +0200962 return nil
963 }
964
Akron439f4ec2021-08-09 15:45:38 +0200965 more, err := io.ReadFull(r, buf[0:16])
Akron3f8571a2021-08-05 11:18:10 +0200966 if err != nil {
Akron527c10c2021-08-13 01:45:18 +0200967 log.Println(err)
Akron3f8571a2021-08-05 11:18:10 +0200968 return nil
969 }
970
Akron439f4ec2021-08-09 15:45:38 +0200971 if more != 16 {
Akron527c10c2021-08-13 01:45:18 +0200972 log.Println("Read bytes do not fit")
Akron439f4ec2021-08-09 15:45:38 +0200973 return nil
974 }
Akron3f8571a2021-08-05 11:18:10 +0200975
Akron3a063ef2021-08-05 19:36:35 +0200976 version := bo.Uint16(buf[0:2])
977
978 if version != VERSION {
Akron527c10c2021-08-13 01:45:18 +0200979 log.Println("Version not compatible")
Akron3a063ef2021-08-05 19:36:35 +0200980 return nil
981 }
982
Akron3f8571a2021-08-05 11:18:10 +0200983 dat.epsilon = int(bo.Uint16(buf[2:4]))
984 dat.unknown = int(bo.Uint16(buf[4:6]))
985 dat.identity = int(bo.Uint16(buf[6:8]))
986 dat.final = int(bo.Uint16(buf[8:10]))
987
988 sigmaCount := int(bo.Uint16(buf[10:12]))
Akronf1a16502021-08-16 15:24:38 +0200989 arraySize := int(bo.Uint32(buf[12:16])) / 2 // Legacy support
Akron3f8571a2021-08-05 11:18:10 +0200990
Akron3a063ef2021-08-05 19:36:35 +0200991 // Shouldn't be relevant though
992 dat.maxSize = arraySize - 1
993
Akron3f8571a2021-08-05 11:18:10 +0200994 for x := 0; x < sigmaCount; x++ {
Akron439f4ec2021-08-09 15:45:38 +0200995 sym, _, err := r.ReadRune()
Akron3f8571a2021-08-05 11:18:10 +0200996 if err == nil && sym != 0 {
Akronea46e8a2021-08-17 00:36:31 +0200997 if int(sym) < 256 {
998 dat.sigmaASCII[int(sym)] = x
999 }
Akron3f8571a2021-08-05 11:18:10 +02001000 dat.sigma[sym] = x
1001 }
Akron3f8571a2021-08-05 11:18:10 +02001002 }
1003
Akron439f4ec2021-08-09 15:45:38 +02001004 _, err = io.ReadFull(r, buf[0:1])
Akron3f8571a2021-08-05 11:18:10 +02001005
1006 if err != nil {
Akron527c10c2021-08-13 01:45:18 +02001007 log.Print(err)
Akron3f8571a2021-08-05 11:18:10 +02001008 return nil
1009 }
1010
Akron3f8571a2021-08-05 11:18:10 +02001011 if string("T") != string(buf[0:1]) {
Akron527c10c2021-08-13 01:45:18 +02001012 log.Println("Not a datok file")
Akron3f8571a2021-08-05 11:18:10 +02001013 return nil
1014 }
1015
1016 // Read based on length
Akronf1a16502021-08-16 15:24:38 +02001017 dat.array = make([]bc, arraySize)
Akron3f8571a2021-08-05 11:18:10 +02001018
Akronbb4aac52021-08-13 00:52:27 +02001019 dataArray, err := io.ReadAll(r)
Akron439f4ec2021-08-09 15:45:38 +02001020
Akronbb4aac52021-08-13 00:52:27 +02001021 if err == io.EOF {
Akron527c10c2021-08-13 01:45:18 +02001022 log.Println(err)
Akronbb4aac52021-08-13 00:52:27 +02001023 return nil
1024 }
1025
Akronf1a16502021-08-16 15:24:38 +02001026 if len(dataArray) < arraySize*8 {
Akron527c10c2021-08-13 01:45:18 +02001027 log.Println("Not enough bytes read")
Akronbb4aac52021-08-13 00:52:27 +02001028 return nil
1029 }
1030
1031 for x := 0; x < arraySize; x++ {
Akronf1a16502021-08-16 15:24:38 +02001032 dat.array[x].base = bo.Uint32(dataArray[x*8 : (x*8)+4])
1033 dat.array[x].check = bo.Uint32(dataArray[(x*8)+4 : (x*8)+8])
Akron3f8571a2021-08-05 11:18:10 +02001034 }
1035
1036 return dat
1037}
1038
Akron439f4ec2021-08-09 15:45:38 +02001039// Show the current state of the buffer,
1040// for testing puroses
Akron3610f102021-08-08 14:13:25 +02001041func showBuffer(buffer []rune, buffo int, buffi int) string {
1042 out := make([]rune, 0, 1024)
1043 for x := 0; x < len(buffer); x++ {
1044 if buffi == x {
1045 out = append(out, '^')
1046 }
1047 if buffo == x {
1048 out = append(out, '[', buffer[x], ']')
1049 } else {
1050 out = append(out, buffer[x])
1051 }
1052 }
1053 return string(out)
1054}
1055
Akron84d68e62021-08-04 17:06:52 +02001056// Transduce an input string against the double array
Akron3610f102021-08-08 14:13:25 +02001057// FSA. The rules are always greedy. If the automaton fails,
1058// it takes the last possible token ending branch.
Akron068874c2021-08-04 15:19:56 +02001059//
Akron4db3ecf2021-08-11 18:49:03 +02001060// Based on Mizobuchi et al (2000), p. 129,
1061// with additional support for IDENTITY, UNKNOWN
1062// and EPSILON transitions and NONTOKEN and TOKENEND handling.
Akron3f8571a2021-08-05 11:18:10 +02001063func (dat *DaTokenizer) Transduce(r io.Reader, w io.Writer) bool {
Akron068874c2021-08-04 15:19:56 +02001064 var a int
Akronb4bbb472021-08-09 11:49:38 +02001065 var t0 uint32
Akronb7e1f132021-08-10 11:52:31 +02001066 t := uint32(1) // Initial state
1067 var ok, rewindBuffer bool
Akron068874c2021-08-04 15:19:56 +02001068
Akron3610f102021-08-08 14:13:25 +02001069 // Remember the last position of a possible tokenend,
1070 // in case the automaton fails.
1071 epsilonState := uint32(0)
1072 epsilonOffset := 0
1073
1074 // Implement a low level buffer for full control,
1075 // however - it is probably better to introduce
1076 // this on a higher level with a io.Reader interface
1077 // The buffer stores a single word and may have white
1078 // space at the end (but not at the beginning).
1079 //
1080 // This is the only backtracking requirement because of
1081 // epsilon transitions, to support tokenizations like:
1082 // "this is an example|.| And it works." vs
1083 // "this is an example.com| application."
Akronb7e1f132021-08-10 11:52:31 +02001084 //
1085 // TODO:
1086 // Store a translation buffer as well, so characters don't
1087 // have to be translated multiple times!
Akron3610f102021-08-08 14:13:25 +02001088 buffer := make([]rune, 1024)
1089 buffo := 0 // Buffer offset
1090 buffi := 0 // Buffer length
1091
Akron3f8571a2021-08-05 11:18:10 +02001092 reader := bufio.NewReader(r)
1093 writer := bufio.NewWriter(w)
1094 defer writer.Flush()
Akron068874c2021-08-04 15:19:56 +02001095
Akron3f8571a2021-08-05 11:18:10 +02001096 var char rune
1097 var err error
1098 eof := false
Akronb7e1f132021-08-10 11:52:31 +02001099 newchar := true
Akron3f8571a2021-08-05 11:18:10 +02001100
Akronc5d8d432021-08-10 16:48:44 +02001101PARSECHAR:
Akron3f8571a2021-08-05 11:18:10 +02001102 for {
1103
Akronb7e1f132021-08-10 11:52:31 +02001104 if newchar {
1105 // Get from reader if buffer is empty
1106 if buffo >= buffi {
Akron1594cb82021-08-11 11:14:56 +02001107 if eof {
1108 break
1109 }
Akronb7e1f132021-08-10 11:52:31 +02001110 char, _, err = reader.ReadRune()
Akron439f4ec2021-08-09 15:45:38 +02001111
Akronb7e1f132021-08-10 11:52:31 +02001112 // No more runes to read
1113 if err != nil {
1114 eof = true
1115 break
1116 }
1117 buffer[buffi] = char
1118 buffi++
Akron3f8571a2021-08-05 11:18:10 +02001119 }
Akronb7e1f132021-08-10 11:52:31 +02001120
1121 char = buffer[buffo]
1122
1123 if DEBUG {
1124 fmt.Println("Current char", string(char), showBuffer(buffer, buffo, buffi))
1125 }
1126
Akron6f1c16c2021-08-17 10:45:42 +02001127 // TODO:
1128 // Better not repeatedly check for a!
1129 // Possibly keep a buffer with a.
Akronea46e8a2021-08-17 00:36:31 +02001130 if int(char) < 256 {
1131 a = dat.sigmaASCII[int(char)]
1132 } else {
1133 a, ok = dat.sigma[char]
1134 if !ok {
1135 a = 0
1136 }
1137 }
Akronb7e1f132021-08-10 11:52:31 +02001138
1139 // Use identity symbol if character is not in sigma
Akronea46e8a2021-08-17 00:36:31 +02001140 if a == 0 && dat.identity != -1 {
Akronb7e1f132021-08-10 11:52:31 +02001141 a = dat.identity
1142 }
1143
1144 t0 = t
1145
1146 // Check for epsilon transitions and remember
Akronf1a16502021-08-16 15:24:38 +02001147 if dat.array[dat.array[t0].getBase()+uint32(dat.epsilon)].getCheck() == t0 {
Akronb7e1f132021-08-10 11:52:31 +02001148 // Remember state for backtracking to last tokenend state
1149 epsilonState = t0
1150 epsilonOffset = buffo
1151 }
Akron3f8571a2021-08-05 11:18:10 +02001152 }
Akron3610f102021-08-08 14:13:25 +02001153
Akronb7e1f132021-08-10 11:52:31 +02001154 // Checks a transition based on t0, a and buffo
Akronf1a16502021-08-16 15:24:38 +02001155 t = dat.array[t0].getBase() + uint32(a)
1156 ta := dat.array[t]
Akron068874c2021-08-04 15:19:56 +02001157
Akron524c5432021-08-05 14:14:27 +02001158 if DEBUG {
Akronb7e1f132021-08-10 11:52:31 +02001159 // Char is only relevant if set
1160 fmt.Println("Check", t0, "-", a, "(", string(char), ")", "->", t)
1161 if false {
1162 fmt.Println(dat.outgoing(t0))
1163 }
Akron524c5432021-08-05 14:14:27 +02001164 }
1165
Akronb7e1f132021-08-10 11:52:31 +02001166 // Check if the transition is invalid according to the double array
Akronf1a16502021-08-16 15:24:38 +02001167 if t > dat.array[1].getCheck() || ta.getCheck() != t0 {
Akron068874c2021-08-04 15:19:56 +02001168
1169 if DEBUG {
Akronf1a16502021-08-16 15:24:38 +02001170 fmt.Println("Match is not fine!", t, "and", ta.getCheck(), "vs", t0)
Akron068874c2021-08-04 15:19:56 +02001171 }
1172
1173 if !ok && a == dat.identity {
Akronb4bbb472021-08-09 11:49:38 +02001174
Akron068874c2021-08-04 15:19:56 +02001175 // Try again with unknown symbol, in case identity failed
Akronb7e1f132021-08-10 11:52:31 +02001176 // Char is only relevant when set
Akron068874c2021-08-04 15:19:56 +02001177 if DEBUG {
Akron3f8571a2021-08-05 11:18:10 +02001178 fmt.Println("UNKNOWN symbol", string(char), "->", dat.unknown)
Akron068874c2021-08-04 15:19:56 +02001179 }
1180 a = dat.unknown
1181
1182 } else if a != dat.epsilon {
Akronb4bbb472021-08-09 11:49:38 +02001183
Akron068874c2021-08-04 15:19:56 +02001184 // Try again with epsilon symbol, in case everything else failed
Akronb4bbb472021-08-09 11:49:38 +02001185 t0 = epsilonState
Akron3610f102021-08-08 14:13:25 +02001186 epsilonState = 0 // reset
1187 buffo = epsilonOffset
Akron439f4ec2021-08-09 15:45:38 +02001188 a = dat.epsilon
1189
Akron3610f102021-08-08 14:13:25 +02001190 if DEBUG {
1191 fmt.Println("Get from epsilon stack and set buffo!", showBuffer(buffer, buffo, buffi))
1192 }
Akronb4bbb472021-08-09 11:49:38 +02001193
Akron068874c2021-08-04 15:19:56 +02001194 } else {
1195 break
1196 }
Akron068874c2021-08-04 15:19:56 +02001197
Akronb7e1f132021-08-10 11:52:31 +02001198 newchar = false
1199 continue
Akronb4bbb472021-08-09 11:49:38 +02001200 }
1201
Akronb7e1f132021-08-10 11:52:31 +02001202 // Transition was successful
1203 rewindBuffer = false
Akron439f4ec2021-08-09 15:45:38 +02001204
1205 // Transition consumes a character
Akronb4bbb472021-08-09 11:49:38 +02001206 if a != dat.epsilon {
1207
Akron3610f102021-08-08 14:13:25 +02001208 buffo++
Akronb4bbb472021-08-09 11:49:38 +02001209
Akron439f4ec2021-08-09 15:45:38 +02001210 // Transition does not produce a character
Akronf1a16502021-08-16 15:24:38 +02001211 if buffo == 1 && ta.isNonToken() {
Akron3610f102021-08-08 14:13:25 +02001212 if DEBUG {
1213 fmt.Println("Nontoken forward", showBuffer(buffer, buffo, buffi))
1214 }
Akron439f4ec2021-08-09 15:45:38 +02001215 rewindBuffer = true
Akron3610f102021-08-08 14:13:25 +02001216 }
Akron3f8571a2021-08-05 11:18:10 +02001217 }
Akron068874c2021-08-04 15:19:56 +02001218
Akronc5d8d432021-08-10 16:48:44 +02001219 // Transition marks the end of a token - so flush the buffer
Akronf1a16502021-08-16 15:24:38 +02001220 if ta.isTokenEnd() {
Akron524c5432021-08-05 14:14:27 +02001221
Akronc5d8d432021-08-10 16:48:44 +02001222 if buffi > 0 {
Akronc5d8d432021-08-10 16:48:44 +02001223 if DEBUG {
Akron01912fc2021-08-12 11:41:58 +02001224 fmt.Println("-> Flush buffer: [", string(buffer[:buffo]), "]", showBuffer(buffer, buffo, buffi))
Akronc5d8d432021-08-10 16:48:44 +02001225 }
Akron01912fc2021-08-12 11:41:58 +02001226 writer.WriteString(string(buffer[:buffo]))
Akronc5d8d432021-08-10 16:48:44 +02001227 rewindBuffer = true
Akron3610f102021-08-08 14:13:25 +02001228 }
Akron1594cb82021-08-11 11:14:56 +02001229 if DEBUG {
1230 fmt.Println("-> Newline")
1231 }
1232 writer.WriteRune('\n')
Akron439f4ec2021-08-09 15:45:38 +02001233 }
Akron3610f102021-08-08 14:13:25 +02001234
Akronc5d8d432021-08-10 16:48:44 +02001235 // Rewind the buffer if necessary
Akron439f4ec2021-08-09 15:45:38 +02001236 if rewindBuffer {
1237
1238 // TODO: Better as a ring buffer
Akron3610f102021-08-08 14:13:25 +02001239 for x, i := range buffer[buffo:buffi] {
1240 buffer[x] = i
1241 }
Akronb4bbb472021-08-09 11:49:38 +02001242
Akron3610f102021-08-08 14:13:25 +02001243 buffi -= buffo
1244 epsilonOffset -= buffo
1245 buffo = 0
1246 if DEBUG {
Akronb4bbb472021-08-09 11:49:38 +02001247 fmt.Println("Remaining:", showBuffer(buffer, buffo, buffi))
Akron3610f102021-08-08 14:13:25 +02001248 }
Akron84d68e62021-08-04 17:06:52 +02001249 }
1250
Akronb7e1f132021-08-10 11:52:31 +02001251 // Move to representative state
Akronf1a16502021-08-16 15:24:38 +02001252 if ta.isSeparate() {
1253 t = ta.getBase()
1254 ta = dat.array[t]
Akronb7e1f132021-08-10 11:52:31 +02001255
1256 if DEBUG {
1257 fmt.Println("Representative pointing to", t)
1258 }
1259 }
1260
Akronc5d8d432021-08-10 16:48:44 +02001261 newchar = true
1262
Akron068874c2021-08-04 15:19:56 +02001263 // TODO:
1264 // Prevent endless epsilon loops!
1265 }
1266
Akron439f4ec2021-08-09 15:45:38 +02001267 // Input reader is not yet finished
Akron3f8571a2021-08-05 11:18:10 +02001268 if !eof {
Akron068874c2021-08-04 15:19:56 +02001269 if DEBUG {
Akronb4bbb472021-08-09 11:49:38 +02001270 fmt.Println("Not at the end - problem", t0, ":", dat.outgoing(t0))
Akron068874c2021-08-04 15:19:56 +02001271 }
1272 return false
1273 }
1274
Akronb7e1f132021-08-10 11:52:31 +02001275 if DEBUG {
1276 fmt.Println("Entering final check")
1277 }
1278
Akronc5d8d432021-08-10 16:48:44 +02001279 // Automaton is in a final state, so flush the buffer and return
Akronf1a16502021-08-16 15:24:38 +02001280 x := dat.array[t].getBase() + uint32(dat.final)
1281
1282 if x < dat.array[1].getCheck() && dat.array[x].getCheck() == t {
Akronb4bbb472021-08-09 11:49:38 +02001283
1284 if buffi > 0 {
Akronb4bbb472021-08-09 11:49:38 +02001285 if DEBUG {
Akron01912fc2021-08-12 11:41:58 +02001286 fmt.Println("-> Flush buffer: [", string(buffer[:buffi]), "]")
Akron3f8571a2021-08-05 11:18:10 +02001287 }
Akron01912fc2021-08-12 11:41:58 +02001288 writer.WriteString(string(buffer[:buffi]))
Akron6e70dc82021-08-11 11:33:18 +02001289
Akronf1a16502021-08-16 15:24:38 +02001290 if dat.array[t].isTokenEnd() {
Akrondf0a3ef2021-08-09 15:53:45 +02001291 writer.WriteRune('\n')
Akronc5d8d432021-08-10 16:48:44 +02001292 if DEBUG {
1293 fmt.Println("-> Newline")
1294 }
Akrondf0a3ef2021-08-09 15:53:45 +02001295 }
Akron84d68e62021-08-04 17:06:52 +02001296 }
1297
Akron6e70dc82021-08-11 11:33:18 +02001298 // Add an additional sentence ending, if the file is over but no explicit
1299 // sentence split was reached. This may be controversial and therefore
1300 // optional via parameter.
Akronf1a16502021-08-16 15:24:38 +02001301 if !dat.array[t0].isTokenEnd() {
Akron6e70dc82021-08-11 11:33:18 +02001302 writer.WriteRune('\n')
1303 if DEBUG {
1304 fmt.Println("-> Newline")
1305 }
1306 }
1307
Akrone61380b2021-08-16 10:10:46 +02001308 // TODO:
1309 // There may be a new line at the end, from an epsilon,
1310 // so we may need to go on!
Akron068874c2021-08-04 15:19:56 +02001311 return true
1312 }
1313
Akronc5d8d432021-08-10 16:48:44 +02001314 // Check epsilon transitions until a final state is reached
1315 t0 = t
Akronf1a16502021-08-16 15:24:38 +02001316 t = dat.array[t0].getBase() + uint32(dat.epsilon)
Akron01912fc2021-08-12 11:41:58 +02001317 a = dat.epsilon
1318 newchar = false
Akronf1a16502021-08-16 15:24:38 +02001319 if dat.array[t].getCheck() == t0 {
Akronc5d8d432021-08-10 16:48:44 +02001320 // Remember state for backtracking to last tokenend state
Akronc5d8d432021-08-10 16:48:44 +02001321 goto PARSECHAR
Akrone61380b2021-08-16 10:10:46 +02001322
Akronc5d8d432021-08-10 16:48:44 +02001323 } else if epsilonState != 0 {
Akronb7e1f132021-08-10 11:52:31 +02001324 t0 = epsilonState
1325 epsilonState = 0 // reset
1326 buffo = epsilonOffset
Akron068874c2021-08-04 15:19:56 +02001327 if DEBUG {
Akronc5d8d432021-08-10 16:48:44 +02001328 fmt.Println("Get from epsilon stack and set buffo!", showBuffer(buffer, buffo, buffi))
Akron068874c2021-08-04 15:19:56 +02001329 }
Akronc5d8d432021-08-10 16:48:44 +02001330 goto PARSECHAR
Akron068874c2021-08-04 15:19:56 +02001331 }
Akronc5d8d432021-08-10 16:48:44 +02001332 return false
Akron068874c2021-08-04 15:19:56 +02001333}