1 ! Copyright (C) 2009 Daniel Ehrenberg.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel accessors regexp.classes math.bits assocs sequences
4 arrays sets regexp.dfa math fry regexp.minimize regexp.ast
5 locals regexp.transition-tables ;
6 IN: regexp.disambiguate
10 : make-partition ( choices classes -- partition )
11 zip [ first ] partition [ values ] bi@ parts boa ;
13 : powerset-partition ( sequence -- partitions )
14 [ length [ 2^ iota ] keep ] keep '[ _ <bits> _ make-partition ] map rest ;
16 : partition>class ( parts -- class )
17 [ out>> [ <not-class> ] map ]
18 [ in>> <and-class> ] bi
21 : singleton-partition ( integer non-integers -- {class,partition} )
23 '[ _ [ class-member? ] with filter ] keep
27 : add-out ( seq partition -- partition' )
28 [ out>> append ] [ in>> ] bi swap parts boa ;
30 : intersection ( seq -- elts )
31 [ f ] [ unclip [ intersect ] reduce ] if-empty ;
33 : meaningful-integers ( partition table -- integers )
34 [ [ in>> ] [ out>> ] bi ] dip
35 '[ [ _ at ] map intersection ] bi@ diff ;
37 : class-integers ( classes integers -- table )
38 '[ _ over '[ _ class-member? ] filter ] H{ } map>assoc ;
40 : add-integers ( partitions classes integers -- partitions )
42 [ _ meaningful-integers ] keep add-out
45 :: class-partitions ( classes -- assoc )
46 classes [ integer? ] partition :> ( integers classes )
48 classes powerset-partition classes integers add-integers
49 [ [ partition>class ] keep 2array ] map [ first ] filter
50 integers [ classes singleton-partition ] map append ;
52 : new-transitions ( transitions -- assoc ) ! assoc is class, partition
53 values [ keys ] gather
54 [ tagged-epsilon? ] reject
57 : get-transitions ( partition state-transitions -- next-states )
58 [ in>> ] dip '[ _ at ] gather sift ;
60 : preserving-epsilon ( state-transitions quot -- new-state-transitions )
61 [ [ drop tagged-epsilon? ] assoc-filter ] bi
62 assoc-union H{ } assoc-like ; inline
64 : disambiguate ( nfa -- nfa )
66 dup new-transitions '[
68 _ swap '[ _ get-transitions ] assoc-map
69 [ nip empty? ] assoc-reject
72 ] change-transitions ;