Example #1
0
File: to_fmt.py Project: vhb/pyrser
def to_fmt(self):
    """
    Return an Fmt representation for pretty-printing
    """
    qual = "evalctx"
    lseval = []
    block = fmt.block(":\n", "", fmt.tab(lseval))
    txt = fmt.sep(" ", [qual, block])
    lseval.append(self._sig.to_fmt())
    if len(self.resolution) > 0:
        lsb = []
        for k in sorted(self.resolution.keys()):
            s = self.resolution[k]
            if s is not None:
                lsb.append(fmt.end("\n", ["'%s': %s (%s)" % (k, s, s().show_name())]))
            else:
                lsb.append(fmt.end("\n", ["'%s': Unresolved" % (k)]))
        if self._translate_to is not None:
            lsb.append("use translator:")
            lsb.append(self._translate_to.to_fmt())
        if self._variadic_types is not None:
            lsb.append("variadic types:\n")
            arity = self._sig.arity
            for t in self._variadic_types:
                lsb.append("[%d] : %s\n" % (arity, t))
                arity += 1
        lseval.append(fmt.block("\nresolution :\n", "", fmt.tab(lsb)))
    return txt
Example #2
0
File: to_fmt.py Project: vhb/pyrser
def to_fmt(self):
    """
    Return an Fmt representation for pretty-printing
    """
    qual = "evalctx"
    lseval = []
    block = fmt.block(":\n", "", fmt.tab(lseval))
    txt = fmt.sep(" ", [qual, block])
    lseval.append(self._sig.to_fmt())
    if len(self.resolution) > 0:
        lsb = []
        for k in sorted(self.resolution.keys()):
            s = self.resolution[k]
            if s is not None:
                lsb.append(
                    fmt.end("\n", ["'%s': %s (%s)" % (k, s, s().show_name())]))
            else:
                lsb.append(fmt.end("\n", ["'%s': Unresolved" % (k)]))
        if self._translate_to is not None:
            lsb.append("use translator:")
            lsb.append(self._translate_to.to_fmt())
        if self._variadic_types is not None:
            lsb.append("variadic types:\n")
            arity = self._sig.arity
            for t in self._variadic_types:
                lsb.append("[%d] : %s\n" % (arity, t))
                arity += 1
        lseval.append(fmt.block("\nresolution :\n", "", fmt.tab(lsb)))
    return txt
Example #3
0
def to_c(self):
    if ((hasattr(self, 'body') and self.body is not None
         and hasattr(self.body, 'to_c'))):
        return fmt.sep("\n",
                       [self.ctype.ctype_to_c(self._name),
                        self.body.to_c()])
    else:
        return fmt.end(';\n', decl_to_c(self))
Example #4
0
def to_c(self):
    if self.already_imported:
        return fmt.sep("", [])
    lsbody = []
    lsbody.append(self.ifndef.to_c())
    lsbody.append(self.define.to_c())
    lsbody.append(self.body.to_c())
    lsbody.append(self.endif.to_c())
    return fmt.end("\n\n", fmt.tab(fmt.sep("\n", lsbody)))
Example #5
0
File: to_fmt.py Project: vhb/pyrser
def to_fmt(self) -> fmt.indentable:
    """
    Return an Fmt representation for pretty-printing
    """
    qual = "scope"
    txt = fmt.sep(" ", [qual])
    name = self.show_name()
    if name != "":
        txt.lsdata.append(name)
    if len(self._hsig) > 0 or len(self.mapTypeTranslate) > 0:
        lsb = []
        if len(self.mapTypeTranslate) > 0:
            lsb.append("translate:\n")
            lsb.append(fmt.end("\n", self.mapTypeTranslate.to_fmt()))
        for k in sorted(self._hsig.keys()):
            s = self._hsig[k]
            lsb.append(fmt.end("\n", [s.to_fmt()]))
        block = fmt.block(":\n", "", fmt.tab(lsb))
        txt.lsdata.append(block)
    return txt
Example #6
0
File: to_fmt.py Project: vhb/pyrser
def to_fmt(self) -> fmt.indentable:
    """
    Return an Fmt representation for pretty-printing
    """
    qual = "scope"
    txt = fmt.sep(" ", [qual])
    name = self.show_name()
    if name != "":
        txt.lsdata.append(name)
    if len(self._hsig) > 0 or len(self.mapTypeTranslate) > 0:
        lsb = []
        if len(self.mapTypeTranslate) > 0:
            lsb.append("translate:\n")
            lsb.append(fmt.end("\n", self.mapTypeTranslate.to_fmt()))
        for k in sorted(self._hsig.keys()):
            s = self._hsig[k]
            lsb.append(fmt.end("\n", [s.to_fmt()]))
        block = fmt.block(":\n", "", fmt.tab(lsb))
        txt.lsdata.append(block)
    return txt
Example #7
0
File: to_c.py Project: Py0s/KooC
def to_c(self):
    thenbody = ';\n'
    if self.thencond is not None and hasattr(self.thencond, 'to_c'):
        thenbody = fmt.tab(self.thencond.to_c())
    lsif = [
        fmt.sep(" ", ["if", fmt.block('(', ')\n', [self.condition.to_c()])]),
        thenbody
    ]
    if self.elsecond is not None and hasattr(self.elsecond, 'to_c'):
        lsif.append("else\n")
        lsif.append(fmt.tab(self.elsecond.to_c()))
    return fmt.end("", lsif)
Example #8
0
def to_c(self):
    thenbody = ';\n'
    if self.thencond is not None and hasattr(self.thencond, 'to_c'):
        thenbody = fmt.tab(self.thencond.to_c())
    lsif = [
        fmt.sep(" ",
                ["if", fmt.block('(', ')\n', [self.condition.to_c()])]),
        thenbody
    ]
    if self.elsecond is not None and hasattr(self.elsecond, 'to_c'):
        lsif.append("else\n")
        lsif.append(fmt.tab(self.elsecond.to_c()))
    return fmt.end("", lsif)
Example #9
0
 def to_fmt(self) -> str:
     """
     Provide a useful representation of the register.
     """
     infos = fmt.end(";\n", [])
     s = fmt.sep(', ', [])
     for ids in sorted(self.states.keys()):
         s.lsdata.append(str(ids))
     infos.lsdata.append(fmt.block('(', ')', [s]))
     infos.lsdata.append("events:" + repr(self.events))
     infos.lsdata.append("named_events:" + repr(list(self.named_events.keys())))
     infos.lsdata.append("uid_events:" + repr(list(self.uid_events.keys())))
     return infos
Example #10
0
File: to_c.py Project: Py0s/KooC
def to_c(self):
    if ((hasattr(self, 'body')
         and self.body is not None
         and hasattr(self.body, 'to_c'))):
        return fmt.sep(
            "\n",
            [
                self.ctype.ctype_to_c(self._name),
                self.body.to_c()
            ]
        )
    else:
        return fmt.end(';\n', decl_to_c(self))
Example #11
0
 def to_tl4t(self) -> fmt.indentable:
     params = []
     if self.p is not None:
         for p in self.p:
             params.append(p.to_tl4t())
     parenth = fmt.block('(', ')', fmt.sep(", ", params))
     lsdecl = fmt.sep(
         ' ', ["fun", fmt.sep('', [self.name, parenth]), ":", self.t])
     lsblock = None
     if hasattr(self, 'block'):
         lsblock = fmt.sep("\n", [lsdecl, self.block.to_tl4t()])
     else:
         lsblock = fmt.end(";\n", lsdecl)
     return lsblock
Example #12
0
File: to_fmt.py Project: vhb/pyrser
def to_fmt(self) -> fmt.indentable:
    """
    Return an Fmt representation for pretty-printing
    """
    qual = "type"
    txt = fmt.sep(" ", [qual])
    txt.lsdata.append(self.show_name())
    if hasattr(self, "_hsig") and len(self._hsig) > 0:
        lsb = []
        for k in sorted(self._hsig.keys()):
            s = self._hsig[k]
            lsb.append(fmt.end("\n", [s.to_fmt()]))
        block = fmt.block(":\n", "", fmt.tab(lsb))
        txt.lsdata.append(block)
    return txt
Example #13
0
File: to_fmt.py Project: vhb/pyrser
def to_fmt(self) -> fmt.indentable:
    """
    Return an Fmt representation for pretty-printing
    """
    qual = "type"
    txt = fmt.sep(" ", [qual])
    txt.lsdata.append(self.show_name())
    if hasattr(self, '_hsig') and len(self._hsig) > 0:
        lsb = []
        for k in sorted(self._hsig.keys()):
            s = self._hsig[k]
            lsb.append(fmt.end("\n", [s.to_fmt()]))
        block = fmt.block(":\n", "", fmt.tab(lsb))
        txt.lsdata.append(block)
    return txt
Example #14
0
 def to_tl4t(self) -> fmt.indentable:
     params = []
     if self.p is not None:
         for p in self.p:
             params.append(p.to_tl4t())
     parenth = fmt.block('(', ')', fmt.sep(", ", params))
     lsdecl = fmt.sep(
         ' ',
         [
             "fun",
             fmt.sep('', [self.name, parenth]),
             ":",
             self.t
         ]
     )
     lsblock = None
     if hasattr(self, 'block'):
         lsblock = fmt.sep("\n", [lsdecl, self.block.to_tl4t()])
     else:
         lsblock = fmt.end(";\n", lsdecl)
     return lsblock
Example #15
0
def to_c(self):
    init_body = None
    if type(self.init) is nodes.Decl:
        init_body = decl_to_c(self.init)
    elif self.init is not None and hasattr(self.init, 'expr'):
        init_body = self.init.expr.to_c()
    cond_body = None
    if self.condition is not None and hasattr(self.condition, 'expr'):
        cond_body = self.condition.expr.to_c()
    inc_body = None
    if self.increment is not None and hasattr(self.increment, 'to_c'):
        inc_body = self.increment.to_c()
    lsfor = [
        fmt.sep(" ", [
            "for",
            fmt.block('(', ')\n',
                      [fmt.sep("; ", [init_body, cond_body, inc_body])])
        ]),
        fmt.tab(self.body.to_c())
    ]
    return fmt.end("", lsfor)
Example #16
0
File: to_c.py Project: Py0s/KooC
def to_c(self):
    init_body = None
    if type(self.init) is nodes.Decl:
        init_body = decl_to_c(self.init)
    elif self.init is not None and hasattr(self.init, 'expr'):
        init_body = self.init.expr.to_c()
    cond_body = None
    if self.condition is not None and hasattr(self.condition, 'expr'):
        cond_body = self.condition.expr.to_c()
    inc_body = None
    if self.increment is not None and hasattr(self.increment, 'to_c'):
        inc_body = self.increment.to_c()
    lsfor = [
        fmt.sep(
            " ",
            [
                "for",
                fmt.block(
                    '(',
                    ')\n',
                    [
                        fmt.sep(
                            "; ",
                            [
                                init_body,
                                cond_body,
                                inc_body
                            ]
                        )
                    ]
                )
            ]
        ),
        fmt.tab(self.body.to_c())
    ]
    return fmt.end("", lsfor)
Example #17
0
def to_c(self):
    return fmt.end(";\n", [self.value])
Example #18
0
 def test_00(self):
     """Test pprint functions"""
     data = fmt.end(";", ["tot"])
     self.assertEqual(str(data), "tot;", "Failed to format end")
     data = fmt.tab(fmt.end(";\n", ["tot"]))
     self.assertEqual(str(data), "    tot;\n", "Failed to format end")
     data = fmt.tab([fmt.end(";\n", ["tot"])])
     self.assertEqual(str(data), "    tot;\n", "Failed to format end")
     data = fmt.end(";", ["", fmt.tab(["\ntot", "\nplop"])])
     self.assertEqual(str(data), ";\n{tab}tot\n{tab}plop;".format(tab=" " * 4), "Failed to format end")
     data = fmt.end(";", ["", fmt.tab(["\ntot", "\nplop"])])
     self.assertEqual(str(data), ";\n{tab}tot\n{tab}plop;".format(tab=" " * 4), "Failed to format end")
     data = fmt.sep(",", ["a", "b", "c"])
     self.assertEqual(str(data), "a,b,c", "Failed to format sep")
     data = fmt.tab(fmt.sep(",\n", ["tot", "tit", "tut"]))
     self.assertEqual(str(data), "{tab}tot,\n{tab}tit,\n{tab}tut".format(tab=" " * 4), "Failed to format end")
     data = fmt.sep(",\n", [fmt.tab(["tot", "tit"]), "tut"])
     self.assertEqual(str(data), "tottit,\ntut", "Failed to format end")
     data = fmt.block("{", "}", ["a", "b", "c"])
     self.assertEqual(str(data), "{abc}", "Failed to format block")
     data = fmt.block("{", "}", [fmt.sep(",", ["a", "b", "c"])])
     self.assertEqual(str(data), "{a,b,c}", "Failed to format block/sep")
     data = fmt.sep(",", [fmt.block("{", "}", ["a", "b"]), fmt.block("{", "}", ["c", "d"])])
     self.assertEqual(str(data), "{ab},{cd}", "Failed to format sep/block")
     data = fmt.end(";\n", ["a", "b", "c"])
     self.assertEqual(str(data), "a;\nb;\nc;\n", "Failed to format a list end by ';\n'")
     data = fmt.tab(fmt.block("{\n", "}\n", ["a\n", "b\n", "c\n"]))
     self.assertEqual(
         str(data), (("{tab}{{\n{tab}a\n" + "{tab}b\n{tab}c\n{tab}}}\n")).format(tab=(" " * 4)), "Failed to indent"
     )
     data = fmt.block("{\n", "}\n", [fmt.tab(["a\n", "b\n", "c\n"])])
     self.assertEqual(
         str(data), (("{{\n{tab}a\n{tab}b\n" + "{tab}c\n}}\n")).format(tab=(" " * 4)), "Failed to indent"
     )
     data = fmt.block(
         "{\n",
         "}\n",
         [fmt.tab(fmt.end("\n", ["a", "b", fmt.tab(fmt.block("[\n", "]", ["b\n", "g\n", "o\n", "e\n"])), "c"]))],
     )
     self.assertEqual(
         str(data),
         (
             (
                 "{{\n{tab}a\n{tab}b\n"
                 + "{tab2}[\n{tab2}b\n{tab2}g\n"
                 + "{tab2}o\n{tab2}e\n{tab2}]\n"
                 + "{tab}c\n}}\n"
             )
         ).format(tab=(" " * 4), tab2=(" " * 8)),
         "Failed to indent",
     )
     data = fmt.block(
         "{\n",
         "}\n",
         [
             fmt.tab(
                 fmt.end(
                     "\n", ["a", "b", fmt.block("[\n", "]", [fmt.tab(fmt.tab(["b\n", "g\n", "o\n", "e\n"]))]), "c"]
                 )
             )
         ],
     )
     self.assertEqual(
         str(data),
         (
             ("{{\n{tab}a\n{tab}b\n" + "{tab}[\n{tab2}b\n{tab2}g\n" + "{tab2}o\n{tab2}e\n{tab}]\n" + "{tab}c\n}}\n")
         ).format(tab=(" " * 4), tab2=(" " * 12)),
         "Failed to indent",
     )
     data = fmt.block("{\n", "}\n", fmt.tab(["a\n", fmt.block("{\n", "}\n", fmt.tab(["d\n", "e\n", "f\n"])), "c\n"]))
     self.assertEqual(
         str(data),
         (("{{\n{tab}a\n" + "{tab}{{\n{tab2}d\n{tab2}e\n{tab2}f\n{tab}}}\n" + "{tab}c\n}}\n")).format(
             tab=(" " * 4), tab2=(" " * 8)
         ),
         "Failed to indent",
     )
     data = fmt.block("{\n", "}\n", fmt.tab(fmt.block("{\n", "}\n", fmt.tab(fmt.end(";\n", ["a", "b", "c"])))))
     self.assertEqual(
         str(data),
         (("{{\n{tab}{{\n" + "{tab2}a;\n{tab2}b;\n{tab2}c;\n" + "{tab}}}\n}}\n")).format(
             tab=(" " * 4), tab2=(" " * 8)
         ),
         "Failed to indent",
     )
     data = fmt.tab(["1", "2", [fmt.sep(",\n", ["tot", "tit", "tut"])], "4"])
     self.assertEqual(
         str(data), ("{tab}12tot,\n{tab}tit,\n" + "{tab}tut4").format(tab=" " * 4), "Failed to format end"
     )
Example #19
0
def to_c(self):
    return fmt.end(":\n", [fmt.sep(" ", [self.value, self.expr.to_c()])])
Example #20
0
def to_c(self):
    body = ';\n'
    if self.expr is not None and hasattr(self.expr, 'to_c'):
        body = self.expr.to_c()
    return fmt.end(";\n", [fmt.sep(" ", [self.value, body])])
Example #21
0
 def to_tl4t(self):
     return fmt.end(";\n", [self.expr.to_tl4t()])
Example #22
0
def to_c(self):
    return fmt.end(";\n", [self.expr.to_c()])
Example #23
0
File: to_yml.py Project: vhb/pyrser
def to_yml_item(item, pp, name):
    global scalar
    refcount = weakref.getweakrefcount(item)
    if refcount > 0:
        name += " &" + str(id(item))
    if type(item).__name__ in scalar:
        tag = fmt.end(
            '\n',
            fmt.sep("", [name, " ",
                         yml_attr(type(item).__name__, repr(item))]))
        pp.append(tag)
        return
    if isinstance(item, weakref.ref):
        name += " *" + str(id(item()))
        tag = fmt.end('\n', fmt.sep("", [name, " ", repr(item)]))
        pp.append(tag)
        return
    if isinstance(item, bytes) or isinstance(item, bytearray):
        inner = fmt.tab([])
        tag = fmt.block(name + " " + str(yml_attr('type', 'bytes')) + ':\n',
                        '----' + name + '----\n', inner)
        inner.lsdata.append(fmt.sep(" ", []))
        bindata = inner.lsdata[-1].lsdata
        i = 0
        for b in item:
            bindata.append("%02X" % b)
            i += 1
            if i > 16:
                bindata.append("\n")
                i = 0
        bindata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, object) and hasattr(item, '__dict__'):
        inner = fmt.tab([])
        tag = fmt.block(
            name + " " + str(yml_attr('type', item.__class__.__name__)) +
            ':\n', '', inner)
        for attr in sorted(vars(item)):
            to_yml_item(getattr(item, attr), inner.lsdata, attr)
        if len(vars(item)) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, list):
        inner = fmt.tab([])
        tag = fmt.block(name + " " + str(yml_attr('type', 'list')) + ':\n', '',
                        inner)
        i = 0
        for subitem in item:
            idxname = str(fmt.sep(" ", ['[', i, ']']))
            to_yml_item(subitem, inner.lsdata, idxname)
            i += 1
        if len(item) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, tuple):
        inner = fmt.tab([])
        tag = fmt.block(name + " " + str(yml_attr('type', 'tuple')) + ':\n',
                        '', inner)
        i = 0
        for subitem in item:
            idxname = str(fmt.sep(" ", ["[", i, "]"]))
            to_yml_item(subitem, inner.lsdata, idxname)
            i += 1
        if len(item) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, dict):
        inner = fmt.tab([])
        tag = fmt.block(name + " " + str(yml_attr('type', 'dict')) + ':\n', '',
                        inner)
        for k in sorted(item.keys()):
            idxname = str(fmt.sep(" ", ["[", repr(k), "]"]))
            to_yml_item(item[k], inner.lsdata, idxname)
        if len(item.keys()) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, set):
        inner = fmt.tab([])
        tag = fmt.block(name + " " + str(yml_attr('type', 'set')) + ':\n', '',
                        inner)
        for subitem in sorted(item):
            inner.lsdata.append(fmt.sep(", ", [repr(subitem)]))
        if len(item) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if item is None:
        tag = fmt.end('\n', [name])
        pp.append(tag)
        return
Example #24
0
 def to_tl4t(self):
     return fmt.end(";\n", [self.expr.to_tl4t()])
Example #25
0
File: to_c.py Project: Py0s/KooC
def to_c(self):
    return fmt.end(";\n", [self.expr.to_c()])
Example #26
0
File: match.py Project: vhb/pyrser
 def to_fmt(self) -> fmt.indentable:
     res = fmt.block('{\n', '}', [fmt.tab([])])
     lines = res.lsdata[0].lsdata
     for stmt in self.stmts:
         lines.append(fmt.end('\n', stmt.to_fmt()))
     return res
Example #27
0
File: to_c.py Project: Py0s/KooC
def to_c(self):
    return fmt.end(":\n", [fmt.sep(" ", [self.value, self.expr.to_c()])])
Example #28
0
File: to_c.py Project: Py0s/KooC
def to_c(self):
    body = ';\n'
    if self.expr is not None and hasattr(self.expr, 'to_c'):
        body = self.expr.to_c()
    return fmt.end(";\n", [fmt.sep(" ", [self.value, body])])
Example #29
0
File: to_c.py Project: Py0s/KooC
def to_c(self):
    return fmt.end(";\n", [self.value])
Example #30
0
File: to_yml.py Project: Py0s/KooC
def to_yml_item(item, pp, name):
    global scalar
    refcount = weakref.getweakrefcount(item)
    if refcount > 0:
        name += " &" + str(id(item))
    if type(item).__name__ in scalar:
        tag = fmt.end(
            '\n',
            fmt.sep(
                "",
                [
                    name,
                    " ",
                    yml_attr(
                        type(item).__name__,
                        repr(item)
                    )
                ]
            )
        )
        pp.append(tag)
        return
    if isinstance(item, weakref.ref):
        name += " *" + str(id(item()))
        tag = fmt.end('\n', fmt.sep("", [name, " ", repr(item)]))
        pp.append(tag)
        return
    if isinstance(item, bytes) or isinstance(item, bytearray):
        inner = fmt.tab([])
        tag = fmt.block(name + " " + str(yml_attr('type', 'bytes')) + ':\n',
                        '----' + name + '----\n', inner)
        inner.lsdata.append(fmt.sep(" ", []))
        bindata = inner.lsdata[-1].lsdata
        i = 0
        for b in item:
            bindata.append("%02X" % b)
            i += 1
            if i > 16:
                bindata.append("\n")
                i = 0
        bindata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, object) and hasattr(item, '__dict__'):
        inner = fmt.tab([])
        tag = fmt.block(name + " " +
                        str(yml_attr('type', item.__class__.__name__))
                        + ':\n',
                        '', inner)
        for attr in sorted(vars(item)):
            to_yml_item(getattr(item, attr), inner.lsdata, attr)
        if len(vars(item)) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, list):
        inner = fmt.tab([])
        tag = fmt.block(
            name + " " + str(yml_attr('type', 'list')) + ':\n',
            '',
            inner
        )
        i = 0
        for subitem in item:
            idxname = str(fmt.sep(" ", ['[', i, ']']))
            to_yml_item(subitem, inner.lsdata, idxname)
            i += 1
        if len(item) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, tuple):
        inner = fmt.tab([])
        tag = fmt.block(name + " " + str(yml_attr('type', 'tuple')) + ':\n',
                        '', inner)
        i = 0
        for subitem in item:
            idxname = str(fmt.sep(" ", ["[", i, "]"]))
            to_yml_item(subitem, inner.lsdata, idxname)
            i += 1
        if len(item) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, dict):
        inner = fmt.tab([])
        tag = fmt.block(name + " " + str(yml_attr('type', 'dict')) + ':\n',
                        '', inner)
        for k in sorted(item.keys()):
            idxname = str(fmt.sep(" ", ["[", repr(k), "]"]))
            to_yml_item(item[k], inner.lsdata, idxname)
        if len(item.keys()) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if isinstance(item, set):
        inner = fmt.tab([])
        tag = fmt.block(name + " " + str(yml_attr('type', 'set')) + ':\n',
                        '', inner)
        for subitem in sorted(item):
            inner.lsdata.append(fmt.sep(", "[repr(subitem)]))
        if len(item) == 0:
            inner.lsdata.append("\n")
        pp.append(tag)
        return
    if item is None:
        tag = fmt.end('\n', [name])
        pp.append(tag)
        return
Example #31
0
 def to_fmt(self) -> fmt.indentable:
     res = fmt.block('{\n', '}', [fmt.tab([])])
     lines = res.lsdata[0].lsdata
     for stmt in self.stmts:
         lines.append(fmt.end('\n', stmt.to_fmt()))
     return res
Example #32
0
 def test_00(self):
     """Test pprint functions"""
     data = fmt.end(";", ["tot"])
     self.assertEqual(str(data), "tot;", "Failed to format end")
     data = fmt.tab(fmt.end(";\n", ["tot"]))
     self.assertEqual(str(data), "    tot;\n", "Failed to format end")
     data = fmt.tab([fmt.end(";\n", ["tot"])])
     self.assertEqual(str(data), "    tot;\n", "Failed to format end")
     data = fmt.end(";", ["", fmt.tab(["\ntot", "\nplop"])])
     self.assertEqual(str(data),
                      ";\n{tab}tot\n{tab}plop;".format(tab=" " * 4),
                      "Failed to format end")
     data = fmt.end(";", ["", fmt.tab(["\ntot", "\nplop"])])
     self.assertEqual(str(data),
                      ";\n{tab}tot\n{tab}plop;".format(tab=" " * 4),
                      "Failed to format end")
     data = fmt.sep(",", ['a', 'b', 'c'])
     self.assertEqual(str(data), "a,b,c", "Failed to format sep")
     data = fmt.tab(fmt.sep(",\n", ["tot", "tit", "tut"]))
     self.assertEqual(str(data),
                      "{tab}tot,\n{tab}tit,\n{tab}tut".format(tab=" " * 4),
                      "Failed to format end")
     data = fmt.sep(",\n", [fmt.tab(["tot", "tit"]), "tut"])
     self.assertEqual(str(data), "tottit,\ntut", "Failed to format end")
     data = fmt.block("{", "}", ['a', 'b', 'c'])
     self.assertEqual(str(data), "{abc}", "Failed to format block")
     data = fmt.block("{", "}", [fmt.sep(",", ['a', 'b', 'c'])])
     self.assertEqual(str(data), "{a,b,c}", "Failed to format block/sep")
     data = fmt.sep(
         ",",
         [fmt.block("{", "}", ['a', 'b']),
          fmt.block("{", "}", ['c', 'd'])])
     self.assertEqual(str(data), "{ab},{cd}", "Failed to format sep/block")
     data = fmt.end(";\n", ['a', 'b', 'c'])
     self.assertEqual(str(data), "a;\nb;\nc;\n",
                      "Failed to format a list end by ';\n'")
     data = fmt.tab(fmt.block("{\n", "}\n", ['a\n', 'b\n', 'c\n']))
     self.assertEqual(str(data),
                      (("{tab}{{\n{tab}a\n" +
                        "{tab}b\n{tab}c\n{tab}}}\n")).format(tab=(" " * 4)),
                      "Failed to indent")
     data = fmt.block("{\n", "}\n", [fmt.tab(['a\n', 'b\n', 'c\n'])])
     self.assertEqual(str(data), (("{{\n{tab}a\n{tab}b\n" +
                                   "{tab}c\n}}\n")).format(tab=(" " * 4)),
                      "Failed to indent")
     data = fmt.block("{\n", "}\n", [
         fmt.tab(
             fmt.end("\n", [
                 'a', 'b',
                 fmt.tab(fmt.block("[\n", "]",
                                   ['b\n', 'g\n', 'o\n', 'e\n'])), 'c'
             ]))
     ])
     self.assertEqual(
         str(data),
         (("{{\n{tab}a\n{tab}b\n" + "{tab2}[\n{tab2}b\n{tab2}g\n" +
           "{tab2}o\n{tab2}e\n{tab2}]\n" + "{tab}c\n}}\n")).format(
               tab=(" " * 4), tab2=(" " * 8)), "Failed to indent")
     data = fmt.block("{\n", "}\n", [
         fmt.tab(
             fmt.end("\n", [
                 'a', 'b',
                 fmt.block(
                     "[\n", "]",
                     [fmt.tab(fmt.tab(['b\n', 'g\n', 'o\n', 'e\n']))]), 'c'
             ]))
     ])
     self.assertEqual(
         str(data),
         (("{{\n{tab}a\n{tab}b\n" + "{tab}[\n{tab2}b\n{tab2}g\n" +
           "{tab2}o\n{tab2}e\n{tab}]\n" + "{tab}c\n}}\n")).format(
               tab=(" " * 4), tab2=(" " * 12)), "Failed to indent")
     data = fmt.block(
         "{\n", "}\n",
         fmt.tab([
             'a\n',
             fmt.block("{\n", "}\n", fmt.tab(['d\n', 'e\n', 'f\n'])), 'c\n'
         ]))
     self.assertEqual(str(data),
                      (("{{\n{tab}a\n" +
                        "{tab}{{\n{tab2}d\n{tab2}e\n{tab2}f\n{tab}}}\n" +
                        "{tab}c\n}}\n")).format(tab=(" " * 4),
                                                tab2=(" " * 8)),
                      "Failed to indent")
     data = fmt.block(
         "{\n", "}\n",
         fmt.tab(
             fmt.block("{\n", "}\n",
                       fmt.tab(fmt.end(";\n", ["a", "b", "c"])))))
     self.assertEqual(str(data),
                      (("{{\n{tab}{{\n" + "{tab2}a;\n{tab2}b;\n{tab2}c;\n" +
                        "{tab}}}\n}}\n")).format(tab=(" " * 4),
                                                 tab2=(" " * 8)),
                      "Failed to indent")
     data = fmt.tab(
         ["1", "2", [fmt.sep(",\n", ["tot", "tit", "tut"])], "4"])
     self.assertEqual(str(data), ("{tab}12tot,\n{tab}tit,\n" +
                                  "{tab}tut4").format(tab=" " * 4),
                      "Failed to format end")
Example #33
0
def to_cython(self, ctype_name: str) -> CStub:
    cstub = CStub()
    # SETUP GENERATION
    cstub.setup = fmt.end('', [])
    cstub.setup.lsdata.append(tpl_setup.substitute(
        ctn=ctype_name,
    ))
    # CSOURCE GENERATION
    pyattr = fmt.end('', [])
    pyxprotos = fmt.end('', [])
    pprotos = fmt.end('', [])
    cprotos = fmt.end('', [])
    gram = fmt.end('//---\n', [])
    gram.lsdata.append(tpl_file.substitute(ctn=ctype_name))
    for k, v in self.__class__._rules.items():
        try:
            if isinstance(v, parsing.Functor):
                genstate = GenState()
                fun_name = k.replace('.', '_')
                #
                if not isinstance(v, functors.Seq):
                    v = functors.Seq(v)
                rule_code = v.to_cython(genstate)
                content = tpl_function.substitute(
                    ctn=ctype_name,
                    rule=fun_name,
                    code=fmt.tab([rule_code]),
                    lvlid=genstate.lvlid,
                    errid=genstate.errid
                )
                rule = fmt.sep(
                               '\n',
                               [
                                "//--- %s" % k,
                                content
                               ]
                )
                pyattr.lsdata.append(tpl_python_attr.substitute(
                    rule=fun_name
                ))
                pprotos.lsdata.append(tpl_pproto.substitute(
                    ctn=ctype_name,
                    rule=fun_name
                ))
                cprotos.lsdata.append(tpl_cproto.substitute(
                    ctn=ctype_name,
                    rule=fun_name
                ))
                pyxprotos.lsdata.append(tpl_pyx_rules.substitute(
                    ctn=ctype_name,
                    rule=fun_name
                ))
                gram.lsdata.append(rule)
        except:
            #print("Can't Transform %s = %s" % (k, to_yml.to_yml(v)))
            pass
    cstub.csource = gram
    # PYTHON GENERATION
    cstub.psource = fmt.end('', [])
    cstub.psource.lsdata.append(tpl_python.substitute(
        ctn=ctype_name,
        rules_attr=str(pyattr)
    ))
    # CHEADER GENERATION
    cstub.cheader = fmt.end('', [])
    cstub.cheader.lsdata.append(tpl_header.substitute(
        ctn=ctype_name,
        cfunctions_proto=str(cprotos)
    ))
    # PXD GENERATION
    cstub.pxd = fmt.end('', [])
    cstub.pxd.lsdata.append(tpl_pxd.substitute(
        ctn=ctype_name,
        pfunctions_proto=str(pprotos)
    ))
    # PYX GENERATION
    cstub.pyx = fmt.end('', [])
    cstub.pyx.lsdata.append(tpl_pyx.substitute(
        ctn=ctype_name,
        rfunctions_proto=str(pyxprotos)
    ))
    return cstub