Skip to content

Feature Request: Function to copy te_expr #122

@SirNate0

Description

@SirNate0

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions