From: Robert Feldt Date: 2003-09-24T07:34:07+09:00 Subject: Re: Is Rockit abandoned? > I guess what I'm looking for is something like: > > * here is a source file we must parse where regular expressions would be > too big a pain (or impossible) > * here is a grammar > * here is a parser > * here's how it all works together > Would examples like this be helpful: # Rockit Tutorial example number X # # NOTE that the API and behavior below is not fixed but the current # design/view of how Rockit 0.6 will work. # # We want to parse brace-delimited balanced string literals like: input_example = "%{1{2}3}" # which should return the parsed string "1{2}3". # This is hard to do with regexps (although I'm sure there is some # special notation added that makes it possible!). # In Rockit we can write a grammar for this like: require 'rockit' g = < '%{' CurlyInner '}'. StringLiteral[inner] CurlyInner = Balanced* Balanced = '{' Balanced* '}' | /[^{}]/ EOG grammar = Rockit::Grammar.new g # generate a parser class from the grammar parser_class = grammar.generate_parser_class # instantiate a parser parser = parser_class.new # then parse p parser.parse(input_example) # => StringLiteral['1{2}3'] # Note that Rockit by default builds an Abstract Syntax Tree (AST) # for you by creating and calling an AstBuilder. If you want to # change how the AST is built or even not build an AST you can define # your own builder: class MyBuilder < parser_class.default_builder_class # Name of method is lower_case version of the AST name specified # in the grammar above. def string_literal(inner) inner end end # now specify that your builder should be used by a parser parser2 = parser_class.new MyBuilder.new p parser2.parse(input_example) # => '1{2}3' ? /Robert