Codebase list cafeobj / 53de403b-1baa-40dc-9f50-f47eadcb46ac/main cl-ppcre / repetition-closures.lisp
53de403b-1baa-40dc-9f50-f47eadcb46ac/main

Tree @53de403b-1baa-40dc-9f50-f47eadcb46ac/main (Download .tar.gz)

repetition-closures.lisp @53de403b-1baa-40dc-9f50-f47eadcb46ac/mainraw · history · blame

  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
;;; -*- Mode: LISP; Syntax: COMMON-LISP; Package: CL-PPCRE; Base: 10 -*-
;;; $Header: /usr/local/cvsrep/cl-ppcre/repetition-closures.lisp,v 1.34 2009/09/17 19:17:31 edi Exp $

;;; This is actually a part of closures.lisp which we put into a
;;; separate file because it is rather complex. We only deal with
;;; REPETITIONs here. Note that this part of the code contains some
;;; rather crazy micro-optimizations which were introduced to be as
;;; competitive with Perl as possible in tight loops.

;;; Copyright (c) 2002-2009, Dr. Edmund Weitz. All rights reserved.

;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:

;;;   * Redistributions of source code must retain the above copyright
;;;     notice, this list of conditions and the following disclaimer.

;;;   * Redistributions in binary form must reproduce the above
;;;     copyright notice, this list of conditions and the following
;;;     disclaimer in the documentation and/or other materials
;;;     provided with the distribution.

;;; THIS SOFTWARE IS PROVIDED BY THE AUTHOR 'AS IS' AND ANY EXPRESSED
;;; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
;;; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
;;; ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
;;; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
;;; GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
;;; INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
;;; WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
;;; NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

(in-package :cl-ppcre)

(defmacro incf-after (place &optional (delta 1) &environment env)
  "Utility macro inspired by C's \"place++\", i.e. first return the
value of PLACE and afterwards increment it by DELTA."
  (with-unique-names (%temp)
    (multiple-value-bind (vars vals store-vars writer-form reader-form)
        (get-setf-expansion place env)
      `(let* (,@(mapcar #'list vars vals)
              (,%temp ,reader-form)
              (,(car store-vars) (+ ,%temp ,delta)))
        ,writer-form
        ,%temp))))

;; code for greedy repetitions with minimum zero

(defmacro greedy-constant-length-closure (check-curr-pos)
  "This is the template for simple greedy repetitions (where simple
means that the minimum number of repetitions is zero, that the inner
regex to be checked is of fixed length LEN, and that it doesn't
contain registers, i.e. there's no need for backtracking).
CHECK-CURR-POS is a form which checks whether the inner regex of the
repetition matches at CURR-POS."
  `(if maximum
    (lambda (start-pos)
      (declare (fixnum start-pos maximum))
      ;; because we know LEN we know in advance where to stop at the
      ;; latest; we also take into consideration MIN-REST, i.e. the
      ;; minimal length of the part behind the repetition
      (let ((target-end-pos (min (1+ (- *end-pos* len min-rest))
                                 ;; don't go further than MAXIMUM
                                 ;; repetitions, of course
                                 (+ start-pos
                                    (the fixnum (* len maximum)))))
            (curr-pos start-pos))
        (declare (fixnum target-end-pos curr-pos))
        (block greedy-constant-length-matcher
          ;; we use an ugly TAGBODY construct because this might be a
          ;; tight loop and this version is a bit faster than our LOOP
          ;; version (at least in CMUCL)
          (tagbody
            forward-loop
            ;; first go forward as far as possible, i.e. while
            ;; the inner regex matches
            (when (>= curr-pos target-end-pos)
              (go backward-loop))
            (when ,check-curr-pos
              (incf curr-pos len)
              (go forward-loop))
            backward-loop
            ;; now go back LEN steps each until we're able to match
            ;; the rest of the regex
            (when (< curr-pos start-pos)
              (return-from greedy-constant-length-matcher nil))
            (let ((result (funcall next-fn curr-pos)))
              (when result
                (return-from greedy-constant-length-matcher result)))
            (decf curr-pos len)
            (go backward-loop)))))
    ;; basically the same code; it's just a bit easier because we're
    ;; not bounded by MAXIMUM
    (lambda (start-pos)
      (declare (fixnum start-pos))
      (let ((target-end-pos (1+ (- *end-pos* len min-rest)))
            (curr-pos start-pos))
        (declare (fixnum target-end-pos curr-pos))
        (block greedy-constant-length-matcher
          (tagbody
            forward-loop
            (when (>= curr-pos target-end-pos)
              (go backward-loop))
            (when ,check-curr-pos
              (incf curr-pos len)
              (go forward-loop))
            backward-loop
            (when (< curr-pos start-pos)
              (return-from greedy-constant-length-matcher nil))
            (let ((result (funcall next-fn curr-pos)))
              (when result
                (return-from greedy-constant-length-matcher result)))
            (decf curr-pos len)
            (go backward-loop)))))))

(defun create-greedy-everything-matcher (maximum min-rest next-fn)
  "Creates a closure which just matches as far ahead as possible,
i.e. a closure for a dot in single-line mode."
  (declare #.*standard-optimize-settings*)
  (declare (fixnum min-rest) (function next-fn))
  (if maximum
    (lambda (start-pos)
      (declare (fixnum start-pos maximum))
      ;; because we know LEN we know in advance where to stop at the
      ;; latest; we also take into consideration MIN-REST, i.e. the
      ;; minimal length of the part behind the repetition
      (let ((target-end-pos (min (+ start-pos maximum)
                                 (- *end-pos* min-rest))))
        (declare (fixnum target-end-pos))
        ;; start from the highest possible position and go backward
        ;; until we're able to match the rest of the regex
        (loop for curr-pos of-type fixnum from target-end-pos downto start-pos
              thereis (funcall next-fn curr-pos))))
    ;; basically the same code; it's just a bit easier because we're
    ;; not bounded by MAXIMUM
    (lambda (start-pos)
      (declare (fixnum start-pos))
      (let ((target-end-pos (- *end-pos* min-rest)))
        (declare (fixnum target-end-pos))
        (loop for curr-pos of-type fixnum from target-end-pos downto start-pos
              thereis (funcall next-fn curr-pos))))))

(defgeneric create-greedy-constant-length-matcher (repetition next-fn)
  (declare #.*standard-optimize-settings*)
  (:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is greedy and the minimal number of
repetitions is zero.  It is furthermore assumed that the inner regex
of REPETITION is of fixed length and doesn't contain registers."))

(defmethod create-greedy-constant-length-matcher ((repetition repetition)
                                                  next-fn)
  (declare #.*standard-optimize-settings*)
  (let ((len (len repetition))
        (maximum (maximum repetition))
        (regex (regex repetition))
        (min-rest (min-rest repetition)))
    (declare (fixnum len min-rest)
             (function next-fn))
    (cond ((zerop len)
            ;; inner regex has zero-length, so we can discard it
            ;; completely
            next-fn)
          (t
            ;; now first try to optimize for a couple of common cases
            (typecase regex
              (str
                (let ((str (str regex)))
                  (if (= 1 len)
                    ;; a single character
                    (let ((chr (schar str 0)))
                      (if (case-insensitive-p regex)
                        (greedy-constant-length-closure
                         (char-equal chr (schar *string* curr-pos)))
                        (greedy-constant-length-closure
                         (char= chr (schar *string* curr-pos)))))
                    ;; a string
                    (if (case-insensitive-p regex)
                      (greedy-constant-length-closure
                       (*string*-equal str curr-pos (+ curr-pos len) 0 len))
                      (greedy-constant-length-closure
                       (*string*= str curr-pos (+ curr-pos len) 0 len))))))
              (char-class
                ;; a character class
                (insert-char-class-tester (regex (schar *string* curr-pos))
                  (greedy-constant-length-closure
                   (char-class-test))))
              (everything
                ;; an EVERYTHING object, i.e. a dot
                (if (single-line-p regex)
                  (create-greedy-everything-matcher maximum min-rest next-fn)
                  (greedy-constant-length-closure
                   (char/= #\Newline (schar *string* curr-pos)))))
              (t
                ;; the general case - we build an inner matcher which
                ;; just checks for immediate success, i.e. NEXT-FN is
                ;; #'IDENTITY
                (let ((inner-matcher (create-matcher-aux regex #'identity)))
                  (declare (function inner-matcher))
                  (greedy-constant-length-closure
                   (funcall inner-matcher curr-pos)))))))))

(defgeneric create-greedy-no-zero-matcher (repetition next-fn)
  (declare #.*standard-optimize-settings*)
  (:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is greedy and the minimal number of
repetitions is zero.  It is furthermore assumed that the inner regex
of REPETITION can never match a zero-length string \(or instead the
maximal number of repetitions is 1)."))

(defmethod create-greedy-no-zero-matcher ((repetition repetition) next-fn)
  (declare #.*standard-optimize-settings*)
  (let ((maximum (maximum repetition))
        ;; REPEAT-MATCHER is part of the closure's environment but it
        ;; can only be defined after GREEDY-AUX is defined
        repeat-matcher)
    (declare (function next-fn))
    (cond
      ((eql maximum 1)
        ;; this is essentially like the next case but with a known
        ;; MAXIMUM of 1 we can get away without a counter; note that
        ;; we always arrive here if CONVERT optimizes <regex>* to
        ;; (?:<regex'>*<regex>)?
        (setq repeat-matcher
                (create-matcher-aux (regex repetition) next-fn))
        (lambda (start-pos)
          (declare (function repeat-matcher))
          (or (funcall repeat-matcher start-pos)
              (funcall next-fn start-pos))))
      (maximum
        ;; we make a reservation for our slot in *REPEAT-COUNTERS*
        ;; because we need to keep track whether we've reached MAXIMUM
        ;; repetitions
        (let ((rep-num (incf-after *rep-num*)))
          (flet ((greedy-aux (start-pos)
                   (declare (fixnum start-pos maximum rep-num)
                            (function repeat-matcher))
                   ;; the actual matcher which first tries to match the
                   ;; inner regex of REPETITION (if we haven't done so
                   ;; too often) and on failure calls NEXT-FN
                   (or (and (< (aref *repeat-counters* rep-num) maximum)
                            (incf (aref *repeat-counters* rep-num))
                            ;; note that REPEAT-MATCHER will call
                            ;; GREEDY-AUX again recursively
                            (prog1
                              (funcall repeat-matcher start-pos)
                              (decf (aref *repeat-counters* rep-num))))
                       (funcall next-fn start-pos))))
            ;; create a closure to match the inner regex and to
            ;; implement backtracking via GREEDY-AUX
            (setq repeat-matcher
                    (create-matcher-aux (regex repetition) #'greedy-aux))
            ;; the closure we return is just a thin wrapper around
            ;; GREEDY-AUX to initialize the repetition counter
            (lambda (start-pos)
              (declare (fixnum start-pos))
              (setf (aref *repeat-counters* rep-num) 0)
              (greedy-aux start-pos)))))
      (t
        ;; easier code because we're not bounded by MAXIMUM, but
        ;; basically the same
        (flet ((greedy-aux (start-pos)
                 (declare (fixnum start-pos)
                          (function repeat-matcher))
                 (or (funcall repeat-matcher start-pos)
                     (funcall next-fn start-pos))))
          (setq repeat-matcher
                  (create-matcher-aux (regex repetition) #'greedy-aux))
          #'greedy-aux)))))

(defgeneric create-greedy-matcher (repetition next-fn)
  (declare #.*standard-optimize-settings*)
  (:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is greedy and the minimal number of
repetitions is zero."))

(defmethod create-greedy-matcher ((repetition repetition) next-fn)
  (declare #.*standard-optimize-settings*)
  (let ((maximum (maximum repetition))
        ;; we make a reservation for our slot in *LAST-POS-STORES* because
        ;; we have to watch out for endless loops as the inner regex might
        ;; match zero-length strings
        (zero-length-num (incf-after *zero-length-num*))
        ;; REPEAT-MATCHER is part of the closure's environment but it
        ;; can only be defined after GREEDY-AUX is defined
        repeat-matcher)
    (declare (fixnum zero-length-num)
             (function next-fn))
    (cond
      (maximum
        ;; we make a reservation for our slot in *REPEAT-COUNTERS*
        ;; because we need to keep track whether we've reached MAXIMUM
        ;; repetitions
        (let ((rep-num (incf-after *rep-num*)))
          (flet ((greedy-aux (start-pos)
                   ;; the actual matcher which first tries to match the
                   ;; inner regex of REPETITION (if we haven't done so
                   ;; too often) and on failure calls NEXT-FN
                   (declare (fixnum start-pos maximum rep-num)
                            (function repeat-matcher))
                   (let ((old-last-pos
                           (svref *last-pos-stores* zero-length-num)))
                     (when (and old-last-pos
                                (= (the fixnum old-last-pos) start-pos))
                       ;; stop immediately if we've been here before,
                       ;; i.e. if the last attempt matched a zero-length
                       ;; string
                       (return-from greedy-aux (funcall next-fn start-pos)))
                     ;; otherwise remember this position for the next
                     ;; repetition
                     (setf (svref *last-pos-stores* zero-length-num) start-pos)
                     (or (and (< (aref *repeat-counters* rep-num) maximum)
                              (incf (aref *repeat-counters* rep-num))
                              ;; note that REPEAT-MATCHER will call
                              ;; GREEDY-AUX again recursively
                              (prog1
                                (funcall repeat-matcher start-pos)
                                (decf (aref *repeat-counters* rep-num))
                                (setf (svref *last-pos-stores* zero-length-num)
                                        old-last-pos)))
                         (funcall next-fn start-pos)))))
            ;; create a closure to match the inner regex and to
            ;; implement backtracking via GREEDY-AUX
            (setq repeat-matcher
                    (create-matcher-aux (regex repetition) #'greedy-aux))
            ;; the closure we return is just a thin wrapper around
            ;; GREEDY-AUX to initialize the repetition counter and our
            ;; slot in *LAST-POS-STORES*
            (lambda (start-pos)
              (declare (fixnum start-pos))
              (setf (aref *repeat-counters* rep-num) 0
                    (svref *last-pos-stores* zero-length-num) nil)
              (greedy-aux start-pos)))))
      (t
        ;; easier code because we're not bounded by MAXIMUM, but
        ;; basically the same
        (flet ((greedy-aux (start-pos)
                 (declare (fixnum start-pos)
                          (function repeat-matcher))
                 (let ((old-last-pos
                         (svref *last-pos-stores* zero-length-num)))
                   (when (and old-last-pos
                              (= (the fixnum old-last-pos) start-pos))
                     (return-from greedy-aux (funcall next-fn start-pos)))
                   (setf (svref *last-pos-stores* zero-length-num) start-pos)
                   (or (prog1
                         (funcall repeat-matcher start-pos)
                         (setf (svref *last-pos-stores* zero-length-num) old-last-pos))
                       (funcall next-fn start-pos)))))
          (setq repeat-matcher
                  (create-matcher-aux (regex repetition) #'greedy-aux))
          (lambda (start-pos)
            (declare (fixnum start-pos))
            (setf (svref *last-pos-stores* zero-length-num) nil)
            (greedy-aux start-pos)))))))
  
;; code for non-greedy repetitions with minimum zero

(defmacro non-greedy-constant-length-closure (check-curr-pos)
  "This is the template for simple non-greedy repetitions \(where
simple means that the minimum number of repetitions is zero, that the
inner regex to be checked is of fixed length LEN, and that it doesn't
contain registers, i.e. there's no need for backtracking).
CHECK-CURR-POS is a form which checks whether the inner regex of the
repetition matches at CURR-POS."
  `(if maximum
    (lambda (start-pos)
      (declare (fixnum start-pos maximum))
      ;; because we know LEN we know in advance where to stop at the
      ;; latest; we also take into consideration MIN-REST, i.e. the
      ;; minimal length of the part behind the repetition
      (let ((target-end-pos (min (1+ (- *end-pos* len min-rest))
                                 (+ start-pos
                                    (the fixnum (* len maximum))))))
        ;; move forward by LEN and always try NEXT-FN first, then
        ;; CHECK-CUR-POS
        (loop for curr-pos of-type fixnum from start-pos
                                          below target-end-pos
                                          by len
              thereis (funcall next-fn curr-pos)
              while ,check-curr-pos
              finally (return (funcall next-fn curr-pos)))))
  ;; basically the same code; it's just a bit easier because we're
  ;; not bounded by MAXIMUM
  (lambda (start-pos)
    (declare (fixnum start-pos))
    (let ((target-end-pos (1+ (- *end-pos* len min-rest))))
      (loop for curr-pos of-type fixnum from start-pos
                                        below target-end-pos
                                        by len
            thereis (funcall next-fn curr-pos)
            while ,check-curr-pos
            finally (return (funcall next-fn curr-pos)))))))

(defgeneric create-non-greedy-constant-length-matcher (repetition next-fn)
  (declare #.*standard-optimize-settings*)
  (:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is non-greedy and the minimal number of
repetitions is zero.  It is furthermore assumed that the inner regex
of REPETITION is of fixed length and doesn't contain registers."))

(defmethod create-non-greedy-constant-length-matcher ((repetition repetition) next-fn)
  (declare #.*standard-optimize-settings*)
  (let ((len (len repetition))
        (maximum (maximum repetition))
        (regex (regex repetition))
        (min-rest (min-rest repetition)))
    (declare (fixnum len min-rest)
             (function next-fn))
    (cond ((zerop len)
            ;; inner regex has zero-length, so we can discard it
            ;; completely
            next-fn)
          (t
            ;; now first try to optimize for a couple of common cases
            (typecase regex
              (str
                (let ((str (str regex)))
                  (if (= 1 len)
                    ;; a single character
                    (let ((chr (schar str 0)))
                      (if (case-insensitive-p regex)
                        (non-greedy-constant-length-closure
                         (char-equal chr (schar *string* curr-pos)))
                        (non-greedy-constant-length-closure
                         (char= chr (schar *string* curr-pos)))))
                    ;; a string
                    (if (case-insensitive-p regex)
                      (non-greedy-constant-length-closure
                       (*string*-equal str curr-pos (+ curr-pos len) 0 len))
                      (non-greedy-constant-length-closure
                       (*string*= str curr-pos (+ curr-pos len) 0 len))))))
              (char-class
                ;; a character class
                (insert-char-class-tester (regex (schar *string* curr-pos))
                  (non-greedy-constant-length-closure
                   (char-class-test))))
              (everything
                (if (single-line-p regex)
                  ;; a dot which really can match everything; we rely
                  ;; on the compiler to optimize this away
                  (non-greedy-constant-length-closure
                   t)
                  ;; a dot which has to watch out for #\Newline
                  (non-greedy-constant-length-closure
                   (char/= #\Newline (schar *string* curr-pos)))))
              (t
                ;; the general case - we build an inner matcher which
                ;; just checks for immediate success, i.e. NEXT-FN is
                ;; #'IDENTITY
                (let ((inner-matcher (create-matcher-aux regex #'identity)))
                  (declare (function inner-matcher))
                  (non-greedy-constant-length-closure
                   (funcall inner-matcher curr-pos)))))))))

(defgeneric create-non-greedy-no-zero-matcher (repetition next-fn)
  (declare #.*standard-optimize-settings*)
  (:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is non-greedy and the minimal number of
repetitions is zero.  It is furthermore assumed that the inner regex
of REPETITION can never match a zero-length string \(or instead the
maximal number of repetitions is 1)."))

(defmethod create-non-greedy-no-zero-matcher ((repetition repetition) next-fn)
  (declare #.*standard-optimize-settings*)
  (let ((maximum (maximum repetition))
        ;; REPEAT-MATCHER is part of the closure's environment but it
        ;; can only be defined after NON-GREEDY-AUX is defined
        repeat-matcher)
    (declare (function next-fn))
    (cond
      ((eql maximum 1)
        ;; this is essentially like the next case but with a known
        ;; MAXIMUM of 1 we can get away without a counter
        (setq repeat-matcher
                (create-matcher-aux (regex repetition) next-fn))
        (lambda (start-pos)
          (declare (function repeat-matcher))
          (or (funcall next-fn start-pos)
              (funcall repeat-matcher start-pos))))
      (maximum
        ;; we make a reservation for our slot in *REPEAT-COUNTERS*
        ;; because we need to keep track whether we've reached MAXIMUM
        ;; repetitions
        (let ((rep-num (incf-after *rep-num*)))
          (flet ((non-greedy-aux (start-pos)
                   ;; the actual matcher which first calls NEXT-FN and
                   ;; on failure tries to match the inner regex of
                   ;; REPETITION (if we haven't done so too often)
                   (declare (fixnum start-pos maximum rep-num)
                            (function repeat-matcher))
                   (or (funcall next-fn start-pos)
                       (and (< (aref *repeat-counters* rep-num) maximum)
                            (incf (aref *repeat-counters* rep-num))
                            ;; note that REPEAT-MATCHER will call
                            ;; NON-GREEDY-AUX again recursively
                            (prog1
                              (funcall repeat-matcher start-pos)
                              (decf (aref *repeat-counters* rep-num)))))))
            ;; create a closure to match the inner regex and to
            ;; implement backtracking via NON-GREEDY-AUX
            (setq repeat-matcher
                    (create-matcher-aux (regex repetition) #'non-greedy-aux))
            ;; the closure we return is just a thin wrapper around
            ;; NON-GREEDY-AUX to initialize the repetition counter
            (lambda (start-pos)
              (declare (fixnum start-pos))
              (setf (aref *repeat-counters* rep-num) 0)
              (non-greedy-aux start-pos)))))
      (t
        ;; easier code because we're not bounded by MAXIMUM, but
        ;; basically the same
        (flet ((non-greedy-aux (start-pos)
                 (declare (fixnum start-pos)
                          (function repeat-matcher))
                 (or (funcall next-fn start-pos)
                     (funcall repeat-matcher start-pos))))
          (setq repeat-matcher
                  (create-matcher-aux (regex repetition) #'non-greedy-aux))
          #'non-greedy-aux)))))
  
(defgeneric create-non-greedy-matcher (repetition next-fn)
  (declare #.*standard-optimize-settings*)
  (:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION is non-greedy and the minimal number of
repetitions is zero."))

(defmethod create-non-greedy-matcher ((repetition repetition) next-fn)
  (declare #.*standard-optimize-settings*)
  ;; we make a reservation for our slot in *LAST-POS-STORES* because
  ;; we have to watch out for endless loops as the inner regex might
  ;; match zero-length strings
  (let ((zero-length-num (incf-after *zero-length-num*))
        (maximum (maximum repetition))
        ;; REPEAT-MATCHER is part of the closure's environment but it
        ;; can only be defined after NON-GREEDY-AUX is defined
        repeat-matcher)
    (declare (fixnum zero-length-num)
             (function next-fn))
    (cond
      (maximum
        ;; we make a reservation for our slot in *REPEAT-COUNTERS*
        ;; because we need to keep track whether we've reached MAXIMUM
        ;; repetitions
        (let ((rep-num (incf-after *rep-num*)))
          (flet ((non-greedy-aux (start-pos)
                   ;; the actual matcher which first calls NEXT-FN and
                   ;; on failure tries to match the inner regex of
                   ;; REPETITION (if we haven't done so too often)
                   (declare (fixnum start-pos maximum rep-num)
                            (function repeat-matcher))
                   (let ((old-last-pos
                           (svref *last-pos-stores* zero-length-num)))
                     (when (and old-last-pos
                                (= (the fixnum old-last-pos) start-pos))
                       ;; stop immediately if we've been here before,
                       ;; i.e. if the last attempt matched a zero-length
                       ;; string
                       (return-from non-greedy-aux (funcall next-fn start-pos)))
                     ;; otherwise remember this position for the next
                     ;; repetition
                     (setf (svref *last-pos-stores* zero-length-num) start-pos)
                     (or (funcall next-fn start-pos)
                         (and (< (aref *repeat-counters* rep-num) maximum)
                              (incf (aref *repeat-counters* rep-num))
                              ;; note that REPEAT-MATCHER will call
                              ;; NON-GREEDY-AUX again recursively
                              (prog1
                                (funcall repeat-matcher start-pos)
                                (decf (aref *repeat-counters* rep-num))
                                (setf (svref *last-pos-stores* zero-length-num)
                                        old-last-pos)))))))
            ;; create a closure to match the inner regex and to
            ;; implement backtracking via NON-GREEDY-AUX
            (setq repeat-matcher
                    (create-matcher-aux (regex repetition) #'non-greedy-aux))
            ;; the closure we return is just a thin wrapper around
            ;; NON-GREEDY-AUX to initialize the repetition counter and our
            ;; slot in *LAST-POS-STORES*
            (lambda (start-pos)
              (declare (fixnum start-pos))
              (setf (aref *repeat-counters* rep-num) 0
                    (svref *last-pos-stores* zero-length-num) nil)
              (non-greedy-aux start-pos)))))
      (t
        ;; easier code because we're not bounded by MAXIMUM, but
        ;; basically the same
        (flet ((non-greedy-aux (start-pos)
                 (declare (fixnum start-pos)
                          (function repeat-matcher))
                 (let ((old-last-pos
                         (svref *last-pos-stores* zero-length-num)))
                   (when (and old-last-pos
                              (= (the fixnum old-last-pos) start-pos))
                     (return-from non-greedy-aux (funcall next-fn start-pos)))
                   (setf (svref *last-pos-stores* zero-length-num) start-pos)
                   (or (funcall next-fn start-pos)
                       (prog1
                         (funcall repeat-matcher start-pos)
                         (setf (svref *last-pos-stores* zero-length-num)
                                 old-last-pos))))))
          (setq repeat-matcher
                  (create-matcher-aux (regex repetition) #'non-greedy-aux))
          (lambda (start-pos)
            (declare (fixnum start-pos))
            (setf (svref *last-pos-stores* zero-length-num) nil)
            (non-greedy-aux start-pos)))))))
  
;; code for constant repetitions, i.e. those with a fixed number of repetitions
                      
(defmacro constant-repetition-constant-length-closure (check-curr-pos)
  "This is the template for simple constant repetitions (where simple
means that the inner regex to be checked is of fixed length LEN, and
that it doesn't contain registers, i.e. there's no need for
backtracking) and where constant means that MINIMUM is equal to
MAXIMUM.  CHECK-CURR-POS is a form which checks whether the inner
regex of the repetition matches at CURR-POS."
  `(lambda (start-pos)
    (declare (fixnum start-pos))
      (let ((target-end-pos (+ start-pos
                               (the fixnum (* len repetitions)))))
        (declare (fixnum target-end-pos))
        ;; first check if we won't go beyond the end of the string
        (and (>= *end-pos* target-end-pos)
             ;; then loop through all repetitions step by step
             (loop for curr-pos of-type fixnum from start-pos
                                               below target-end-pos
                                               by len
                   always ,check-curr-pos)
             ;; finally call NEXT-FN if we made it that far
             (funcall next-fn target-end-pos)))))

(defgeneric create-constant-repetition-constant-length-matcher
    (repetition next-fn)
  (declare #.*standard-optimize-settings*)
  (:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION has a constant number of repetitions.
It is furthermore assumed that the inner regex of REPETITION is of
fixed length and doesn't contain registers."))

(defmethod create-constant-repetition-constant-length-matcher
       ((repetition repetition) next-fn)
  (declare #.*standard-optimize-settings*)
  (let ((len (len repetition))
        (repetitions (minimum repetition))
        (regex (regex repetition)))
    (declare (fixnum len repetitions)
             (function next-fn))
    (if (zerop len)
      ;; if the length is zero it suffices to try once
      (create-matcher-aux regex next-fn)
      ;; otherwise try to optimize for a couple of common cases
      (typecase regex
        (str
          (let ((str (str regex)))
            (if (= 1 len)
              ;; a single character
              (let ((chr (schar str 0)))
                (if (case-insensitive-p regex)
                  (constant-repetition-constant-length-closure
                   (and (char-equal chr (schar *string* curr-pos))
                        (1+ curr-pos)))
                  (constant-repetition-constant-length-closure
                   (and (char= chr (schar *string* curr-pos))
                        (1+ curr-pos)))))
              ;; a string
              (if (case-insensitive-p regex)
                (constant-repetition-constant-length-closure
                 (let ((next-pos (+ curr-pos len)))
                   (declare (fixnum next-pos))
                   (and (*string*-equal str curr-pos next-pos 0 len)
                        next-pos)))
                (constant-repetition-constant-length-closure
                 (let ((next-pos (+ curr-pos len)))
                   (declare (fixnum next-pos))
                   (and (*string*= str curr-pos next-pos 0 len)
                        next-pos)))))))
        (char-class
          ;; a character class
          (insert-char-class-tester (regex (schar *string* curr-pos))
            (constant-repetition-constant-length-closure
             (and (char-class-test)
                  (1+ curr-pos)))))
        (everything
          (if (single-line-p regex)
            ;; a dot which really matches everything - we just have to
            ;; advance the index into *STRING* accordingly and check
            ;; if we didn't go past the end
            (lambda (start-pos)
              (declare (fixnum start-pos))
              (let ((next-pos (+ start-pos repetitions)))
                (declare (fixnum next-pos))
                (and (<= next-pos *end-pos*)
                     (funcall next-fn next-pos))))
            ;; a dot which is not in single-line-mode - make sure we
            ;; don't match #\Newline
            (constant-repetition-constant-length-closure
             (and (char/= #\Newline (schar *string* curr-pos))
                  (1+ curr-pos)))))
        (t
          ;; the general case - we build an inner matcher which just
          ;; checks for immediate success, i.e. NEXT-FN is #'IDENTITY
          (let ((inner-matcher (create-matcher-aux regex #'identity)))
            (declare (function inner-matcher))
            (constant-repetition-constant-length-closure
             (funcall inner-matcher curr-pos))))))))
  
(defgeneric create-constant-repetition-matcher (repetition next-fn)
  (declare #.*standard-optimize-settings*)
  (:documentation "Creates a closure which tries to match REPETITION.
It is assumed that REPETITION has a constant number of repetitions."))

(defmethod create-constant-repetition-matcher ((repetition repetition) next-fn)
  (declare #.*standard-optimize-settings*)
  (let ((repetitions (minimum repetition))
        ;; we make a reservation for our slot in *REPEAT-COUNTERS*
        ;; because we need to keep track of the number of repetitions
        (rep-num (incf-after *rep-num*))
        ;; REPEAT-MATCHER is part of the closure's environment but it
        ;; can only be defined after NON-GREEDY-AUX is defined
        repeat-matcher)
    (declare (fixnum repetitions rep-num)
             (function next-fn))
    (if (zerop (min-len repetition))
      ;; we make a reservation for our slot in *LAST-POS-STORES*
      ;; because we have to watch out for needless loops as the inner
      ;; regex might match zero-length strings
      (let ((zero-length-num (incf-after *zero-length-num*)))
        (declare (fixnum zero-length-num))
        (flet ((constant-aux (start-pos)
                 ;; the actual matcher which first calls NEXT-FN and
                 ;; on failure tries to match the inner regex of
                 ;; REPETITION (if we haven't done so too often)
                 (declare (fixnum start-pos)
                          (function repeat-matcher))
                 (let ((old-last-pos
                         (svref *last-pos-stores* zero-length-num)))
                   (when (and old-last-pos
                              (= (the fixnum old-last-pos) start-pos))
                     ;; if we've been here before we matched a
                     ;; zero-length string the last time, so we can
                     ;; just carry on because we will definitely be
                     ;; able to do this again often enough
                     (return-from constant-aux (funcall next-fn start-pos)))
                   ;; otherwise remember this position for the next
                   ;; repetition
                   (setf (svref *last-pos-stores* zero-length-num) start-pos)
                   (cond ((< (aref *repeat-counters* rep-num) repetitions)
                           ;; not enough repetitions yet, try it again
                           (incf (aref *repeat-counters* rep-num))
                           ;; note that REPEAT-MATCHER will call
                           ;; CONSTANT-AUX again recursively
                           (prog1
                             (funcall repeat-matcher start-pos)
                             (decf (aref *repeat-counters* rep-num))
                             (setf (svref *last-pos-stores* zero-length-num)
                                     old-last-pos)))
                         (t
                           ;; we're done - call NEXT-FN
                           (funcall next-fn start-pos))))))
          ;; create a closure to match the inner regex and to
          ;; implement backtracking via CONSTANT-AUX
          (setq repeat-matcher
                  (create-matcher-aux (regex repetition) #'constant-aux))
          ;; the closure we return is just a thin wrapper around
          ;; CONSTANT-AUX to initialize the repetition counter
          (lambda (start-pos)
            (declare (fixnum start-pos))
            (setf (aref *repeat-counters* rep-num) 0
                  (aref *last-pos-stores* zero-length-num) nil)
            (constant-aux start-pos))))
      ;; easier code because we don't have to care about zero-length
      ;; matches but basically the same
      (flet ((constant-aux (start-pos)
               (declare (fixnum start-pos)
                        (function repeat-matcher))
               (cond ((< (aref *repeat-counters* rep-num) repetitions)
                       (incf (aref *repeat-counters* rep-num))
                       (prog1
                         (funcall repeat-matcher start-pos)
                         (decf (aref *repeat-counters* rep-num))))
                     (t (funcall next-fn start-pos)))))
        (setq repeat-matcher
                (create-matcher-aux (regex repetition) #'constant-aux))
        (lambda (start-pos)
          (declare (fixnum start-pos))
          (setf (aref *repeat-counters* rep-num) 0)
          (constant-aux start-pos))))))
  
;; the actual CREATE-MATCHER-AUX method for REPETITION objects which
;; utilizes all the functions and macros defined above

(defmethod create-matcher-aux ((repetition repetition) next-fn)
  (declare #.*standard-optimize-settings*)
  (with-slots (minimum maximum len min-len greedyp contains-register-p)
      repetition
    (cond ((and maximum
                (zerop maximum))
           ;; this should have been optimized away by CONVERT but just
           ;; in case...
           (error "Got REPETITION with MAXIMUM 0 \(should not happen)"))
          ((and maximum
                (= minimum maximum 1))
           ;; this should have been optimized away by CONVERT but just
           ;; in case...
           (error "Got REPETITION with MAXIMUM 1 and MINIMUM 1 \(should not happen)"))
          ((and (eql minimum maximum)
                len
                (not contains-register-p))
           (create-constant-repetition-constant-length-matcher repetition next-fn))
          ((eql minimum maximum)
           (create-constant-repetition-matcher repetition next-fn))
          ((and greedyp
                len
                (not contains-register-p))
           (create-greedy-constant-length-matcher repetition next-fn))
          ((and greedyp
                (or (plusp min-len)
                    (eql maximum 1)))
           (create-greedy-no-zero-matcher repetition next-fn))
          (greedyp
           (create-greedy-matcher repetition next-fn))
          ((and len
                (plusp len)
                (not contains-register-p))
           (create-non-greedy-constant-length-matcher repetition next-fn))
          ((or (plusp min-len)
               (eql maximum 1))
           (create-non-greedy-no-zero-matcher repetition next-fn))
          (t
           (create-non-greedy-matcher repetition next-fn)))))