Created
February 12, 2014 05:39
-
-
Save NigelThorne/8950566 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'parslet' | |
class Parslet::Atoms::FixedLength < Parslet::Atoms::Base | |
attr_reader :len, :parslet | |
def initialize(parslet, len, tag=:length) | |
super() | |
raise ArgumentError, | |
"Asking for zero length of a parslet. (#{parslet.inspect} length #{len})" \ | |
if len == 0 | |
@parslet = parslet | |
@len = len | |
@tag = tag | |
@error_msgs = { | |
:lenrep => "Expected #{parslet.inspect} to be #{len} long", | |
:unconsumed => "Extra input after last repetition" | |
} | |
end | |
def try(source, context, consume_all) | |
start_pos = source.pos | |
success, value = parslet.apply(source, context, false) | |
return succ(value) if success && value.str.length == @len | |
context.err_at( | |
self, | |
source, | |
@error_msgs[:lenrep], | |
start_pos, | |
[value]) | |
end | |
precedence REPETITION | |
def to_s_inner(prec) | |
parslet.to_s(prec) + "{len:#{@len}}" | |
end | |
end | |
module Parslet::Atoms::DSL | |
def fixed(len) | |
Parslet::Atoms::FixedLength.new(self, len) | |
end | |
end | |
class MyParser < Parslet::Parser | |
rule(:dollars) { | |
match('[0-9]').repeat(1).as(:dollars) | |
} | |
rule(:comma_separated_dollars) { | |
match('[0-9]').repeat(1, 3).as(:dollars) >> ( match(',') >> match('[0-9]').repeat(3, 3).as(:dollars) ).repeat(1) | |
} | |
rule(:cents) { | |
match('[0-9]').repeat(2, 2).as(:cents) | |
} | |
rule(:currency) { | |
(str('$') >> (comma_separated_dollars | dollars) >> str('.') >> cents).as(:currency) | |
# order is important in (comma_separated_dollars | dollars) | |
} | |
rule(:fixed_str) {str("bob").fixed(4)} | |
rule(:fixed_c) {currency.fixed(4)} | |
end | |
puts MyParser.new.fixed_c.parse("bob").inspect | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment