From 8e12f4a4ac15287c953f846ca00d7e15be37f7bc Mon Sep 17 00:00:00 2001 From: "Ryan C. Gordon" Date: Mon, 8 Feb 2010 04:42:51 -0500 Subject: [PATCH] Free the parse tree once we're done with it. --HG-- branch : calculator-experiment --- calculator.c | 34 +++++++++++++++++++++++++++++++++- calculator.lemon | 2 +- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/calculator.c b/calculator.c index 57fddb1d..c94bd67a 100644 --- a/calculator.c +++ b/calculator.c @@ -497,10 +497,42 @@ static double run_expr(const Expression *expr) return 0.0; // oh well. } // run_expr -static void parse_complete(const Expression *expr) +static void free_expr(Context *ctx, Expression *expr) +{ + if (operator_is_unary(expr->op)) + { + const ExpressionUnary *unary = (const ExpressionUnary *) expr; + free_expr(ctx, unary->operand); + } // if + else if (operator_is_binary(expr->op)) + { + const ExpressionBinary *binary = (const ExpressionBinary *) expr; + free_expr(ctx, binary->left); + free_expr(ctx, binary->right); + } // else if + else if (operator_is_ternary(expr->op)) + { + const ExpressionTernary *ternary = (const ExpressionTernary *) expr; + free_expr(ctx, ternary->left); + free_expr(ctx, ternary->center); + free_expr(ctx, ternary->right); + } // else if + else if (expr->op == OP_STRING_LITERAL) + { + Free(ctx, (void *) ((ExpressionStringLiteral *)expr)->string); + } // else if + else if (expr->op == OP_IDENTIFIER) + { + Free(ctx, (void *) ((ExpressionIdentifier *)expr)->identifier); + } // else if + Free(ctx, expr); +} // free_expr + +static void parse_complete(Context *ctx, Expression *expr) { print_expr(expr, 0); printf("Result: %lf\n\n", run_expr(expr)); + free_expr(ctx, expr); } // parse_complete diff --git a/calculator.lemon b/calculator.lemon index 2d8a154c..329b3920 100644 --- a/calculator.lemon +++ b/calculator.lemon @@ -72,7 +72,7 @@ // The rules... -calculator ::= expression(B). { parse_complete(B); } +calculator ::= expression(B). { parse_complete(ctx, B); } %type identifier { const char * } %destructor identifier { (void) ctx; } // !!! FIXME: remove this later, it's just to shut up the compiler for now.