]> gitweb.factorcode.org Git - factor.git/blob - basis/regexp/compiler/compiler.factor
Merge branch 'master' into regexp
[factor.git] / basis / regexp / compiler / compiler.factor
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 ;
7 IN: regexp.compiler
8
9 : literals>cases ( literal-transitions -- case-body )
10     [ 1quotation ] assoc-map ;
11
12 : non-literals>dispatch ( non-literal-transitions -- quot )
13     [ [ '[ dup _ class-member? ] ] [ '[ drop _ execute ] ] bi* ] assoc-map
14     [ 3drop ] suffix '[ _ cond ] ;
15
16 : expand-one-or ( or-class transition -- alist )
17     [ seq>> ] dip '[ _ 2array ] map ;
18
19 : expand-or ( alist -- new-alist )
20     [
21         first2 over or-class?
22         [ expand-one-or ] [ 2array 1array ] if
23     ] map concat ;
24
25 : split-literals ( transitions -- case default )
26     >alist expand-or [ first integer? ] partition
27     [ literals>cases ] [ non-literals>dispatch ] bi* ;
28
29 :: step ( last-match index str case-body final? -- last-index/f )
30     final? index last-match ?
31     index str bounds-check? [
32         index 1+ str
33         index str nth-unsafe
34         case-body case
35     ] when ; inline
36
37 : transitions>quot ( transitions final-state? -- quot )
38     [ split-literals suffix ] dip
39     '[ { array-capacity string } declare _ _ step ] ;
40
41 : word>quot ( word dfa -- quot )
42     [ transitions>> at ]
43     [ final-states>> key? ] 2bi
44     transitions>quot ;
45
46 : states>code ( words dfa -- )
47     '[
48         [
49             dup _ word>quot
50             (( last-match index string -- ? ))
51             define-declared
52         ] each
53     ] with-compilation-unit ;
54
55 : transitions-at ( transitions assoc -- new-transitions )
56     dup '[
57         [ _ at ]
58         [ [ _ at ] assoc-map ] bi*
59     ] assoc-map ;
60
61 : states>words ( dfa -- words dfa )
62     dup transitions>> keys [ gensym ] H{ } map>assoc
63     [ [ transitions-at ] rewrite-transitions ]
64     [ values ]
65     bi swap ; 
66
67 : dfa>word ( dfa -- word )
68     states>words [ states>code ] keep start-state>> ;
69
70 : check-string ( string -- string )
71     dup string? [ "String required" throw ] unless ;
72
73 : run-regexp ( start-index string word -- ? )
74     { [ f ] [ >fixnum ] [ check-string ] [ execute ] } spread ; inline
75
76 : dfa>quotation ( dfa -- quot )
77     dfa>word '[ _ run-regexp ] ;
78
79 TUPLE: quot-matcher quot ;
80 C: <quot-matcher> quot-matcher
81
82 M: quot-matcher match-index-from
83     quot>> call( index string -- i/f ) ;