Skip to content

Instantly share code, notes, and snippets.

@d11wtq
Created November 30, 2011 07:13
Show Gist options
  • Save d11wtq/1408322 to your computer and use it in GitHub Desktop.
Save d11wtq/1408322 to your computer and use it in GitHub Desktop.
require 'whittle'
class Parser < Whittle::Parser
class StringParser < Whittle::Parser
rule('"')
rule(:esc => /\\./).as { |esc| eval('"' + esc + '"') }
rule(:chars => /[^\\"]+/)
rule(:body) do |r|
r[:body, :esc].as { |body, esc| body << esc }
r[:body, :chars].as { |body, chars| body << chars }
r[:esc]
r[:chars]
end
rule(:string) do |r|
r['"', :body, '"'].as { |_, body, _| body }
end
start(:string)
end
rule(:wsp => /\s+/).skip!
rule("(")
rule(")")
rule(",")
rule(:identifier => /[a-zA-Z_][a-zA-Z0-9_]*/)
rule(:string => /"(\\.|[^"\\]+)*"/).as { |str| StringParser.new.parse(str) }
rule(:expr) do |r|
r[:invocation]
r[:string]
end
rule(:args) do |r|
r[:args, ",", :expr].as { |args, _, expr| args << expr }
r[:expr].as { |expr| [expr] }
end
rule(:invocation) do |r|
r[:identifier, "(", :args, ")"].as { |id, _, args, _| { :invocation => id, :args => args } }
end
start(:expr)
end
require 'pp'
pp Parser.new.parse('foo(" string with some spaces and \\" an escape \\\\ here")')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment