Skip to content

Instantly share code, notes, and snippets.

@jolts
Created February 24, 2009 05:17
Show Gist options
  • Save jolts/69431 to your computer and use it in GitHub Desktop.
Save jolts/69431 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'logger'
require File.dirname(__FILE__) + '/rules.rb'
class ParseError < RuntimeError; end
class Parser
def initialize
@logger = Logger.new(STDOUT)
@tokenize = Proc.new {|string| string.scan(/\w+/) }
@match_rule = Proc.new do |string|
$rules.each_value {|value| true if string.match(value) }
end
@current_rule = Proc.new do |string|
rules = ''
$rules.select {|key, value| rules = key[0] if string.match(value) }
rules
end
end
def parse(str)
# Returns array where first value is the rule
result = []
# Unless it matches we add the rule to our result along with the tokens
raise ParseError, "unable to lex #{str}" unless @match_rule.call(str)
result << @current_rule.call(str)
tokens = @tokenize.call(str)
tokens.each { |token| result << token }
result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment