1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors combinators kernel math sequences strings sets
4 assocs prettyprint.backend prettyprint.custom make lexer
5 namespaces parser arrays fry locals regexp.minimize
6 regexp.parser regexp.nfa regexp.dfa regexp.traversal
7 regexp.transition-tables splitting sorting regexp.ast
11 TUPLE: regexp raw parse-tree options dfa ;
13 : <optioned-regexp> ( string options -- regexp )
14 [ dup parse-regexp ] [ string>options ] bi*
15 2dup <with-options> ast>dfa
18 : <regexp> ( string -- regexp ) "" <optioned-regexp> ;
22 : (match) ( string regexp -- dfa-traverser )
23 dfa>> <dfa-traverser> do-match ; inline
27 : match ( string regexp -- slice/f )
28 (match) return-match ;
30 : matches? ( string regexp -- ? )
32 [ [ length ] bi@ = ] [ drop f ] if* ;
34 : match-head ( string regexp -- end/f ) match [ length ] [ f ] if* ;
36 : match-at ( string m regexp -- n/f finished? )
38 2dup swap length > [ 2drop f f ] [ tail-slice t ] if
39 ] dip swap [ match-head f ] [ 2drop f t ] if ;
41 : match-range ( string m regexp -- a/f b/f )
43 drop nip rot drop dupd +
45 [ 3drop drop f f ] [ drop [ 1+ ] dip match-range ] if
48 : first-match ( string regexp -- slice/f )
49 dupd 0 swap match-range rot over [ <slice> ] [ 3drop f ] if ;
51 : re-cut ( string regexp -- end/f start )
53 [ split1-slice swap ] [ "" like f swap ] if* ;
57 : (re-split) ( string regexp -- )
58 over [ [ re-cut , ] keep (re-split) ] [ 2drop ] if ;
62 : re-split ( string regexp -- seq )
63 [ (re-split) ] { } make ;
65 : re-replace ( string regexp replacement -- result )
66 [ re-split ] dip join ;
68 : next-match ( string regexp -- end/f match/f )
70 [ [ split1-slice nip ] keep ] [ 2drop f f ] if ;
72 : all-matches ( string regexp -- seq )
73 [ dup ] swap '[ _ next-match ] [ ] produce nip harvest ;
75 : count-matches ( string regexp -- n )
80 : find-regexp-syntax ( string -- prefix suffix )
93 } swap [ subseq? not nip ] curry assoc-find drop ;
95 : parsing-regexp ( accum end -- accum )
96 lexer get dup skip-blank
97 [ [ index-from dup 1+ swap ] 2keep swapd subseq swap ] change-lexer-column
98 lexer get dup still-parsing-line?
99 [ (parse-token) ] [ drop f ] if
100 <optioned-regexp> parsed ;
104 : R! CHAR: ! parsing-regexp ; parsing
105 : R" CHAR: " parsing-regexp ; parsing
106 : R# CHAR: # parsing-regexp ; parsing
107 : R' CHAR: ' parsing-regexp ; parsing
108 : R( CHAR: ) parsing-regexp ; parsing
109 : R/ CHAR: / parsing-regexp ; parsing
110 : R@ CHAR: @ parsing-regexp ; parsing
111 : R[ CHAR: ] parsing-regexp ; parsing
112 : R` CHAR: ` parsing-regexp ; parsing
113 : R{ CHAR: } parsing-regexp ; parsing
114 : R| CHAR: | parsing-regexp ; parsing
119 [ raw>> dup find-regexp-syntax swap % swap % % ]
120 [ options>> options>string % ] bi
122 ] keep present-text ;