-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix.go
698 lines (564 loc) · 14.1 KB
/
matrix.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
package datok
import (
"bufio"
"compress/gzip"
"io"
"log"
"os"
)
const (
MAMAGIC = "MATOK"
EOT = 4
)
type MatrixTokenizer struct {
sigma map[rune]int
sigmaASCII [256]int
array []uint32
stateCount int
// Special symbols in sigma
epsilon int
unknown int
identity int
}
// ToMatrix turns the intermediate tokenizer into a
// matrix representation.
func (auto *Automaton) ToMatrix() *MatrixTokenizer {
mat := &MatrixTokenizer{
sigma: make(map[rune]int),
unknown: auto.unknown,
identity: auto.identity,
epsilon: auto.epsilon,
stateCount: auto.stateCount,
}
max := 0
// Init with identity
if mat.identity != -1 {
for i := 0; i < 256; i++ {
mat.sigmaASCII[i] = mat.identity
}
max = mat.identity
}
for num, sym := range auto.sigmaRev {
if int(sym) < 256 {
mat.sigmaASCII[int(sym)] = num
}
mat.sigma[sym] = num
if num > auto.sigmaCount {
panic("sigmaCount is smaller")
}
// Find max
// see https://dev.to/jobinrjohnson/branchless-programming-does-it-really-matter-20j4
max -= ((max - num) & ((max - num) >> 31))
// if num > max {
// max = num
// }
}
// Add final entry to the list (maybe not necessary actually)
remember := make([]bool, auto.stateCount+2)
// lower sigmaCount, as no final value exists
mat.array = make([]uint32, (auto.stateCount+1)*(max+1))
// Store all transitions in matrix
var toMatrix func([]uint32, int)
toMatrix = func(matrix []uint32, start int) {
if start > auto.stateCount {
panic("stateCount is smaller")
}
if remember[start] {
return
}
remember[start] = true
for alpha, t := range auto.transitions[start] {
matrix[(alpha-1)*auto.stateCount+start] = uint32(t.end)
// Mark nontoken transitions
if t.nontoken {
matrix[(alpha-1)*auto.stateCount+start] |= FIRSTBIT
}
toMatrix(matrix, t.end)
}
}
toMatrix(mat.array, 1)
return mat
}
// Type of tokenizer
func (MatrixTokenizer) Type() string {
return MAMAGIC
}
// Save stores the matrix data in a file
func (mat *MatrixTokenizer) Save(file string) (n int64, err error) {
f, err := os.Create(file)
if err != nil {
log.Println(err)
return 0, err
}
defer f.Close()
gz := gzip.NewWriter(f)
defer gz.Close()
n, err = mat.WriteTo(gz)
if err != nil {
log.Println(err)
return n, err
}
gz.Flush()
return n, nil
}
// WriteTo stores the matrix data in an io.Writer.
func (mat *MatrixTokenizer) WriteTo(w io.Writer) (n int64, err error) {
wb := bufio.NewWriter(w)
defer wb.Flush()
// Store magical header
all, err := wb.Write([]byte(MAMAGIC))
if err != nil {
log.Println(err)
return int64(all), err
}
// Get sigma as a list
// In datok it's 16 - 4*4
sigmalist := make([]rune, len(mat.sigma)+16)
max := 0
for sym, num := range mat.sigma {
sigmalist[num] = sym
// Find max
// see https://dev.to/jobinrjohnson/branchless-programming-does-it-really-matter-20j4
max -= ((max - num) & ((max - num) >> 31))
// if num > max {
// max = num
// }
}
// Add final entry to the list (maybe not necessary actually)
sigmalist = sigmalist[:max+1]
buf := make([]byte, 0, 14)
bo.PutUint16(buf[0:2], VERSION)
bo.PutUint16(buf[2:4], uint16(mat.epsilon))
bo.PutUint16(buf[4:6], uint16(mat.unknown))
bo.PutUint16(buf[6:8], uint16(mat.identity))
bo.PutUint32(buf[8:12], uint32(mat.stateCount))
bo.PutUint16(buf[12:14], uint16(len(sigmalist)))
more, err := wb.Write(buf[0:14])
if err != nil {
log.Println(err)
return int64(all), err
}
all += more
// Write sigma
for _, sym := range sigmalist {
more, err = wb.WriteRune(sym)
if err != nil {
log.Println(err)
return int64(all), err
}
all += more
}
if err != nil {
log.Println(err)
return int64(all), err
}
// Test marker - could be checksum
more, err = wb.Write([]byte("M"))
if err != nil {
log.Println(err)
return int64(all), err
}
all += more
for _, x := range mat.array {
bo.PutUint32(buf[0:4], uint32(x))
more, err = wb.Write(buf[0:4])
if err != nil {
log.Println(err)
return int64(all), err
}
all += more
if more != 4 {
log.Println("Can not write base uint32")
return int64(all), err
}
}
return int64(all), err
}
// LoadMatrixFile reads a matrix represented tokenizer
// from a file.
func LoadMatrixFile(file string) *MatrixTokenizer {
f, err := os.Open(file)
if err != nil {
log.Println(err)
return nil
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
log.Println(err)
return nil
}
defer gz.Close()
// Todo: Read the whole file!
return ParseMatrix(gz)
}
// ParseMatrix reads a matrix represented tokenizer
// from an io.Reader
func ParseMatrix(ior io.Reader) *MatrixTokenizer {
// Initialize tokenizer with default values
mat := &MatrixTokenizer{
sigma: make(map[rune]int),
epsilon: 0,
unknown: 0,
identity: 0,
stateCount: 0,
}
r := bufio.NewReader(ior)
buf := make([]byte, 1024)
buf = buf[0:len(MAMAGIC)]
_, err := r.Read(buf)
if err != nil {
log.Println(err)
return nil
}
if string(MAMAGIC) != string(buf) {
log.Println("Not a matok file")
return nil
}
more, err := io.ReadFull(r, buf[0:14])
if err != nil {
log.Println(err)
return nil
}
if more != 14 {
log.Println("Read bytes do not fit")
return nil
}
version := bo.Uint16(buf[0:2])
if version != VERSION {
log.Println("Version not compatible")
return nil
}
mat.epsilon = int(bo.Uint16(buf[2:4]))
mat.unknown = int(bo.Uint16(buf[4:6]))
mat.identity = int(bo.Uint16(buf[6:8]))
mat.stateCount = int(bo.Uint32(buf[8:12]))
sigmaCount := int(bo.Uint16(buf[12:14]))
arraySize := (mat.stateCount + 1) * sigmaCount
// Init with identity
if mat.identity != -1 {
for i := 0; i < 256; i++ {
mat.sigmaASCII[i] = mat.identity
}
}
for x := 0; x < sigmaCount; x++ {
sym, _, err := r.ReadRune()
if err == nil && sym != 0 {
if int(sym) < 256 {
mat.sigmaASCII[int(sym)] = x
}
mat.sigma[sym] = x
}
}
_, err = io.ReadFull(r, buf[0:1])
if err != nil {
log.Print(err)
return nil
}
if string("M") != string(buf[0:1]) {
log.Println("Not a matok file")
return nil
}
// Read based on length
mat.array = make([]uint32, arraySize)
dataArray, err := io.ReadAll(r)
if err == io.EOF {
log.Println(err)
return nil
}
if len(dataArray) < arraySize*4 {
log.Println("Not enough bytes read", len(dataArray), arraySize*4)
return nil
}
for x := 0; x < arraySize; x++ {
mat.array[x] = bo.Uint32(dataArray[x*4 : (x*4)+4])
}
return mat
}
// Transduce input to ouutput
func (mat *MatrixTokenizer) Transduce(r io.Reader, w io.Writer) bool {
return mat.TransduceTokenWriter(r, NewTokenWriter(w, SIMPLE))
}
// TransduceTokenWriter transduces an input string against
// the matrix FSA. The rules are always greedy. If the
// automaton fails, it takes the last possible token ending
// branch.
func (mat *MatrixTokenizer) TransduceTokenWriter(r io.Reader, w *TokenWriter) bool {
var a int
var t0 uint32
t := uint32(1) // Initial state
var ok, rewindBuffer bool
// Remember the last position of a possible tokenend,
// in case the automaton fails.
epsilonState := uint32(0)
epsilonOffset := 0
// Remember if the last transition was epsilon
sentenceEnd := false
// Remember if a text end was already set
textEnd := false
buffer := make([]rune, 1024)
bufft := 0 // Buffer token offset
buffc := 0 // Buffer current symbol
buffi := 0 // Buffer length
// The buffer is organized as follows:
// [ t[....c..]..i]
reader := bufio.NewReader(r)
defer w.Flush()
var char rune
var err error
eof := false
eot := false
newchar := true
PARSECHARM:
for {
if newchar {
// Get from reader if buffer is empty
if buffc >= buffi {
if eof {
break
}
char, _, err = reader.ReadRune()
// No more runes to read
if err != nil {
if err == io.EOF {
eof = true
break
}
log.Fatalln(err)
os.Exit(1)
return false
}
buffer[buffi] = char
buffi++
}
char = buffer[buffc]
if DEBUG {
log.Println("Current char", string(char), int(char), showBufferNew(buffer, bufft, buffc, buffi))
}
eot = false
// TODO:
// Better not repeatedly check for a!
// Possibly keep a buffer with a.
if int(char) < 256 {
eot = int(char) == EOT
// mat.SigmaASCII[] is initialized with mat.identity
a = mat.sigmaASCII[int(char)]
} else {
a, ok = mat.sigma[char]
// Use identity symbol if character is not in sigma
if !ok && mat.identity != -1 {
// TODO: Maybe use unknown?
a = mat.identity
}
}
t0 = t
// Check for epsilon transitions and remember
// TODO: Can t0 be negative here?
if mat.array[(mat.epsilon-1)*mat.stateCount+int(t0)] != 0 {
// Remember state for backtracking to last tokenend state
// Maybe not necessary - and should be simpler!
// Just Remove
// t0 &= ^FIRSTBIT
epsilonState = t0
epsilonOffset = buffc
if DEBUG {
log.Println("epsilonOffset is set to", buffc)
}
}
}
// can happen when no identity is defined.
// This shouldn't be tested in every loop
if a == 0 {
t = 0
} else {
// Checks a transition based on t0, a and buffo
t = mat.array[(int(a)-1)*mat.stateCount+int(t0)]
}
if DEBUG {
// Char is only relevant if set
log.Println("Check", t0, "-", a, "(", string(char), ")", "->", t)
}
// Check if the transition is invalid according to the matrix
if t == 0 {
if DEBUG {
log.Println("Match is not fine!")
}
if !ok && a == mat.identity {
// Try again with unknown symbol, in case identity failed
// Char is only relevant when set
if DEBUG {
log.Println("UNKNOWN symbol", string(char), "->", mat.unknown)
}
a = mat.unknown
} else if a != mat.epsilon && epsilonState != 0 {
// Try again with epsilon symbol, in case everything else failed
t0 = epsilonState
epsilonState = 0 // reset
buffc = epsilonOffset
a = mat.epsilon
if DEBUG {
log.Println("Get from epsilon stack and set buffo!", showBufferNew(buffer, bufft, buffc, buffi))
}
} else {
if DEBUG {
log.Println("Fail!")
}
// w.Fail(bufft)
// The following procedure means the automaton fails to consume a certain character.
// In the tokenization scenario, this means, the tokenizer will drop the old or current data as a
// token and start blank at the root node of the automaton for the remaining data.
// It may be beneficial to have something like a "drop()" event to capture these cases,
// as they are likely the result of a bad automaton design.
// fmt.Println("Problem", len(buffer), buffc, bufft)
if buffc-bufft <= 0 {
buffc++
if buffc == 0 {
eof = true
break
}
}
// This will hopefully be branchless by the compiler
if DEBUG {
log.Println("-> Flush buffer: [", string(buffer[bufft:buffc]), "]", showBufferNew(buffer, bufft, buffc, buffi))
}
w.Token(bufft, buffer[:buffc])
sentenceEnd = false
textEnd = false
if DEBUG {
log.Println("-> Rewind buffer", bufft, buffc, buffi, epsilonOffset)
}
copy(buffer[0:], buffer[buffc:buffi])
buffi -= buffc
epsilonState = 0
buffc = 0
bufft = 0
a = mat.epsilon
// Restart from root state
t = uint32(1)
newchar = true
// goto PARSECHARM
continue
}
newchar = false
eot = false
continue
}
// Transition was successful
rewindBuffer = false
// Transition consumes no character
if a == mat.epsilon {
// Transition marks the end of a token - so flush the buffer
if buffc-bufft > 0 {
if DEBUG {
log.Println("-> Flush buffer: [", string(buffer[bufft:buffc]), "]", showBufferNew(buffer, bufft, buffc, buffi))
}
w.Token(bufft, buffer[:buffc])
rewindBuffer = true
sentenceEnd = false
textEnd = false
} else {
sentenceEnd = true
w.SentenceEnd(buffc)
}
// Transition consumes a character
} else {
buffc++
// Transition does not produce a character
// Hopefully generated branchless code
if buffc-bufft == 1 && (t&FIRSTBIT) != 0 {
if DEBUG {
log.Println("Nontoken forward", showBufferNew(buffer, bufft, buffc, buffi))
}
bufft++
// rewindBuffer = true
}
}
if eot {
eot = false
if !sentenceEnd {
sentenceEnd = true
w.SentenceEnd(buffc)
}
textEnd = true
w.TextEnd(buffc)
rewindBuffer = true
if DEBUG {
log.Println("END OF TEXT")
}
}
// Rewind the buffer if necessary
if rewindBuffer {
if DEBUG {
log.Println("-> Rewind buffer", bufft, buffc, buffi, epsilonOffset)
}
copy(buffer[0:], buffer[buffc:buffi])
buffi -= buffc
// epsilonOffset -= buffo
epsilonOffset = 0
epsilonState = 0
buffc = 0
bufft = 0
if DEBUG {
log.Println("Remaining:", showBufferNew(buffer, bufft, buffc, buffi))
}
}
t &= ^FIRSTBIT
newchar = true
// TODO:
// Prevent endless epsilon loops!
}
// Input reader is not yet finished
if !eof {
if DEBUG {
log.Println("Not at the end")
}
// This should never happen
return false
}
if DEBUG {
log.Println("Entering final check")
}
// Check epsilon transitions as long as possible
t0 = t
t = mat.array[(int(mat.epsilon)-1)*mat.stateCount+int(t0)]
a = mat.epsilon
newchar = false
// t can't be < 0
if t != 0 {
// Remember state for backtracking to last tokenend state
goto PARSECHARM
} else if epsilonState != 0 {
t0 = epsilonState
epsilonState = 0 // reset
buffc = epsilonOffset
if DEBUG {
log.Println("Get from epsilon stack and set buffo!", showBufferNew(buffer, bufft, buffc, buffi))
}
goto PARSECHARM
}
// something left in buffer
if buffc-bufft > 0 {
if DEBUG {
log.Println("-> Flush buffer: [", string(buffer[bufft:buffc]), "]", showBufferNew(buffer, bufft, buffc, buffi))
}
w.Token(bufft, buffer[:buffc])
sentenceEnd = false
textEnd = false
}
// Add an additional sentence ending, if the file is over but no explicit
// sentence split was reached. This may be controversial and therefore
// optional via parameter.
if !sentenceEnd {
w.SentenceEnd(buffc)
if DEBUG {
log.Println("Sentence end")
}
}
if !textEnd {
w.TextEnd(buffc)
if DEBUG {
log.Println("Text end")
}
}
return true
}