-
Notifications
You must be signed in to change notification settings - Fork 2
/
matcher.pas
1923 lines (1790 loc) · 69.4 KB
/
matcher.pas
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
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{$MODE OBJFPC} { -*- delphi -*- }
{$INCLUDE settings.inc}
unit matcher;
interface
uses
storable, grammarian;
type
TByteCode = Byte;
TMatcherFlags = type Integer;
TMatcherFlag = type TByteCode;
PCompiledPattern = ^TCompiledPattern;
TCompiledPattern = packed array[TByteCode] of TByteCode;
const
mfUnset = -1; // not a valid flag value
type
TMatcher = class(TStorable) // @RegisterStorableClass
protected
FTokens: TTokens; { must be stored lexically sorted }
FOriginalTokens: TTokens; { must be stored in the same order as FTokens }
FPattern: PCompiledPattern;
FPatternLength: TByteCode;
function GetTokenID(Token: UTF8String): TByteCode; { argument must be lowercase }
public
constructor Create(Tokens, OriginalTokens: TTokens; Pattern: PCompiledPattern; PatternLength: TByteCode); { tokens are case-aware }
destructor Destroy(); override;
constructor Read(Stream: TReadStream); override;
procedure Write(Stream: TWriteStream); override;
function Matches(Tokens: TTokens; Start: Cardinal; Flags: TMatcherFlags = 0): Cardinal; { case-insensitive, but tokens must be lowercase already }
function GetCanonicalMatch(Separator: UTF8String; Flags: TMatcherFlags = 0): UTF8String;
{$IFDEF DEBUG} function GetPatternDescription(): UTF8String; {$ENDIF}
{$IFDEF DEBUG} function GetPatternDotFileLabels(): UTF8String; {$ENDIF}
end;
procedure CompilePattern(S: UTF8String; out Singular: TMatcher; out Plural: TMatcher);
{
CompilePattern() takes a string that consists of a space-separated list of tokens or nested lists.
Nested lists are marked by round brackets (...).
Tokens can have a "+" suffix indicating that the token can be repeated.
Tokens can have a "?" suffix indicating that the token can be omitted.
Nested lists can have suffixes to indicate what kind of list it is:
(a b c) - sequence list (all tokens must appear in order)
(a b c)? - optional sequence list (if any appear, they must all appear, in order)
(a b c)@ - alternatives (one of the tokens must appear)
(a b c)* - zero or more of the alternatives must appear, in any order
(a b c)# - one or more of the alternatives must appear, in any order
(a b c)% - zero or more of the alternatives must appear, but they must be in the order given
(a b c)& - one or more of the alternatives must appear, but they must be in the order given
Tokens and nested lists can be split with a "/" to indicate alternative singular/plural forms.
Tokens and nested lists can be suffixed (after the suffixes mentioned above) with ":" and an
integer in the range 0..31 to indicate a flag that must be matched for that token or list to be
considered. Flag indices are zero-based. (TMatcherFlags' least-significant-bit corresponds to
flag zero, the second bit corresponds to flag 1, and so forth.)
Special characters can be escaped using \.
Examples:
'a b c' - only matched by "a b c"
'the? ((glowing green)# lantern/lanterns)&' - returns a singular matcher that matches:
"the glowing", "the green", "the lantern",
"the glowing green", "the glowing lantern", "the green lantern",
"the glowing green lantern", and all of those again without "the"
...and a plural matcher that matches the same but with "lanterns" instead of "lantern".
'(two beads)/bead' - returns a matcher that matches "two beads" and
a matcher that matches "bead".
'the? burning:0 bush' - returns a matcher that matches either:
'the burning bush' and 'burning bush' when flag 0 is set
just 'the bush' and 'bush' when flag 0 is not set
}
{$IFDEF DEBUG}
function HasPatternChars(S: UTF8String): Boolean;
function HasSingularVsPluralAnnotation(S: UTF8String): Boolean;
{$ENDIF}
implementation
uses
{$IFDEF DEBUG} debug, {$ENDIF}
sysutils;
{ A compiled pattern consists of a zero byte, a series of byte pairs,
and a $FF byte. Each sequence of byte pairs is a state for a
pattern-matching state machine and is identified by the position of
the first byte in that sequence in the overall sequence. The first
state in the pattern is the start state for running the
pattern. Each byte pair represents a state transition for the state
and consists of a byte representing the token to match to follow
the transition, and a byte representing the state to switch to if
that token is matched. The special token ID $FE is always
matched. There is also a special state ID, $FF, meaning the pattern
matched. For other state IDs, the least significant bit of the
second byte of each transition is set if the state machine must
avoid transitioning through this state twice while matching the
pattern.
Notes:
- The first byte of each state is currently unused (it's only
helpful in aligning the states to even byte boundaries). It
provides eight bits of per-state magic for future expansion.
- Since the whole pattern has to fit in 255 bytes and each
transition takes at least 2 bytes; the most tokens that could
possibly be used in a pattern is therefore 127. Token $FF
indicates the end of the state. Token $FE indicates is always
matched. This leaves tokens $80 to FD for other magic purposes.
- Tokens $81 to $A0 are used for transitions that require certain
flags to be set, tokens $A1 to $C0 are used for transitions that
require certain flags not to be set, and tokens $C1 to $FD
aren't used.
- States always start on an even numbered byte, since each state
is an even number of bytes long; so the least-significant bit of
each transition byte can be used for magic. It's used for
indicating that the transition can't be repeated.
- No state can start on the last three bytes, so state IDs $FF,
$FE, and $FD can be used for magic. Currently only $FF is used
in the pattern, to indicate a successful match. $FE is used in
the state machine to indicate blocked paths (one of the magic
tokens could be used easily too, if necessary). $FD is used for
debugging purposes.
For example,
00 00 04 FF 00 01 FF FF
...would match the token sequence 00 01, but nothing else.
Similarly,
00 00 06 FE 06 FF 00 01 FF FF
...would match either the token 01 on its own, or the token
sequence 00 01.
Transitions are listed in the states of a pattern in canonical
order, and to get the canonical value should be walked depth first
until you get a match, avoiding following any token-specific
transition more than once.
For example:
00 00 07 01 07 02 07 FF 00 FE 00 FE FF FF
...would match the following sequences:
00, 01, 02, 00 01, 00 02, 01 00, 01 02, 02 00, 02 01, 00 01 02,
00 02 01, 01 00 02, 01 02 00, 02 00 01, 02 01 00
...but the canonical sequence that represents this pattern would
be:
00 01 02
}
const
kFlagCount = BitSizeOf(TMatcherFlags);
{ Magic State Flags }
msfNormal = $00;
{ Magic Tokens }
mtMaxTrueToken = $7F;
mtNone = $80;
mtFlagMin = $81;
mtFlagMax = mtFlagMin + kFlagCount - 1;
mtNegativeFlagMin = mtFlagMax + 1;
mtNegativeFlagMax = mtNegativeFlagMin + kFlagCount - 1;
mtFollow = $FE; {$IF mtFollow <= mtNegativeFlagMin} {$ERROR TMatcherFlags is too wide} {$ENDIF}
mtStateEnd = $FF;
{ Magic Pattern States }
mpsMatch = $FF;
mpsBlocked = $FE;
{$IFOPT C+} mpsNotSerialised = $FD; {$ENDIF}
mpsMaxTrueTransition = $FC;
mpsPreventDuplicatesMask = $01;
type
PState = ^TState;
PTransition = ^TTransition;
TState = record
Transitions: PTransition;
IncomingTransitionCount, OutgoingTransitionCount: Cardinal;
NextState: PState;
PreviousState: PState;
Index: TByteCode;
end;
TTransition = record
Token: TByteCode;
State: PState;
BlockDuplicates: Boolean;
NextTransition: PTransition;
end;
TGetStateCallback = function (): PState of object;
TTokenReporterCallback = procedure (Token: UTF8String) of object;
TTokenFinderCallback = function (Token: UTF8String): TByteCode of object;
TPatternNode = class
protected
procedure ReportTokens(Callback: TTokenReporterCallback); virtual; abstract;
procedure FixTokenIDs(Callback: TTokenFinderCallback); virtual; abstract;
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); virtual; abstract;
public
constructor Create();
destructor Destroy(); override;
end;
TTokenNode = class(TPatternNode)
protected
FToken: UTF8String;
FTokenID: TByteCode;
procedure ReportTokens(Callback: TTokenReporterCallback); override;
procedure FixTokenIDs(Callback: TTokenFinderCallback); override;
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
public
constructor Create(Token: UTF8String);
end;
TRepeatableTokenNode = class(TTokenNode)
protected
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
public
end;
TFlagNode = class(TPatternNode)
protected
FFlag: TMatcherFlag;
FSecondaryNode: TPatternNode;
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
procedure ReportTokens(Callback: TTokenReporterCallback); override;
procedure FixTokenIDs(Callback: TTokenFinderCallback); override;
public
constructor Create(Flag: TMatcherFlag; SecondaryNode: TPatternNode);
destructor Destroy(); override;
end;
TChildrenPatternNode = class(TPatternNode)
protected
FChildren: array of TPatternNode;
procedure ReportTokens(Callback: TTokenReporterCallback); override;
procedure FixTokenIDs(Callback: TTokenFinderCallback); override;
public
constructor Create(Children: array of TPatternNode); // fails if the array is length=0
destructor Destroy(); override;
end;
TSequencePatternNode = class(TChildrenPatternNode)
protected
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
end;
TOptionalSequencePatternNode = class(TChildrenPatternNode)
protected
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
end;
TRepeatableSequencePatternNode = class(TChildrenPatternNode)
protected
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
end;
TAlternativesPatternNode = class(TChildrenPatternNode)
protected
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
end;
TZeroOrMoreUnorderedPatternNode = class(TChildrenPatternNode)
protected
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
end;
TZeroOrMoreOrderedPatternNode = class(TChildrenPatternNode)
protected
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
end;
TOneOrMoreUnorderedPatternNode = class(TChildrenPatternNode)
protected
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
end;
TOneOrMoreOrderedPatternNode = class(TChildrenPatternNode)
protected
procedure HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False); override;
end;
procedure DualQuickSort(var PrimaryList, SecondaryList: TTokens); forward;
procedure DualQuickSort(var PrimaryList, SecondaryList: TTokens; L, R: Integer); forward;
procedure DualQuickSort(var PrimaryList, SecondaryList: TTokens);
begin
Assert(Low(PrimaryList) >= Low(Integer));
Assert(High(PrimaryList) <= High(Integer));
Assert(Length(PrimaryList) = Length(SecondaryList));
if (Length(PrimaryList) > 1) then
DualQuickSort(PrimaryList, SecondaryList, Low(PrimaryList), High(PrimaryList)); // $R-
end;
procedure DualQuickSort(var PrimaryList, SecondaryList: TTokens; L, R: Integer);
{ based on QuickSort in rtl/objpas/classes/lists.inc }
var
I, J : Integer;
P, Q : UTF8String;
begin
repeat
I := L;
J := R;
P := PrimaryList[(L + R) div 2];
repeat
while (P > PrimaryList[I]) do
I := I + 1; // $R-
while (P < PrimaryList[J]) do
J := J - 1; // $R-
if (I <= J) then
begin
Q := PrimaryList[I];
PrimaryList[I] := PrimaryList[J];
PrimaryList[J] := Q;
Q := SecondaryList[I];
SecondaryList[I] := SecondaryList[J];
SecondaryList[J] := Q;
I := I + 1; // $R-
J := J - 1; // $R-
end;
until (I > J);
if (L < J) then
DualQuickSort(PrimaryList, SecondaryList, L, J);
L := I;
until (I >= R);
end;
procedure DualRemoveDuplicates(var PrimaryList, SecondaryList: TTokens);
var
Index, Count: Cardinal;
NewPrimaryList, NewSecondaryList: TTokens;
Last: UTF8String;
begin
Assert(Length(PrimaryList) = Length(SecondaryList));
Assert(Length(PrimaryList) > 0);
SetLength(NewPrimaryList, Length(PrimaryList)); // $DFA- for NewPrimaryList
NewPrimaryList[0] := PrimaryList[0];
SetLength(NewSecondaryList, Length(SecondaryList)); // $DFA- for NewSecondaryList
NewSecondaryList[0] := SecondaryList[0];
Index := 1;
Count := 1;
Last := PrimaryList[0];
while (Index < Length(PrimaryList)) do
begin
if (PrimaryList[Index] <> Last) then
begin
Last := PrimaryList[Index];
NewPrimaryList[Count] := Last;
NewSecondaryList[Count] := SecondaryList[Index];
Inc(Count);
end;
Inc(Index);
end;
SetLength(NewPrimaryList, Count);
PrimaryList := NewPrimaryList;
SetLength(NewSecondaryList, Count);
SecondaryList := NewSecondaryList;
end;
procedure AddTransition(State: PState; Token: TByteCode; TargetState: PState; BlockDuplicates: Boolean);
var
Transition: PTransition;
begin
Assert(Assigned(State));
Assert(Assigned(TargetState));
New(Transition);
Transition^.Token := Token;
Transition^.State := TargetState;
Transition^.BlockDuplicates := BlockDuplicates;
Transition^.NextTransition := State^.Transitions;
State^.Transitions := Transition;
Inc(State^.OutgoingTransitionCount);
Inc(TargetState^.IncomingTransitionCount);
end;
procedure NewPattern(out Pattern: PCompiledPattern; Length: TByteCode); inline;
begin
Assert(Length > 0);
Assert(Length < High(PtrUInt) div SizeOf(TByteCode));
Pattern := nil; { not strictly necessary }
GetMem(Pattern, Length*SizeOf(TByteCode)); // $R-
end;
procedure DisposePattern(var Pattern: PCompiledPattern; Length: TByteCode); inline;
begin
Assert(Assigned(Pattern));
FreeMem(Pattern, Length*SizeOf(TByteCode)); // $R-
Pattern := nil;
end;
constructor TPatternNode.Create();
begin
inherited;
end;
destructor TPatternNode.Destroy();
begin
inherited;
end;
constructor TTokenNode.Create(Token: UTF8String);
begin
inherited Create();
FToken := Token;
end;
procedure TTokenNode.ReportTokens(Callback: TTokenReporterCallback);
Begin
Callback(FToken);
end;
procedure TTokenNode.FixTokenIDs(Callback: TTokenFinderCallback);
begin
FTokenID := Callback(FToken);
end;
procedure TTokenNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
begin
{
Token
A=---------->Z
}
AddTransition(StartState, FTokenID, TargetState, BlockDuplicates);
end;
procedure TRepeatableTokenNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
MiddleState1, MiddleState2: PState;
begin
{
Token
A=---------->O----------->O----------->Z
<-----------
}
MiddleState1 := GetNewState();
MiddleState2 := GetNewState();
AddTransition(StartState, mtFollow, MiddleState1, BlockDuplicates);
AddTransition(MiddleState1, FTokenID, MiddleState2, False);
AddTransition(MiddleState2, mtFollow, MiddleState1, False);
AddTransition(MiddleState2, mtFollow, TargetState, False);
end;
constructor TFlagNode.Create(Flag: TMatcherFlag; SecondaryNode: TPatternNode);
begin
inherited Create();
Assert(Flag < kFlagCount);
FFlag := Flag;
Assert(Assigned(SecondaryNode));
FSecondaryNode := SecondaryNode;
end;
destructor TFlagNode.Destroy();
begin
FSecondaryNode.Free();
end;
procedure TFlagNode.ReportTokens(Callback: TTokenReporterCallback);
begin
FSecondaryNode.ReportTokens(Callback);
end;
procedure TFlagNode.FixTokenIDs(Callback: TTokenFinderCallback);
begin
FSecondaryNode.FixTokenIDs(Callback);
end;
procedure TFlagNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
MiddleState: PState;
begin
{
Flag
A=---------->O---[...]--->Z
------------------------>
Negative Flag
}
MiddleState := GetNewState();
AddTransition(StartState, mtFlagMin + FFlag, MiddleState, BlockDuplicates); // $R-
FSecondaryNode.HookStates(MiddleState, TargetState, GetNewState, BlockDuplicates); // XXX should BlockDuplicates be specified here?
if (StartState <> TargetState) then
AddTransition(StartState, mtNegativeFlagMin + FFlag, TargetState, BlockDuplicates); // $R-
end;
constructor TChildrenPatternNode.Create(Children: array of TPatternNode);
var
Index: Cardinal;
begin
Assert(Length(Children) > 0);
inherited Create();
SetLength(FChildren, Length(Children));
for Index := 0 to Length(Children)-1 do // $R-
FChildren[Index] := Children[Index];
end;
destructor TChildrenPatternNode.Destroy();
var
Index: Cardinal;
begin
Assert(Length(FChildren) > 0);
for Index := Low(FChildren) to High(FChildren) do // $R-
FChildren[Index].Free();
end;
procedure TChildrenPatternNode.ReportTokens(Callback: TTokenReporterCallback);
var
Index: Cardinal;
begin
Assert(Length(FChildren) > 0);
for Index := Low(FChildren) to High(FChildren) do // $R-
FChildren[Index].ReportTokens(Callback);
end;
procedure TChildrenPatternNode.FixTokenIDs(Callback: TTokenFinderCallback);
var
Index: Cardinal;
begin
Assert(Length(FChildren) > 0);
for Index := Low(FChildren) to High(FChildren) do // $R-
FChildren[Index].FixTokenIDs(Callback);
end;
procedure TSequencePatternNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
CurrentState, NextState: PState;
Index: Cardinal;
begin
{
A=--[...]--->(O---[...]--->)*Z
}
CurrentState := StartState;
if (Length(FChildren) > 1) then
for Index := Low(FChildren) to High(FChildren)-1 do // $R-
begin
NextState := GetNewState();
FChildren[Index].HookStates(CurrentState, NextState, GetNewState, BlockDuplicates);
BlockDuplicates := False;
CurrentState := NextState;
end;
FChildren[High(FChildren)].HookStates(CurrentState, TargetState, GetNewState, BlockDuplicates);
end;
procedure TOptionalSequencePatternNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
FirstState, CurrentState, NextState: PState;
Index: Cardinal;
begin
{
A=---------->O---[...]--->(O---[...]--->)*Z
--------------------------->
}
if (BlockDuplicates) then
begin
FirstState := GetNewState();
AddTransition(StartState, mtFollow, FirstState, BlockDuplicates);
end
else
FirstState := StartState;
CurrentState := FirstState;
if (Length(FChildren) > 1) then
for Index := Low(FChildren) to High(FChildren)-1 do // $R-
begin
NextState := GetNewState();
FChildren[Index].HookStates(CurrentState, NextState, GetNewState, BlockDuplicates);
BlockDuplicates := False;
CurrentState := NextState;
end;
FChildren[High(FChildren)].HookStates(CurrentState, TargetState, GetNewState, BlockDuplicates);
AddTransition(FirstState, mtFollow, TargetState, False);
end;
procedure TRepeatableSequencePatternNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
FirstState, CurrentState, NextState: PState;
Index: Cardinal;
begin
{
A=---------->O---[...]--->(O---[...]--->)*Z
<---------------------------
}
if (BlockDuplicates) then
begin
FirstState := GetNewState();
AddTransition(StartState, mtFollow, FirstState, BlockDuplicates);
end
else
FirstState := StartState;
CurrentState := FirstState;
if (Length(FChildren) > 1) then
for Index := Low(FChildren) to High(FChildren)-1 do // $R-
begin
NextState := GetNewState();
FChildren[Index].HookStates(CurrentState, NextState, GetNewState, BlockDuplicates);
BlockDuplicates := False;
CurrentState := NextState;
end;
FChildren[High(FChildren)].HookStates(CurrentState, TargetState, GetNewState, BlockDuplicates);
AddTransition(TargetState, mtFollow, FirstState, False);
end;
procedure TAlternativesPatternNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
Index: Cardinal;
MiddleState: PState;
begin
{
If BlockDuplicates is false:
A---[...]--->Z
(---[...]--->)*
If BlockDuplicates is true:
A=---------->M---[...]--->Z
(---[...]--->)*
(because
TZeroOrMoreUnorderedPatternNode.Create([TAlternativesPatternNode.Create([TTokenNode.Create('A'),
TTokenNode.Create('B')]),
TTokenNode.Create('C')])
...should allow AC and BC but not AB, ABC, or BAC)
}
if (BlockDuplicates) then
begin
MiddleState := GetNewState();
AddTransition(StartState, mtFollow, MiddleState, BlockDuplicates);
end
else
MiddleState := StartState;
Assert(Length(FChildren) > 0);
for Index := Low(FChildren) to High(FChildren) do // $R-
FChildren[Index].HookStates(MiddleState, TargetState, GetNewState, BlockDuplicates);
end;
procedure TZeroOrMoreUnorderedPatternNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
Index: Cardinal;
MiddleState: PState;
begin
{
A=---------->M............M----------->Z
<---[...]-==
(<---[...]-==)*
(because
TAlternativesPatternNode.Create([TZeroOrMoreUnorderedPatternNode.Create([TTokenNode.Create('A'),
TTokenNode.Create('B')]),
TTokenNode.Create('C')])
...should allow AB, BA, and C, but not CA etc)
}
MiddleState := GetNewState();
AddTransition(StartState, mtFollow, MiddleState, BlockDuplicates);
Assert(Length(FChildren) > 0);
for Index := Low(FChildren) to High(FChildren) do // $R-
FChildren[Index].HookStates(MiddleState, MiddleState, GetNewState, True);
AddTransition(MiddleState, mtFollow, TargetState, False);
end;
procedure TZeroOrMoreOrderedPatternNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
Index: Cardinal;
CurrentState, NextState: PState;
begin
{
If BlockDuplicates is false:
A---[...]--->(O---[...]--->)*Z
-----------> ----------->
If BlockDuplicates is true:
A=---------->M---[...]--->(O---[...]--->)*Z
-----------> ----------->
}
if (BlockDuplicates) then
begin
CurrentState := GetNewState();
AddTransition(StartState, mtFollow, CurrentState, BlockDuplicates);
end
else
CurrentState := StartState;
if (Length(FChildren) > 1) then
for Index := Low(FChildren) to High(FChildren)-1 do // $R-
begin
NextState := GetNewState();
FChildren[Index].HookStates(CurrentState, NextState, GetNewState);
AddTransition(CurrentState, mtFollow, NextState, False);
CurrentState := NextState;
end;
FChildren[High(FChildren)].HookStates(CurrentState, TargetState, GetNewState, BlockDuplicates);
AddTransition(CurrentState, mtFollow, TargetState, False);
end;
procedure TOneOrMoreUnorderedPatternNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
Index: Cardinal;
MiddleState1, MiddleState2: PState;
begin
{
A=---------->O(==-[...]--->)*O----------->Z
<-----------
}
MiddleState1 := GetNewState();
MiddleState2 := GetNewState();
AddTransition(StartState, mtFollow, MiddleState1, BlockDuplicates);
Assert(Length(FChildren) > 0);
for Index := Low(FChildren) to High(FChildren) do // $R-
FChildren[Index].HookStates(MiddleState1, MiddleState2, GetNewState, True);
AddTransition(MiddleState2, mtFollow, MiddleState1, False);
AddTransition(MiddleState2, mtFollow, TargetState, False);
end;
procedure TOneOrMoreOrderedPatternNode.HookStates(StartState: PState; TargetState: PState; GetNewState: TGetStateCallback; BlockDuplicates: Boolean = False);
var
Index: Cardinal;
S1, S2, S3, S4: PState;
begin
{
One child:
A=--[...]--->Z
Two children without BlockDuplicates:
/------------------------->\
A---[...]--->S2----------->S3---[...]--->Z
\------------------------->/
(S1) (S1) (S2)
Three or more children without BlockDuplicates:
(............................)*
/------------------------->\/------------------------->\
A---[...]--->S2----------->S3---[...]--->S4----------->S5---[...]--->Z
\------------------------->/\------------------------->/
(S1) (S1) (S2) (S3) (S4)
(S1) (S2)
Two children with BlockDuplicates:
/------------------------->\
A=---------->S1---[...]--->S2----------->S3---[...]--->Z
\------------------------->/
(S1) (S2)
Three or more children with BlockDuplicates:
(............................)*
/------------------------->\/------------------------->\
A=---------->S1---[...]--->S2----------->S3---[...]--->S4----------->S5---[...]--->Z
\------------------------->/\------------------------->/
(S1) (S2) (S3) (S4)
(S1) (S2)
}
if (Length(FChildren) = 1) then
begin
FChildren[Low(FChildren)].HookStates(StartState, TargetState, GetNewState, BlockDuplicates);
end
else
begin
if (BlockDuplicates) then
begin
S1 := GetNewState();
AddTransition(StartState, mtFollow, S1, BlockDuplicates);
end
else
begin
S1 := StartState;
end;
S2 := GetNewState();
if (Length(FChildren) > 2) then
for Index := Low(FChildren) to High(FChildren)-2 do // $R-
begin
S3 := GetNewState();
S4 := GetNewState();
FChildren[Index].HookStates(S1, S2, GetNewState);
AddTransition(S1, mtFollow, S3, False);
AddTransition(S2, mtFollow, S3, False);
AddTransition(S2, mtFollow, S4, False);
S1 := S3;
S2 := S4;
end;
S3 := GetNewState();
FChildren[High(FChildren)-1].HookStates(S1, S2, GetNewState);
AddTransition(S1, mtFollow, S3, False);
AddTransition(S2, mtFollow, S3, False);
FChildren[High(FChildren)].HookStates(S3, TargetState, GetNewState);
AddTransition(S2, mtFollow, TargetState, False);
end;
end;
//{$DEFINE DEBUG_PATTERN_COMPILER}
type
TPatternCompiler = class
protected
FRoot: TPatternNode;
FTokens, FOriginalTokens: TTokens;
FFirstState, FLastState: PState;
function GetNewState(): PState;
procedure TokenCollector(Token: UTF8String);
function GetTokenID(Token: UTF8String): TByteCode; { case-sensitive }
public
constructor Create(Root: TPatternNode);
destructor Destroy(); override;
function GetAtomisedTokens(): TTokens;
function GetAtomisedOriginalTokens(): TTokens;
procedure GetCompiledPattern(out Pattern: PCompiledPattern; out PatternLength: TByteCode);
end;
constructor TPatternCompiler.Create(Root: TPatternNode);
begin
inherited Create();
FRoot := Root;
FRoot.ReportTokens(@TokenCollector);
Assert(High(FTokens) <= mtMaxTrueToken, 'Too many unique strings in pattern');
DualQuickSort(FTokens, FOriginalTokens);
DualRemoveDuplicates(FTokens, FOriginalTokens);
FRoot.FixTokenIDs(@GetTokenID);
end;
destructor TPatternCompiler.Destroy();
begin
Assert(Assigned(FRoot));
Assert(not Assigned(FFirstState));
Assert(not Assigned(FLastState));
FRoot.Destroy();
inherited;
end;
function TPatternCompiler.GetNewState(): PState;
begin
New(Result);
Result^.Transitions := nil;
Result^.IncomingTransitionCount := 0;
Result^.OutgoingTransitionCount := 0;
Result^.Index := 0;
Result^.NextState := FLastState;
Result^.PreviousState := FLastState^.PreviousState;
FLastState^.PreviousState^.NextState := Result;
FLastState^.PreviousState := Result;
end;
procedure TPatternCompiler.TokenCollector(Token: UTF8String);
begin
SetLength(FTokens, Length(FTokens)+1);
FTokens[High(FTokens)] := Canonicalise(Token);
SetLength(FOriginalTokens, Length(FOriginalTokens)+1);
FOriginalTokens[High(FOriginalTokens)] := Token;
end;
function TPatternCompiler.GetTokenID(Token: UTF8String): TByteCode;
var
L, R, M: TByteCode;
begin
Assert(Low(FTokens) >= 0);
Assert(High(FTokens) <= mtMaxTrueToken);
Assert(Length(FTokens) > 0);
Token := Canonicalise(Token);
L := Low(FTokens);
R := High(FTokens); // $R-
repeat
M := (R-L) div 2 + L; // $R-
if (FTokens[M] < Token) then
L := M+1 // $R-
else
R := M;
until (L >= R);
Assert(FTokens[R] = Token);
Result := R;
end;
function TPatternCompiler.GetAtomisedTokens(): TTokens;
begin
Result := FTokens;
end;
function TPatternCompiler.GetAtomisedOriginalTokens(): TTokens;
begin
Result := FOriginalTokens;
end;
procedure TPatternCompiler.GetCompiledPattern(out Pattern: PCompiledPattern; out PatternLength: TByteCode);
{$DEFINE OPT_SURROGATES}
{$DEFINE OPT_REDUNDANT_TRANSITIONS}
//{$DEFINE OPT_FIRST_STATE}
function GetUltimateTarget(State: PState): PState;
begin
Result := State;
while ((Result^.OutgoingTransitionCount = 1) and (Result^.Transitions^.Token = mtFollow)) do
begin
Assert(Assigned(Result));
Assert(Result <> FLastState);
Assert(not Assigned(Result^.Transitions^.NextTransition));
Assert(Assigned(Result^.Transitions^.State));
Result := Result^.Transitions^.State;
end;
end;
function StateNeedsSerialising(State: PState): Boolean; inline;
begin
Assert(Assigned(State));
Result := (State = FFirstState) or // we don't know how to optimise the first state away currently, see OPT_FIRST_STATE
((State^.IncomingTransitionCount > 0) and
({$IFDEF OPT_SURROGATES} (State^.OutgoingTransitionCount > 1) or (State^.Transitions^.Token <> mtFollow) {$ELSE} True {$ENDIF}));
end;
function TransitionIsSubSetOfAnother(Transition: PTransition; State: PState): Boolean; inline;
var
CandidateTransition: PTransition;
begin
Assert(Assigned(State));
Assert(Assigned(Transition));
CandidateTransition := State^.Transitions;
repeat
if (CandidateTransition <> Transition) then
begin
if (((Transition^.Token > mtMaxTrueToken) and (CandidateTransition^.Token = mtFollow)) and
(CandidateTransition^.State = Transition^.State) and
((CandidateTransition^.BlockDuplicates = Transition^.BlockDuplicates) or
(CandidateTransition^.BlockDuplicates = False))) then
begin
Result := True;
exit;
end;
end;
CandidateTransition := CandidateTransition^.NextTransition;
until not Assigned(CandidateTransition);
Result := False;
end;
var
State {$IFDEF OPT_SURROGATES}, NewTargetState {$ENDIF}: PState;
Index: Cardinal;
Transition {$IFDEF OPT_REDUNDANT_TRANSITIONS}, PrevTransition {$ENDIF}: PTransition;
DidSomething: Boolean;
begin
{ Build state machine }
New(FFirstState);
FFirstState^.Transitions := nil;
FFirstState^.IncomingTransitionCount := 1; // so that it doesn't get optimised away
FFirstState^.OutgoingTransitionCount := 0;
FFirstState^.Index := 0;
FFirstState^.PreviousState := nil;
New(FLastState);
FLastState^.Transitions := nil;
FLastState^.IncomingTransitionCount := 0;
FLastState^.OutgoingTransitionCount := 0;
FLastState^.Index := 0;
FLastState^.NextState := nil;
FFirstState^.NextState := FLastState;
FLastState^.PreviousState := FFirstState;
FRoot.HookStates(FFirstState, FLastState, @GetNewState);
repeat
DidSomething := False;
{$IFDEF OPT_SURROGATES}
{ Optimise transitions through surrogates }
State := FFirstState;
repeat
Assert(Assigned(State));
if (StateNeedsSerialising(State)) then
begin
Assert(State^.OutgoingTransitionCount >= 1);
Transition := State^.Transitions;
repeat
Assert(Assigned(Transition));
NewTargetState := GetUltimateTarget(Transition^.State);
if (NewTargetState <> Transition^.State) then
begin
Dec(Transition^.State^.IncomingTransitionCount);
Transition^.State := NewTargetState;
Inc(Transition^.State^.IncomingTransitionCount);
DidSomething := True;
end;
Assert((Transition^.State = FLastState) or StateNeedsSerialising(Transition^.State));
Transition := Transition^.NextTransition;
until (not Assigned(Transition));
end;
State := State^.NextState;
until (State = FLastState);
{$ENDIF}
{$IFDEF OPT_REDUNDANT_TRANSITIONS}
{ Optimise redundant state transitions }
State := FFirstState;
repeat
Assert(Assigned(State));
if (StateNeedsSerialising(State)) then
begin
Assert(State^.OutgoingTransitionCount >= 1);
Transition := State^.Transitions;
PrevTransition := nil;
repeat
Assert(Assigned(Transition));
if (TransitionIsSubSetOfAnother(Transition, State)) then
begin
if (Assigned(PrevTransition)) then
begin
PrevTransition^.NextTransition := Transition^.NextTransition;
Dec(Transition^.State^.IncomingTransitionCount);
Dispose(Transition);
Dec(State^.OutgoingTransitionCount);
Transition := PrevTransition^.NextTransition;
end
else
begin
Assert(Assigned(Transition^.NextTransition));