Skip to content

Instantly share code, notes, and snippets.

@mlen
Created October 29, 2014 10:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlen/d90f901352f4d5df97aa to your computer and use it in GitHub Desktop.
Save mlen/d90f901352f4d5df97aa to your computer and use it in GitHub Desktop.
require 'parslet'
module Strings
class Parser < Parslet::Parser
rule(:spaces) { match['\s\n'].repeat }
rule(:eq) { str("=") >> spaces }
rule(:colon) { str(";") >> spaces }
rule(:string) { str('"') >> (str('\\') >> any | str('"').absent? >> any).repeat.as(:internal) >> str('"') >> spaces }
rule(:comment) { str("/*") >> (str("*/").absent? >> any).repeat >> str("*/") >> spaces }
rule(:keyval) { string.as(:key) >> eq >> string.as(:value) >> colon }
rule(:line) { keyval.as(:keyval) | comment.as(:comment) }
rule(:file) { (spaces >> line.repeat).as(:file) }
root(:file)
end
class Transform < Parslet::Transform
rule(internal: simple(:i)) { i.str }
rule(key: subtree(:key)) { key }
rule(value: subtree(:val)) { val }
rule(keyval: subtree(:kv)) { {kv[:key] => kv[:value]} }
rule(comment: simple(:c)) { {} }
rule(file: subtree(:file)) { file.reduce({}) {|a,b| a.merge(b) } }
end
def self.parse(source)
Transform.new.apply(Parser.new.parse(source))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment