Dynamic Literal

27 views
Skip to first unread message

mil...@gmail.com

unread,
Nov 19, 2012, 1:41:52 PM11/19/12
to modgr...@googlegroups.com
Hello,
I have some grammar objects but I need to replace a section of the grammar with different literal strings at parse time. What is the best way to do this?

Alex Stewart

unread,
Dec 14, 2012, 1:38:26 PM12/14/12
to modgr...@googlegroups.com, mil...@gmail.com
Hey, there..  Sorry about the late reply..

I'm not quite sure exactly what you mean by "replace a section of the grammar"..  If you mean that you want to define a grammar where you can replace portions of it with different grammars when you call it at different times, it happens there is a (currently not well documented but present) feature which can do this.  If you use the "REF" construct in your grammar, like so:

class Foo (Grammar):
  grammar = (SomeGrammar, REF('Bar'), SomeOtherGrammar)

then when you call the parse function, you can use the "data" argument to pass a grammar class to use for "Bar" when the parser encounters the REF:

  parser = Foo.parser()
  parser.parse_string('some text', data={'Bar': MyBarGrammar})

For simple cases (such as just changing a literal), you can create the grammar on the fly, like so:

  parser.parse_string('some text', data={'Bar': L('mybarliteral')})

(you can also specify a default to use when defining the "REF", etc.. see http://packages.python.org/modgrammar/libref.html#references)

If you mean you want the parse result to appear as though it matched something different than it actually did, this generally isn't recommended (it usually means you should be interpreting the results using class inheritance/tags/etc instead of looking at the matched text), but it is possible.  You can define your grammar class so that it overrides the "string" attribute on its instances, like so:

class Foo (Grammar):
  grammar = (...)

  def elem_init(self, sessiondata):
    self.string = "foostring"

--Alex
Reply all
Reply to author
Forward
0 new messages