refactor(library/deep_copy): use replace to implement deep_copy

Signed-off-by: Leonardo de Moura <leonardo@microsoft.com>
This commit is contained in:
Leonardo de Moura 2014-06-11 13:48:28 -07:00
parent 4f83b1a50b
commit 1c5d3295cc

View file

@ -6,10 +6,11 @@ Author: Leonardo de Moura
*/
#include "util/buffer.h"
#include "kernel/expr.h"
#include "kernel/expr_maps.h"
#include "kernel/replace_fn.h"
namespace lean {
expr copy(expr const & a) {
scoped_expr_caching scope(false);
switch (a.kind()) {
case expr_kind::Var: return mk_var(var_idx(a));
case expr_kind::Constant: return mk_constant(const_name(a), const_levels(a));
@ -25,44 +26,13 @@ expr copy(expr const & a) {
lean_unreachable(); // LCOV_EXCL_LINE
}
/** \brief Implements deep copy of kernel expressions. */
class deep_copy_fn {
expr_cell_map<expr> m_cache;
expr apply(expr const & a) {
bool sh = false;
if (is_shared(a)) {
auto r = m_cache.find(a.raw());
if (r != m_cache.end())
return r->second;
sh = true;
}
expr r;
switch (a.kind()) {
case expr_kind::Var:
case expr_kind::Constant:
case expr_kind::Sort:
case expr_kind::Macro: r = copy(a); break;
case expr_kind::App: r = mk_app(apply(app_fn(a)), apply(app_arg(a))); break;
case expr_kind::Lambda: r = mk_lambda(binding_name(a), apply(binding_domain(a)), apply(binding_body(a))); break;
case expr_kind::Pi: r = mk_pi(binding_name(a), apply(binding_domain(a)), apply(binding_body(a))); break;
case expr_kind::Let: r = mk_let(let_name(a), apply(let_type(a)), apply(let_value(a)), apply(let_body(a))); break;
case expr_kind::Meta: r = mk_metavar(mlocal_name(a), apply(mlocal_type(a))); break;
case expr_kind::Local: r = mk_local(mlocal_name(a), local_pp_name(a), apply(mlocal_type(a))); break;
}
if (sh)
m_cache.insert(std::make_pair(a.raw(), r));
return r;
}
public:
/**
\brief Return a new expression that is equal to the given
argument, but does not share any memory cell with it.
*/
expr operator()(expr const & a) {
scoped_expr_caching set(false);
return apply(a);
}
};
expr deep_copy(expr const & e) { return deep_copy_fn()(e); }
expr deep_copy(expr const & e) {
scoped_expr_caching scope(false);
return replace(e, [](expr const & e, unsigned) {
if (is_atomic(e))
return some_expr(copy(e));
else
return none_expr();
});
}
}