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 : condition>quot ( condition -- quot )
14 [ question>> ] [ yes>> ] [ no>> ] tri
15 [ condition>quot ] bi@
16 '[ dup _ class-member? _ _ if ]
18 [ [ 3drop ] ] [ '[ drop _ execute ] ] if-empty
21 : non-literals>dispatch ( non-literal-transitions -- quot )
22 table>condition condition>quot ;
24 : expand-one-or ( or-class transition -- alist )
25 [ seq>> ] dip '[ _ 2array ] map ;
27 : expand-or ( alist -- new-alist )
30 [ expand-one-or ] [ 2array 1array ] if
33 : split-literals ( transitions -- case default )
34 >alist expand-or [ first integer? ] partition
35 [ literals>cases ] [ non-literals>dispatch ] bi* ;
37 :: step ( last-match index str case-body final? -- last-index/f )
38 final? index last-match ?
39 index str bounds-check? [
45 : transitions>quot ( transitions final-state? -- quot )
46 [ split-literals suffix ] dip
47 '[ { array-capacity sequence } declare _ _ step ] ;
49 : word>quot ( word dfa -- quot )
51 [ final-states>> key? ] 2bi
54 : states>code ( words dfa -- )
58 (( last-match index string -- ? ))
61 ] with-compilation-unit ;
63 : transitions-at ( transitions assoc -- new-transitions )
66 [ [ _ at ] assoc-map ] bi*
69 : states>words ( dfa -- words dfa )
70 dup transitions>> keys [ gensym ] H{ } map>assoc
71 [ [ transitions-at ] rewrite-transitions ]
75 : dfa>word ( dfa -- word )
76 states>words [ states>code ] keep start-state>> ;
78 : check-sequence ( string -- string )
79 ! Make this configurable
80 dup sequence? [ "String required" throw ] unless ;
82 : run-regexp ( start-index string word -- ? )
83 { [ f ] [ >fixnum ] [ check-sequence ] [ execute ] } spread ; inline
85 : dfa>quotation ( dfa -- quot )
86 dfa>word '[ _ run-regexp ] ;
88 TUPLE: quot-matcher quot ;
89 C: <quot-matcher> quot-matcher
91 M: quot-matcher match-index-from
92 quot>> call( index string -- i/f ) ;