1 ! Copyright (C) 2007, 2008 Chris Double, Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel sequences strings namespaces make math assocs
4 vectors arrays math.parser accessors unicode.categories
5 sequences.deep peg peg.private peg.search math.ranges words ;
8 TUPLE: just-parser p1 ;
13 dup remaining>> empty? [ drop f ] unless
18 M: just-parser (compile) ( parser -- quot )
19 p1>> compile-parser just-pattern curry ;
21 : just ( parser -- parser )
22 just-parser boa wrap-peg ;
24 : 1token ( ch -- parser ) 1string token ;
26 : (list-of) ( items separator repeat1? -- parser )
27 >r over 2seq r> [ repeat1 ] [ repeat0 ] if [ concat ] action 2seq
28 [ unclip 1vector swap first append ] action ;
30 : list-of ( items separator -- parser )
33 : list-of-many ( items separator -- parser )
36 : epsilon ( -- parser ) V{ } token ;
38 : any-char ( -- parser ) [ drop t ] satisfy ;
42 : flatten-vectors ( pair -- vector )
43 first2 over push-all ;
47 : exactly-n ( parser n -- parser' )
48 swap <repetition> seq ;
50 : at-most-n ( parser n -- parser' )
55 -rot 1- at-most-n 2choice
58 : at-least-n ( parser n -- parser' )
59 dupd exactly-n swap repeat0 2seq
60 [ flatten-vectors ] action ;
62 : from-m-to-n ( parser m n -- parser' )
63 >r [ exactly-n ] 2keep r> swap - at-most-n 2seq
64 [ flatten-vectors ] action ;
66 : pack ( begin body end -- parser )
67 >r >r hide r> r> hide 3seq [ first ] action ;
69 : surrounded-by ( parser begin end -- parser' )
70 [ token ] bi@ swapd pack ;
72 : 'digit' ( -- parser )
73 [ digit? ] satisfy [ digit> ] action ;
75 : 'integer' ( -- parser )
76 'digit' repeat1 [ 10 digits>integer ] action ;
78 : 'string' ( -- parser )
80 [ CHAR: " = ] satisfy hide ,
81 [ CHAR: " = not ] satisfy repeat0 ,
82 [ CHAR: " = ] satisfy hide ,
83 ] seq* [ first >string ] action ;
85 : (range-pattern) ( pattern -- string )
86 #! Given a range pattern, produce a string containing
87 #! all characters within that range.
90 [ CHAR: - = ] satisfy hide ,
97 : range-pattern ( pattern -- parser )
98 #! 'pattern' is a set of characters describing the
99 #! parser to be produced. Any single character in
100 #! the pattern matches that character. If the pattern
101 #! begins with a ^ then the set is negated (the element
102 #! matches any character not in the set). Any pair of
103 #! characters separated with a dash (-) represents the
104 #! range of characters from the first to the second,
106 dup first CHAR: ^ = [
107 rest (range-pattern) [ member? not ] curry satisfy
109 (range-pattern) [ member? ] curry satisfy