def from_rules(cls, rules, symbol=ROOT, lexicon=None):
    """Recursively form a derivation from a rule list."""

    # If the current symbol is a Terminal, close current branch and return.
    if isinstance(symbol, grammar.Terminal):
      return symbol
    if symbol not in lexicon.keys():
      next_rule = rules.pop()
    else:
      next_rule = lexicon[symbol].pop()

    return Derivation(
        next_rule,
        tuple(
            cls.from_rules(rules, symbol=next_symbol, lexicon=lexicon)
            for next_symbol in next_rule.rhs))
Recursively form a derivation from a rule list.
language/gscan/data/grammar.py