1 ! Copyright (C) 2007, 2008 Chris Double, Doug Coleman.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors fry kernel literals make math math.parser
4 ranges peg peg.private peg.search sequences splitting strings
10 TUPLE: just-parser p1 ;
12 M: just-parser parser-quot
13 p1>> execute-parser-quot [
15 dup remaining>> empty? [ drop f ] unless
21 : just ( parser -- parser )
22 just-parser boa wrap-peg ;
24 : 1token ( ch -- parser ) 1string token ;
26 : (list-of) ( items separator repeat1? -- parser )
27 [ over 2seq ] dip [ repeat1 ] [ repeat0 ] if
28 [ concat ] action 2seq
29 [ unclip 1vector swap first append ] action ;
31 : list-of ( items separator -- parser )
34 : list-of-many ( items separator -- parser )
37 CONSTANT: epsilon $[ V{ } token ]
39 CONSTANT: any-char $[ [ drop t ] satisfy ]
43 : flatten-vectors ( pair -- vector )
48 : exactly-n ( parser n -- parser' )
49 swap <repetition> seq ;
51 : at-most-n ( parser n -- parser' )
55 [ exactly-n ] [ 1 - at-most-n ] 2bi 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 [ [ exactly-n ] 2keep ] dip swap - at-most-n 2seq
64 [ flatten-vectors ] action ;
66 : pack ( begin body end -- parser )
67 [ hide ] [ ] [ hide ] tri* 3seq [ first ] action ;
69 : surrounded-by ( parser begin end -- parser' )
70 [ token ] bi@ swapd pack ;
72 : digit-parser ( -- parser )
73 [ digit? ] satisfy [ digit> ] action ;
75 : integer-parser ( -- parser )
76 [ digit? ] satisfy repeat1 [ string>number ] action ;
78 : string-parser ( -- 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 ,
94 ] action peg-replace ;
96 : range-pattern ( pattern -- parser )
97 ! 'pattern' is a set of characters describing the
98 ! parser to be produced. Any single character in
99 ! the pattern matches that character. If the pattern
100 ! begins with a ^ then the set is negated (the element
101 ! matches any character not in the set). Any pair of
102 ! characters separated with a dash (-) represents the
103 ! range of characters from the first to the second,
106 (range-pattern) dup length 1 =
107 [ first '[ _ = ] ] [ '[ _ member? ] ] if
109 [ [ not ] compose ] when satisfy