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
40 ! '[ { array-capacity string } declare _ _ step ] ;
42 : word>quot ( word dfa -- quot )
44 [ final-states>> key? ] 2bi
47 : states>code ( words dfa -- )
51 (( last-match index string -- ? ))
54 ] with-compilation-unit ;
56 : transitions-at ( transitions assoc -- new-transitions )
59 [ [ _ at ] assoc-map ] bi*
62 : states>words ( dfa -- words dfa )
63 dup transitions>> keys [ gensym ] H{ } map>assoc
64 [ [ transitions-at ] rewrite-transitions ]
68 : dfa>word ( dfa -- word )
69 states>words [ states>code ] keep start-state>> ;
71 : run-regexp ( string word -- ? )
72 [ f 0 ] 2dip execute ; inline
74 : dfa>quotation ( dfa -- quot )
75 dfa>word '[ _ run-regexp ] ;
77 TUPLE: quot-matcher quot ;
78 C: <quot-matcher> quot-matcher
80 M: quot-matcher match-index
81 quot>> call( string -- i/f ) ;