Created
February 24, 2009 05:17
-
-
Save jolts/69431 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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