Exemple #1
0
def main():
    argparser = argparse.ArgumentParser(
        description=inspect.getdoc(sys.modules[__name__]))
    argparser.add_argument('json_file',
                           nargs='?',
                           default='grammar/src/grammar.json',
                           help='file holding the JSON form of the grammar')
    argparser.add_argument('-v',
                           '--verbose',
                           help='increase output verbosity',
                           action="store_true")
    argparser.add_argument(
        '-ll',
        help='compute LL(1) parser table and associated conflicts',
        action="store_true")
    argparser.add_argument(
        '-lalr',
        help='compute LALR(1) parser table and associated conflicts',
        action="store_true")
    argparser.add_argument('-lr',
                           help='compute LR(1) item sets',
                           action="store_true")
    argparser.add_argument('-limit',
                           type=int,
                           help='limit on number of LALR(1) item sets')
    args = argparser.parse_args()
    with open(args.json_file) as infile:
        json_text = "".join(infile.readlines())

    g = Grammar.Load(json_text, 'translation_unit')

    if args.lalr:
        print("=Grammar:\n")
        print(g.pretty_str())
        parse_table = g.LALR1(max_item_sets=args.limit)
        parse_table.write(sys.stdout)
        if parse_table.has_conflicts():
            sys.exit(1)
        sys.exit(0)
    if args.lr:
        lr1_itemsets = g.LR1_ItemSets()
        for IS in lr1_itemsets:
            print("\n{}".format(str(IS)))
        sys.exit(0)

    elif args.ll:
        (table, conflicts) = g.LL1()

        for key, reduction in table.items():
            (non_terminal, token) = key
            print("{} {}: {}".format(non_terminal, str(token), str(reduction)))

        for (lhs, terminal, action, action2) in conflicts:
            print("conflict: {}->{}: {}  {}".format(lhs, terminal, action,
                                                    action2))
        if len(conflicts) > 0:
            sys.exit(1)
    else:
        if args.verbose:
            g.dump()
        else:
            print(g.pretty_str())

    sys.exit(0)