def from_cfg(cls, cfg: CFG): """ Build RSA from a given cfpq_data context-free grammar @param cfg: CFG on which RSA is built @return: initialized class """ grammar = cfg.to_text() productions = dict() for line in grammar.split("\n")[:-1]: part_line = line.split(" -> ") right = part_line[1] if right == "": right = "epsilon" if part_line[0] in productions: productions[part_line[0]] += " | " + right else: productions[part_line[0]] = right grammar_new = "" for nonterminal in productions: grammar_new += nonterminal + " -> " + productions[nonterminal] + "\n" grammar_new = grammar_new[:-1] return RecursiveAutomaton.from_rsm(rsm_from_text(grammar_new))
def test_rsm_from_and_to_txt(grammar): (fd, fname) = tempfile.mkstemp() rsm_1 = cfpq_data.rsm_from_text(grammar) path = cfpq_data.rsm_to_txt(rsm_1, fname) rsm_2 = cfpq_data.rsm_from_txt(path) os.close(fd) os.unlink(fname) assert set(cfpq_data.rsm_to_text(rsm_1).splitlines()) == set( cfpq_data.rsm_to_text(rsm_2).splitlines())
import pytest import cfpq_data cnf_1 = cfpq_data.cnf_from_text("S -> a S b | a b") cnf_2 = cfpq_data.cnf_from_text( "S -> sco_r S sco | t_r S t | sco_r sco | t_r t") rsm_1 = cfpq_data.rsm_from_text("S -> a S b | a b") rsm_2 = cfpq_data.rsm_from_text( "S -> sco_r S sco | t_r S t | sco_r sco | t_r t") @pytest.mark.parametrize("cnf", [cnf_1, cnf_2]) def test_cfg_from_cnf(cnf): cfg = cfpq_data.cfg_from_cnf(cnf) for word in cfg.get_words(4): assert cfg.contains(word) and cnf.contains(word) @pytest.mark.parametrize("rsm", [rsm_1, rsm_2]) def test_cfg_from_rsm(rsm): cfg = cfpq_data.cfg_from_rsm(rsm) for word in cfg.get_words(4): assert cfg.contains(word) and rsm.contains(word)
import cfpq_data cfg_1 = cfpq_data.cfg_from_text("S -> a S b S\nS -> a b\n") exp_cfg_1 = cfpq_data.cfg_from_text("S -> b S c S\nS -> b c\n") cfg_2 = cfpq_data.cfg_from_text("S -> a b c d\n") exp_cfg_2 = cfpq_data.cfg_from_text("S -> b c c d\n") cnf_1 = cfpq_data.cnf_from_text("S -> a") exp_cnf_1 = cfpq_data.cnf_from_text("S -> b") cnf_2 = cfpq_data.cnf_from_text("S -> b") exp_cnf_2 = cfpq_data.cnf_from_text("S -> c") rsm_1 = cfpq_data.rsm_from_text("S -> a b\n") exp_rsm_1 = cfpq_data.rsm_from_text("S -> b c\n") rsm_2 = cfpq_data.rsm_from_text("S -> b a\n") exp_rsm_2 = cfpq_data.rsm_from_text("S -> c b\n") @pytest.mark.parametrize( "cfg, exp_cfg", [ (cfg_1, exp_cfg_1), (cfg_2, exp_cfg_2), ], ) def test_change_terminals_in_cfg(cfg, exp_cfg): act_cfg = cfpq_data.change_terminals_in_cfg(cfg, {"a": "b", "b": "c"})
def test_rsm_to_text(grammar, expected): rsm = cfpq_data.rsm_from_text(grammar) actual = set(cfpq_data.rsm_to_text(rsm).splitlines()) assert actual == expected
def test_rsm_from_text(grammar, expected): rsm = cfpq_data.rsm_from_text(grammar) for word in expected: if word is not None: assert rsm.contains(word)