forked from ovenpasta/thunderchez
-
Notifications
You must be signed in to change notification settings - Fork 0
/
irregex.sls
4008 lines (3780 loc) · 167 KB
/
irregex.sls
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
;;; Chez-Scheme library for Alex Shinn's Irregex
;;;
;;; Copyright (c) 2016 Federico Beffa <[email protected]>
;;;
;;; Permission to use, copy, modify, and distribute this software for
;;; any purpose with or without fee is hereby granted, provided that the
;;; above copyright notice and this permission notice appear in all
;;; copies.
;;;
;;; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
;;; WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
;;; AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
;;; DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA
;;; OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
;;; TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
;;; PERFORMANCE OF THIS SOFTWARE.
(library (irregex)
(export
irregex
string->irregex
sre->irregex
string->sre
maybe-string->sre
irregex?
irregex-match-data?
irregex-new-matches
irregex-reset-matches!
irregex-search
irregex-search/matches
irregex-match
irregex-search/chunked
irregex-match/chunked
irregex-fold/chunked
make-irregex-chunker
irregex-match-substring
irregex-match-subchunk
irregex-match-start-chunk
irregex-match-end-chunk
irregex-match-start-index
irregex-match-end-index
irregex-match-num-submatches
irregex-match-names
irregex-match-valid-index?
irregex-fold
irregex-replace
irregex-replace/all
irregex-dfa
irregex-dfa/search
irregex-nfa
irregex-flags
irregex-lengths
irregex-names
irregex-num-submatches
irregex-extract
irregex-split
sre->cset)
(import
(except (rnrs) error find filter remove)
(rnrs r5rs)
(rnrs mutable-pairs)
(rnrs mutable-strings)
(only (chezscheme) include))
;; definition from irregex
(define (error msg . args)
(display msg)
(for-each (lambda (x) (display " ") (write x)) args)
(newline)
(0))
;;;; irregex.scm -- IrRegular Expressions
;;
;; Copyright (c) 2005-2015 Alex Shinn. All rights reserved.
;; BSD-style license: http://synthcode.com/license.txt
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; At this moment there was a loud ring at the bell, and I could
;; hear Mrs. Hudson, our landlady, raising her voice in a wail of
;; expostulation and dismay.
;;
;; "By heaven, Holmes," I said, half rising, "I believe that
;; they are really after us."
;;
;; "No, it's not quite so bad as that. It is the unofficial
;; force, -- the Baker Street irregulars."
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Notes
;;
;; This code should not require any porting - it should work out of
;; the box in any R[45]RS Scheme implementation. Slight modifications
;; are needed for R6RS (a separate R6RS-compatible version is included
;; in the distribution as irregex-r6rs.scm).
;;
;; The goal of portability makes this code a little clumsy and
;; inefficient. Future versions will include both cleanup and
;; performance tuning, but you can only go so far while staying
;; portable. AND-LET*, SRFI-9 records and custom macros would've been
;; nice.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; History
;; 0.9.4: 2015/12/14 - performance improvement for {n,m} matches
;; 0.9.3: 2014/07/01 - R7RS library
;; 0.9.2: 2012/11/29 - fixed a bug in -fold on conditional bos patterns
;; 0.9.1: 2012/11/27 - various accumulated bugfixes
;; 0.9.0: 2012/06/03 - Using tags for match extraction from Peter Bex.
;; 0.8.3: 2011/12/18 - various accumulated bugfixes
;; 0.8.2: 2010/08/28 - (...)? submatch extraction fix and alternate
;; named submatches from Peter Bex
;; Added irregex-split, irregex-extract,
;; irregex-match-names and irregex-match-valid-index?
;; to Chicken and Guile module export lists and made
;; the latter accept named submatches. The procedures
;; irregex-match-{start,end}-{index,chunk} now also
;; accept named submatches, with the index argument
;; made optional. Improved argument type checks.
;; Disallow negative submatch index.
;; Improve performance of backtracking matcher.
;; Refactor charset handling into a consistent API
;; 0.8.1: 2010/03/09 - backtracking irregex-match fix and other small fixes
;; 0.8.0: 2010/01/20 - optimizing DFA compilation, adding SRE escapes
;; inside PCREs, adding utility SREs
;; 0.7.5: 2009/08/31 - adding irregex-extract and irregex-split
;; *-fold copies match data (use *-fold/fast for speed)
;; irregex-opt now returns an SRE
;; 0.7.4: 2009/05/14 - empty alternates (or) and empty csets always fail,
;; bugfix in default finalizer for irregex-fold/chunked
;; 0.7.3: 2009/04/14 - adding irregex-fold/chunked, minor doc fixes
;; 0.7.2: 2009/02/11 - some bugfixes, much improved documentation
;; 0.7.1: 2008/10/30 - several bugfixes (thanks to Derick Eddington)
;; 0.7.0: 2008/10/20 - support abstract chunked strings
;; 0.6.2: 2008/07/26 - minor bugfixes, allow global disabling of utf8 mode,
;; friendlier error messages in parsing, \Q..\E support
;; 0.6.1: 2008/07/21 - added utf8 mode, more utils, bugfixes
;; 0.6: 2008/05/01 - most of PCRE supported
;; 0.5: 2008/04/24 - fully portable R4RS, many PCRE features implemented
;; 0.4: 2008/04/17 - rewriting NFA to use efficient closure compilation,
;; normal strings only, but all of the spencer tests pass
;; 0.3: 2008/03/10 - adding DFA converter (normal strings only)
;; 0.2: 2005/09/27 - adding irregex-opt (like elisp's regexp-opt) utility
;; 0.1: 2005/08/18 - simple NFA interpreter over abstract chunked strings
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Data Structures
(define irregex-tag '*irregex-tag*)
(define (make-irregex dfa dfa/search nfa flags submatches lengths names)
(vector irregex-tag dfa dfa/search nfa flags submatches lengths names))
(define (irregex? obj)
(and (vector? obj)
(= 8 (vector-length obj))
(eq? irregex-tag (vector-ref obj 0))))
(define (irregex-dfa x) (vector-ref x 1))
(define (irregex-dfa/search x) (vector-ref x 2))
(define (irregex-nfa x) (vector-ref x 3))
(define (irregex-flags x) (vector-ref x 4))
(define (irregex-num-submatches x) (vector-ref x 5))
(define (irregex-lengths x) (vector-ref x 6))
(define (irregex-names x) (vector-ref x 7))
(define (vector-copy v)
(let ((r (make-vector (vector-length v))))
(do ((i (- (vector-length v) 1) (- i 1)))
((< i 0) r)
(vector-set! r i (vector-ref v i)))))
(define (irregex-new-matches irx)
(make-irregex-match (irregex-num-submatches irx) (irregex-names irx)))
(define (irregex-reset-matches! m)
(do ((i (- (vector-length m) 1) (- i 1)))
((<= i 3) m)
(vector-set! m i #f)))
(define (irregex-copy-matches m)
(and (vector? m) (vector-copy m)))
(define irregex-match-tag '*irregex-match-tag*)
(define (irregex-match-data? obj)
(and (vector? obj)
(>= (vector-length obj) 11)
(eq? irregex-match-tag (vector-ref obj 0))))
(define (make-irregex-match count names)
(let ((res (make-vector (+ (* 4 (+ 2 count)) 3) #f)))
(vector-set! res 0 irregex-match-tag)
(vector-set! res 2 names)
res))
(define (irregex-match-num-submatches m)
(- (quotient (- (vector-length m) 3) 4) 2))
(define (irregex-match-chunker m)
(vector-ref m 1))
(define (irregex-match-names m)
(vector-ref m 2))
(define (irregex-match-chunker-set! m str)
(vector-set! m 1 str))
(define (%irregex-match-start-chunk m n) (vector-ref m (+ 3 (* n 4))))
(define (%irregex-match-start-index m n) (vector-ref m (+ 4 (* n 4))))
(define (%irregex-match-end-chunk m n) (vector-ref m (+ 5 (* n 4))))
(define (%irregex-match-end-index m n) (vector-ref m (+ 6 (* n 4))))
(define (%irregex-match-fail m)
(vector-ref m (- (vector-length m) 1)))
(define (%irregex-match-fail-set! m x)
(vector-set! m (- (vector-length m) 1) x))
;; public interface with error checking
(define (irregex-match-start-chunk m . opt)
(let ((n (irregex-match-numeric-index "irregex-match-start-chunk" m opt)))
(and n (%irregex-match-start-chunk m n))))
(define (irregex-match-start-index m . opt)
(let ((n (irregex-match-numeric-index "irregex-match-start-index" m opt)))
(and n (%irregex-match-start-index m n))))
(define (irregex-match-end-chunk m . opt)
(let ((n (irregex-match-numeric-index "irregex-match-end-chunk" m opt)))
(and n (%irregex-match-end-chunk m n))))
(define (irregex-match-end-index m . opt)
(let ((n (irregex-match-numeric-index "irregex-match-end-index" m opt)))
(and n (%irregex-match-end-index m n))))
(define (irregex-match-start-chunk-set! m n start)
(vector-set! m (+ 3 (* n 4)) start))
(define (irregex-match-start-index-set! m n start)
(vector-set! m (+ 4 (* n 4)) start))
(define (irregex-match-end-chunk-set! m n end)
(vector-set! m (+ 5 (* n 4)) end))
(define (irregex-match-end-index-set! m n end)
(vector-set! m (+ 6 (* n 4)) end))
;; Tags use indices that are aligned to start/end positions just like the
;; match vectors. ie, a tag 0 is a start tag, 1 is its corresponding end tag.
;; They start at 0, which requires us to map them to submatch index 1.
;; Sorry for the horrible name ;)
(define (irregex-match-chunk&index-from-tag-set! m t chunk index)
(vector-set! m (+ 7 (* t 2)) chunk)
(vector-set! m (+ 8 (* t 2)) index))
;; Helper procedure to convert any type of index from a rest args list
;; to a numeric index. Named submatches are converted to their corresponding
;; numeric index, and numeric submatches are checked for validity.
;; An error is raised for invalid numeric or named indices, #f is returned
;; for defined but nonmatching indices.
(define (irregex-match-numeric-index location m opt)
(cond
((not (irregex-match-data? m))
(error (string-append location ": not match data") m))
((not (pair? opt)) 0)
((pair? (cdr opt))
(apply error (string-append location ": too many arguments") m opt))
(else
(let ((n (car opt)))
(if (number? n)
(if (and (integer? n) (exact? n))
(if (irregex-match-valid-numeric-index? m n)
(and (irregex-match-matched-numeric-index? m n) n)
(error (string-append location ": not a valid index")
m n))
(error (string-append location ": not an exact integer") n))
(let lp ((ls (irregex-match-names m))
(unknown? #t))
(cond
((null? ls)
(and unknown?
(error (string-append location ": unknown match name") n)))
((eq? n (caar ls))
(if (%irregex-match-start-chunk m (cdar ls))
(cdar ls)
(lp (cdr ls) #f)))
(else (lp (cdr ls) unknown?)))))))))
(define (irregex-match-valid-numeric-index? m n)
(and (>= n 0) (< (+ 3 (* n 4)) (- (vector-length m) 4))))
(define (irregex-match-matched-numeric-index? m n)
(and (vector-ref m (+ 4 (* n 4)))
#t))
(define (irregex-match-valid-named-index? m n)
(and (assq n (irregex-match-names m))
#t))
(define (irregex-match-valid-index? m n)
(if (not (irregex-match-data? m))
(error "irregex-match-valid-index?: not match data" m))
(if (integer? n)
(if (not (exact? n))
(error "irregex-match-valid-index?: not an exact integer" n)
(irregex-match-valid-numeric-index? m n))
(irregex-match-valid-named-index? m n)))
(define (irregex-match-substring m . opt)
(let* ((n (irregex-match-numeric-index "irregex-match-substring" m opt))
(cnk (irregex-match-chunker m)))
(and n
((chunker-get-substring cnk)
(%irregex-match-start-chunk m n)
(%irregex-match-start-index m n)
(%irregex-match-end-chunk m n)
(%irregex-match-end-index m n)))))
(define (irregex-match-subchunk m . opt)
(let* ((n (irregex-match-numeric-index "irregex-match-subchunk" m opt))
(cnk (irregex-match-chunker m))
(get-subchunk (chunker-get-subchunk cnk)))
(if (not get-subchunk)
(error "this chunk type does not support match subchunks")
(and n (get-subchunk
(%irregex-match-start-chunk m n)
(%irregex-match-start-index m n)
(%irregex-match-end-chunk m n)
(%irregex-match-end-index m n))))))
;; chunkers tell us how to navigate through chained chunks of strings
(define (make-irregex-chunker get-next get-str . o)
(let* ((get-start (or (and (pair? o) (car o)) (lambda (cnk) 0)))
(o (if (pair? o) (cdr o) o))
(get-end (or (and (pair? o) (car o))
(lambda (cnk) (string-length (get-str cnk)))))
(o (if (pair? o) (cdr o) o))
(get-substr
(or (and (pair? o) (car o))
(lambda (cnk1 start cnk2 end)
(if (eq? cnk1 cnk2)
(substring (get-str cnk1) start end)
(let loop ((cnk (get-next cnk1))
(res (list (substring (get-str cnk1)
start
(get-end cnk1)))))
(if (eq? cnk cnk2)
(string-cat-reverse
(cons (substring (get-str cnk)
(get-start cnk)
end)
res))
(loop (get-next cnk)
(cons (substring (get-str cnk)
(get-start cnk)
(get-end cnk))
res))))))))
(o (if (pair? o) (cdr o) o))
(get-subchunk (and (pair? o) (car o))))
(if (not (and (procedure? get-next) (procedure? get-str)
(procedure? get-start) (procedure? get-substr)))
(error "make-irregex-chunker: expected a procdure"))
(vector get-next get-str get-start get-end get-substr get-subchunk)))
(define (chunker-get-next cnk) (vector-ref cnk 0))
(define (chunker-get-str cnk) (vector-ref cnk 1))
(define (chunker-get-start cnk) (vector-ref cnk 2))
(define (chunker-get-end cnk) (vector-ref cnk 3))
(define (chunker-get-substring cnk) (vector-ref cnk 4))
(define (chunker-get-subchunk cnk) (vector-ref cnk 5))
(define (chunker-prev-chunk cnk start end)
(if (eq? start end)
#f
(let ((get-next (chunker-get-next cnk)))
(let lp ((start start))
(let ((next (get-next start)))
(if (eq? next end)
start
(and next (lp next))))))))
(define (chunker-prev-char cnk start end)
(let ((prev (chunker-prev-chunk cnk start end)))
(and prev
(string-ref ((chunker-get-str cnk) prev)
(- ((chunker-get-end cnk) prev) 1)))))
(define (chunker-next-char cnk src)
(let ((next ((chunker-get-next cnk) src)))
(and next
(string-ref ((chunker-get-str cnk) next)
((chunker-get-start cnk) next)))))
(define (chunk-before? cnk a b)
(and (not (eq? a b))
(let ((next ((chunker-get-next cnk) a)))
(and next
(if (eq? next b)
#t
(chunk-before? cnk next b))))))
;; For look-behind searches, wrap an existing chunker such that it
;; returns the same results but ends at a given point.
(define (wrap-end-chunker cnk src i)
(make-irregex-chunker
(lambda (x) (and (not (eq? x src)) ((chunker-get-next cnk) x)))
(chunker-get-str cnk)
(chunker-get-start cnk)
(lambda (x) (if (eq? x src) i ((chunker-get-end cnk) x)))
(chunker-get-substring cnk)
(chunker-get-subchunk cnk)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; String Utilities
;; Unicode version (skip surrogates)
(define *all-chars*
`(/ ,(integer->char 0) ,(integer->char #xD7FF)
,(integer->char #xE000) ,(integer->char #x10FFFF)))
;; ASCII version, offset to not assume 0-255
;; (define *all-chars* `(/ ,(integer->char (- (char->integer #\space) 32)) ,(integer->char (+ (char->integer #\space) 223))))
;; set to #f to ignore even an explicit request for utf8 handling
(define *allow-utf8-mode?* #t)
;; (define *named-char-properties* '())
(define (string-scan-char str c . o)
(let ((end (string-length str)))
(let scan ((i (if (pair? o) (car o) 0)))
(cond ((= i end) #f)
((eqv? c (string-ref str i)) i)
(else (scan (+ i 1)))))))
(define (string-scan-char-escape str c . o)
(let ((end (string-length str)))
(let scan ((i (if (pair? o) (car o) 0)))
(cond ((= i end) #f)
((eqv? c (string-ref str i)) i)
((eqv? c #\\) (scan (+ i 2)))
(else (scan (+ i 1)))))))
(define (string-scan-pred str pred . o)
(let ((end (string-length str)))
(let scan ((i (if (pair? o) (car o) 0)))
(cond ((= i end) #f)
((pred (string-ref str i)) i)
(else (scan (+ i 1)))))))
(define (string-split-char str c)
(let ((end (string-length str)))
(let lp ((i 0) (from 0) (res '()))
(define (collect) (cons (substring str from i) res))
(cond ((>= i end) (reverse (collect)))
((eqv? c (string-ref str i)) (lp (+ i 1) (+ i 1) (collect)))
(else (lp (+ i 1) from res))))))
(define (char-alphanumeric? c)
(or (char-alphabetic? c) (char-numeric? c)))
(define (%substring=? a b start1 start2 len)
(let lp ((i 0))
(cond ((>= i len)
#t)
((char=? (string-ref a (+ start1 i)) (string-ref b (+ start2 i)))
(lp (+ i 1)))
(else
#f))))
;; SRFI-13 extracts
(define (%%string-copy! to tstart from fstart fend)
(do ((i fstart (+ i 1))
(j tstart (+ j 1)))
((>= i fend))
(string-set! to j (string-ref from i))))
(define (string-cat-reverse string-list)
(string-cat-reverse/aux
(fold (lambda (s a) (+ (string-length s) a)) 0 string-list)
string-list))
(define (string-cat-reverse/aux len string-list)
(let ((res (make-string len)))
(let lp ((i len) (ls string-list))
(if (pair? ls)
(let* ((s (car ls))
(slen (string-length s))
(i (- i slen)))
(%%string-copy! res i s 0 slen)
(lp i (cdr ls)))))
res))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; List Utilities
;; like the one-arg IOTA case
(define (zero-to n)
(if (<= n 0)
'()
(let lp ((i (- n 1)) (res '()))
(if (zero? i) (cons 0 res) (lp (- i 1) (cons i res))))))
;; SRFI-1 extracts (simplified 1-ary versions)
(define (find pred ls)
(cond ((find-tail pred ls) => car)
(else #f)))
(define (find-tail pred ls)
(let lp ((ls ls))
(cond ((null? ls) #f)
((pred (car ls)) ls)
(else (lp (cdr ls))))))
(define (last ls)
(if (not (pair? ls))
(error "can't take last of empty list" ls)
(let lp ((ls ls))
(if (pair? (cdr ls))
(lp (cdr ls))
(car ls)))))
(define (any pred ls)
(and (pair? ls)
(let lp ((head (car ls)) (tail (cdr ls)))
(if (null? tail)
(pred head)
(or (pred head) (lp (car tail) (cdr tail)))))))
(define (every pred ls)
(or (null? ls)
(let lp ((head (car ls)) (tail (cdr ls)))
(if (null? tail)
(pred head)
(and (pred head) (lp (car tail) (cdr tail)))))))
(define (fold kons knil ls)
(let lp ((ls ls) (res knil))
(if (null? ls)
res
(lp (cdr ls) (kons (car ls) res)))))
(define (filter pred ls)
(let lp ((ls ls) (res '()))
(if (null? ls)
(reverse res)
(lp (cdr ls) (if (pred (car ls)) (cons (car ls) res) res)))))
(define (remove pred ls)
(let lp ((ls ls) (res '()))
(if (null? ls)
(reverse res)
(lp (cdr ls) (if (pred (car ls)) res (cons (car ls) res))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Flags
(define (bit-shr n i)
(quotient n (expt 2 i)))
(define (bit-shl n i)
(* n (expt 2 i)))
(define (bit-not n) (- #xFFFF n))
(define (bit-ior a b)
(cond
((zero? a) b)
((zero? b) a)
(else
(+ (if (or (odd? a) (odd? b)) 1 0)
(* 2 (bit-ior (quotient a 2) (quotient b 2)))))))
(define (bit-and a b)
(cond
((zero? a) 0)
((zero? b) 0)
(else
(+ (if (and (odd? a) (odd? b)) 1 0)
(* 2 (bit-and (quotient a 2) (quotient b 2)))))))
(define (integer-log n)
(define (b8 n r)
(if (>= n (bit-shl 1 8)) (b4 (bit-shr n 8) (+ r 8)) (b4 n r)))
(define (b4 n r)
(if (>= n (bit-shl 1 4)) (b2 (bit-shr n 4) (+ r 4)) (b2 n r)))
(define (b2 n r)
(if (>= n (bit-shl 1 2)) (b1 (bit-shr n 2) (+ r 2)) (b1 n r)))
(define (b1 n r) (if (>= n (bit-shl 1 1)) (+ r 1) r))
(if (>= n (bit-shl 1 16)) (b8 (bit-shr n 16) 16) (b8 n 0)))
(define (flag-set? flags i)
(= i (bit-and flags i)))
(define (flag-join a b)
(if b (bit-ior a b) a))
(define (flag-clear a b)
(bit-and a (bit-not b)))
(define ~none 0)
(define ~searcher? 1)
(define ~consumer? 2)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Parsing Embedded SREs in PCRE Strings
;; (define (with-read-from-string str i proc)
;; (define (port-size in)
;; (let lp ((i 0)) (if (eof-object? (read-char in)) i (lp (+ i 1)))))
;; (let* ((len (string-length str))
;; (tail-len (- len i))
;; (in (open-input-string (substring str i len)))
;; (sre (read in))
;; (unused-len (port-size in)))
;; (close-input-port in)
;; (proc sre (- tail-len unused-len))))
(define close-token (list 'close))
(define dot-token (string->symbol "."))
(define (with-read-from-string str i proc)
(define end (string-length str))
(define (read i k)
(cond
((>= i end) (error "unterminated embedded SRE" str))
(else
(case (string-ref str i)
((#\()
(let lp ((i (+ i 1)) (ls '()))
(read
i
(lambda (x j)
(cond
((eq? x close-token)
(k (reverse ls) j))
((eq? x dot-token)
(if (null? ls)
(error "bad dotted form" str)
(read j (lambda (y j2)
(read j2 (lambda (z j3)
(if (not (eq? z close-token))
(error "bad dotted form" str)
(k (append (reverse (cdr ls))
(cons (car ls) y))
j3))))))))
(else
(lp j (cons x ls))))))))
((#\))
(k close-token (+ i 1)))
((#\;)
(let skip ((i (+ i 1)))
(if (or (>= i end) (eqv? #\newline (string-ref str i)))
(read (+ i 1) k)
(skip (+ i 1)))))
((#\' #\`)
(read (+ i 1)
(lambda (sexp j)
(let ((q (if (eqv? #\' (string-ref str i)) 'quote 'quasiquote)))
(k (list q sexp) j)))))
((#\,)
(let* ((at? (and (< (+ i 1) end) (eqv? #\@ (string-ref str (+ i 1)))))
(u (if at? 'uquote-splicing 'unquote))
(j (if at? (+ i 2) (+ i 1))))
(read j (lambda (sexp j) (k (list u sexp) j)))))
((#\")
(let scan ((from (+ i 1)) (i (+ i 1)) (res '()))
(define (collect)
(if (= from i) res (cons (substring str from i) res)))
(if (>= i end)
(error "unterminated string in embeded SRE" str)
(case (string-ref str i)
((#\") (k (string-cat-reverse (collect)) (+ i 1)))
((#\\) (scan (+ i 1) (+ i 2) (collect)))
(else (scan from (+ i 1) res))))))
((#\#)
(case (string-ref str (+ i 1))
((#\;)
(read (+ i 2) (lambda (sexp j) (read j k))))
((#\\)
(read (+ i 2)
(lambda (sexp j)
(k (case sexp
((space) #\space)
((newline) #\newline)
(else (let ((s (if (number? sexp)
(number->string sexp)
(symbol->string sexp))))
(string-ref s 0))))
j))))
((#\t #\f)
(k (eqv? #\t (string-ref str (+ i 1))) (+ i 2)))
(else
(error "bad # syntax in simplified SRE" i))))
(else
(cond
((char-whitespace? (string-ref str i))
(read (+ i 1) k))
(else ;; symbol/number
(let scan ((j (+ i 1)))
(cond
((or (>= j end)
(let ((c (string-ref str j)))
(or (char-whitespace? c)
(memv c '(#\; #\( #\) #\" #\# #\\)))))
(let ((str2 (substring str i j)))
(k (or (string->number str2) (string->symbol str2)) j)))
(else (scan (+ j 1))))))))))))
(read i (lambda (res j)
(if (eq? res 'close-token)
(error "unexpected ')' in SRE" str j)
(proc res j)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;; Parsing PCRE Strings
(define ~save? 1)
(define ~case-insensitive? 2)
(define ~multi-line? 4)
(define ~single-line? 8)
(define ~ignore-space? 16)
(define ~utf8? 32)
(define (symbol-list->flags ls)
(let lp ((ls ls) (res ~none))
(if (not (pair? ls))
res
(lp (cdr ls)
(flag-join
res
(case (car ls)
((i ci case-insensitive) ~case-insensitive?)
((m multi-line) ~multi-line?)
((s single-line) ~single-line?)
((x ignore-space) ~ignore-space?)
((u utf8) (if *allow-utf8-mode?* ~utf8? ~none))
(else #f)))))))
(define (maybe-string->sre obj)
(if (string? obj) (string->sre obj) obj))
(define (string->sre str . o)
(if (not (string? str)) (error "string->sre: expected a string" str))
(let ((end (string-length str))
(flags (symbol-list->flags o)))
(let lp ((i 0) (from 0) (flags flags) (res '()) (st '()))
;; handle case sensitivity at the literal char/string level
(define (cased-char ch)
(if (and (flag-set? flags ~case-insensitive?)
(char-alphabetic? ch))
`(or ,ch ,(char-altcase ch))
ch))
(define (cased-string str)
(if (flag-set? flags ~case-insensitive?)
(sre-sequence (map cased-char (string->list str)))
str))
;; accumulate the substring from..i as literal text
(define (collect)
(if (= i from) res (cons (cased-string (substring str from i)) res)))
;; like collect but breaks off the last single character when
;; collecting literal data, as the argument to ?/*/+ etc.
(define (collect/single)
(let* ((utf8? (flag-set? flags ~utf8?))
(j (if (and utf8? (> i 1))
(utf8-backup-to-initial-char str (- i 1))
(- i 1))))
(cond
((< j from)
res)
(else
(let ((c (cased-char (if utf8?
(utf8-string-ref str j (- i j))
(string-ref str j)))))
(cond
((= j from)
(cons c res))
(else
(cons c
(cons (cased-string (substring str from j))
res)))))))))
;; collects for use as a result, reversing and grouping OR
;; terms, and some ugly tweaking of `function-like' groups and
;; conditionals
(define (collect/terms)
(let* ((ls (collect))
(func
(and (pair? ls)
(memq (last ls)
'(atomic if look-ahead neg-look-ahead
look-behind neg-look-behind
=> submatch-named
w/utf8 w/noutf8))))
(prefix (if (and func (memq (car func) '(=> submatch-named)))
(list 'submatch-named (cadr (reverse ls)))
(and func (list (car func)))))
(ls (if func
(if (memq (car func) '(=> submatch-named))
(reverse (cddr (reverse ls)))
(reverse (cdr (reverse ls))))
ls)))
(let lp ((ls ls) (term '()) (res '()))
(define (shift)
(cons (sre-sequence term) res))
(cond
((null? ls)
(let* ((res (sre-alternate (shift)))
(res (if (flag-set? flags ~save?)
(list 'submatch res)
res)))
(if prefix
(if (eq? 'if (car prefix))
(cond
((not (pair? res))
'epsilon)
((memq (car res)
'(look-ahead neg-look-ahead
look-behind neg-look-behind))
res)
((eq? 'seq (car res))
`(if ,(cadr res)
,(sre-sequence (cddr res))))
(else
`(if ,(cadadr res)
,(sre-sequence (cddadr res))
,(sre-alternate (cddr res)))))
`(,@prefix ,res))
res)))
((eq? 'or (car ls)) (lp (cdr ls) '() (shift)))
(else (lp (cdr ls) (cons (car ls) term) res))))))
(define (save)
(cons (cons flags (collect)) st))
;; main parsing
(if (>= i end)
(if (pair? st)
(error "unterminated parenthesis in regexp" str)
(collect/terms))
(let ((c (string-ref str i)))
(case c
((#\.)
(lp (+ i 1) (+ i 1) flags
(cons (if (flag-set? flags ~single-line?) 'any 'nonl)
(collect))
st))
((#\?)
(let ((res (collect/single)))
(if (null? res)
(error "? can't follow empty pattern" str res)
(let ((x (car res)))
(lp (+ i 1)
(+ i 1)
flags
(cons
(if (pair? x)
(case (car x)
((*) `(*? ,@(cdr x)))
((+) `(**? 1 #f ,@(cdr x)))
((?) `(?? ,@(cdr x)))
((**) `(**? ,@(cdr x)))
((=) `(**? ,(cadr x) ,@(cdr x)))
((>=) `(**? ,(cadr x) #f ,@(cddr x)))
(else `(? ,x)))
`(? ,x))
(cdr res))
st)))))
((#\+ #\*)
(let* ((res (collect/single))
(x (if (pair? res) (car res) 'epsilon))
(op (string->symbol (string c))))
(cond
((sre-repeater? x)
(error "duplicate repetition (e.g. **) in pattern" str res))
((sre-empty? x)
(error "can't repeat empty pattern (e.g. ()*)" str res))
(else
(lp (+ i 1) (+ i 1) flags
(cons (list op x) (cdr res))
st)))))
((#\()
(cond
((>= (+ i 1) end)
(error "unterminated parenthesis in regexp" str))
((not (memv (string-ref str (+ i 1)) '(#\? #\*))) ; normal case
(lp (+ i 1) (+ i 1) (flag-join flags ~save?) '() (save)))
((>= (+ i 2) end)
(error "unterminated parenthesis in regexp" str))
((eqv? (string-ref str (+ i 1)) #\*)
(if (eqv? #\' (string-ref str (+ i 2)))
(with-read-from-string str (+ i 3)
(lambda (sre j)
(if (or (>= j end) (not (eqv? #\) (string-ref str j))))
(error "unterminated (*'...) SRE escape" str)
(lp (+ j 1) (+ j 1) flags (cons sre (collect)) st))))
(error "bad regexp syntax: (*FOO) not supported" str)))
(else ;; (?...) case
(case (string-ref str (+ i 2))
((#\#)
(let ((j (string-scan-char str #\) (+ i 3))))
(lp (+ j i) (+ j 1) flags (collect) st)))
((#\:)
(lp (+ i 3) (+ i 3) (flag-clear flags ~save?) '() (save)))
((#\=)
(lp (+ i 3) (+ i 3) (flag-clear flags ~save?)
'(look-ahead) (save)))
((#\!)
(lp (+ i 3) (+ i 3) (flag-clear flags ~save?)
'(neg-look-ahead) (save)))
((#\<)
(cond
((>= (+ i 3) end)
(error "unterminated parenthesis in regexp" str))
(else
(case (string-ref str (+ i 3))
((#\=)
(lp (+ i 4) (+ i 4) (flag-clear flags ~save?)
'(look-behind) (save)))
((#\!)
(lp (+ i 4) (+ i 4) (flag-clear flags ~save?)
'(neg-look-behind) (save)))
(else
(let ((j (and (char-alphabetic?
(string-ref str (+ i 3)))
(string-scan-char str #\> (+ i 4)))))
(if j
(lp (+ j 1) (+ j 1) (flag-clear flags ~save?)
`(,(string->symbol (substring str (+ i 3) j))
submatch-named)
(save))
(error "invalid (?< sequence" str))))))))
((#\>)
(lp (+ i 3) (+ i 3) (flag-clear flags ~save?)
'(atomic) (save)))
;;((#\' #\P) ; named subpatterns
;; )
;;((#\R) ; recursion
;; )
((#\()
(cond
((>= (+ i 3) end)
(error "unterminated parenthesis in regexp" str))
((char-numeric? (string-ref str (+ i 3)))
(let* ((j (string-scan-char str #\) (+ i 3)))
(n (string->number (substring str (+ i 3) j))))
(if (not n)
(error "invalid conditional reference" str)
(lp (+ j 1) (+ j 1) (flag-clear flags ~save?)
`(,n if) (save)))))
((char-alphabetic? (string-ref str (+ i 3)))
(let* ((j (string-scan-char str #\) (+ i 3)))
(s (string->symbol (substring str (+ i 3) j))))
(lp (+ j 1) (+ j 1) (flag-clear flags ~save?)
`(,s if) (save))))
(else
(lp (+ i 2) (+ i 2) (flag-clear flags ~save?)
'(if) (save)))))
((#\{)
(error "unsupported Perl-style cluster" str))
(else
(let ((old-flags flags))
(let lp2 ((j (+ i 2)) (flags flags) (invert? #f))
(define (join x)
((if invert? flag-clear flag-join) flags x))
(define (new-res res)
(let ((before (flag-set? old-flags ~utf8?))
(after (flag-set? flags ~utf8?)))
(if (eq? before after)
res
(cons (if after 'w/utf8 'w/noutf8) res))))
(cond
((>= j end)
(error "incomplete cluster" str i))
(else
(case (string-ref str j)
((#\i)
(lp2 (+ j 1) (join ~case-insensitive?) invert?))
((#\m)
(lp2 (+ j 1) (join ~multi-line?) invert?))
((#\x)
(lp2 (+ j 1) (join ~ignore-space?) invert?))
((#\u)
(if *allow-utf8-mode?*
(lp2 (+ j 1) (join ~utf8?) invert?)
(lp2 (+ j 1) flags invert?)))
((#\-)
(lp2 (+ j 1) flags (not invert?)))
((#\))
(lp (+ j 1) (+ j 1) flags (new-res (collect))
st))
((#\:)
(lp (+ j 1) (+ j 1) flags (new-res '())
(cons (cons old-flags (collect)) st)))
(else
(error "unknown regex cluster modifier" str)
)))))))))))
((#\))
(if (null? st)
(error "too many )'s in regexp" str)
(lp (+ i 1)
(+ i 1)
(caar st)
(cons (collect/terms) (cdar st))
(cdr st))))
((#\[)
(apply
(lambda (sre j)
(lp (+ j 1) (+ j 1) flags (cons sre (collect)) st))