import copy


def tree_map(func, node):
    """
    Returns a copy of the tree, with each node replaced with ``func(node)``.

    :param func: A transformer function.
    :type func: typing.Callable[[d20.ast.ChildMixin], d20.ast.ChildMixin]
    :param node: The root of the tree to transform.
    :type node: d20.ast.ChildMixin
    """
    copied = copy.copy(node)
    for i, child in enumerate(copied.children):
        copied.set_child(i, tree_map(func, child))
    return func(copied)