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 ;
10 CONSTANT: just-pattern [
12 dup remaining>> empty? [ drop f ] unless
16 M: just-parser (compile) ( parser -- quot )
17 p1>> compile-parser-quot just-pattern compose ;
19 : just ( parser -- parser )
20 just-parser boa wrap-peg ;
22 : 1token ( ch -- parser ) 1string token ;
24 : (list-of) ( items separator repeat1? -- parser )
25 [ over 2seq ] dip [ repeat1 ] [ repeat0 ] if
26 [ concat ] action 2seq
27 [ unclip 1vector swap first append ] action ;
29 : list-of ( items separator -- parser )
32 : list-of-many ( items separator -- parser )
35 : epsilon ( -- parser ) V{ } token ;
37 : any-char ( -- parser ) [ drop t ] satisfy ;
41 : flatten-vectors ( pair -- vector )
46 : exactly-n ( parser n -- parser' )
47 swap <repetition> seq ;
49 : at-most-n ( parser n -- parser' )
53 [ exactly-n ] [ 1 - at-most-n ] 2bi 2choice
56 : at-least-n ( parser n -- parser' )
57 dupd exactly-n swap repeat0 2seq
58 [ flatten-vectors ] action ;
60 : from-m-to-n ( parser m n -- parser' )
61 [ [ exactly-n ] 2keep ] dip swap - at-most-n 2seq
62 [ flatten-vectors ] action ;
64 : pack ( begin body end -- parser )
65 [ hide ] [ ] [ hide ] tri* 3seq [ first ] action ;
67 : surrounded-by ( parser begin end -- parser' )
68 [ token ] bi@ swapd pack ;
70 : digit-parser ( -- parser )
71 [ digit? ] satisfy [ digit> ] action ;
73 : integer-parser ( -- parser )
74 [ digit? ] satisfy repeat1 [ string>number ] action ;
76 : string-parser ( -- parser )
78 [ CHAR: " = ] satisfy hide ,
79 [ CHAR: " = not ] satisfy repeat0 ,
80 [ CHAR: " = ] satisfy hide ,
81 ] seq* [ first >string ] action ;
83 : (range-pattern) ( pattern -- string )
84 ! Given a range pattern, produce a string containing
85 ! all characters within that range.
88 [ CHAR: - = ] satisfy hide ,
95 : range-pattern ( pattern -- parser )
96 ! 'pattern' is a set of characters describing the
97 ! parser to be produced. Any single character in
98 ! the pattern matches that character. If the pattern
99 ! begins with a ^ then the set is negated (the element
100 ! matches any character not in the set). Any pair of
101 ! characters separated with a dash (-) represents the
102 ! range of characters from the first to the second,
104 dup first CHAR: ^ = [
105 rest (range-pattern) [ member? not ] curry satisfy
107 (range-pattern) [ member? ] curry satisfy