Skip to content

Instantly share code, notes, and snippets.

@rramsden
Created January 17, 2011 04:53
Show Gist options
  • Save rramsden/782511 to your computer and use it in GitHub Desktop.
Save rramsden/782511 to your computer and use it in GitHub Desktop.
require 'yaml'
require 'parslet'
module Prolog
include Parslet
rule(:collection) { statement.repeat.as(:collection) }
rule(:statement) { ((headed|headless) >> str('.') >> newline?).as(:statement) }
rule(:headed) { (structure >> space? >> str(':-') >> space? >> conjunction).as(:headed) }
rule(:headless) { structure.as(:headless) }
rule(:conjunction) { (structure >> divider).repeat >> structure | structure }
rule(:parameter_list) { (term >> divider).repeat >> term | term }
rule(:term) { atom | variable | structure }
rule(:variable) { match('[A-Z_]') >> match('[a-z0-9A-Z_]').repeat }
rule(:atom) { match('[a-z]') >> match('[a-zA-Z0-9_]').repeat }
rule(:structure) { atom.as(:functor) >> str('(') >> parameter_list.as(:params) >> str(')') }
# helper rules
rule(:divider) { space? >> str(',') >> space? }
rule(:newline?) { (str("\n") | str("\r\n") | str("\r")).maybe }
rule(:space) { str(' ').repeat(1) }
rule(:space?) { space.maybe }
end
class Parser
include Prolog
def initialize(str)
puts collection.parse(str).to_yaml
end
end
contents = File.open(ARGV[0]).read()
Parser.new(contents)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment