-
Notifications
You must be signed in to change notification settings - Fork 11
Make your own parser
Nick Nicholas edited this page Jul 3, 2017
·
2 revisions
New operators and functions are defined in terms of _parse
and ctx
. _parse
is the internal counterpart to .parse
.
ctx
is a Rsec::ParseContext
instance, which is derived from StringScanner
. Any methods of StringScanner
is available for ctx
.
Example
This parser accepts any character (by advancing the StringScanner
position), and returns a random number:
class RandomParser
include Rsec
def _parse ctx
ctx.pos += 1
rand
end
end
p = RandomParser.new
p.parse '5' #=> a random number
Wait! Why bother? Feel the wrath of combinators!
p = /./.r.map { rand }
The parser is defined as a regex matching a single character (/./
), converted into an Rsec token (.r
); its result (map
) is given as a random number (rand
).