From 0a4966ae959c9cc031933bb316ea05905bc5c3a9 Mon Sep 17 00:00:00 2001 From: Bruno BELANYI Date: Sat, 30 Nov 2019 19:24:37 +0100 Subject: [PATCH] calculator: add executable calculator It can both evaluate and print the given expression. It uses `click` to parse its CLI options. --- calculator/run.py | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100755 calculator/run.py diff --git a/calculator/run.py b/calculator/run.py new file mode 100755 index 0000000..2ed4563 --- /dev/null +++ b/calculator/run.py @@ -0,0 +1,50 @@ +#! /usr/bin/env python +import click + +from calculator.eval import Evaluator +from calculator.parse import parse_infix, parse_postfix, parse_prefix +from calculator.print import Printer + +STR_TO_PARSER = { + "infix": parse_infix, + "prefix": parse_prefix, + "postfix": parse_postfix, +} + + +@click.group(invoke_without_command=True, chain=True) +@click.option( + "--expr-type", + default="infix", + type=click.Choice(["infix", "prefix", "postfix"], case_sensitive=False), +) +@click.pass_context +def cli(ctx, expr_type): + ctx.ensure_object(dict) + ctx.obj["input"] = STR_TO_PARSER[expr_type]( + input(f"Input your {expr_type} expression: ") + ) + if ctx.invoked_subcommand is None: + ctx.invoke(eval_tree) + + +@cli.command(name="print") +@click.pass_context +def print_tree(ctx): + """ + Print the parsed AST. + """ + Printer().print(ctx.obj["input"]) + + +@cli.command(name="eval") +@click.pass_context +def eval_tree(ctx): + """ + Evaluate the parsed expression. + """ + print(Evaluator().visit_and_get_value(ctx.obj["input"])) + + +if __name__ == "__main__": + cli(obj={})