tinyexpr icon indicating copy to clipboard operation
tinyexpr copied to clipboard

Feature Request: Function to copy te_expr

Open SirNate0 opened this issue 10 months ago • 0 comments

I needed to be able to copy expressions for my use of the library. I modified the library a bit for use with C++ already, so the below code is probably not exactly correct for the base library, but it should be pretty close.

te_expr* te_copy(te_expr* expr)
{
    if (!expr) return expr;

    te_expr* out = nullptr;

    switch(TYPE_MASK(expr->type)) {
        case TE_CONSTANT: 
            out = NEW_EXPR(expr->type);
            out->value = expr->value;
            return out;
        case TE_VARIABLE: 
            out = NEW_EXPR(expr->type);
            out->bound = expr->bound;
            return out;

        case TE_FUNCTION0: case TE_FUNCTION1: case TE_FUNCTION2: case TE_FUNCTION3:
        case TE_FUNCTION4: case TE_FUNCTION5: case TE_FUNCTION6: case TE_FUNCTION7:
            out = NEW_EXPR(expr->type);
            out->function = expr->function;
            for (unsigned i = 0; i < ARITY(expr->type); ++i)
                out->parameters[i] = te_copy((te_expr*)expr->parameters[i]);
            return out;

        case TE_CLOSURE0: case TE_CLOSURE1: case TE_CLOSURE2: case TE_CLOSURE3:
        case TE_CLOSURE4: case TE_CLOSURE5: case TE_CLOSURE6: case TE_CLOSURE7:
            out = NEW_EXPR(expr->type);
            out->function = expr->function;
            for (unsigned i = 0; i < ARITY(expr->type); ++i)
                out->parameters[i] = te_copy((te_expr*)expr->parameters[i]);
            // The closure parameter is not allocated, so the pointer is copied directly.
            out->parameters[ARITY(expr->type)] = expr->parameters[ARITY(expr->type)];
            return out;

        default:
            return nullptr;
    }
}

If there is interest, I can see about porting it back to the base library.

SirNate0 avatar Jan 11 '25 16:01 SirNate0