1 ! Copyright (C) 2007, 2008 Chris Double, Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors kernel make math math.parser math.ranges peg
4 peg.private peg.search sequences strings unicode vectors ;
7 TUPLE: just-parser p1 ;
9 CONSTANT: just-pattern [
11 dup remaining>> empty? [ drop f ] unless
15 M: just-parser (compile) ( parser -- quot )
16 p1>> compile-parser-quot just-pattern compose ;
18 : just ( parser -- parser )
19 just-parser boa wrap-peg ;
21 : 1token ( ch -- parser ) 1string token ;
23 : (list-of) ( items separator repeat1? -- parser )
24 [ over 2seq ] dip [ repeat1 ] [ repeat0 ] if
25 [ concat ] action 2seq
26 [ unclip 1vector swap first append ] action ;
28 : list-of ( items separator -- parser )
31 : list-of-many ( items separator -- parser )
34 : epsilon ( -- parser ) V{ } token ;
36 : any-char ( -- parser ) [ drop t ] satisfy ;
40 : flatten-vectors ( pair -- vector )
45 : exactly-n ( parser n -- parser' )
46 swap <repetition> seq ;
48 : at-most-n ( parser n -- parser' )
52 [ exactly-n ] [ 1 - at-most-n ] 2bi 2choice
55 : at-least-n ( parser n -- parser' )
56 dupd exactly-n swap repeat0 2seq
57 [ flatten-vectors ] action ;
59 : from-m-to-n ( parser m n -- parser' )
60 [ [ exactly-n ] 2keep ] dip swap - at-most-n 2seq
61 [ flatten-vectors ] action ;
63 : pack ( begin body end -- parser )
64 [ hide ] [ ] [ hide ] tri* 3seq [ first ] action ;
66 : surrounded-by ( parser begin end -- parser' )
67 [ token ] bi@ swapd pack ;
69 : digit-parser ( -- parser )
70 [ digit? ] satisfy [ digit> ] action ;
72 : integer-parser ( -- parser )
73 [ digit? ] satisfy repeat1 [ string>number ] action ;
75 : string-parser ( -- parser )
77 [ CHAR: " = ] satisfy hide ,
78 [ CHAR: " = not ] satisfy repeat0 ,
79 [ CHAR: " = ] satisfy hide ,
80 ] seq* [ first >string ] action ;
82 : (range-pattern) ( pattern -- string )
83 ! Given a range pattern, produce a string containing
84 ! all characters within that range.
87 [ CHAR: - = ] satisfy hide ,
94 : range-pattern ( pattern -- parser )
95 ! 'pattern' is a set of characters describing the
96 ! parser to be produced. Any single character in
97 ! the pattern matches that character. If the pattern
98 ! begins with a ^ then the set is negated (the element
99 ! matches any character not in the set). Any pair of
100 ! characters separated with a dash (-) represents the
101 ! range of characters from the first to the second,
103 dup first CHAR: ^ = [
104 rest (range-pattern) [ member? not ] curry satisfy
106 (range-pattern) [ member? ] curry satisfy