Verified Commit 7f4e8d1b authored by Vladimír Štill's avatar Vladimír Štill
Browse files

CFL: Fix printing of CFGs

parent 19a7de51
Loading
Loading
Loading
Loading
+4 −1
Original line number Diff line number Diff line
@@ -25,6 +25,9 @@ class Nonterminal:
    def __hash__(self):
        return hash(self.name)

    def __lt__(self, other) -> bool:
        return self.name < other.name


class Character:
    def __init__(self, name: str):
+5 −4
Original line number Diff line number Diff line
@@ -424,12 +424,13 @@ class CFG:
        return GeneratesResult(cnf.init in table[n - 1][0], cnf, table)

    def to_string(self) -> str:
        nonterms = sorted(self.nonterminals)
        nonterms.remove(self.init)
        nonterms.insert(0, self.init)
        # put initial state first
        nonterms = sorted(self.nonterminals, key=lambda x: (x != self.init, x))
        out = []

        for r in self.rules.keys():
        for r in nonterms:
            if r not in self.rules:
                continue
            to = sorted(map(lambda prds: "".join(map(lambda x: x.name, prds))
                                         if prds else "ε", self.rules[r]))
            out.append(f"{r.name} -> {' | '.join(to)}")