Convert parser-combinators.replace to pegs

db4
Chris Double 2007-12-20 17:06:21 +13:00
parent 42e20874fe
commit 6bd283ffa3
3 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,43 @@
! Copyright (C) 2006 Chris Double.
! See http://factorcode.org/license.txt for BSD license.
USING: help.syntax help.markup peg peg.replace ;
HELP: tree-write
{ $values
{ "object" "an object" } }
{ $description
"Write the object to the standard output stream, unless "
"it is an array, in which case recurse through the array "
"writing each object to the stream." }
{ $example "{ 65 \"bc\" { 68 \"ef\" } } tree-write" "AbcDef" } ;
HELP: search
{ $values
{ "string" "a string" }
{ "parser" "a peg based parser" }
{ "seq" "a sequence" }
}
{ $description
"Returns a sequence containing the parse results of all substrings "
"from the input string that successfully parse using the "
"parser."
}
{ $example "\"one 123 two 456\" 'integer' search" "V{ 123 456 }" }
{ $example "\"one 123 \\\"hello\\\" two 456\" 'integer' 'string' 2array choice search" "V{ 123 \"hello\" 456 }" }
{ $see-also replace } ;
HELP: replace
{ $values
{ "string" "a string" }
{ "parser" "a peg based parser" }
{ "result" "a string" }
}
{ $description
"Returns a copy of the original string but with all substrings that "
"successfully parse with the given parser replaced with "
"the result of that parser."
}
{ $example "\"one 123 two 456\" 'integer' [ 2 * number>string ] action replace" "\"one 246 two 912\"" }
{ $see-also search } ;

View File

@ -0,0 +1,18 @@
! Copyright (C) 2007 Chris Double.
! See http://factorcode.org/license.txt for BSD license.
!
USING: kernel math math.parser arrays tools.test peg peg.replace ;
IN: temporary
{ V{ 123 456 } } [
"abc 123 def 456" 'integer' search
] unit-test
{ V{ 123 "hello" 456 } } [
"one 123 \"hello\" two 456" 'integer' 'string' 2array choice search
] unit-test
{ "abc 246 def 912" } [
"abc 123 def 456" 'integer' [ 2 * number>string ] action replace
] unit-test

View File

@ -0,0 +1,32 @@
! Copyright (C) 2006 Chris Double.
! See http://factorcode.org/license.txt for BSD license.
USING: kernel math io io.streams.string sequences strings
combinators peg memoize arrays ;
IN: peg.replace
: tree-write ( object -- )
{
{ [ dup number? ] [ write1 ] }
{ [ dup string? ] [ write ] }
{ [ dup sequence? ] [ [ tree-write ] each ] }
{ [ t ] [ write ] }
} cond ;
MEMO: any-char-parser ( -- parser )
[ drop t ] satisfy ;
: search ( string parser -- seq )
any-char-parser [ drop f ] action 2array choice repeat0 parse dup [
parse-result-ast [ ] subset
] [
drop { }
] if ;
: (replace) ( string parser -- seq )
any-char-parser 2array choice repeat0 parse parse-result-ast [ ] subset ;
: replace ( string parser -- result )
[ (replace) [ tree-write ] each ] string-out ;