]> gitweb.factorcode.org Git - factor.git/blob - basis/regexp/disambiguate/disambiguate.factor
use reject instead of [ ... not ] filter.
[factor.git] / basis / regexp / disambiguate / disambiguate.factor
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
7
8 TUPLE: parts in out ;
9
10 : make-partition ( choices classes -- partition )
11     zip [ first ] partition [ values ] bi@ parts boa ;
12
13 : powerset-partition ( sequence -- partitions )
14     [ length [ 2^ iota ] keep ] keep '[ _ <bits> _ make-partition ] map rest ;
15
16 : partition>class ( parts -- class )
17     [ out>> [ <not-class> ] map ]
18     [ in>> <and-class> ] bi
19     prefix <and-class> ;
20
21 : singleton-partition ( integer non-integers -- {class,partition} )
22     dupd
23     '[ _ [ class-member? ] with filter ] keep
24     prefix f parts boa
25     2array ;
26
27 : add-out ( seq partition -- partition' )
28     [ out>> append ] [ in>> ] bi swap parts boa ;
29
30 : intersection ( seq -- elts )
31     [ f ] [ unclip [ intersect ] reduce ] if-empty ;
32
33 : meaningful-integers ( partition table -- integers )
34     [ [ in>> ] [ out>> ] bi ] dip
35     '[ [ _ at ] map intersection ] bi@ diff ;
36
37 : class-integers ( classes integers -- table )
38     '[ _ over '[ _ class-member? ] filter ] H{ } map>assoc ;
39
40 : add-integers ( partitions classes integers -- partitions )
41     class-integers '[
42         [ _ meaningful-integers ] keep add-out
43     ] map ;
44
45 :: class-partitions ( classes -- assoc )
46     classes [ integer? ] partition :> ( integers classes )
47     
48     classes powerset-partition classes integers add-integers
49     [ [ partition>class ] keep 2array ] map [ first ] filter
50     integers [ classes singleton-partition ] map append ;
51
52 : new-transitions ( transitions -- assoc ) ! assoc is class, partition
53     values [ keys ] gather
54     [ tagged-epsilon? ] reject
55     class-partitions ;
56
57 : get-transitions ( partition state-transitions -- next-states )
58     [ in>> ] dip '[ _ at ] gather sift ;
59
60 : preserving-epsilon ( state-transitions quot -- new-state-transitions )
61     [ [ drop tagged-epsilon? ] assoc-filter ] bi
62     assoc-union H{ } assoc-like ; inline
63
64 : disambiguate ( nfa -- nfa )  
65     expand-ors [
66         dup new-transitions '[
67             [
68                 _ swap '[ _ get-transitions ] assoc-map
69                 [ nip empty? not ] assoc-filter 
70             ] preserving-epsilon
71         ] assoc-map
72     ] change-transitions ;