aniero / tire_swing

Simple node and visitor definitions for Treetop grammars

This URL has Read+Write access

aniero (author)
Fri Dec 05 18:03:15 -0800 2008
commit  4a72d7893ea9d631aba75a97a80d8e87d9896eb4
tree    5f5e2cba1ca51a1c6580633fd9f2772cbd6c3d03
parent  9debea61f0275d6fc7c6f90f01e7737bfb538a96
tire_swing / lib / tire_swing / parser_extension.rb
2c7cc490 » aniero 2008-08-10 Added parser extension to m... 1 module TireSwing
2
3 module ParserExtension
4
5 def ast(io)
6 parser = new
7 result = parser.parse(io)
8 if result
9 result.build
10 else
d973c291 » aniero 2008-11-17 Updated error handling to i... 11 raise ParseError.new(
12 [
13 parser.failure_reason,
14 parser.input.split("\n")[parser.failure_line-1],
15 " " * parser.failure_index + "^"
16 ].join("\n"),
17 parser
18 )
2c7cc490 » aniero 2008-08-10 Added parser extension to m... 19 end
20 end
21
22 end
23
24 # Extends the treetop-provided grammar parser with a .ast class method for simple parsing and building of
25 # an AST defined by TireSwing. Takes the grammar module as an argument.
26 #
66662475 » aniero 2008-08-11 Replaced #create_node helpe... 27 # Additionally, this defines a #node method on the grammar to delegate to the class or the AST to create
28 # new nodes, e.g. <node(:variable)> instead of <AST.create_node(:variable)>
5eb8e937 » aniero 2008-08-10 Updated some of the example... 29 #
30 # You can specify an alternate module which contains the AST if desired.
2c7cc490 » aniero 2008-08-10 Added parser extension to m... 31 def self.parses_grammar(grammar, ast=nil)
4338421e » aniero 2008-12-05 activesupport "compatibilit... 32 # use either extlib or activesupport, if that's loaded instead
33 parser = grammar.to_s + "Parser"
34 parser = if defined?(Extlib::Inflection)
4a72d789 » aniero 2008-12-05 Fixing a method parameter I... Comment 35 Extlib::Inflection.constantize(parser)
4338421e » aniero 2008-12-05 activesupport "compatibilit... 36 else
37 parser.constantize
38 end
2c7cc490 » aniero 2008-08-10 Added parser extension to m... 39 ast ||= grammar
40 parser.module_eval do
41 extend ParserExtension
66662475 » aniero 2008-08-11 Replaced #create_node helpe... 42 define_method(:node) { |*args| ast.create_node(*args) }
2c7cc490 » aniero 2008-08-10 Added parser extension to m... 43 end
44 end
45
46 end