Beispiel #1
0
class Parser:
    def __init__(self, syntaxtable=default_syntax_table):
        self.syntaxtable = syntaxtable
        self.scope = Scope()
        self.sentencenode = SentenceNode()

    def get_scope(self):
        return self.scope

    def is_syntax_character(self, character):
        return self.syntaxtable.has_character(character)

    def read(self, stream: StreamController):
        return self.syntaxtable.read(stream, self)

    def parse(self, stream: TextIOBase):
        """
        parse source code from file-like object.

        Parameters
        ----------
        stream: io.TextIOBase
          this file-like object used to input.
        """

        controller = StreamController(stream)
        while controller.peek():
            node = self.read(controller)
            if node:
                self.sentencenode.add(node)

    def parse_string(self, source: str):
        """
        parse source code from str object.

        Parameters
        ----------
        source: str
          source code for input.
        """

        with StringIO(source) as stream:
            self.parse(stream)

    def result(self):
        """
        get template object that parsed from source code.

        Returns
        -------
        template: peco.template.Template
          parsed template
        """

        template = Template(self.sentencenode, self.scope)
        return template
Beispiel #2
0
 def test_write(self):
     with StringIO() as stream:
         text1 = "a"
         text2 = "b"
         text3 = "c"
         node = SentenceNode()
         node.add(TextNode(text1))
         node.add(TextNode(text2))
         node.add(TextNode(text3))
         node.write(stream)
         self.assertEqual(stream.getvalue(), text1 + text2 + text3)