Exemplo n.º 1
0
def parse_grammar(initial, terminals, non_terminals, productions):
    """
    Parse grammar from plain text to CP format
    """
    G = Grammar()
    productions = productions.split('\n')
    f['epsilon'] = G.Epsilon
    f['EOF'] = G.EOF
    f[initial] = G.NonTerminal(initial, True)

    for terminal in terminals.split(' '):
        f[terminal] = G.Terminal(terminal)

    for non_terminal in non_terminals.split(' '):
        if non_terminal != f[initial].Name:
            f[non_terminal] = G.NonTerminal(non_terminal)

    # Parsing productions
    for production in productions:
        if not production:
            continue
        parse_production(production, G)
        if errors:
            break

    if errors:
        return (-1, errors)

    return (0, G)
Exemplo n.º 2
0
def G5():
    G = Grammar()
    S = G.NonTerminal('S', True)
    A = G.NonTerminal('A')
    a = G.Terminal('a')

    S %= S + A | A
    A %= a

    return G