Skip to content

CloneIn trait for AST nodes #4284

@overlookmotel

Description

@overlookmotel

We need to be able to clone AST nodes. But we cannot implement Clone on most AST types because oxc_allocator::Box is not Clone.

There is a good reason for that - Box stores the value it owns in arena allocator, so there is no Box::new method, only Box::new_in which takes an &Allocator param for the arena to allocate it in.

I propose a new trait CloneIn:

trait CloneIn<'alloc> {
    fn clone_in(&self, allocator: &'alloc Allocator) -> Self;
}

Impl for oxc_allocator::Box:

impl<'alloc, T> CloneIn<'alloc> for Box<'alloc, T>
where
    T: CloneIn<'alloc>,
{
    fn clone_in(&self, allocator: &'alloc Allocator) -> Self {
        Box::new_in(self.deref().clone_in(allocator), allocator)
    }
}

(I'm actually not sure if I have this right - maybe 'alloc lifetime should be on fn clone_in<'alloc> not CloneIn<'alloc>)

Same as Clone, CloneIn can be implemented on any type where all its fields/variants are also CloneIn.

We could make a derive macro for CloneIn so can just #[derive(CloneIn)] on AST types.

NB: clone_in should always clone into the arena of the provided allocator, which may be different from the arena that self is in. i.e. you can use clone_in to copy objects from one arena to another.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Priority

None yet

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions