Skip to content

Commit

Permalink
Add Treetop.load_string which loads a grammar description stored in s…
Browse files Browse the repository at this point in the history
…tring.

Refactor Treetop.load and replace ruby_source with ruby_source_string which compiles
a source stored in string.
  • Loading branch information
hagabaka committed May 25, 2008
1 parent 436225c commit 06ee20f
Showing 1 changed file with 17 additions and 10 deletions.
27 changes: 17 additions & 10 deletions lib/treetop/compiler/grammar_compiler.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,30 @@ def compile(source_path, target_path = source_path.gsub(/\.(treetop|tt)\Z/, '.rb
target_file.write(ruby_source(source_path))
end
end

def ruby_source(source_path)
File.open(source_path) do |source_file|
parser = MetagrammarParser.new
result = parser.parse(source_file.read)
unless result
raise RuntimeError.new(parser.failure_reason)
end
result.compile

# compile a string containing treetop source
def ruby_source_string(s)
parser = MetagrammarParser.new
result = parser.parse(s)
unless result
raise RuntimeError.new(parser.failure_reason)
end
result.compile
end
end
end

# compile a treetop source file and load it
def self.load(path)
adjusted_path = path =~ /\.(treetop|tt)\Z/ ? path : path + '.treetop'
File.open(adjusted_path) do |source_file|
load_string(source_file.read)
end
end

# compile a treetop source string and load it
def self.load_string(s)
compiler = Treetop::Compiler::GrammarCompiler.new
Object.class_eval(compiler.ruby_source(adjusted_path))
Object.class_eval(compiler.ruby_source_string(s))
end
end

0 comments on commit 06ee20f

Please sign in to comment.