//! Reconstruct structured expressions from rustc's various constant representations.
use super::*;
use rustc_const_eval::interpret::{FnVal, InterpResult, interp_ok};
use rustc_middle::mir::interpret;
use rustc_middle::{mir, ty};

impl ConstantLiteral {
    /// Rustc always represents string constants as `&[u8]`, but this
    /// is not nice to consume. This associated function interpret
    /// bytes as an unicode string, and as a byte string otherwise.
    fn byte_str(bytes: Vec<u8>) -> Self {
        match String::from_utf8(bytes.clone()) {
            Ok(s) => Self::Str(s),
            Err(_) => Self::ByteStr(bytes),
        }
    }
}

#[tracing::instrument(level = "trace", skip(s))]
pub(crate) fn scalar_int_to_constant_literal<'tcx, S: UnderOwnerState<'tcx>>(
    s: &S,
    x: rustc_middle::ty::ScalarInt,
    ty: rustc_middle::ty::Ty<'tcx>,
) -> ConstantLiteral {
    match ty.kind() {
        ty::Char => ConstantLiteral::Char(
            char::try_from(x).s_expect(s, "scalar_int_to_constant_literal: expected a char"),
        ),
        ty::Bool => ConstantLiteral::Bool(
            x.try_to_bool()
                .s_expect(s, "scalar_int_to_constant_literal: expected a bool"),
        ),
        ty::Int(kind) => {
            let v = x.to_int(x.size());
            ConstantLiteral::Int(ConstantInt::Int(v, kind.sinto(s)))
        }
        ty::Uint(kind) => {
            let v = x.to_uint(x.size());
            ConstantLiteral::Int(ConstantInt::Uint(v, kind.sinto(s)))
        }
        ty::Float(kind) => {
            let v = x.to_bits_unchecked();
            bits_and_type_to_float_constant_literal(v, kind.sinto(s))
        }
        ty::Pat(inner, _) => scalar_int_to_constant_literal(s, x, *inner),
        _ => {
            let ty_sinto: Ty = ty.sinto(s);
            supposely_unreachable_fatal!(
                s,
                "scalar_int_to_constant_literal_ExpectedLiteralType";
                { ty, ty_sinto, x }
            )
        }
    }
}

/// Converts a bit-representation of a float of type `ty` to a constant literal
fn bits_and_type_to_float_constant_literal(bits: u128, ty: FloatTy) -> ConstantLiteral {
    use rustc_apfloat::{Float, ieee};
    let string = match &ty {
        FloatTy::F16 => ieee::Half::from_bits(bits).to_string(),
        FloatTy::F32 => ieee::Single::from_bits(bits).to_string(),
        FloatTy::F64 => ieee::Double::from_bits(bits).to_string(),
        FloatTy::F128 => ieee::Quad::from_bits(bits).to_string(),
    };
    ConstantLiteral::Float(string, ty)
}

impl ConstantExprKind {
    pub fn decorate(self, ty: Ty, _span: Span) -> Decorated<Self> {
        Decorated {
            contents: Box::new(self),
            ty,
        }
    }
}

/// Whether a `DefId` is a `AnonConst`. An anonymous constant is
/// generated by Rustc, hoisting every constat bits from items as
/// separate top-level items. This AnonConst mechanism is internal to
/// Rustc; we don't want to reflect that, instead we prefer inlining
/// those. `is_anon_const` is used to detect such AnonConst so that we
/// can evaluate and inline them.
pub(crate) fn is_anon_const(
    did: rustc_span::def_id::DefId,
    tcx: rustc_middle::ty::TyCtxt<'_>,
) -> bool {
    matches!(
        tcx.def_kind(did),
        rustc_hir::def::DefKind::AnonConst | rustc_hir::def::DefKind::InlineConst
    )
}

/// Evaluate a `ty::Const`.
pub fn eval_ty_constant<'tcx, S: UnderOwnerState<'tcx>>(
    s: &S,
    uv: rustc_middle::ty::UnevaluatedConst<'tcx>,
) -> Option<ty::Const<'tcx>> {
    use ty::TypeVisitableExt;
    let tcx = s.base().tcx;
    let typing_env = s.typing_env();
    if uv.has_non_region_param() {
        return None;
    }
    let span = tcx.def_span(uv.def);
    let erased_uv = tcx.erase_and_anonymize_regions(uv);
    let val = tcx
        .const_eval_resolve_for_typeck(typing_env, erased_uv, span)
        .ok()?
        .ok()?;
    let ty = tcx.type_of(uv.def).instantiate(tcx, uv.args);
    let ty = normalize(tcx, typing_env, ty);
    Some(ty::Const::new_value(tcx, val, ty))
}

impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ConstantExpr> for ty::Const<'tcx> {
    #[tracing::instrument(level = "trace", skip(s))]
    fn sinto(&self, s: &S) -> ConstantExpr {
        let tcx = s.base().tcx;
        let span = rustc_span::DUMMY_SP;
        match self.kind() {
            ty::ConstKind::Param(p) => {
                let ty = p.find_const_ty_from_env(s.param_env());
                let kind = ConstantExprKind::ConstRef { id: p.sinto(s) };
                kind.decorate(ty.sinto(s), span.sinto(s))
            }
            ty::ConstKind::Infer(..) => {
                fatal!(s[span], "ty::ConstKind::Infer node? {:#?}", self)
            }

            ty::ConstKind::Unevaluated(ucv) => {
                if s.base().options.inline_anon_consts
                    && is_anon_const(ucv.def, tcx)
                    && let Some(val) = eval_ty_constant(s, ucv)
                {
                    val.sinto(s)
                } else {
                    use rustc_middle::query::QueryKey;
                    let span = tcx
                        .def_ident_span(ucv.def)
                        .unwrap_or_else(|| ucv.def.default_span(tcx));
                    let item = translate_item_ref(s, ucv.def, ucv.args);
                    let kind = ConstantExprKind::NamedGlobal(item);
                    let ty = tcx.type_of(ucv.def).instantiate(tcx, ucv.args);
                    let ty = normalize(tcx, s.typing_env(), ty);
                    kind.decorate(ty.sinto(s), span.sinto(s))
                }
            }

            ty::ConstKind::Value(val) => valtree_to_constant_expr(s, val.valtree, val.ty, span),
            ty::ConstKind::Error(_) => fatal!(s[span], "ty::ConstKind::Error"),
            ty::ConstKind::Expr(e) => fatal!(s[span], "ty::ConstKind::Expr {:#?}", e),

            ty::ConstKind::Bound(i, bound) => {
                supposely_unreachable_fatal!(s[span], "ty::ConstKind::Bound"; {i, bound})
            }
            _ => fatal!(s[span], "unexpected case"),
        }
    }
}

impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ConstantExpr> for ty::Value<'tcx> {
    #[tracing::instrument(level = "trace", skip(s))]
    fn sinto(&self, s: &S) -> ConstantExpr {
        valtree_to_constant_expr(s, self.valtree, self.ty, rustc_span::DUMMY_SP)
    }
}

#[tracing::instrument(level = "trace", skip(s))]
pub(crate) fn valtree_to_constant_expr<'tcx, S: UnderOwnerState<'tcx>>(
    s: &S,
    valtree: rustc_middle::ty::ValTree<'tcx>,
    ty: rustc_middle::ty::Ty<'tcx>,
    span: rustc_span::Span,
) -> ConstantExpr {
    let ty = normalize(s.base().tcx, s.typing_env(), ty::Unnormalized::new_wip(ty));

    let kind = match (&*valtree, ty.kind()) {
        (_, ty::Ref(_, inner_ty, _)) => {
            ConstantExprKind::Borrow(valtree_to_constant_expr(s, valtree, *inner_ty, span))
        }
        (ty::ValTreeKind::Branch(valtrees), ty::Str) => {
            let bytes = valtrees
                .iter()
                .map(|x| match x.try_to_leaf() {
                    Some(leaf) => leaf.to_u8(),
                    None => fatal!(
                        s[span],
                        "Expected a flat list of leaves while translating \
                            a str literal, got a arbitrary valtree."
                    ),
                })
                .collect();
            ConstantExprKind::Literal(ConstantLiteral::byte_str(bytes))
        }
        (ty::ValTreeKind::Branch(fields), ty::Array(..) | ty::Slice(..) | ty::Tuple(..)) => {
            let fields = fields.iter().map(|field| field.sinto(s)).collect();
            match ty.kind() {
                ty::Array(..) | ty::Slice(..) => ConstantExprKind::Array { fields },
                ty::Tuple(_) => ConstantExprKind::Tuple { fields },
                _ => unreachable!(),
            }
        }
        (ty::ValTreeKind::Branch(_), ty::Adt(def, _)) => {
            let contents: rustc_middle::ty::DestructuredAdtConst =
                ty::Value { valtree, ty }.destructure_adt_const();

            let fields = contents.fields.iter().copied();
            let variant_idx = contents.variant;
            let variant_def = &def.variant(variant_idx);

            ConstantExprKind::Adt {
                kind: get_variant_kind(def, variant_idx, s),
                fields: fields
                    .into_iter()
                    .zip(&variant_def.fields)
                    .map(|(value, field)| ConstantFieldExpr {
                        field: field.did.sinto(s),
                        value: value.sinto(s),
                    })
                    .collect(),
            }
        }
        (ty::ValTreeKind::Leaf(x), ty::RawPtr(_, _)) => {
            let raw_address = x.to_bits_unchecked();
            ConstantExprKind::Literal(ConstantLiteral::PtrNoProvenance(raw_address))
        }
        (ty::ValTreeKind::Leaf(x), _) => {
            ConstantExprKind::Literal(scalar_int_to_constant_literal(s, *x, ty))
        }
        _ => supposely_unreachable_fatal!(
            s[span], "valtree_to_expr";
            {valtree, ty}
        ),
    };
    kind.decorate(ty.sinto(s), span.sinto(s))
}

/// Use the const-eval interpreter to convert an evaluated operand back to a structured
/// constant expression.
fn op_to_const<'tcx, S: UnderOwnerState<'tcx>>(
    s: &S,
    span: rustc_span::Span,
    ecx: &rustc_const_eval::const_eval::CompileTimeInterpCx<'tcx>,
    op: rustc_const_eval::interpret::OpTy<'tcx>,
) -> InterpResult<'tcx, ConstantExpr> {
    use rustc_const_eval::interpret::Projectable;
    // Code inspired from `try_destructure_mir_constant_for_user_output` and
    // `const_eval::eval_queries::op_to_const`.
    let tcx = s.base().tcx;
    let ty = op.layout.ty;
    // Helper for struct-likes.
    let read_fields = |of: rustc_const_eval::interpret::OpTy<'tcx>, field_count| {
        (0..field_count).map(move |i| {
            let field_op = ecx.project_field(&of, rustc_abi::FieldIdx::from_usize(i))?;
            op_to_const(s, span, ecx, field_op)
        })
    };
    let kind = match ty.kind() {
        // Detect statics
        _ if let Some(place) = op.as_mplace_or_imm().left()
            && let ptr = place.ptr()
            && let (alloc_id, _, _) = ecx.ptr_get_alloc_id(ptr, 0)?
            && let interpret::GlobalAlloc::Static(did) = tcx.global_alloc(alloc_id) =>
        {
            let item = translate_item_ref(s, did, ty::GenericArgsRef::default());
            ConstantExprKind::NamedGlobal(item)
        }
        ty::Char | ty::Bool | ty::Uint(_) | ty::Int(_) | ty::Float(_) => {
            let scalar = ecx.read_scalar(&op)?;
            let scalar_int = scalar.try_to_scalar_int().unwrap();
            let lit = scalar_int_to_constant_literal(s, scalar_int, ty);
            ConstantExprKind::Literal(lit)
        }
        ty::Adt(adt_def, ..) if adt_def.is_union() => {
            ConstantExprKind::Todo("Cannot translate constant of union type".into())
        }
        ty::Adt(adt_def, ..) => {
            let variant = ecx.read_discriminant(&op)?;
            let op = if adt_def.is_enum() {
                ecx.project_downcast(&op, variant)?
            } else {
                op
            };
            let field_count = adt_def.variants()[variant].fields.len();
            let fields = read_fields(op, field_count)
                .zip(&adt_def.variant(variant).fields)
                .map(|(value, field)| {
                    interp_ok(ConstantFieldExpr {
                        field: field.did.sinto(s),
                        value: value?,
                    })
                })
                .collect::<InterpResult<Vec<_>>>()?;
            ConstantExprKind::Adt {
                kind: get_variant_kind(adt_def, variant, s),
                fields,
            }
        }
        ty::Closure(def_id, args) => {
            // A closure is essentially an adt with funky generics and some builtin impls.
            let def_id: DefId = def_id.sinto(s);
            let field_count = args.as_closure().upvar_tys().len();
            let fields = read_fields(op, field_count)
                .map(|value| {
                    interp_ok(ConstantFieldExpr {
                        // HACK: Closure fields don't have their own def_id, but Charon doesn't use
                        // field DefIds so we put a dummy one.
                        field: def_id.clone(),
                        value: value?,
                    })
                })
                .collect::<InterpResult<Vec<_>>>()?;
            ConstantExprKind::Adt {
                kind: VariantKind::Struct,
                fields,
            }
        }
        ty::Tuple(args) => {
            let fields = read_fields(op, args.len()).collect::<InterpResult<Vec<_>>>()?;
            ConstantExprKind::Tuple { fields }
        }
        ty::Array(..) | ty::Slice(..) => {
            let len = op.len(ecx)?;
            let fields = (0..len)
                .map(|i| {
                    let op = ecx.project_index(&op, i)?;
                    op_to_const(s, span, ecx, op)
                })
                .collect::<InterpResult<Vec<_>>>()?;
            ConstantExprKind::Array { fields }
        }
        ty::Str => {
            let str = ecx.read_str(&op.assert_mem_place())?;
            ConstantExprKind::Literal(ConstantLiteral::Str(str.to_owned()))
        }
        ty::FnDef(def_id, args) => {
            let item = translate_item_ref(s, *def_id, args);
            ConstantExprKind::FnDef(item)
        }
        ty::FnPtr(..) => {
            let fn_ptr = ecx.read_pointer(&op)?;
            let FnVal::Instance(instance) = ecx.get_ptr_fn(fn_ptr)?;
            let def_id = instance.def_id();
            let generics = instance.args;
            let fun = translate_item_ref(s, def_id, generics);
            ConstantExprKind::FnPtr(fun)
        }
        ty::RawPtr(..) | ty::Ref(..) => {
            if let Some(op) = ecx.deref_pointer(&op).discard_err() {
                // Valid pointer case
                let val = op_to_const(s, span, ecx, op.into())?;
                match ty.kind() {
                    ty::Ref(..) => ConstantExprKind::Borrow(val),
                    ty::RawPtr(.., mutability) => ConstantExprKind::RawBorrow {
                        arg: val,
                        mutability: mutability.sinto(s),
                    },
                    _ => unreachable!(),
                }
            } else {
                // Invalid pointer; try reading it as a raw address
                let scalar = ecx.read_scalar(&op)?;
                let scalar_int = scalar.try_to_scalar_int().unwrap();
                let v = scalar_int.to_uint(scalar_int.size());
                let lit = ConstantLiteral::PtrNoProvenance(v);
                ConstantExprKind::Literal(lit)
            }
        }
        ty::Pat(..) => {
            let op = ecx.project_field(&op, FieldIdx::from_u16(0))?;
            *op_to_const(s, span, ecx, op)?.contents
        }
        ty::Dynamic(..)
        | ty::Foreign(..)
        | ty::UnsafeBinder(..)
        | ty::CoroutineClosure(..)
        | ty::Coroutine(..)
        | ty::CoroutineWitness(..) => ConstantExprKind::Todo("Unhandled constant type".into()),
        ty::Alias(..) | ty::Param(..) | ty::Bound(..) | ty::Placeholder(..) | ty::Infer(..) => {
            fatal!(s[span], "Encountered evaluated constant of non-monomorphic type"; {op})
        }
        ty::Never | ty::Error(..) => {
            fatal!(s[span], "Encountered evaluated constant of invalid type"; {ty})
        }
    };
    let val = kind.decorate(ty.sinto(s), span.sinto(s));
    interp_ok(val)
}

pub fn const_value_to_constant_expr<'tcx, S: UnderOwnerState<'tcx>>(
    s: &S,
    ty: rustc_middle::ty::Ty<'tcx>,
    val: mir::ConstValue,
    span: rustc_span::Span,
) -> InterpResult<'tcx, ConstantExpr> {
    let tcx = s.base().tcx;
    let typing_env = s.typing_env();
    let (ecx, op) =
        rustc_const_eval::const_eval::mk_eval_cx_for_const_val(tcx.at(span), typing_env, val, ty)
            .unwrap();
    op_to_const(s, span, &ecx, op)
}
