1 ! Copyright (C) 2009 Daniel Ehrenberg.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: regexp.classes kernel sequences regexp.negation
4 quotations regexp.minimize assocs fry math locals combinators
5 accessors words compiler.units kernel.private strings
6 sequences.private arrays regexp.matchers call ;
9 : literals>cases ( literal-transitions -- case-body )
10 [ 1quotation ] assoc-map ;
12 : non-literals>dispatch ( non-literal-transitions -- quot )
13 [ [ '[ dup _ class-member? ] ] [ '[ drop _ execute ] ] bi* ] assoc-map
14 [ 3drop ] suffix '[ _ cond ] ;
16 : expand-one-or ( or-class transition -- alist )
17 [ seq>> ] dip '[ _ 2array ] map ;
19 : expand-or ( alist -- new-alist )
22 [ expand-one-or ] [ 2array 1array ] if
25 : split-literals ( transitions -- case default )
26 >alist expand-or [ first integer? ] partition
27 [ literals>cases ] [ non-literals>dispatch ] bi* ;
29 :: step ( last-match index str case-body final? -- last-index/f )
30 final? index last-match ?
31 index str bounds-check? [
37 : transitions>quot ( transitions final-state? -- quot )
38 [ split-literals suffix ] dip
39 '[ { array-capacity string } declare _ _ step ] ;
41 : word>quot ( word dfa -- quot )
43 [ final-states>> key? ] 2bi
46 : states>code ( words dfa -- )
50 (( last-match index string -- ? ))
53 ] with-compilation-unit ;
55 : transitions-at ( transitions assoc -- new-transitions )
58 [ [ _ at ] assoc-map ] bi*
61 : states>words ( dfa -- words dfa )
62 dup transitions>> keys [ gensym ] H{ } map>assoc
63 [ [ transitions-at ] rewrite-transitions ]
67 : dfa>word ( dfa -- word )
68 states>words [ states>code ] keep start-state>> ;
70 : check-string ( string -- string )
71 dup string? [ "String required" throw ] unless ;
73 : run-regexp ( start-index string word -- ? )
74 { [ f ] [ >fixnum ] [ check-string ] [ execute ] } spread ; inline
76 : dfa>quotation ( dfa -- quot )
77 dfa>word '[ _ run-regexp ] ;
79 TUPLE: quot-matcher quot ;
80 C: <quot-matcher> quot-matcher
82 M: quot-matcher match-index-from
83 quot>> call( index string -- i/f ) ;