Skip to content

Instantly share code, notes, and snippets.

@NigelThorne
Last active August 29, 2015 13:57
Show Gist options
  • Save NigelThorne/9425445 to your computer and use it in GitHub Desktop.
Save NigelThorne/9425445 to your computer and use it in GitHub Desktop.
Parslet example of transforms with default values
require 'pp'
require 'parslet'
module Example # as in 'lots of insipid and stupid parenthesis'
class Parser < Parslet::Parser
rule(:ws) { match('[\s]').repeat(1) }
rule(:ws?) { ws.maybe }
rule(:number) { match('[0-9]').repeat(1) }
rule(:offset) { ws? >> str("[") >> number.as(:offset) >> str("]") }
rule(:format_code) { ws? >> str("d").as(:code) >> ws? }
rule(:format) { (offset.maybe >> format_code).as(:format) }
root(:format)
end
class Transform < Parslet::Transform
rule(:code => simple(:x)) { {:o=>"0", :c=>x} }
rule(:offset=> simple(:o),:code => simple(:c)) { {:o=>o,:c=>c} }
end
end
parser = Example::Parser.new
transform = Example::Transform.new
[
" d",
" [2] d ",
" [3] d "].each do |pexp|
begin
result = parser.parse(pexp)
puts result.inspect
puts "String: \"#{pexp}\" Result: #{result.inspect} Transformed: #{transform.apply(result)}"
rescue Parslet::ParseFailed => m
puts "String: \"#{pexp}\" Error: #{m}"
end
puts
end
require 'pp'
require 'parslet'
module Example # as in 'lots of insipid and stupid parenthesis'
class Parser < Parslet::Parser
rule(:ws) { match('[\s]').repeat(1) }
rule(:ws?) { ws.maybe }
rule(:number) { match('[0-9]').repeat(1).as(:number) }
rule(:offset) { (ws? >> str("[") >> number >> str("]")) }
rule(:format_code) { ws? >> str("d").as(:code) >> ws? }
rule(:format) { (offset.maybe.as(:offset_val).as(:offset) >> format_code).as(:format) }
root(:format)
end
class Transform < Parslet::Transform
rule({:number => simple(:i)}) { i.to_i }
rule({:offset_val => simple(:v)}) { v || 5 }
rule(:format=>{:offset=>simple(:o), :code=>simple(:c)}) { "Format #{c.to_s*o}" }
end
end
parser = Example::Parser.new
transform = Example::Transform.new
[ " d",
" [2] d ",
" [3] d ",
].each do |pexp|
begin
result = parser.parse(pexp)
puts result.inspect
puts "String: \"#{pexp}\" \n Result: #{result.inspect}\n Transformed: #{transform.apply(result)}"
rescue Parslet::ParseFailed => m
puts "String: \"#{pexp}\" Error: #{m}"
end
puts
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment