-
Notifications
You must be signed in to change notification settings - Fork 11
/
RegexMatcher.ns
3136 lines (2725 loc) · 99.2 KB
/
RegexMatcher.ns
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
Newspeak3
'Regex'
class RegexMatcher usingPlatform: platform = (
(* Ported to NS2 by Ryan Macnak from Vassil Bykov's Regular Expression Matcher Smalltalk library.
Copyright (c) 1996 - 2008 Vassili Bykov
Copyright (c) 2009 Vassil Bykov, Ryan Macnak and other contributors.
Licensed under the MIT license:
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the ''Software''), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ''AS IS'', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE *)
|
(* Imports *)
private Association = platform squeak Association.
private Map = platform squeak Dictionary.
private List = platform squeak OrderedCollection.
private Set = platform squeak Set.
private WriteStream = platform squeak WriteStream.
private ReadStream = platform squeak ReadStream.
private Transcript = platform squeak Transcript.
private MessageNotUnderstood = platform squeak MessageNotUnderstood.
(* module variables *)
Cr = Character cr.
Lf = Character lf.
BackslashConstants
BackslashSpecials
EscapedLetterSelectors
NamedClassSelectors
|RxParser initializeStuff.
RxsPredicate initializeStuff) (
public class CompilationError = RegexError (
(* Regex compilation error *)
) (
) : (
)
public class MatchError = RegexError (
(* Regex matching error *)
) (
) : (
)
public class RegexError = Error (
(* Regex error *)
) (
) : (
)
class RxCharSetParser on: aStream = (
(* I am a parser created to parse the insides of a character set ([...]) construct. I create and answer a collection of 'elements', each being an instance of one of: RxsCharacter, RxsRange, or RxsPredicate. *)
|
source lookahead elements
|source: aStream.
lookahead: aStream next.
elements: List new) (
addChar: aChar = (
elements add: (RxsCharacter with: aChar)
)
addRangeFrom: firstChar to: lastChar = (
firstChar asInteger > lastChar asInteger ifTrue:
[signalSyntaxException: ' bad character range'].
elements add: (RxsRange from: firstChar to: lastChar)
)
match: aCharacter = (
aCharacter = lookahead
ifFalse: [signalSyntaxException: 'unexpected character: ', (String with: lookahead)].
^source atEnd
ifTrue: [lookahead: nil]
ifFalse: [lookahead: source next]
)
public parse = (
lookahead = "-" ifTrue:
[self addChar: "-".
self match: "-"].
[lookahead isNil] whileFalse: [self parseStep].
^elements
)
parseCharOrRange = (
| firstChar |
firstChar: lookahead.
self match: firstChar.
lookahead = "-" ifTrue:
[self match: "-".
lookahead isNil
ifTrue: [^self addChar: firstChar; addChar: "-"]
ifFalse:
[self addRangeFrom: firstChar to: lookahead.
^self match: lookahead]].
self addChar: firstChar
)
parseEscapeChar = (
self match: "\".
"-" = lookahead
ifTrue: [elements add: (RxsCharacter with: "-")]
ifFalse: [elements add: (RxsPredicate forEscapedLetter: lookahead)].
self match: lookahead
)
parseNamedSet = (
| name |
self match: "["; match: ":".
name:: (String with: lookahead), (source upTo: ":").
lookahead:: source next.
self match: "]".
elements add: (RxsPredicate forNamedClass: name)
)
parseStep = (
lookahead = "[" ifTrue:
[source peek = ":"
ifTrue: [^self parseNamedSet]
ifFalse: [^self parseCharOrRange]].
lookahead = "\" ifTrue:
[^self parseEscapeChar].
lookahead = "-" ifTrue:
[signalSyntaxException: 'invalid range'].
self parseCharOrRange
)
) : (
)
class RxMatchOptimizer for: aRegex ignoreCase: aBoolean = (
(* A match start optimizer, handy for searching a string. Takes a regex syntax tree and sets itself up so that prefix characters or matcher states that cannot start a match are later recognized with #canStartMatch:in: method.
Used by RxMatcher, but can be used by other matchers (if implemented) as well. *)
|
ignoreCase prefixes nonPrefixes conditions testBlock methodPredicates nonMethodPredicates predicates nonPredicates
|ignoreCase:: aBoolean.
prefixes:: Set new: 10.
nonPrefixes:: Set new: 10.
conditions:: Set new: 3.
methodPredicates:: Set new: 3.
nonMethodPredicates:: Set new: 3.
predicates:: Set new: 3.
nonPredicates:: Set new: 3.
aRegex dispatchTo: self. (* If the whole expression is nullable,
end-of-line is an implicit can-match condition! *)
aRegex isNullable ifTrue: [conditions add: #atEndOfLine].
testBlock:: self determineTestMethod) (
public canStartMatch: aCharacter in: aMatcher = (
(* Answer whether a match could commence at the given lookahead
character, or in the current state of <aMatcher>. True answered
by this method does not mean a match will definitly occur, while false
answered by this method *does* guarantee a match will never occur. *)
aCharacter isNil ifTrue: [^true].
^testBlock == nil or: [testBlock value: aCharacter value: aMatcher]
)
public conditionTester = (
(* #any condition is filtered at the higher level;
it cannot appear among the conditions here. *)
| matchCondition |
conditions isEmpty ifTrue: [^nil].
conditions size = 1 ifTrue:
[matchCondition:: conditions detect: [:ignored | true].
(* Special case all of the possible conditions. *)
#atBeginningOfLine = matchCondition ifTrue: [^[:c :matcher | matcher atBeginningOfLine]].
#atEndOfLine = matchCondition ifTrue: [^[:c :matcher | matcher atEndOfLine]].
#atBeginningOfWord = matchCondition ifTrue: [^[:c :matcher | matcher atBeginningOfWord]].
#atEndOfWord = matchCondition ifTrue: [^[:c :matcher | matcher atEndOfWord]].
#atWordBoundary = matchCondition ifTrue: [^[:c :matcher | matcher atWordBoundary]].
#notAtWordBoundary = matchCondition ifTrue: [^[:c :matcher | matcher notAtWordBoundary]].
signalCompilationException: 'invalid match condition'].
(* More than one condition. Capture them as an array in scope. *)
matchCondition:: conditions asArray.
^[:c :matcher |
matchCondition contains:
[:conditionSelector |
matcher perform: conditionSelector]]
)
determineTestMethod = (
(* Answer a block closure that will work as a can-match predicate.
Answer nil if no viable optimization is possible (too many chars would
be able to start a match). *)
| testers |
(conditions includes: #any) ifTrue: [^nil].
testers:: List new: 5.
{#prefixTester. #nonPrefixTester. #conditionTester. #methodPredicateTester. #nonMethodPredicateTester. #predicateTester. #nonPredicateTester}
do:
[:selector |
| tester |
tester:: self perform: selector.
tester notNil ifTrue: [testers add: tester]].
testers isEmpty ifTrue: [^nil].
testers size = 1 ifTrue: [^testers first].
testers:: testers asArray.
^[:char :matcher | testers contains: [:t | t value: char value: matcher]]
)
public methodPredicateTester = (
| p selector |
methodPredicates isEmpty ifTrue: [^nil].
p:: self optimizeSet: methodPredicates. (* also allows copying closures *)
^p size = 1
ifTrue:
[(* might be a pretty common case *)
selector:: p first.
[:char :matcher |
RxParser doHandlingMessageNotUnderstood:
[char perform: selector]]]
ifFalse:
[[:char :m |
RxParser doHandlingMessageNotUnderstood:
[p contains: [:sel | char perform: sel]]]]
)
public nonMethodPredicateTester = (
| p selector |
nonMethodPredicates isEmpty ifTrue: [^nil].
p:: self optimizeSet: nonMethodPredicates. (* also allows copying closures *)
^p size = 1
ifTrue:
[selector:: p first.
[:char :matcher |
RxParser doHandlingMessageNotUnderstood:
[(char perform: selector) not]]]
ifFalse:
[[:char :m |
RxParser doHandlingMessageNotUnderstood:
[p contains: [:sel | (char perform: sel) not]]]]
)
public nonPredicateTester = (
| p pred |
nonPredicates isEmpty ifTrue: [^nil].
p:: self optimizeSet: nonPredicates. (* also allows copying closures *)
^p size = 1
ifTrue:
[pred:: p first.
[:char :matcher | (pred value: char) not]]
ifFalse:
[[:char :m | p contains: [:some | (some value: char) not]]]
)
public nonPrefixTester = (
| np nonPrefixChar |
nonPrefixes isEmpty ifTrue: [^nil].
np:: self optimizeSet: nonPrefixes. (* also allows copying closures *)
^np size = 1 (* might be be pretty common case *)
ifTrue:
[nonPrefixChar:: np first.
[:char :matcher | char ~= nonPrefixChar]]
ifFalse: [[:char : matcher | (np includes: char) not]]
)
optimizeSet: aSet = (
(* If a set is small, convert it to array to speed up lookup
(Array has no hashing overhead, beats Set on small number
of elements). *)
^aSet size < 10 ifTrue: [aSet asArray] ifFalse: [aSet]
)
public predicateTester = (
| p pred |
predicates isEmpty ifTrue: [^nil].
p:: self optimizeSet: predicates. (* also allows copying closures *)
^p size = 1
ifTrue:
[pred:: p first.
[:char :matcher | pred value: char]]
ifFalse:
[[:char :m | p contains: [:some | some value: char]]]
)
public prefixTester = (
| p prefixChar |
prefixes isEmpty ifTrue: [^nil].
p:: self optimizeSet: prefixes. (* also allows copying closures *)
ignoreCase ifTrue: [p:: p collect: [:each | each asUppercase]].
^p size = 1 (* might be a pretty common case *)
ifTrue:
[prefixChar:: p first.
ignoreCase
ifTrue: [[:char :matcher | char sameAs: prefixChar]]
ifFalse: [[:char :matcher | char = prefixChar]]]
ifFalse:
[ignoreCase
ifTrue: [[:char :matcher | p includes: char asUppercase]]
ifFalse: [[:char :matcher | p includes: char]]]
)
public syntaxAny = (
(* Any special char is among the prefixes. *)
conditions add: #any
)
public syntaxBeginningOfLine = (
(* Beginning of line is among the prefixes. *)
conditions add: #atBeginningOfLine
)
public syntaxBeginningOfWord = (
(* Beginning of line is among the prefixes. *)
conditions add: #atBeginningOfWord
)
public syntaxBranch: branchNode = (
(* If the head piece of the branch is transparent (allows 0 matches),
we must recurse down the branch. Otherwise, just the head atom
is important. *)
(branchNode piece isNullable and: [branchNode branch notNil])
ifTrue: [branchNode branch dispatchTo: self].
branchNode piece dispatchTo: self
)
public syntaxCharSet: charSetNode = (
(* All these (or none of these) characters is the prefix. *)
charSetNode isNegated
ifTrue: [nonPrefixes addAll: (charSetNode enumerableSetIgnoringCase: ignoreCase)]
ifFalse: [prefixes addAll: (charSetNode enumerableSetIgnoringCase: ignoreCase)].
charSetNode hasPredicates ifTrue:
[charSetNode isNegated
ifTrue: [nonPredicates addAll: charSetNode predicates]
ifFalse: [predicates addAll: charSetNode predicates]]
)
public syntaxCharacter: charNode = (
(* This character is the prefix, of one of them. *)
prefixes add: charNode character
)
public syntaxEndOfLine = (
(* Beginning of line is among the prefixes. *)
conditions add: #atEndOfLine
)
public syntaxEndOfWord = (
conditions add: #atEndOfWord
)
public syntaxEpsilon = (
(* Empty string, terminate the recursion (do nothing). *)
)
public syntaxMessagePredicate: messagePredicateNode = (
messagePredicateNode negated
ifTrue: [nonMethodPredicates add: messagePredicateNode selector]
ifFalse: [methodPredicates add: messagePredicateNode selector]
)
public syntaxNonWordBoundary = (
conditions add: #notAtWordBoundary
)
public syntaxPiece: pieceNode = (
(* Pass on to the atom. *)
pieceNode atom dispatchTo: self
)
public syntaxPredicate: predicateNode = (
predicates add: predicateNode predicate
)
public syntaxRegex: regexNode = (
(* All prefixes of the regex's branches should be combined.
Therefore, just recurse. *)
regexNode branch dispatchTo: self.
regexNode regex notNil
ifTrue: [regexNode regex dispatchTo: self]
)
public syntaxWordBoundary = (
conditions add: #atWordBoundary
)
) : (
)
public class RxMatcher for: syntaxTreeRoot ignoreCase: aBoolean = (
(* This is a recursive regex matcher. Not strikingly efficient, but simple. Also, keeps track of matched subexpressions. The life cycle goes as follows:
1. Initialization. Accepts a syntax tree (presumably produced by RxParser) and compiles it into a matcher built of other classes in this category.
2. Matching. Accepts a stream or a string and returns a boolean indicating whether the whole stream or its prefix -- depending on the message sent -- matches the regex.
3. Subexpression query. After a successful match, and before any other match, the matcher may be queried about the range of specific stream (string) positions that matched to certain parenthesized subexpressions of the original expression.
Any number of queries may follow a successful match, and any number or matches may follow a successful initialization.
Note that `matcher' is actually a sort of a misnomer. The actual matcher is a web of Rxm* instances built by RxMatcher during initialization. RxMatcher is just the interface facade of this network. It is also a builder of it, and also provides a stream-like protocol to easily access the stream being matched.
Slots:
matcher <RxmLink> The entry point into the actual matcher.
stream <Stream> The stream currently being matched against.
markerPositions <Array of: Integer> Positions of markers' matches.
markerCount <Integer> Number of markers.
lastResult <Boolean> Whether the latest match attempt succeeded or not.
lastChar <Character | nil> character last seen in the matcher stream *)
|
matcher ignoreCase startOptimizer stream markerPositions markerCount lastResult lastChar
|ignoreCase:: aBoolean.
self buildFrom: syntaxTreeRoot.
startOptimizer:: RxMatchOptimizer for: syntaxTreeRoot ignoreCase: aBoolean) (
allocateMarker = (
(* Answer an integer to use as an index of the next marker. *)
markerCount:: markerCount + 1.
^markerCount
)
public atBeginningOfLine = (
^self position = 0 or: [lastChar = Cr]
)
public atBeginningOfWord = (
^(self isWordChar: lastChar) not
and: [self isWordChar: stream peek]
)
public atEnd = (
^stream atEnd
)
public atEndOfLine = (
^self atEnd or: [stream peek = Cr]
)
public atEndOfWord = (
^(self isWordChar: lastChar)
and: [(self isWordChar: stream peek) not]
)
public atWordBoundary = (
^(self isWordChar: lastChar)
xor: (self isWordChar: stream peek)
)
buildFrom: aSyntaxTreeRoot = (
(* Private - Entry point of matcher build process. *)
markerCount:: 0. (* must go before #dispatchTo: ! *)
matcher:: aSyntaxTreeRoot dispatchTo: self.
matcher terminateWith: RxmTerminator new
)
public copy: aString replacingMatchesWith: replacementString = (
(* Copy <aString>, except for the matches. Replace each match with <aString>. *)
| answer |
answer:: (String new: 40) writeStream.
self
copyStream: aString readStream
to: answer
replacingMatchesWith: replacementString.
^answer contents
)
public copy: aString translatingMatchesUsing: aBlock = (
(* Copy <aString>, except for the matches. For each match, evaluate <aBlock> passing the matched substring as the argument. Expect the block to answer a String, and replace the match with the answer. *)
| answer |
answer:: (String new: 40) writeStream.
self copyStream: aString readStream to: answer translatingMatchesUsing: aBlock.
^answer contents
)
public copyStream: aStream to: writeStream replacingMatchesWith: aString = (
(* Copy the contents of <aStream> on the <writeStream>, except for the matches. Replace each match with <aString>. *)
| searchStart matchStart matchEnd |
stream:: aStream.
lastChar:: nil.
[searchStart:: aStream position.
self proceedSearchingStream: aStream] whileTrue:
[matchStart:: (self subBeginning: 1) first.
matchEnd:: (self subEnd: 1) first.
aStream position: searchStart.
searchStart to: matchStart - 1 do:
[:ignoredPos | writeStream nextPut: aStream next].
writeStream nextPutAll: aString.
aStream position: matchEnd.
(* Be extra careful about successful matches which consume no input.
After those, make sure to advance or finish if already at end. *)
matchEnd = searchStart ifTrue:
[aStream atEnd
ifTrue: [^self (* rest after end of whileTrue: block is a no-op if atEnd *)]
ifFalse: [writeStream nextPut: aStream next]]].
aStream position: searchStart.
[aStream atEnd] whileFalse: [writeStream nextPut: aStream next]
)
public copyStream: aStream to: writeStream translatingMatchesUsing: aBlock = (
(* Copy the contents of <aStream> on the <writeStream>, except for the matches. For each match, evaluate <aBlock> passing the matched substring as the argument. Expect the block to answer a String, and write the answer to <writeStream> in place of the match. *)
| searchStart matchStart matchEnd match |
stream:: aStream.
lastChar:: nil.
[searchStart:: aStream position.
self proceedSearchingStream: aStream] whileTrue:
[matchStart:: (self subBeginning: 1) first.
matchEnd:: (self subEnd: 1) first.
aStream position: searchStart.
searchStart to: matchStart - 1 do:
[:ignoredPos | writeStream nextPut: aStream next].
match:: (String new: matchEnd - matchStart + 1) writeStream.
matchStart to: matchEnd - 1 do:
[:ignoredPos | match nextPut: aStream next].
writeStream nextPutAll: (aBlock value: match contents).
(* Be extra careful about successful matches which consume no input.
After those, make sure to advance or finish if already at end. *)
matchEnd = searchStart ifTrue:
[aStream atEnd
ifTrue: [^self (* rest after end of whileTrue: block is a no-op if atEnd *)]
ifFalse: [writeStream nextPut: aStream next]]].
aStream position: searchStart.
[aStream atEnd] whileFalse: [writeStream nextPut: aStream next]
)
public currentState = (
(* Answer an opaque object that can later be used to restore the
matcher's state (for backtracking). *)
| origPosition origLastChar |
origPosition:: stream position.
origLastChar:: lastChar.
^ [stream position: origPosition.
lastChar:: origLastChar]
)
hookBranchOf: regexNode onto: endMarker = (
(* Private - Recurse down the chain of regexes starting at
regexNode, compiling their branches and hooking their tails
to the endMarker node. *)
| rest |
rest:: regexNode regex isNil
ifTrue: [nil]
ifFalse: [self hookBranchOf: regexNode regex onto: endMarker].
^RxmBranch new
next: ((regexNode branch dispatchTo: self)
pointTailTo: endMarker;
yourself);
alternative: rest;
yourself
)
isWordChar: aCharacterOrNil = (
(* Answer whether the argument is a word constituent character:
alphanumeric or _. *)
^aCharacterOrNil ~~ nil
and: [aCharacterOrNil isAlphaNumeric]
)
makeOptional: aMatcher = (
(* Private - Wrap this matcher so that the result would match 0 or 1
occurrences of the matcher. *)
| dummy branch |
dummy:: RxmLink new.
branch:: (RxmBranch new beLoopback)
next: aMatcher;
alternative: dummy.
aMatcher pointTailTo: dummy.
^branch
)
makePlus: aMatcher = (
(* Private - Wrap this matcher so that the result would match 1 and more
occurrences of the matcher. *)
| loopback |
loopback:: (RxmBranch new beLoopback)
next: aMatcher.
aMatcher pointTailTo: loopback.
^aMatcher
)
makeStar: aMatcher = (
(* Private - Wrap this matcher so that the result would match 0 and more
occurrences of the matcher. *)
| dummy detour loopback |
dummy:: RxmLink new.
detour:: RxmBranch new
next: aMatcher;
alternative: dummy.
loopback:: (RxmBranch new beLoopback)
next: aMatcher;
alternative: dummy.
aMatcher pointTailTo: loopback.
^detour
)
public markerPositionAt: anIndex add: position = (
(* Remember position of another instance of the given marker. *)
(markerPositions at: anIndex) addFirst: position
)
public matches: aString = (
(* Match against a string. *)
^self matchesStream: aString readStream
)
public matchesIn: aString = (
(* Search aString repeatedly for the matches of the receiver. Answer an List of all matches (substrings). *)
| result |
result:: List new.
self
matchesOnStream: aString readStream
do: [:match | result add: match].
^result
)
public matchesIn: aString collect: aBlock = (
(* Search aString repeatedly for the matches of the receiver. Evaluate aBlock for each match passing the matched substring as the argument, collect evaluation results in an List, and return in. The following example shows how to use this message to split a string into words. *)
(* '\w+' asRegex matchesIn: 'Now is the Time' collect: [:each | each asLowercase] *)
| result |
result:: List new.
self
matchesOnStream: aString readStream
do: [:match | result add: (aBlock value: match)].
^result
)
public matchesIn: aString do: aBlock = (
(* Search aString repeatedly for the matches of the receiver.
Evaluate aBlock for each match passing the matched substring
as the argument. *)
self
matchesOnStream: aString readStream
do: aBlock
)
public matchesOnStream: aStream = (
| result |
result:: List new.
self
matchesOnStream: aStream
do: [:match | result add: match].
^result
)
public matchesOnStream: aStream collect: aBlock = (
| result |
result:: List new.
self
matchesOnStream: aStream
do: [:match | result add: (aBlock value: match)].
^result
)
public matchesOnStream: aStream do: aBlock = (
(* Be extra careful about successful matches which consume no input.
After those, make sure to advance or finish if already at end. *)
| position |
[position:: aStream position.
self searchStream: aStream] whileTrue:
[aBlock value: (self subexpression: 1).
position = aStream position ifTrue:
[aStream atEnd
ifTrue: [^self]
ifFalse: [aStream next]]]
)
public matchesPrefix: aString = (
(* Match against a string. *)
^self matchesStreamPrefix: aString readStream
)
public matchesStream: theStream = (
(* Match thyself against a positionable stream. *)
^(self matchesStreamPrefix: theStream)
and: [stream atEnd]
)
public matchesStreamPrefix: theStream = (
(* Match thyself against a positionable stream. *)
stream:: theStream.
lastChar:: nil.
^self tryMatch
)
public matchingRangesIn: aString = (
(* Search aString repeatedly for the matches of the receiver. Answer an List of ranges of each match (index of first character to: index of last character). *)
| result |
result:: List new.
self
matchesIn: aString
do: [:match | result add: (self position - match size + 1 to: self position)].
^result
)
public next = (
lastChar:: stream next.
^lastChar
)
notAtWordBoundary = (
^self atWordBoundary not
)
public position = (
^stream position
)
proceedSearchingStream: aStream = (
| position |
position:: aStream position.
[aStream atEnd] whileFalse:
[self tryMatch ifTrue: [^true].
aStream position: position.
lastChar:: aStream next.
position:: aStream position].
(* Try match at the very stream end too! *)
self tryMatch ifTrue: [^true].
^false
)
public restoreState: aBlock = (
aBlock value
)
search: aString = (
(* Search the string for occurrence of something matching myself.
Answer a Boolean indicating success. *)
^self searchStream: aString readStream
)
searchStream: aStream = (
(* Search the stream for occurrence of something matching myself.
After the search has occurred, stop positioned after the end of the
matched substring. Answer a Boolean indicating success. *)
| position |
stream:: aStream.
lastChar:: nil.
position:: aStream position.
[aStream atEnd] whileFalse:
[self tryMatch ifTrue: [^true].
aStream position: position.
lastChar:: aStream next.
position:: aStream position].
(* Try match at the very stream end too! *)
self tryMatch ifTrue: [^true].
^false
)
subBeginning: subIndex = (
^markerPositions at: subIndex * 2 - 1
)
subEnd: subIndex = (
^markerPositions at: subIndex * 2
)
public subexpression: subIndex = (
(* Answer a string that matched the subexpression at the given index.
If there are multiple matches, answer the last one.
If there are no matches, answer nil.
(NB: it used to answer an empty string but I think nil makes more sense). *)
| matches |
matches:: self subexpressions: subIndex.
^matches isEmpty ifTrue: [nil] ifFalse: [matches last]
)
subexpressionCount = (
^markerCount // 2
)
subexpressions: subIndex = (
(* Answer an array of all matches of the subexpression at the given index.
The answer is always an array; it is empty if there are no matches. *)
| originalPosition startPositions stopPositions reply |
originalPosition:: stream position.
startPositions:: self subBeginning: subIndex.
stopPositions:: self subEnd: subIndex.
(startPositions isEmpty or: [stopPositions isEmpty]) ifTrue: [^Array new].
reply:: List new.
startPositions with: stopPositions do:
[:start :stop |
stream position: start.
reply add: (stream next: stop - start)].
stream position: originalPosition.
^reply asArray
)
supportsSubexpressions = (
^true
)
public syntaxAny = (
(* Double dispatch from the syntax tree.
Create a matcher for any non-null character. *)
^RxmPredicate new
predicate: [:char | char asInteger ~= 0]
)
public syntaxBeginningOfLine = (
(* Double dispatch from the syntax tree.
Create a matcher for beginning-of-line condition. *)
^RxmSpecial new beBeginningOfLine
)
public syntaxBeginningOfWord = (
(* Double dispatch from the syntax tree.
Create a matcher for beginning-of-word condition. *)
^RxmSpecial new beBeginningOfWord
)
public syntaxBranch: branchNode = (
(* Double dispatch from the syntax tree.
Branch node is a link in a chain of concatenated pieces.
First build the matcher for the rest of the chain, then make
it for the current piece and hook the rest to it. *)
| result next rest |
branchNode branch isNil
ifTrue: [^branchNode piece dispatchTo: self].
(* Optimization: glue a sequence of individual characters into a single string to match. *)
branchNode piece isAtomic ifTrue:
[result:: WriteStream on: (String new: 40).
next:: branchNode tryMergingInto: result.
result:: result contents.
result size > 1 ifTrue: (* worth merging *)
[rest:: next notNil
ifTrue: [next dispatchTo: self]
ifFalse: [nil].
^(RxmSubstring new substring: result ignoreCase: ignoreCase)
pointTailTo: rest;
yourself]].
(* No optimization possible or worth it, just concatenate all. *)
^(branchNode piece dispatchTo: self)
pointTailTo: (branchNode branch dispatchTo: self);
yourself
)
public syntaxCharSet: charSetNode = (
(* Double dispatch from the syntax tree.
A character set is a few characters, and we either match any of them,
or match any that is not one of them. *)
^RxmPredicate with: (charSetNode predicateIgnoringCase: ignoreCase)
)
public syntaxCharacter: charNode = (
(* Double dispatch from the syntax tree.
We get here when no merging characters into strings was possible. *)
| wanted |
wanted:: charNode character.
^RxmPredicate new predicate:
(ignoreCase
ifTrue: [[:char | char sameAs: wanted]]
ifFalse: [[:char | char = wanted]])
)
public syntaxEndOfLine = (
(* Double dispatch from the syntax tree.
Create a matcher for end-of-line condition. *)
^RxmSpecial new beEndOfLine
)
public syntaxEndOfWord = (
(* Double dispatch from the syntax tree.
Create a matcher for end-of-word condition. *)
^RxmSpecial new beEndOfWord
)
public syntaxEpsilon = (
(* Double dispatch from the syntax tree. Match empty string. This is unlikely
to happen in sane expressions, so we'll live without special epsilon-nodes. *)
^RxmSubstring new
substring: String new
ignoreCase: ignoreCase
)
public syntaxMessagePredicate: messagePredicateNode = (
(* Double dispatch from the syntax tree.
Special link can handle predicates. *)
^messagePredicateNode negated
ifTrue: [RxmPredicate new bePerformNot: messagePredicateNode selector]
ifFalse: [RxmPredicate new bePerform: messagePredicateNode selector]
)
public syntaxNonWordBoundary = (
(* Double dispatch from the syntax tree.
Create a matcher for the word boundary condition. *)
^RxmSpecial new beNotWordBoundary
)
public syntaxPiece: pieceNode = (
(* Double dispatch from the syntax tree.
Piece is an atom repeated a few times. Take care of a special
case when the atom is repeated just once. *)
| atom |
atom:: pieceNode atom dispatchTo: self.
^pieceNode isSingular
ifTrue: [atom]
ifFalse: [pieceNode isStar
ifTrue: [self makeStar: atom]
ifFalse: [pieceNode isPlus
ifTrue: [self makePlus: atom]
ifFalse: [pieceNode isOptional
ifTrue: [self makeOptional: atom]
ifFalse: [signalCompilationException: 'repetitions are not supported by RxMatcher']]]]
)
public syntaxPredicate: predicateNode = (
(* Double dispatch from the syntax tree.
A character set is a few characters, and we either match any of them,
or match any that is not one of them. *)
^RxmPredicate with: predicateNode predicate
)
public syntaxRegex: regexNode = (
(* Double dispatch from the syntax tree.
Regex node is a chain of branches to be tried. Should compile this
into a bundle of parallel branches, between two marker nodes. *)
| startIndex endIndex endNode alternatives |
startIndex:: self allocateMarker.
endIndex:: self allocateMarker.
endNode:: RxmMarker new index: endIndex.
alternatives:: self hookBranchOf: regexNode onto: endNode.
^(RxmMarker new index: startIndex)
pointTailTo: alternatives;
yourself
)
public syntaxWordBoundary = (
(* Double dispatch from the syntax tree.
Create a matcher for the word boundary condition. *)
^RxmSpecial new beWordBoundary
)
tryMatch = (
(* Match thyself against the current stream. *)
markerPositions:: Array new: markerCount.
1 to: markerCount do: [:i | markerPositions at: i put: List new].
startOptimizer == nil
ifTrue: [lastResult:: matcher matchAgainst: self]
ifFalse: [lastResult:: (startOptimizer canStartMatch: stream peek in: self)
and: [matcher matchAgainst: self]].
^lastResult
)
) : (
public for: aRegex = (
^self for: aRegex ignoreCase: false
)
public forString: aString = (
(* Create and answer a matcher that will match the regular expression
`aString'. *)
^self for: (RxParser new parse: aString)
)
public forString: aString ignoreCase: aBoolean = (
(* Create and answer a matcher that will match the regular expression
`aString'. *)
^self for: (RxParser new parse: aString) ignoreCase: aBoolean
)
)
class RxParser = (
(* The regular expression parser. Translates a regular expression read from a stream into a parse tree. ('accessing' protocol). The tree can later be passed to a matcher initialization method. All other classes in this category implement the tree. Refer to their comments for any details.
Instance variables:
input <Stream> A stream with the regular expression being parsed.
lookahead <Character> *)
|
input lookahead
|) (
atom = (
(* An atom is one of a lot of possibilities, see below. *)
| atom |
(lookahead = #epsilon or:
[lookahead = "|" or:
[lookahead = ")"
or: [lookahead = "*" or: [lookahead = "+" or: [lookahead = "?"]]]]])
ifTrue: [^RxsEpsilon new].
lookahead = "(" ifTrue:
[(* <atom> ::= '(' <regex> ')' *)
self match: "(".
atom:: self regex.
self match: ")".
^atom].
lookahead = "[" ifTrue:
[(* <atom> ::= '[' <characterSet> ']' *)
self match: "[".
atom:: self characterSet.
self match: "]".
^atom].
lookahead = ":" ifTrue:
[(* <atom> ::= ':' <messagePredicate> ':' *)
self match: ":".
atom:: self messagePredicate.
self match: ":".
^atom].
lookahead = "." ifTrue:
[(* any non-whitespace character *)
self next.
^RxsContextCondition new beAny].
lookahead = "^" ifTrue:
[(* beginning of line condition *)
self next.
^RxsContextCondition new beBeginningOfLine].
lookahead = "$" ifTrue:
[(* end of line condition *)
self next.
^RxsContextCondition new beEndOfLine].
lookahead = "\" ifTrue:
[(* <atom> ::= '\' <character> *)
self next.
lookahead = #epsilon ifTrue:
[self signalParseError: 'bad quotation'].
(BackslashConstants includesKey: lookahead) ifTrue:
[atom:: RxsCharacter with: (BackslashConstants at: lookahead).
self next.
^atom].
self ifSpecial: lookahead
then: [:node | self next. ^node]].
(* If passed through the above, the following is a regular character. *)
atom:: RxsCharacter with: lookahead.
self next.
^atom
)
branch = (
(* <branch> ::= e | <piece> <branch> *)
| piece branch |
piece:: self piece.
(lookahead = #epsilon or: [lookahead = "|" or: [lookahead = ")" ]])
ifTrue: [branch:: nil]
ifFalse: [branch:: self branch].
^RxsBranch piece: piece branch: branch