- orphan:
Translation#
Translation is one of the most common tasks in language processing. 竜 TatSu doesn’t impose a way to create translators, but it dose expose the functionality it uses to generate Python source code from grammars.
Print Translation#
Translation in 竜 TatSu is based on subclasses of NodeWalker. Print-based translation
relies on classes that inherit from IndentPrintMixin, a strategy copied from
the new PEG parser in Python (see PEP 617).
IndentPrintMixin provides an indent() method, which is a context manager,
and should be used thus:
class MyTranslationWalker(NodeWalker, IndentPrintMixin):
def walk_SomeNodeType(self, node: NodeType):
self.print('some preamble')
with self.indent():
# continue walking the tree
self.print('something else')
The self.print() method takes note of the current level of indentation, so
output will be indented by the indent passed to
the IndentPrintMixin constructor, or to the indent(amount: int) method.
The mixin keeps as stack of the indent amounts so it can go back to where it
was after each with indent(amount=n): statement:
def walk_SomeNodeType(self, node: NodeType):
with self.indent(amount=2):
self.print(node.exp)
The printed code can be retrieved using the printed_text() method, but other
possibilities are available by assigning a stream-like object to
self.output_stream in the __init__() method.
A good example of how to do code generation with a NodeWalker and
IndentPrintMixin is 竜 TatSu’s own code generator, which can be found
in tatsu/ngcodegen/pythongen.py, or the model generation found in
tatsu/ngcodegen/objectomdel.py.