(C) Integarting the Expr Class

Required Changes

The parse functions call the constructors of the expression tree class Expr. That means they own the created expression node. When they return the pointer they transfer ownership to the caller. This means two things:

  • When a parse function creates a new node its not only the owner of this node but also all its child nodes.

  • It therefore transfers the ownership of a complete expression tree not just one node.

This needs to be documented:

1
2
3
4
5
6
// The returned expression tree is owned by the called function:
const struct Expr *parseExpr(void);
const struct Expr *parseTerm(void);
const struct Expr *parsePowerExpr(void);
const struct Expr *parseUnaryExpr(void);
const struct Expr *parseFactor(void);

Now it is clear that function parseExprStatement() becomes the owner of the complete expression tree by calling parseExpr(). So here we also have to call the destructor before we return:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
void
parseExprStatement(void)
{
    const struct Expr *expr = parseExpr();
    //printf("> %lf\n", evalExpr(expr));
    printExprTree(expr);
    expected(SEMICOLON);
    getToken();
    deleteExpr(expr);
}