@SuppressWarnings("unchecked")
    @Override
    public Expression<?> visit(SubQueryExpression<?> expr, C context) {
        QueryMetadata md = new DefaultQueryMetadata();
        md.setValidate(false);
        md.setDistinct(expr.getMetadata().isDistinct());
        md.setModifiers(expr.getMetadata().getModifiers());
        md.setUnique(expr.getMetadata().isUnique());
        for (QueryFlag flag : expr.getMetadata().getFlags()) {
            md.addFlag(new QueryFlag(flag.getPosition(), flag.getFlag().accept(this, context)));
        }
        for (Expression<?> e : expr.getMetadata().getGroupBy()) {
            md.addGroupBy(e.accept(this, context));
        }
        Predicate having = expr.getMetadata().getHaving();
        if (having != null) {
            md.addHaving((Predicate) having.accept(this, context));
        }
        for (JoinExpression je : expr.getMetadata().getJoins()) {
            md.addJoin(je.getType(), je.getTarget().accept(this, context));
            if (je.getCondition() != null) {
                md.addJoinCondition((Predicate) je.getCondition().accept(this, context));
            }
            for (JoinFlag jf : je.getFlags()) {
                md.addJoinFlag(new JoinFlag(jf.getFlag().accept(this, context), jf.getPosition()));
            }
        }
        for (OrderSpecifier<?> os : expr.getMetadata().getOrderBy()) {
            OrderSpecifier<?> os2 = new OrderSpecifier(os.getOrder(), os.getTarget().accept(this,
                    context), os.getNullHandling());
            md.addOrderBy(os2);
        }
        for (Map.Entry<ParamExpression<?>, Object> entry : expr.getMetadata().getParams()
                .entrySet()) {
            md.setParam((ParamExpression) entry.getKey().accept(this, context), entry.getValue());
        }
        if (expr.getMetadata().getProjection() != null) {
            md.setProjection(expr.getMetadata().getProjection().accept(this, context));
        }
        Predicate where = expr.getMetadata().getWhere();
        if (where != null) {
           md.addWhere((Predicate) where.accept(this, context));
        }
        if (expr.getMetadata().equals(md)) {
            return expr;
        } else {
            return new SubQueryExpressionImpl(expr.getType(), md);
        }
    }
{@code ReplaceVisitor} is a deep visitor that can be customized to replace segments of
expression trees

@param <C> context type
querydsl-core/src/main/java/com/querydsl/core/support/ReplaceVisitor.java