Coerce in rustc_hir_typeck::coercion - Rust
Description: API documentation for the Rust `Coerce` struct in crate `rustc_hir_typeck`.

Skip to main content

## Coerce

# Struct Coerce

Source

    struct Coerce<'a, 'tcx> {
        fcx: &'a FnCtxt<'a, 'tcx>,
        cause: ObligationCause<'tcx>,
        use_lub: bool,
        allow_two_phase: AllowTwoPhase,
        coerce_never: bool,
    }

## Fields§

§`fcx: &'a FnCtxt<'a, 'tcx>`§`cause: ObligationCause<'tcx>`§`use_lub: bool`§`allow_two_phase: AllowTwoPhase`

Determines whether or not allow_two_phase_borrow is set on any autoref adjustments we create while coercing. We don’t want to allow deref coercions to create two-phase borrows, at least initially, but we do need two-phase borrows for function argument reborrows. See #47489 and #48598 See docs on the “AllowTwoPhase” type for a more detailed discussion

§`coerce_never: bool`

Whether we allow `NeverToAny` coercions. This is unsound if we’re coercing a place expression without it counting as a read in the MIR. This is a side-effect of HIR not really having a great distinction between places and values.

## Implementations§

Source§

### impl<'f, 'tcx> Coerce<'f, 'tcx>

Source

#### fn new( fcx: &'f FnCtxt<'f, 'tcx>, cause: ObligationCause<'tcx>, allow_two_phase: AllowTwoPhase, coerce_never: bool, ) -> Self

Source

#### fn unify_raw( &self, a: Ty<'tcx>, b: Ty<'tcx>, leak_check: ForceLeakCheck, ) -> InferResult<'tcx, Ty<'tcx>>

Source

#### fn unify( &self, a: Ty<'tcx>, b: Ty<'tcx>, leak_check: ForceLeakCheck, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Unify two types (using sub or lub).

Source

#### fn unify_and( &self, a: Ty<'tcx>, b: Ty<'tcx>, adjustments: impl IntoIterator<Item = Adjustment<'tcx>>, final_adjustment: Adjust, leak_check: ForceLeakCheck, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Unify two types (using sub or lub) and produce a specific coercion.

Source

#### fn coerce( &self, a: Ty<'tcx>, b: Ty<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Source

#### fn coerce_from_inference_variable( &self, a: Ty<'tcx>, b: Ty<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Coercing from an inference variable. In this case, we have no information about the source type, so we can’t really do a true coercion and we always fall back to subtyping (`unify_and`).

Source

#### fn coerce_to_ref( &self, a: Ty<'tcx>, b: Ty<'tcx>, r_b: Region<'tcx>, mutbl_b: Mutability, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Handles coercing some arbitrary type `a` to some reference (`b`). This handles a few cases:

- Introducing reborrows to give more flexible lifetimes
- Deref coercions to allow `&T` to coerce to `&T::Target`
- Coercing mutable references to immutable references These coercions can be freely intermixed, for example we are able to coerce `&mut T` to `&mut T::Target`.

Source

#### fn coerce_unsized( &self, source: Ty<'tcx>, target: Ty<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Performs [unsized coercion] by emulating a fulfillment loop on a `CoerceUnsized` goal until all `CoerceUnsized` and `Unsize` goals are successfully selected.

unsized coercion

Source

#### fn coerce_unsized_old_solver( &self, obligation: Obligation<'tcx, Predicate<'tcx>>, coercion: &mut InferOk<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>, coerce_unsized_did: DefId, unsize_did: DefId, ) -> Result<(), TypeError<'tcx>>

Source

#### fn unpin_obligation( &self, source: Ty<'tcx>, target: Ty<'tcx>, ty: Ty<'tcx>, ) -> PredicateObligation<'tcx>

Create an obligation for `ty: Unpin`, where .

Source

#### fn maybe_pin_ref_to_ref( &self, a: Ty<'tcx>, b: Ty<'tcx>, ) -> Option<CoerceMaybePinnedRef<'tcx>>

Checks if the given types are compatible for coercion from a pinned reference to a normal reference.

Source

#### fn coerce_pin_ref_to_ref( &self, _: CoerceMaybePinnedRef<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Coerces from a pinned reference to a normal reference.

Source

#### fn maybe_to_pin_ref( &self, a: Ty<'tcx>, b: Ty<'tcx>, ) -> Option<CoerceMaybePinnedRef<'tcx>>

Checks if the given types are compatible for coercion to a pinned reference.

Source

#### fn coerce_to_pin_ref( &self, _: CoerceMaybePinnedRef<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Applies reborrowing and auto-borrowing that results to `Pin<&T>` or `Pin<&mut T>`:

Currently we only support the following coercions:

- Reborrowing `Pin<&mut T>` -> `Pin<&mut T>`
- Reborrowing `Pin<&T>` -> `Pin<&T>`
- Auto-borrowing `&mut T` -> `Pin<&mut T>` where `T: Unpin`
- Auto-borrowing `&mut T` -> `Pin<&T>` where `T: Unpin`
- Auto-borrowing `&T` -> `Pin<&T>` where `T: Unpin`

In the future we might want to support other reborrowing coercions, such as:

- `Pin<Box<T>>` as `Pin<&T>`
- `Pin<Box<T>>` as `Pin<&mut T>`

Source

#### fn coerce_reborrow( &self, a: Ty<'tcx>, b: Ty<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Applies generic exclusive reborrowing on type implementing `Reborrow`.

Source

#### fn coerce_shared_reborrow( &self, a: Ty<'tcx>, b: Ty<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Applies generic exclusive reborrowing on type implementing `Reborrow`.

Source

#### fn coerce_from_fn_pointer( &self, a: Ty<'tcx>, a_sig: PolyFnSig<'tcx>, b: Ty<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Source

#### fn coerce_from_fn_item( &self, a: Ty<'tcx>, b: Ty<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Source

#### fn coerce_closure_to_fn( &self, a: Ty<'tcx>, b: Ty<'tcx>, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

Attempts to coerce from a closure to a function pointer. Fails if the closure has any upvars.

Source

#### fn coerce_to_raw_ptr( &self, a: Ty<'tcx>, b: Ty<'tcx>, mutbl_b: Mutability, ) -> InferResult<'tcx, (Vec<Adjustment<'tcx>>, Ty<'tcx>)>

## Methods from Deref<Target = FnCtxt<'a, 'tcx>>§

Source

#### pub(crate) fn check_expr_match( &self, expr: &'tcx Expr<'tcx>, scrut: &'tcx Expr<'tcx>, arms: &'tcx [Arm<'tcx>], orig_expected: Expectation<'tcx>, match_src: MatchSource, ) -> Ty<'tcx>

Source

#### fn explain_never_type_coerced_to_unit( &self, err: &mut Diag<'_>, arm: &Arm<'tcx>, arm_ty: Ty<'tcx>, prior_arm: Option<(Option<HirId>, Ty<'tcx>, Span)>, expr: &Expr<'tcx>, )

Source

#### fn suggest_removing_semicolon_for_coerce( &self, diag: &mut Diag<'_>, expr: &Expr<'tcx>, arm_ty: Ty<'tcx>, prior_arm: Option<(Option<HirId>, Ty<'tcx>, Span)>, )

Source

#### fn warn_arms_when_scrutinee_diverges(&self, arms: &'tcx [Arm<'tcx>])

When the previously checked expression (the scrutinee) diverges, warn the user about the match arms being unreachable.

Source

#### pub(crate) fn if_fallback_coercion( &self, if_span: Span, cond_expr: &'tcx Expr<'tcx>, then_expr: &'tcx Expr<'tcx>, coercion: &mut CoerceMany<'tcx>, ) -> bool

Handle the fallback arm of a desugared if(-let) like a missing else.

Returns `true` if there was an error forcing the coercion to the `()` type.

Source

#### fn is_from_assert_macro(&self, span: Span) -> bool

Check if the span comes from an assert-like macro expansion.

Source

#### fn explain_if_expr( &self, err: &mut Diag<'_>, ret_reason: Option<(Span, String)>, if_span: Span, cond_expr: &'tcx Expr<'tcx>, then_expr: &'tcx Expr<'tcx>, error: &mut bool, )

Explain why `if` expressions without `else` evaluate to `()` and detect likely irrefutable `if let PAT = EXPR {}` expressions that could be turned into `let PAT = EXPR;`.

Source

#### pub(crate) fn maybe_get_coercion_reason( &self, hir_id: HirId, sp: Span, ) -> Option<(Span, String)>

Source

#### pub(crate) fn if_cause( &self, expr_id: HirId, else_expr: &'tcx Expr<'tcx>, tail_defines_return_position_impl_trait: Option<LocalDefId>, ) -> ObligationCause<'tcx>

Source

#### pub(crate) fn demand_scrutinee_type( &self, scrut: &'tcx Expr<'tcx>, contains_ref_bindings: Option<Mutability>, no_arms: bool, ) -> Ty<'tcx>

Source

#### pub(crate) fn return_position_impl_trait_from_match_expectation( &self, expectation: Expectation<'tcx>, ) -> Option<LocalDefId>

Source

#### pub(crate) fn autoderef( &'a self, span: Span, base_ty: Ty<'tcx>, ) -> Autoderef<'a, 'tcx>

Source

#### pub(crate) fn try_overloaded_deref( &self, span: Span, base_ty: Ty<'tcx>, ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>>

Source

#### pub(crate) fn adjust_steps( &self, autoderef: &Autoderef<'a, 'tcx>, ) -> Vec<Adjustment<'tcx>>

Returns the adjustment steps.

Source

#### pub(crate) fn adjust_steps_as_infer_ok( &self, autoderef: &Autoderef<'a, 'tcx>, ) -> InferOk<'tcx, Vec<Adjustment<'tcx>>>

Source

#### pub(crate) fn check_expr_call( &self, call_expr: &'tcx Expr<'tcx>, callee_expr: &'tcx Expr<'tcx>, arg_exprs: &'tcx [Expr<'tcx>], expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### pub(crate) fn check_call_abi(&self, abi: ExternAbi, span: Span)

Can a function with this ABI be called with a rust call expression?

Some ABIs cannot be called from rust, either because rust does not know how to generate code for the call, or because a call does not semantically make sense.

Source

#### fn try_overloaded_call_step( &self, call_expr: &'tcx Expr<'tcx>, callee_expr: &'tcx Expr<'tcx>, arg_exprs: &'tcx [Expr<'tcx>], autoderef: &Autoderef<'a, 'tcx>, ) -> Option<CallStep<'tcx>>

Source

#### fn try_overloaded_call_traits( &self, call_expr: &Expr<'_>, adjusted_ty: Ty<'tcx>, opt_arg_exprs: Option<&'tcx [Expr<'tcx>]>, ) -> Option<(Option<Adjustment<'tcx>>, MethodCallee<'tcx>)>

Source

#### fn is_scalable_vector_ctor(&self, callee_ty: Ty<'_>) -> bool

Source

#### fn identify_bad_closure_def_and_call( &self, err: &mut Diag<'_>, hir_id: HirId, callee_node: &ExprKind<'_>, callee_span: Span, )

Give appropriate suggestion when encountering `||{/* not callable */}()`, where the likely intention is to call the closure, suggest `(||{})()`. (#55851)

Source

#### fn maybe_suggest_bad_array_definition( &self, err: &mut Diag<'_>, call_expr: &'tcx Expr<'tcx>, callee_expr: &'tcx Expr<'tcx>, ) -> bool

Give appropriate suggestion when encountering `[("a", 0) ("b", 1)]`, where the likely intention is to create an array containing tuples.

Source

#### fn confirm_builtin_call( &self, call_expr: &'tcx Expr<'tcx>, callee_expr: &'tcx Expr<'tcx>, callee_ty: Ty<'tcx>, arg_exprs: &'tcx [Expr<'tcx>], expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### fn suggest_call_as_method( &self, diag: &mut Diag<'_>, segment: &'tcx PathSegment<'tcx>, arg_exprs: &'tcx [Expr<'tcx>], call_expr: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, )

Attempts to reinterpret `method(rcvr, args...)` as `rcvr.method(args...)` and suggesting the fix if the method probe is successful.

Source

#### fn report_invalid_callee( &self, call_expr: &'tcx Expr<'tcx>, callee_expr: &'tcx Expr<'tcx>, callee_ty: Ty<'tcx>, arg_exprs: &'tcx [Expr<'tcx>], ) -> ErrorGuaranteed

Source

#### fn confirm_deferred_closure_call( &self, call_expr: &'tcx Expr<'tcx>, arg_exprs: &'tcx [Expr<'tcx>], expected: Expectation<'tcx>, closure_def_id: LocalDefId, fn_sig: FnSig<'tcx>, ) -> Ty<'tcx>

Source

#### pub(crate) fn enforce_context_effects( &self, call_hir_id: Option<HirId>, span: Span, callee_did: DefId, callee_args: GenericArgsRef<'tcx>, )

Source

#### fn confirm_overloaded_call( &self, call_expr: &'tcx Expr<'tcx>, arg_exprs: &'tcx [Expr<'tcx>], expected: Expectation<'tcx>, method: MethodCallee<'tcx>, ) -> Ty<'tcx>

Source

#### fn pointer_kind( &self, t: Ty<'tcx>, span: Span, ) -> Result<Option<PointerKind<'tcx>>, ErrorGuaranteed>

Returns the kind of unsize information of t, or None if t is unknown.

Source

#### pub(crate) fn check_expr_closure( &self, closure: &Closure<'tcx>, expr_span: Span, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### fn deduce_closure_signature( &self, expected_ty: Ty<'tcx>, closure_kind: ClosureKind, ) -> (Option<ExpectedSig<'tcx>>, Option<ClosureKind>)

Given the expected type, figures out what it can about this closure we are about to type check:

Source

#### fn deduce_closure_signature_from_predicates( &self, expected_ty: Ty<'tcx>, closure_kind: ClosureKind, predicates: impl DoubleEndedIterator<Item = (Predicate<'tcx>, Span)>, ) -> (Option<ExpectedSig<'tcx>>, Option<ClosureKind>)

Source

#### fn deduce_sig_from_projection( &self, cause_span: Option<Span>, closure_kind: ClosureKind, projection: PolyProjectionPredicate<'tcx>, ) -> Option<ExpectedSig<'tcx>>

Given a projection like “<F as Fn(X)>::Result == Y”, we can deduce everything we need to know about a closure or coroutine.

The `cause_span` should be the span that caused us to have this expected signature, or `None` if we can’t readily know that.

Source

#### fn extract_sig_from_projection( &self, cause_span: Option<Span>, projection: PolyProjectionPredicate<'tcx>, ) -> Option<ExpectedSig<'tcx>>

Given an `FnOnce::Output` or `AsyncFn::Output` projection, extract the args and return type to infer a `ty::PolyFnSig` for the closure.

Source

#### fn extract_sig_from_projection_and_future_bound( &self, cause_span: Option<Span>, projection: PolyProjectionPredicate<'tcx>, ) -> Option<ExpectedSig<'tcx>>

When an async closure is passed to a function that has a “two-part” `Fn` and `Future` trait bound, like:

    use std::future::Future;

    fn not_exactly_an_async_closure<F, Fut>(_f: F)
    where
        F: FnOnce(String, u32) -> Fut,
        Fut: Future<Output = i32>,
    {}

The we want to be able to extract the signature to guide inference in the async closure. We will have two projection predicates registered in this case. First, we identify the `FnOnce<Args, Output = ?Fut>` bound, and if the output type is an inference variable `?Fut`, we check if that is bounded by a `Future<Output = Ty>` projection.

This function is actually best-effort with the return type; if we don’t find a `Future` projection, we still will return arguments that we extracted from the `FnOnce` projection, and the output will be an unconstrained type variable instead.

Source

#### fn sig_of_closure( &self, expr_def_id: LocalDefId, decl: &FnDecl<'tcx>, closure_kind: ClosureKind, expected_sig: Option<ExpectedSig<'tcx>>, ) -> ClosureSignatures<'tcx>

Source

#### fn sig_of_closure_no_expectation( &self, expr_def_id: LocalDefId, decl: &FnDecl<'tcx>, closure_kind: ClosureKind, ) -> ClosureSignatures<'tcx>

If there is no expected signature, then we will convert the types that the user gave into a signature.

Source

#### fn sig_of_closure_with_expectation( &self, expr_def_id: LocalDefId, decl: &FnDecl<'tcx>, closure_kind: ClosureKind, expected_sig: ExpectedSig<'tcx>, ) -> ClosureSignatures<'tcx>

Invoked to compute the signature of a closure expression. This combines any user-provided type annotations (e.g., `|x: u32| -> u32 { .. }`) with the expected signature.

The approach is as follows:

- Let `S` be the (higher-ranked) signature that we derive from the user’s annotations.
- Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
  - If we have no expectation `E`, then the signature of the closure is `S`.
  - Otherwise, the signature of the closure is E. Moreover:
    - Skolemize the late-bound regions in `E`, yielding `E'`.
    - Instantiate all the late-bound regions bound in the closure within `S` with fresh (existential) variables, yielding `S'`
    - Require that `E' = S'`
      - We could use some kind of subtyping relationship here, I imagine, but equality is easier and works fine for our purposes.

The key intuition here is that the user’s types must be valid from “the inside” of the closure, but the expectation ultimately drives the overall signature.

##### §Examples

ⓘ

    fn with_closure<F>(_: F)
      where F: Fn(&u32) -> &u32 { .. }

    with_closure(|x: &u32| { ... })

Here:

- E would be `fn(&u32) -> &u32`.
- S would be `fn(&u32) -> ?T`
- E’ is `&'!0 u32 -> &'!0 u32`
- S’ is `&'?0 u32 -> ?T`

S’ can be unified with E’ with `['?0 = '!0, ?T = &'!10 u32]`.

##### §Arguments

- `expr_def_id`: the `LocalDefId` of the closure expression
- `decl`: the HIR declaration of the closure
- `body`: the body of the closure
- `expected_sig`: the expected signature (if any). Note that this is missing a binder: that is, there may be late-bound regions with depth 1, which are bound then by the closure.

Source

#### fn sig_of_closure_with_mismatched_number_of_arguments( &self, expr_def_id: LocalDefId, decl: &FnDecl<'tcx>, expected_sig: ExpectedSig<'tcx>, ) -> ClosureSignatures<'tcx>

Source

#### fn merge_supplied_sig_with_expectation( &self, expr_def_id: LocalDefId, decl: &FnDecl<'tcx>, closure_kind: ClosureKind, expected_sigs: ClosureSignatures<'tcx>, ) -> InferResult<'tcx, ClosureSignatures<'tcx>>

Enforce the user’s types against the expectation. See `sig_of_closure_with_expectation` for details on the overall strategy.

Source

#### fn supplied_sig_of_closure( &self, expr_def_id: LocalDefId, decl: &FnDecl<'tcx>, closure_kind: ClosureKind, ) -> PolyFnSig<'tcx>

If there is no expected signature, then we will convert the types that the user gave into a signature.

Also, record this closure signature for later.

Source

#### fn deduce_future_output_from_obligations( &self, body_def_id: LocalDefId, ) -> Option<Ty<'tcx>>

Invoked when we are translating the coroutine that results from desugaring an `async fn`. Returns the “sugared” return type of the `async fn` – that is, the return type that the user specified. The “desugared” return type is an `impl Future<Output = T>`, so we do this by searching through the obligations to extract the `T`.

Source

#### fn deduce_future_output_from_projection( &self, cause_span: Span, predicate: PolyProjectionPredicate<'tcx>, ) -> Option<Ty<'tcx>>

Given a projection like

`<X as Future>::Output = T`

where `X` is some type that has no late-bound regions, returns `Some(T)`. If the projection is for some other trait, returns `None`.

Source

#### fn error_sig_of_closure( &self, decl: &FnDecl<'tcx>, guar: ErrorGuaranteed, ) -> PolyFnSig<'tcx>

Converts the types that the user supplied, in case that doing so should yield an error, but returns back a signature where all parameters are of type `ty::Error`.

Source

#### fn closure_sigs( &self, expr_def_id: LocalDefId, bound_sig: PolyFnSig<'tcx>, ) -> ClosureSignatures<'tcx>

Source

#### pub(crate) fn coerce( &self, expr: &'tcx Expr<'tcx>, expr_ty: Ty<'tcx>, target: Ty<'tcx>, allow_two_phase: AllowTwoPhase, cause: Option<ObligationCause<'tcx>>, ) -> RelateResult<'tcx, Ty<'tcx>>

Attempt to coerce an expression to a type, and return the adjusted type of the expression, if successful. Adjustments are only recorded if the coercion succeeded. The expressions must not have any preexisting adjustments.

Source

#### pub(crate) fn may_coerce(&self, expr_ty: Ty<'tcx>, target_ty: Ty<'tcx>) -> bool

Probe whether `expr_ty` can be coerced to `target_ty`. This has no side-effects, and may return false positives if types are not yet fully constrained by inference.

Returns false if the coercion is not possible, or if the coercion creates any sub-obligations that result in errors.

This should only be used for diagnostics.

Source

#### pub(crate) fn deref_steps_for_suggestion( &self, expr_ty: Ty<'tcx>, target: Ty<'tcx>, ) -> Option<usize>

Given a type and a target type, this function will calculate and return how many dereference steps needed to coerce `expr_ty` to `target`. If it’s not possible, return `None`.

Source

#### pub(crate) fn deref_once_mutably_for_diagnostic( &self, expr_ty: Ty<'tcx>, ) -> Option<Ty<'tcx>>

Given a type, this function will calculate and return the type given for `<Ty as Deref>::Target` only if `Ty` also implements `DerefMut`.

This function is for diagnostics only, since it does not register trait or region sub-obligations. (presumably we could, but it’s not particularly important for diagnostics…)

Source

#### fn sig_for_coerce_lub( &self, ty: Ty<'tcx>, closure_upvars_terr: TypeError<'tcx>, ) -> Result<PolyFnSig<'tcx>, TypeError<'tcx>>

Source

#### fn sig_for_fn_def_coercion( &self, fndef: Ty<'tcx>, expected_safety: Option<Safety>, ) -> Result<PolyFnSig<'tcx>, TypeError<'tcx>>

Source

#### fn sig_for_closure_coercion( &self, closure: Ty<'tcx>, expected_safety: Option<Safety>, closure_upvars_terr: TypeError<'tcx>, ) -> Result<PolyFnSig<'tcx>, TypeError<'tcx>>

Source

#### fn try_find_coercion_lub( &self, cause: &ObligationCause<'tcx>, exprs: &[&'tcx Expr<'tcx>], prev_ty: Ty<'tcx>, new: &Expr<'_>, new_ty: Ty<'tcx>, ) -> RelateResult<'tcx, Ty<'tcx>>

Given some expressions, their known unified type and another expression, tries to unify the types, potentially inserting coercions on any of the provided expressions and returns their LUB (aka “common supertype”).

This is really an internal helper. From outside the coercion module, you should instantiate a `CoerceMany` instance.

Source

#### pub(crate) fn emit_type_mismatch_suggestions( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, expr_ty: Ty<'tcx>, expected: Ty<'tcx>, expected_ty_expr: Option<&'tcx Expr<'tcx>>, error: Option<TypeError<'tcx>>, )

Source

#### pub(crate) fn emit_coerce_suggestions( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, expr_ty: Ty<'tcx>, expected: Ty<'tcx>, expected_ty_expr: Option<&'tcx Expr<'tcx>>, error: Option<TypeError<'tcx>>, )

Source

#### fn adjust_expr_for_assert_eq_macro( &self, found_expr: &mut &'tcx Expr<'tcx>, expected_expr: &mut Option<&'tcx Expr<'tcx>>, )

Really hacky heuristic to remap an `assert_eq!` error to the user expressions provided to the macro.

Source

#### pub(crate) fn demand_suptype( &self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>, )

Requires that the two types unify, and prints an error message if they don’t.

Source

#### pub(crate) fn demand_suptype_diag( &'a self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>, ) -> Result<(), Diag<'a>>

Source

#### pub(crate) fn demand_suptype_with_origin( &'a self, cause: &ObligationCause<'tcx>, expected: Ty<'tcx>, actual: Ty<'tcx>, ) -> Result<(), Diag<'a>>

Source

#### pub(crate) fn demand_eqtype( &self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>, )

Source

#### pub(crate) fn demand_eqtype_diag( &'a self, sp: Span, expected: Ty<'tcx>, actual: Ty<'tcx>, ) -> Result<(), Diag<'a>>

Source

#### pub(crate) fn demand_eqtype_with_origin( &'a self, cause: &ObligationCause<'tcx>, expected: Ty<'tcx>, actual: Ty<'tcx>, ) -> Result<(), Diag<'a>>

Source

#### pub(crate) fn demand_coerce( &self, expr: &'tcx Expr<'tcx>, checked_ty: Ty<'tcx>, expected: Ty<'tcx>, expected_ty_expr: Option<&'tcx Expr<'tcx>>, allow_two_phase: AllowTwoPhase, ) -> Ty<'tcx>

Source

#### pub(crate) fn demand_coerce_diag( &'a self, expr: &'tcx Expr<'tcx>, checked_ty: Ty<'tcx>, expected: Ty<'tcx>, expected_ty_expr: Option<&'tcx Expr<'tcx>>, allow_two_phase: AllowTwoPhase, ) -> Result<Ty<'tcx>, Diag<'a>>

Checks that the type of `expr` can be coerced to `expected`.

N.B., this code relies on `self.diverges` to be accurate. In particular, assignments to `!` will be permitted if the diverges flag is currently “always”.

Source

#### pub(crate) fn note_source_of_type_mismatch_constraint( &self, err: &mut Diag<'_>, expr: &Expr<'_>, source: TypeMismatchSource<'tcx>, ) -> bool

Notes the point at which a variable is constrained to some type incompatible with some expectation given by `source`.

Source

#### pub(crate) fn annotate_loop_expected_due_to_inference( &self, err: &mut Diag<'_>, expr: &Expr<'_>, error: Option<TypeError<'tcx>>, )

Source

#### fn annotate_expected_due_to_let_ty( &self, err: &mut Diag<'_>, expr: &Expr<'_>, error: Option<TypeError<'tcx>>, )

Source

#### fn annotate_mut_binding_to_immutable_binding( &self, err: &mut Diag<'_>, expr: &Expr<'_>, expr_ty: Ty<'tcx>, expected: Ty<'tcx>, error: Option<TypeError<'tcx>>, ) -> bool

Detect the following case

    fn change_object(mut b: &Ty) {
        let a = Ty::new();
        b = a;
    }

where the user likely meant to modify the value behind there reference, use `b` as an out parameter, instead of mutating the local binding. When encountering this we suggest:

    fn change_object(b: &'_ mut Ty) {
        let a = Ty::new();
        *b = a;
    }

Source

#### fn annotate_alternative_method_deref( &self, err: &mut Diag<'_>, expr: &Expr<'_>, error: Option<TypeError<'tcx>>, )

Source

#### pub(crate) fn get_conversion_methods_for_diagnostic( &self, span: Span, expected: Ty<'tcx>, checked_ty: Ty<'tcx>, hir_id: HirId, ) -> Vec<AssocItem>

Source

#### fn has_only_self_parameter(&self, method: &AssocItem) -> bool

This function checks whether the method is not static and does not accept other parameters than `self`.

Source

#### pub(crate) fn maybe_get_block_expr( &self, expr: &Expr<'tcx>, ) -> Option<&'tcx Expr<'tcx>>

If the given `HirId` corresponds to a block with a trailing expression, return that expression

Source

#### pub(crate) fn is_destruct_assignment_desugaring(&self, expr: &Expr<'_>) -> bool

Returns whether the given expression is a destruct assignment desugaring. For example, `(a, b) = (1, &2);` Here we try to find the pattern binding of the expression, `default_binding_modes` is false only for destruct assignment desugaring.

Source

#### fn explain_self_literal( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, )

Source

#### fn note_wrong_return_ty_due_to_generic_arg( &self, err: &mut Diag<'_>, expr: &Expr<'_>, checked_ty: Ty<'tcx>, )

Source

#### pub(crate) fn precedence(&self, expr: &Expr<'_>) -> ExprPrecedence

Source

#### pub(crate) fn check_expr_has_type_or_error( &self, expr: &'tcx Expr<'tcx>, expected_ty: Ty<'tcx>, extend_err: impl FnOnce(&mut Diag<'_>), ) -> Ty<'tcx>

Check an expr with an expectation type, and also demand that the expr’s evaluated type is a subtype of the expectation at the end. This is a hard requirement.

Source

#### pub(crate) fn check_expr_coercible_to_type( &self, expr: &'tcx Expr<'tcx>, expected: Ty<'tcx>, expected_ty_expr: Option<&'tcx Expr<'tcx>>, ) -> Ty<'tcx>

Check an expr with an expectation type, and also demand that the expr’s evaluated type is a coercible to the expectation at the end. This is a hard requirement.

Source

#### pub(crate) fn check_expr_coercible_to_type_or_error( &self, expr: &'tcx Expr<'tcx>, expected: Ty<'tcx>, expected_ty_expr: Option<&'tcx Expr<'tcx>>, extend_err: impl FnOnce(&mut Diag<'_>, Ty<'tcx>), ) -> Ty<'tcx>

Source

#### pub(crate) fn check_expr_with_hint( &self, expr: &'tcx Expr<'tcx>, expected: Ty<'tcx>, ) -> Ty<'tcx>

Check an expr with an expectation type. Don’t actually enforce that expectation is related to the expr’s evaluated type via subtyping or coercion. This is usually called because we want to do that subtype/coerce call manually for better diagnostics.

Source

#### fn check_expr_with_expectation_and_needs( &self, expr: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, needs: Needs, ) -> Ty<'tcx>

Check an expr with an expectation type, and also `Needs` which will prompt typeck to convert any implicit immutable derefs to mutable derefs.

Source

#### pub(crate) fn check_expr(&self, expr: &'tcx Expr<'tcx>) -> Ty<'tcx>

Check an expr with no expectations.

Source

#### pub(crate) fn check_expr_with_needs( &self, expr: &'tcx Expr<'tcx>, needs: Needs, ) -> Ty<'tcx>

Check an expr with no expectations, but with `Needs` which will prompt typeck to convert any implicit immutable derefs to mutable derefs.

Source

#### pub(crate) fn check_expr_with_expectation( &self, expr: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Check an expr with an expectation type which may be used to eagerly guide inference when evaluating that expr.

Source

#### pub(crate) fn check_expr_with_expectation_and_args( &self, expr: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, call_expr_and_args: Option<(&'tcx Expr<'tcx>, &'tcx [Expr<'tcx>])>, ) -> Ty<'tcx>

Same as `Self::check_expr_with_expectation`, but allows us to pass in the arguments of a `ExprKind::Call` when evaluating its callee that is an `ExprKind::Path`. We use this to refine the spans for certain well-formedness guarantees for the path expr.

Source

#### fn check_expr_kind( &self, expr: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_unop( &self, unop: UnOp, oprnd: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_addr_of( &self, kind: BorrowKind, mutbl: Mutability, oprnd: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_named_place_expr(&self, oprnd: &'tcx Expr<'tcx>)

Does this expression refer to a place that either:

- Is based on a local or static.
- Contains a dereference Note that the adjustments for the children of `expr` should already have been resolved.

Source

#### pub(crate) fn check_expr_path( &self, qpath: &'tcx QPath<'tcx>, expr: &'tcx Expr<'tcx>, call_expr_and_args: Option<(&'tcx Expr<'tcx>, &'tcx [Expr<'tcx>])>, ) -> Ty<'tcx>

Source

#### fn check_expr_break( &self, destination: Destination, expr_opt: Option<&'tcx Expr<'tcx>>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_continue( &self, destination: Destination, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_return( &self, expr_opt: Option<&'tcx Expr<'tcx>>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_become( &self, call: &'tcx Expr<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### pub(crate) fn check_return_or_body_tail( &self, return_expr: &'tcx Expr<'tcx>, explicit_return: bool, )

Check an expression that is being returned. For example, this is called with `return_expr: $expr` when `return $expr` is encountered.

Note that this function must only be called in function bodies.

`explicit_return` is `true` if we’re checking an explicit `return expr`, and `false` if we’re checking a trailing expression.

Source

#### fn emit_return_outside_of_fn_body( &self, expr: &Expr<'_>, kind: ReturnLikeStatementKind, )

Emit an error because `return` or `become` is used outside of a function body.

`expr` is the `return` (`become`) “statement”, `kind` is the kind of the statement either `Return` or `Become`.

Source

#### fn point_at_return_for_opaque_ty_error( &self, errors: &mut Vec<FulfillmentError<'tcx>>, hir_id: HirId, span: Span, return_expr_ty: Ty<'tcx>, return_span: Span, )

Source

#### pub(crate) fn check_lhs_assignable( &self, lhs: &'tcx Expr<'tcx>, code: ErrCode, op_span: Span, adjust_err: impl FnOnce(&mut Diag<'_>), )

Source

#### pub(crate) fn check_for_missing_semi( &self, expr: &'tcx Expr<'tcx>, err: &mut Diag<'_>, ) -> bool

Check if the expression that could not be assigned to was a typoed expression that

Source

#### pub(crate) fn comes_from_while_condition( &self, original_expr_id: HirId, then: impl FnOnce(&Expr<'_>), )

as opposed from the body of a while loop, which we can naively check by iterating parents until we find a loop…

Source

#### fn check_expr_if( &self, expr_id: HirId, cond_expr: &'tcx Expr<'tcx>, then_expr: &'tcx Expr<'tcx>, opt_else_expr: Option<&'tcx Expr<'tcx>>, sp: Span, orig_expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_assign( &self, expr: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, lhs: &'tcx Expr<'tcx>, rhs: &'tcx Expr<'tcx>, span: Span, ) -> Ty<'tcx>

Type check assignment expression `expr` of form `lhs = rhs`. The expected type is `()` and is passed to the function for the purposes of diagnostics.

Source

#### fn expr_assign_expected_bool_error( &self, expr: &'tcx Expr<'tcx>, lhs: &'tcx Expr<'tcx>, rhs: &'tcx Expr<'tcx>, span: Span, ) -> ErrorGuaranteed

The expected type is `bool` but this will result in `()` so we can reasonably say that the user intended to write `lhs == rhs` instead of `lhs = rhs`. The likely cause of this is `if foo = bar { .. }`.

Source

#### pub(crate) fn check_expr_let( &self, let_expr: &'tcx LetExpr<'tcx>, hir_id: HirId, ) -> Ty<'tcx>

Source

#### fn check_expr_loop( &self, body: &'tcx Block<'tcx>, source: LoopSource, expected: Expectation<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_method_call( &self, expr: &'tcx Expr<'tcx>, segment: &'tcx PathSegment<'tcx>, rcvr: &'tcx Expr<'tcx>, args: &'tcx [Expr<'tcx>], expected: Expectation<'tcx>, ) -> Ty<'tcx>

Checks a method call.

Source

#### fn check_expr_use( &self, used_expr: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Checks use `x.use`.

Source

#### fn check_expr_cast( &self, e: &'tcx Expr<'tcx>, t: &'tcx Ty<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_unsafe_binder_cast( &self, span: Span, kind: UnsafeBinderCastKind, inner_expr: &'tcx Expr<'tcx>, hir_ty: Option<&'tcx Ty<'tcx>>, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_array( &self, args: &'tcx [Expr<'tcx>], expected: Expectation<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn suggest_array_len(&self, expr: &'tcx Expr<'tcx>, array_len: u64)

Source

#### pub(crate) fn check_expr_const_block( &self, block: &'tcx ConstBlock, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_repeat( &self, element: &'tcx Expr<'tcx>, count: &'tcx ConstArg<'tcx>, expected: Expectation<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_tuple( &self, elements: &'tcx [Expr<'tcx>], expected: Expectation<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_struct( &self, expr: &Expr<'tcx>, expected: Expectation<'tcx>, qpath: &'tcx QPath<'tcx>, fields: &'tcx [ExprField<'tcx>], base_expr: &'tcx StructTailExpr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_struct_fields( &self, adt_ty: Ty<'tcx>, expected: Expectation<'tcx>, expr: &Expr<'_>, path_span: Span, variant: &'tcx VariantDef, hir_fields: &'tcx [ExprField<'tcx>], base_expr: &'tcx StructTailExpr<'tcx>, )

Source

#### fn check_struct_fields_on_error( &self, fields: &'tcx [ExprField<'tcx>], base_expr: &'tcx StructTailExpr<'tcx>, )

Source

#### fn report_missing_fields( &self, adt_ty: Ty<'tcx>, span: Span, full_span: Span, remaining_fields: UnordMap<Ident, (FieldIdx, &FieldDef)>, variant: &'tcx VariantDef, hir_fields: &'tcx [ExprField<'tcx>], args: GenericArgsRef<'tcx>, )

Report an error for a struct field expression when there are fields which aren’t provided.

    error: missing field `you_can_use_this_field` in initializer of `foo::Foo`
     --> src/main.rs:8:5
      |
    8 |     foo::Foo {};
      |     ^^^^^^^^ missing `you_can_use_this_field`

    error: aborting due to 1 previous error

Source

#### fn suggest_fru_from_range_and_emit( &self, last_expr_field: &ExprField<'tcx>, variant: &VariantDef, args: GenericArgsRef<'tcx>, err: Diag<'_>, )

If the last field is a range literal, but it isn’t supposed to be, then they probably meant to use functional update syntax.

Source

#### fn report_private_fields( &self, adt_ty: Ty<'tcx>, span: Span, expr_span: Span, private_fields: Vec<&FieldDef>, used_fields: &'tcx [ExprField<'tcx>], )

Report an error for a struct field expression when there are invisible fields.

    error: cannot construct `Foo` with struct literal syntax due to private fields
     --> src/main.rs:8:5
      |
    8 |     foo::Foo {};
      |     ^^^^^^^^

    error: aborting due to 1 previous error

Source

#### fn report_unknown_field( &self, ty: Ty<'tcx>, variant: &'tcx VariantDef, expr: &Expr<'_>, field: &ExprField<'_>, skip_fields: &[ExprField<'_>], kind_name: &str, ) -> ErrorGuaranteed

Source

#### fn available_field_names( &self, variant: &'tcx VariantDef, expr: &Expr<'_>, skip_fields: &[ExprField<'_>], ) -> Vec<Symbol>

Source

#### fn name_series_display(&self, names: Vec<Symbol>) -> String

Source

#### fn find_adt_field( &self, base_def: AdtDef<'tcx>, ident: Ident, ) -> Option<(FieldIdx, &'tcx FieldDef)>

Find the position of a field named `ident` in `base_def`, accounting for unnammed fields. Return whether such a field has been found. The path to it is stored in `nested_fields`. `ident` must have been adjusted beforehand.

Source

#### fn check_expr_field( &self, expr: &'tcx Expr<'tcx>, base: &'tcx Expr<'tcx>, field: Ident, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Check field access expressions, this works for both structs and tuples. Returns the Ty of the field.

ⓘ

    base.field
    ^^^^^^^^^^ expr
    ^^^^       base
         ^^^^^ field

Source

#### fn suggest_await_on_field_access( &self, err: &mut Diag<'_>, field_ident: Ident, base: &'tcx Expr<'tcx>, ty: Ty<'tcx>, )

Source

#### fn ban_nonexisting_field( &self, ident: Ident, base: &'tcx Expr<'tcx>, expr: &'tcx Expr<'tcx>, base_ty: Ty<'tcx>, ) -> ErrorGuaranteed

Source

#### fn ban_private_field_access( &self, expr: &Expr<'tcx>, expr_t: Ty<'tcx>, field: Ident, base_did: DefId, return_ty: Option<Ty<'tcx>>, ) -> ErrorGuaranteed

Source

#### fn ban_take_value_of_method( &self, expr: &Expr<'tcx>, expr_t: Ty<'tcx>, field: Ident, ) -> ErrorGuaranteed

Source

#### fn point_at_param_definition(&self, err: &mut Diag<'_>, param: ParamTy)

Source

#### fn maybe_suggest_array_indexing( &self, err: &mut Diag<'_>, base: &Expr<'_>, field: Ident, len: Const<'tcx>, )

Source

#### fn suggest_first_deref_field( &self, err: &mut Diag<'_>, base: &Expr<'_>, field: Ident, )

Source

#### fn no_such_field_err( &self, field: Ident, base_ty: Ty<'tcx>, expr: &Expr<'tcx>, ) -> Diag<'_>

Source

#### fn private_field_err(&self, field: Ident, base_did: DefId) -> Diag<'_>

Source

#### pub(crate) fn get_field_candidates_considering_privacy_for_diag( &self, span: Span, base_ty: Ty<'tcx>, mod_id: DefId, hir_id: HirId, ) -> Vec<Vec<(Ident, Ty<'tcx>)>>

Source

#### pub(crate) fn check_for_nested_field_satisfying_condition_for_diag( &self, span: Span, matches: &impl Fn(Ident, Ty<'tcx>) -> bool, (candidate_name, candidate_ty): (Ident, Ty<'tcx>), field_path: Vec<Ident>, mod_id: DefId, hir_id: HirId, ) -> Option<Vec<Ident>>

This method is called after we have encountered a missing field error to recursively search for the field

Source

#### fn check_expr_index( &self, base: &'tcx Expr<'tcx>, idx: &'tcx Expr<'tcx>, expr: &'tcx Expr<'tcx>, brackets_span: Span, ) -> Ty<'tcx>

Source

#### fn find_and_report_unsatisfied_index_impl( &self, base_expr: &Expr<'_>, base_ty: Ty<'tcx>, ) -> Option<(ErrorGuaranteed, Ty<'tcx>, Ty<'tcx>)>

Try to match an implementation of `Index` against a self type, and report the unsatisfied predicates that result from confirming this impl.

Given an index expression, sometimes the `Self` type shallowly but does not deeply satisfy an impl predicate. Instead of simply saying that the type does not support being indexed, we want to point out exactly what nested predicates cause this to be, so that the user can add them to fix their code.

Source

#### fn point_at_index(&self, errors: &mut Vec<FulfillmentError<'tcx>>, span: Span)

Source

#### fn check_expr_yield( &self, value: &'tcx Expr<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_expr_asm_operand(&self, expr: &'tcx Expr<'tcx>, is_input: bool)

Source

#### fn check_expr_asm(&self, asm: &'tcx InlineAsm<'tcx>, span: Span) -> Ty<'tcx>

Source

#### fn check_expr_offset_of( &self, container: &'tcx Ty<'tcx>, fields: &[Ident], expr: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### pub(crate) fn type_inference_fallback(&self)

Performs type inference fallback, setting `FnCtxt::diverging_fallback_has_occurred` if the never type fallback has occurred.

Source

#### fn fallback_types(&self) -> bool

Source

#### fn fallback_if_possible( &self, ty: Ty<'tcx>, diverging_fallback: &UnordSet<Ty<'tcx>>, diverging_fallback_ty: Ty<'tcx>, fallback_to_f32: &UnordSet<FloatVid>, ) -> bool

Tries to apply a fallback to `ty` if it is an unsolved variable.

- Unconstrained ints are replaced with `i32`.

- Unconstrained floats are replaced with `f64`, except when there is a trait predicate `f32: From<{float}>`, in which case `f32` is used as the fallback instead.

- Non-numerics may get replaced with `()` or `!`, depending on how they were categorized by `Self::calculate_diverging_fallback`, crate’s edition, and the setting of `#![rustc_never_type_options(fallback = ...)]`.

Fallback becomes very dubious if we have encountered type-checking errors. In that case, fallback to Error.

Sets `FnCtxt::diverging_fallback_has_occurred` if never type fallback is performed during this call.

Source

#### fn calculate_fallback_to_f32( &self, unresolved_variables: &[Ty<'tcx>], ) -> UnordSet<FloatVid>

Existing code relies on `f32: From<T>` (usually written as `T: Into<f32>`) resolving `T` to `f32` when the type of `T` is inferred from an unsuffixed float literal. Using the default fallback of `f64`, this would break when adding `impl From<f16> for f32`, as there are now two float type which could be `T`, meaning that the fallback of `f64` would be used and compilation error would occur as `f32` does not implement `From<f64>`. To avoid breaking existing code, we instead fallback `T` to `f32` when there is a trait predicate `f32: From<T>`. This means code like the following will continue to compile:

    fn foo<T: Into<f32>>(_: T) {}

    foo(1.0);

Source

#### fn calculate_diverging_fallback( &self, unresolved_variables: &[Ty<'tcx>], ) -> (UnordSet<Ty<'tcx>>, Ty<'tcx>)

Source

#### fn lint_never_type_fallback_flowing_into_unsafe_code( &self, unsafe_infer_vars: &OnceCell<UnordMap<TyVid, (HirId, Span, UnsafeUseReason)>>, coercion_graph: &VecGraph<TyVid, true>, root_vid: TyVid, )

Source

#### fn lint_obligations_broken_by_never_type_fallback_change( &self, diverging_vids: &[TyVid], coercions: &VecGraph<TyVid, true>, )

Source

#### fn create_coercion_graph(&self) -> VecGraph<TyVid, true>

Returns a graph whose nodes are (unresolved) inference variables and where an edge `?A -> ?B` indicates that the variable `?A` is coerced to `?B`.

Source

#### fn root_vid(&self, ty: Ty<'tcx>) -> Option<TyVid>

If `ty` is an unresolved type variable, returns its root vid.

Source

#### pub(crate) fn root_float_vid(&self, ty: Ty<'tcx>) -> Option<FloatVid>

If `ty` is an unresolved float type variable, returns its root vid.

Source

#### fn try_to_suggest_annotations( &self, diverging_vids: &[TyVid], coercions: &VecGraph<TyVid, true>, ) -> SuggestAnnotations

Given a set of diverging vids and coercions, walk the HIR to gather a set of suggestions which can be applied to preserve fallback to unit.

Source

#### pub(crate) fn transform_args_for_inherent_type_const( &self, def_id: DefId, args: GenericArgsRef<'tcx>, ) -> GenericArgsRef<'tcx>

Transform generic args for inherent associated type constants (IACs).

IACs have a different generic parameter structure than regular associated constants:

- Regular assoc const: parent (impl) generic params + own generic params
- IAC (type_const): Self type + own generic params

Source

#### pub(crate) fn warn_if_unreachable(&self, id: HirId, span: Span, kind: &str)

Produces warning on the given node, if the current point in the function is unreachable, and there hasn’t been another warning.

Source

#### pub(crate) fn resolve_vars_with_obligations<T: TypeFoldable<TyCtxt<'tcx>>>( &self, t: T, ) -> T

Resolves type and const variables in `t` if possible. Unlike the infcx version (resolve_vars_if_possible), this version will also select obligations if it seems useful, in an effort to get more type information.

Source

#### pub(crate) fn record_deferred_call_resolution( &self, closure_def_id: LocalDefId, r: DeferredCallResolution<'tcx>, )

Source

#### pub(crate) fn remove_deferred_call_resolutions( &self, closure_def_id: LocalDefId, ) -> Vec<DeferredCallResolution<'tcx>>

Source

#### fn tag(&self) -> String

Source

#### pub(crate) fn local_ty(&self, span: Span, nid: HirId) -> Ty<'tcx>

Source

#### pub(crate) fn write_ty(&self, id: HirId, ty: Ty<'tcx>)

Source

#### pub(crate) fn write_field_index(&self, hir_id: HirId, index: FieldIdx)

Source

#### pub(crate) fn write_resolution( &self, hir_id: HirId, r: Result<(DefKind, DefId), ErrorGuaranteed>, )

Source

#### pub(crate) fn write_method_call_and_enforce_effects( &self, hir_id: HirId, span: Span, method: MethodCallee<'tcx>, )

Source

#### fn write_args(&self, node_id: HirId, args: GenericArgsRef<'tcx>)

Source

#### pub(crate) fn write_user_type_annotation_from_args( &self, hir_id: HirId, def_id: DefId, args: GenericArgsRef<'tcx>, user_self_ty: Option<UserSelfTy<'tcx>>, )

Given the args that we just converted from the HIR, try to canonicalize them and store them as user-given parameters (i.e., parameters that must be respected by the NLL check).

This should be invoked before any unifications have occurred, so that annotations like `Vec<_>` are preserved properly.

Source

#### pub(crate) fn write_user_type_annotation( &self, hir_id: HirId, canonical_user_type_annotation: CanonicalUserType<'tcx>, )

Source

#### pub(crate) fn apply_adjustments( &self, expr: &Expr<'_>, adj: Vec<Adjustment<'tcx>>, )

Source

#### pub(crate) fn normalize<T>(&self, span: Span, value: Unnormalized<'tcx, T>) -> T
where T: TypeFoldable<TyCtxt<'tcx>>,

Source

#### pub(crate) fn require_type_meets( &self, ty: Ty<'tcx>, span: Span, code: ObligationCauseCode<'tcx>, def_id: DefId, )

Source

#### pub(crate) fn require_type_is_sized( &self, ty: Ty<'tcx>, span: Span, code: ObligationCauseCode<'tcx>, )

Source

#### pub(crate) fn require_type_is_sized_deferred( &self, ty: Ty<'tcx>, span: Span, code: ObligationCauseCode<'tcx>, )

Source

#### pub(crate) fn require_type_has_static_alignment(&self, ty: Ty<'tcx>, span: Span)

Source

#### pub(crate) fn register_bound( &self, ty: Ty<'tcx>, def_id: DefId, cause: ObligationCause<'tcx>, )

Source

#### pub(crate) fn lower_ty(&self, hir_ty: &Ty<'tcx>) -> LoweredTy<'tcx>

Source

#### pub(crate) fn collect_impl_trait_clauses_from_hir_ty( &self, hir_ty: &'tcx Ty<'tcx>, ) -> Clauses<'tcx>

Walk a `hir_ty` and collect any clauses that may have come from a type within the `hir_ty`. These clauses will be canonicalized with a user type annotation so that we can enforce these bounds in borrowck, too.

Source

#### pub(crate) fn lower_ty_saving_user_provided_ty( &self, hir_ty: &'tcx Ty<'tcx>, ) -> Ty<'tcx>

Source

#### pub(crate) fn lower_const_arg( &self, const_arg: &'tcx ConstArg<'tcx>, ty: Ty<'tcx>, ) -> Const<'tcx>

Source

#### pub(crate) fn node_ty(&self, id: HirId) -> Ty<'tcx>

Source

#### pub(crate) fn node_ty_opt(&self, id: HirId) -> Option<Ty<'tcx>>

Source

#### pub(crate) fn register_wf_obligation( &self, term: Term<'tcx>, span: Span, code: ObligationCauseCode<'tcx>, )

Registers an obligation for checking later, during regionck, that `arg` is well-formed.

Source

#### pub(crate) fn add_wf_bounds(&self, args: GenericArgsRef<'tcx>, span: Span)

Registers obligations that all `args` are well-formed.

Source

#### pub(crate) fn field_ty( &self, span: Span, field: &'tcx FieldDef, args: GenericArgsRef<'tcx>, ) -> Ty<'tcx>

Source

#### pub(crate) fn drain_stalled_coroutine_obligations(&self)

Drain all obligations that are stalled on coroutines defined in this body.

Source

#### pub(crate) fn report_ambiguity_errors(&self)

Source

#### pub(crate) fn select_obligations_where_possible( &self, mutate_fulfillment_errors: impl Fn(&mut Vec<FulfillmentError<'tcx>>), )

Select as many obligations as we can at present.

Source

#### pub(crate) fn make_overloaded_place_return_type( &self, method: MethodCallee<'tcx>, ) -> Ty<'tcx>

For the overloaded place expressions (`*x`, `x[3]`), the trait returns a type of `&T`, but the actual type we assign to the expression is `T`. So this function just peels off the return type by one layer to yield `T`.

Source

#### pub(crate) fn type_var_is_sized(&self, self_ty: TyVid) -> bool

Source

#### pub(crate) fn err_args( &self, len: usize, guar: ErrorGuaranteed, ) -> Vec<Ty<'tcx>>

Source

#### pub(crate) fn resolve_ty_and_res_fully_qualified_call( &self, qpath: &'tcx QPath<'tcx>, hir_id: HirId, span: Span, ) -> (Res, Option<LoweredTy<'tcx>>, &'tcx [PathSegment<'tcx>])

Resolves an associated value path into a base type and associated constant, or method resolution. The newly resolved definition is written into `type_dependent_defs`.

Source

#### pub(crate) fn get_fn_decl( &self, blk_id: HirId, ) -> Option<(LocalDefId, &'tcx FnDecl<'tcx>)>

Given a `HirId`, return the `HirId` of the enclosing function and its `FnDecl`.

Source

#### pub(crate) fn note_internal_mutation_in_method( &self, err: &mut Diag<'_>, expr: &Expr<'_>, expected: Option<Ty<'tcx>>, found: Ty<'tcx>, )

Source

#### pub(crate) fn instantiate_value_path( &self, segments: &'tcx [PathSegment<'tcx>], self_ty: Option<LoweredTy<'tcx>>, res: Res, span: Span, path_span: Span, hir_id: HirId, ) -> (Ty<'tcx>, Res)

Source

#### pub(crate) fn add_required_obligations_for_hir( &self, span: Span, def_id: DefId, args: GenericArgsRef<'tcx>, hir_id: HirId, )

Add all the obligations that are required, instantiated and normalized appropriately.

Source

#### pub(crate) fn add_required_obligations_with_code( &self, span: Span, def_id: DefId, args: GenericArgsRef<'tcx>, code: impl Fn(usize, Span) -> ObligationCauseCode<'tcx>, )

Source

#### pub(crate) fn try_structurally_resolve_const( &self, sp: Span, ct: Const<'tcx>, ) -> Const<'tcx>

Source

#### pub(crate) fn structurally_resolve_type( &self, sp: Span, ty: Ty<'tcx>, ) -> Ty<'tcx>

Resolves `ty` by a single level if `ty` is a type variable.

When the new solver is enabled, this will also attempt to normalize the type if it’s a projection (note that it will not deeply normalize projections within the type, just the outermost layer of the type).

If no resolution is possible, then an error is reported. Numeric inference variables may be left unresolved.

Source

#### pub(crate) fn type_must_be_known_at_this_point( &self, sp: Span, ty: Ty<'tcx>, ) -> Ty<'tcx>

Source

#### pub(crate) fn structurally_resolve_const( &self, sp: Span, ct: Const<'tcx>, ) -> Const<'tcx>

Source

#### pub(crate) fn with_breakable_ctxt<F: FnOnce() -> R, R>( &self, id: HirId, ctxt: BreakableCtxt<'tcx>, f: F, ) -> (BreakableCtxt<'tcx>, R)

Source

#### pub(crate) fn probe_instantiate_query_response( &self, span: Span, original_values: &OriginalQueryValues<'tcx>, query_result: &Canonical<'tcx, QueryResponse<'tcx, Ty<'tcx>>>, ) -> InferResult<'tcx, Ty<'tcx>>

Instantiate a QueryResponse in a probe context, without a good ObligationCause.

Source

#### pub(crate) fn expr_in_place(&self, expr_id: HirId) -> bool

Returns `true` if an expression is contained inside the LHS of an assignment expression.

Source

#### pub(crate) fn adjust_fulfillment_error_for_expr_obligation( &self, error: &mut FulfillmentError<'tcx>, ) -> bool

Source

#### fn point_at_expr_if_possible( &self, error: &mut FulfillmentError<'tcx>, callee_def_id: DefId, expr: &'tcx Expr<'tcx>, predicate_self_type_to_point_at: Option<GenericArg<'tcx>>, param_to_point_at: Option<GenericArg<'tcx>>, fallback_param_to_point_at: Option<GenericArg<'tcx>>, self_param_to_point_at: Option<GenericArg<'tcx>>, ) -> bool

Source

#### fn point_at_path_if_possible( &self, error: &mut FulfillmentError<'tcx>, def_id: DefId, arg: GenericArg<'tcx>, qpath: &QPath<'tcx>, ) -> bool

Source

#### fn point_at_generic_if_possible( &self, error: &mut FulfillmentError<'tcx>, def_id: DefId, param_to_point_at: GenericArg<'tcx>, segment: &PathSegment<'tcx>, ) -> bool

Source

#### fn find_ambiguous_parameter_in<T: TypeVisitable<TyCtxt<'tcx>>>( &self, item_def_id: DefId, t: T, ) -> Option<GenericArg<'tcx>>

Source

#### fn closure_span_overlaps_error( &self, error: &FulfillmentError<'tcx>, span: Span, ) -> bool

Source

#### fn point_at_field_if_possible( &self, def_id: DefId, param_to_point_at: GenericArg<'tcx>, variant_def_id: DefId, expr_fields: &[ExprField<'tcx>], ) -> Option<(&'tcx Expr<'tcx>, Ty<'tcx>)>

Source

#### fn blame_specific_arg_if_possible( &self, error: &mut FulfillmentError<'tcx>, def_id: DefId, param_to_point_at: GenericArg<'tcx>, call_hir_id: HirId, callee_span: Span, receiver: Option<&'tcx Expr<'tcx>>, args: &'tcx [Expr<'tcx>], ) -> bool

- `blame_specific_*` means that the function will recursively traverse the expression, looking for the most-specific-possible span to blame.

- `point_at_*` means that the function will only go “one level”, pointing at the specific expression mentioned.

`blame_specific_arg_if_possible` will find the most-specific expression anywhere inside the provided function call expression, and mark it as responsible for the fulfillment error.

Source

#### pub(crate) fn blame_specific_expr_if_possible( &self, error: &mut FulfillmentError<'tcx>, expr: &'tcx Expr<'tcx>, )

Recursively searches for the most-specific blameable expression. For example, if you have a chain of constraints like:

- want `Vec<i32>: Copy`
- because `Option<Vec<i32>>: Copy` needs `Vec<i32>: Copy` because `impl <T: Copy> Copy for Option<T>`
- because `(Option<Vec<i32>, bool)` needs `Option<Vec<i32>>: Copy` because `impl <A: Copy, B: Copy> Copy for (A, B)`

then if you pass in `(Some(vec![1, 2, 3]), false)`, this helper `point_at_specific_expr_if_possible` will find the expression `vec![1, 2, 3]` as the “most blameable” reason for this missing constraint.

This function only updates the error span.

Source

#### fn blame_specific_expr_if_possible_for_obligation_cause_code( &self, obligation_cause_code: &ObligationCauseCode<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Result<&'tcx Expr<'tcx>, &'tcx Expr<'tcx>>

Source

#### fn blame_specific_expr_if_possible_for_derived_predicate_obligation( &self, obligation: &ImplDerivedCause<'tcx>, expr: &'tcx Expr<'tcx>, ) -> Result<&'tcx Expr<'tcx>, &'tcx Expr<'tcx>>

We want to achieve the error span in the following example:

ⓘ

    struct Burrito<Filling> {
      filling: Filling,
    }
    impl <Filling: Delicious> Delicious for Burrito<Filling> {}
    fn eat_delicious_food<Food: Delicious>(_food: Food) {}

    fn will_type_error() {
      eat_delicious_food(Burrito { filling: Kale });
    } //                                    ^--- The trait bound `Kale: Delicious`
      //                                         is not satisfied

Without calling this function, the error span will cover the entire argument expression.

Before we do any of this logic, we recursively call `point_at_specific_expr_if_possible` on the parent obligation. Hence we refine the `expr` “outwards-in” and bail at the first kind of expression/impl we don’t recognize.

This function returns a `Result<&Expr, &Expr>` - either way, it returns the `Expr` whose span should be reported as an error. If it is `Ok`, then it means it refined successful. If it is `Err`, then it may be only a partial success - but it cannot be refined even further.

Source

#### fn blame_specific_part_of_expr_corresponding_to_generic_param( &self, param: GenericArg<'tcx>, expr: &'tcx Expr<'tcx>, in_ty: GenericArg<'tcx>, ) -> Result<&'tcx Expr<'tcx>, &'tcx Expr<'tcx>>

Drills into `expr` to arrive at the equivalent location of `find_generic_param` in `in_ty`. For example, given

- expr: `(Some(vec![1, 2, 3]), false)`
- param: `T`
- in_ty: `(Option<Vec<T>, bool)`

we would drill until we arrive at `vec![1, 2, 3]`.

If successful, we return `Ok(refined_expr)`. If unsuccessful, we return `Err(partially_refined_expr`), which will go as far as possible. For example, given `(foo(), false)` instead, we would drill to `foo()` and then return `Err("foo()")`.

This means that you can (and should) use the `?` try operator to chain multiple calls to this function with different types, since you can only continue drilling the second time if you succeeded the first time.

Source

#### pub(crate) fn check_asms(&self)

Source

#### pub(crate) fn check_repeat_exprs(&self)

Source

#### pub(crate) fn check_argument_types( &self, call_span: Span, call_expr: &'tcx Expr<'tcx>, formal_input_tys: &[Ty<'tcx>], formal_output: Ty<'tcx>, expectation: Expectation<'tcx>, provided_args: &'tcx [Expr<'tcx>], c_variadic: bool, tuple_arguments: TupleArgumentsFlag, fn_def_id: Option<DefId>, )

Generic function that factors out common logic from function calls, method calls and overloaded operators.

Source

#### fn check_place_expr_if_unsized(&self, ty: Ty<'tcx>, expr: &'tcx Expr<'tcx>)

If `unsized_fn_params` is active, check that unsized values are place expressions. Since the removal of `unsized_locals` in https://github.com/rust-lang/rust/pull/142911 we can’t store them in MIR locals as temporaries.

If `unsized_fn_params` is inactive, this will be checked in borrowck instead.

Source

#### fn report_arg_errors( &self, compatibility_diagonal: IndexVec<ProvidedIdx, Compatibility<'tcx>>, formal_and_expected_inputs: IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>, provided_args: IndexVec<ProvidedIdx, &'tcx Expr<'tcx>>, c_variadic: bool, err_code: ErrCode, fn_def_id: Option<DefId>, call_span: Span, call_expr: &'tcx Expr<'tcx>, tuple_arguments: TupleArgumentsFlag, ) -> ErrorGuaranteed

Source

#### fn suggest_ptr_null_mut( &self, expected_ty: Ty<'tcx>, provided_ty: Ty<'tcx>, arg: &Expr<'tcx>, err: &mut Diag<'_>, )

Source

#### pub(crate) fn check_expr_lit( &self, lit: &Lit, lint_id: HirId, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### pub(crate) fn check_struct_path( &self, qpath: &QPath<'tcx>, hir_id: HirId, ) -> Result<(&'tcx VariantDef, Ty<'tcx>), ErrorGuaranteed>

Source

#### fn check_decl_initializer( &self, hir_id: HirId, pat: &'tcx Pat<'tcx>, init: &'tcx Expr<'tcx>, ) -> Ty<'tcx>

Source

#### pub(crate) fn check_decl(&self, decl: Declaration<'tcx>) -> Ty<'tcx>

Source

#### fn check_decl_local(&self, local: &'tcx LetStmt<'tcx>)

Type check a `let` statement.

Source

#### fn check_stmt(&self, stmt: &'tcx Stmt<'tcx>)

Source

#### pub(crate) fn check_block_no_value(&self, blk: &'tcx Block<'tcx>)

Source

#### pub(crate) fn check_expr_block( &self, blk: &'tcx Block<'tcx>, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### fn parent_item_span(&self, id: HirId) -> Option<Span>

Source

#### fn get_expr_coercion_span(&self, expr: &Expr<'_>) -> Span

If `expr` is a `match` expression that has only one non-`!` arm, use that arm’s tail expression’s `Span`, otherwise return `expr.span`. This is done to give better errors when given code like the following:

    if false { return 0i32; } else { 1u32 }
    //                               ^^^^ point at this instead of the whole `if` expression

Source

#### fn overwrite_local_ty_if_err( &self, hir_id: HirId, pat: &'tcx Pat<'tcx>, ty: Ty<'tcx>, )

Source

#### fn finish_resolving_struct_path( &self, qpath: &QPath<'tcx>, path_span: Span, hir_id: HirId, ) -> (Res, LoweredTy<'tcx>)

Source

#### pub(super) fn adjust_fulfillment_errors_for_expr_obligation( &self, errors: &mut Vec<FulfillmentError<'tcx>>, )

Given a vector of fulfillment errors, try to adjust the spans of the errors to more accurately point at the cause of the failure.

This applies to calls, methods, and struct expressions. This will also try to deduplicate errors that are due to the same cause but might have been created with different `ObligationCause`s.

Source

#### fn label_fn_like( &self, err: &mut Diag<'_>, callable_def_id: Option<DefId>, callee_ty: Option<Ty<'tcx>>, call_expr: &'tcx Expr<'tcx>, expected_ty: Option<Ty<'tcx>>, expected_idx: Option<usize>, matched_inputs: &IndexVec<ExpectedIdx, Option<ProvidedIdx>>, formal_and_expected_inputs: &IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>, is_method: bool, tuple_arguments: TupleArgumentsFlag, )

Source

#### fn label_generic_mismatches( &self, err: &mut Diag<'_>, callable_def_id: Option<DefId>, matched_inputs: &IndexVec<ExpectedIdx, Option<ProvidedIdx>>, provided_arg_tys: &IndexVec<ProvidedIdx, (Ty<'tcx>, Span)>, formal_and_expected_inputs: &IndexVec<ExpectedIdx, (Ty<'tcx>, Ty<'tcx>)>, is_method: bool, )

Source

#### fn get_hir_param_info( &self, def_id: DefId, is_method: bool, ) -> Option<(IndexVec<ExpectedIdx, (Option<GenericIdx>, FnParam<'_>)>, &Generics<'_>)>

Returns the parameters of a function, with their generic parameters if those are the full type of that parameter.

Returns `None` if the body is not a named function (e.g. a closure).

Source

#### pub(crate) fn obligations_for_self_ty( &self, self_ty: TyVid, ) -> PredicateObligations<'tcx>

Returns a list of all obligations whose self type has been unified with the unconstrained type `self_ty`.

Source

#### fn predicate_has_self_ty( &self, predicate: Predicate<'tcx>, expected_vid: TyVid, ) -> bool

Source

#### fn type_matches_expected_vid(&self, expected_vid: TyVid, ty: Ty<'tcx>) -> bool

Source

#### pub(crate) fn obligations_for_self_ty_next( &self, self_ty: TyVid, ) -> PredicateObligations<'tcx>

Source

#### pub(crate) fn from_float_for_f32_root_vids(&self) -> UnordSet<FloatVid>

Only needed for the `From<{float}>` for `f32` type fallback.

Source

#### fn predicate_from_float_for_f32_root_vid( &self, from_trait: DefId, predicate: Predicate<'tcx>, ) -> Option<FloatVid>

Source

#### fn from_float_for_f32_root_vids_next(&self) -> UnordSet<FloatVid>

Source

#### pub(crate) fn body_fn_sig(&self) -> Option<FnSig<'tcx>>

Source

#### pub(crate) fn suggest_semicolon_at_end(&self, span: Span, err: &mut Diag<'_>)

Source

#### pub(crate) fn suggest_mismatched_types_on_tail( &self, err: &mut Diag<'_>, expr: &'tcx Expr<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, blk_id: HirId, ) -> bool

On implicit return expressions with mismatched types, provides the following suggestions:

- Points out the method’s return type as the reason for the expected type.
- Possible missing semicolon.
- Possible missing return type if the return type is the default, and not `fn main()`.

Source

#### pub(crate) fn suggest_fn_call( &self, err: &mut Diag<'_>, expr: &Expr<'_>, found: Ty<'tcx>, can_satisfy: impl FnOnce(Ty<'tcx>) -> bool, ) -> bool

When encountering an fn-like type, try accessing the output of the type and suggesting calling it if it satisfies a predicate (i.e. if the output has a method or a field):

ⓘ

    fn foo(x: usize) -> usize { x }
    let x: usize = foo;  // suggest calling the `foo` function: `foo(42)`

Source

#### pub(crate) fn extract_callable_info( &self, ty: Ty<'tcx>, ) -> Option<(DefIdOrName, Ty<'tcx>, Vec<Ty<'tcx>>)>

Extracts information about a callable type for diagnostics. This is a heuristic – it doesn’t necessarily mean that a type is always callable, because the callable type must also be well-formed to be called.

Source

#### pub(crate) fn suggest_two_fn_call( &self, err: &mut Diag<'_>, lhs_expr: &'tcx Expr<'tcx>, lhs_ty: Ty<'tcx>, rhs_expr: &'tcx Expr<'tcx>, rhs_ty: Ty<'tcx>, can_satisfy: impl FnOnce(Ty<'tcx>, Ty<'tcx>) -> bool, ) -> bool

Source

#### pub(crate) fn suggest_collect( &self, err: &mut Diag<'_>, expr: &Expr<'_>, expected_type: Ty<'tcx>, found_type: Ty<'tcx>, ) -> bool

Suggests calling `.collect()` on an `Iterator` it can be collected in the return type

ⓘ

    let x: String = "foo".chars().map(|c| c); // with a .collect() here the code compiles

Source

#### pub(crate) fn suggest_remove_last_method_call( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, expected: Ty<'tcx>, ) -> bool

Source

#### pub(crate) fn suggest_deref_ref_or_into( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, expected_ty_expr: Option<&'tcx Expr<'tcx>>, ) -> bool

Source

#### fn deconstruct_option_or_result( &self, found_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> Option<(Ty<'tcx>, Ty<'tcx>, Option<(Ty<'tcx>, Ty<'tcx>)>)>

If `ty` is `Option<T>`, returns `T, T, None`. If `ty` is `Result<T, E>`, returns `T, T, Some(E, E)`. Otherwise, returns `None`.

Source

#### pub(crate) fn suggest_boxing_when_appropriate( &self, err: &mut Diag<'_>, span: Span, hir_id: HirId, expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool

When encountering the expected boxed value allocated in the stack, suggest allocating it in the heap by calling `Box::new()`.

Source

#### pub(crate) fn suggest_no_capture_closure( &self, err: &mut Diag<'_>, expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool

When encountering a closure that captures variables, where a FnPtr is expected, suggest a non-capturing closure

Source

#### pub(crate) fn suggest_calling_boxed_future_when_appropriate( &self, err: &mut Diag<'_>, expr: &Expr<'_>, expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool

When encountering an `impl Future` where `BoxFuture` is expected, suggest `Box::pin`.

Source

#### pub(crate) fn suggest_missing_semicolon( &self, err: &mut Diag<'_>, expression: &'tcx Expr<'tcx>, expected: Ty<'tcx>, needs_block: bool, parent_is_closure: bool, )

A common error is to forget to add a semicolon at the end of a block, e.g.,

ⓘ

    fn foo() {
        bar_that_returns_u32()
    }

This routine checks if the return expression in a block would make sense on its own as a statement and the return type has been left as default or has been specified as `()`. If so, it suggests adding a semicolon.

If the expression is the expression of a closure without block (`|| expr`), a block is needed to be added too (`|| { expr; }`). This is denoted by `needs_block`.

Source

#### pub(crate) fn is_next_stmt_expr_continuation(&self, hir_id: HirId) -> bool

Source

#### pub(crate) fn suggest_missing_return_type( &self, err: &mut Diag<'_>, fn_decl: &FnDecl<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, fn_id: LocalDefId, ) -> bool

A possible error is to forget to add a return type that is needed:

ⓘ

    fn foo() {
        bar_that_returns_u32()
    }

This routine checks if the return type is left as default, the method is not part of an `impl` block and that it isn’t the `main` method. If so, it suggests setting the return type.

Source

#### fn can_add_return_type(&self, fn_id: LocalDefId) -> bool

Checks whether we can add a return type to a function. Assumes given function doesn’t have a explicit return type.

Source

#### fn try_note_caller_chooses_ty_for_ty_param( &self, diag: &mut Diag<'_>, expected: Ty<'tcx>, found: Ty<'tcx>, )

Source

#### fn try_suggest_return_impl_trait( &self, err: &mut Diag<'_>, expected: Ty<'tcx>, found: Ty<'tcx>, fn_id: LocalDefId, )

check whether the return type is a generic type with a trait bound only suggest this if the generic param is not present in the arguments if this is true, hint them towards changing the return type to `impl Trait`

ⓘ

    fn cant_name_it<T: Fn() -> u32>() -> T {
        || 3
    }

Source

#### pub(crate) fn suggest_missing_break_or_return_expr( &self, err: &mut Diag<'_>, expr: &'tcx Expr<'tcx>, fn_decl: &FnDecl<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, id: HirId, fn_id: LocalDefId, )

Source

#### pub(crate) fn suggest_missing_parentheses( &self, err: &mut Diag<'_>, expr: &Expr<'_>, ) -> bool

Source

#### pub(crate) fn suggest_block_to_brackets_peeling_refs( &self, diag: &mut Diag<'_>, expr: &Expr<'_>, expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool

Given an expression type mismatch, peel any `&` expressions until we get to a block expression, and then suggest replacing the braces with square braces if it was possibly mistaken array syntax.

Source

#### pub(crate) fn suggest_clone_for_ref( &self, diag: &mut Diag<'_>, expr: &Expr<'_>, expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool

Source

#### pub(crate) fn suggest_copied_cloned_or_as_ref( &self, diag: &mut Diag<'_>, expr: &Expr<'_>, expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool

Source

#### pub(crate) fn suggest_into( &self, diag: &mut Diag<'_>, expr: &Expr<'_>, expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool

Source

#### pub(crate) fn suggest_option_to_bool( &self, diag: &mut Diag<'_>, expr: &Expr<'_>, expr_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, ) -> bool

When expecting a `bool` and finding an `Option`, suggests using `let Some(..)` or `.is_some()`

Source

#### pub(crate) fn suggest_deref_unwrap_or( &self, err: &mut Diag<'_>, callee_ty: Option<Ty<'tcx>>, call_ident: Option<Ident>, expected_ty: Ty<'tcx>, provided_ty: Ty<'tcx>, provided_expr: &Expr<'tcx>, is_method: bool, )

Source

#### pub(crate) fn suggest_block_to_brackets( &self, diag: &mut Diag<'_>, blk: &Block<'_>, blk_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, )

Suggest wrapping the block in square brackets instead of curly braces in case the block was mistaken array syntax, e.g. `{ 1 }` -> `[ 1 ]`.

Source

#### pub(crate) fn suggest_floating_point_literal( &self, err: &mut Diag<'_>, expr: &Expr<'_>, expected_ty: Ty<'tcx>, ) -> bool

Source

#### pub(crate) fn suggest_null_ptr_for_literal_zero_given_to_ptr_arg( &self, err: &mut Diag<'_>, expr: &Expr<'_>, expected_ty: Ty<'tcx>, ) -> bool

Suggest providing `std::ptr::null()` or `std::ptr::null_mut()` if they pass in a literal 0 to an raw pointer.

Source

#### pub(crate) fn suggest_associated_const( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, expected_ty: Ty<'tcx>, ) -> bool

Source

#### fn is_loop(&self, id: HirId) -> bool

Source

#### fn is_local_statement(&self, id: HirId) -> bool

Source

#### pub(crate) fn note_type_is_not_clone( &self, diag: &mut Diag<'_>, expected_ty: Ty<'tcx>, found_ty: Ty<'tcx>, expr: &Expr<'_>, )

Suggest that `&T` was cloned instead of `T` because `T` does not implement `Clone`, which is a side-effect of autoref.

Source

#### fn note_type_is_not_clone_inner_expr<'b>( &'b self, expr: &'b Expr<'b>, ) -> &'b Expr<'b>

Given a type mismatch error caused by `&T` being cloned instead of `T`, and the `expr` as the source of this type mismatch, try to find the method call as the source of this error and return that instead. Otherwise, return the original expression.

Source

#### pub(crate) fn is_field_suggestable( &self, field: &FieldDef, hir_id: HirId, span: Span, ) -> bool

Source

#### pub(crate) fn suggest_missing_unwrap_expect( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool

Source

#### pub(crate) fn suggest_coercing_result_via_try_operator( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, ) -> bool

Source

#### pub(crate) fn suggest_returning_value_after_loop( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, expected: Ty<'tcx>, ) -> bool

Source

#### pub(crate) fn suggest_semicolon_in_repeat_expr( &self, err: &mut Diag<'_>, expr: &Expr<'_>, expr_ty: Ty<'tcx>, ) -> bool

Suggest replacing comma with semicolon in incorrect repeat expressions like `["_", 10]` or `vec![String::new(), 10]`.

Source

#### pub(crate) fn suggest_compatible_variants( &self, err: &mut Diag<'_>, expr: &Expr<'_>, expected: Ty<'tcx>, expr_ty: Ty<'tcx>, ) -> bool

If the expected type is an enum (Issue #55250) with any variants whose sole field is of the found type, suggest such variants. (Issue #42764)

Source

#### pub(crate) fn suggest_non_zero_new_unwrap( &self, err: &mut Diag<'_>, expr: &Expr<'_>, expected: Ty<'tcx>, expr_ty: Ty<'tcx>, ) -> bool

Source

#### fn can_use_as_ref( &self, expr: &Expr<'_>, ) -> Option<(Vec<(Span, String)>, &'static str)>

Identify some cases where `as_ref()` would be appropriate and suggest it.

Given the following code:

ⓘ

    struct Foo;
    fn takes_ref(_: &Foo) {}
    let ref opt = Some(Foo);

    opt.map(|param| takes_ref(param));

Suggest using `opt.as_ref().map(|param| takes_ref(param));` instead.

It only checks for `Option` and `Result` and won’t work with

ⓘ

    opt.map(|param| { takes_ref(param) });

Source

#### pub(crate) fn suggest_deref_or_ref( &self, expr: &Expr<'tcx>, checked_ty: Ty<'tcx>, expected: Ty<'tcx>, ) -> Option<(Vec<(Span, String)>, String, Applicability, bool, bool)>

This function is used to determine potential “simple” improvements or users’ errors and provide them useful help. For example:

ⓘ

    fn some_fn(s: &str) {}

    let x = "hey!".to_owned();
    some_fn(x); // error

No need to find every potential function which could make a coercion to transform a `String` into a `&str` since a `&` would do the trick!

In addition of this check, it also checks between references mutability state. If the expected is mutable but the provided isn’t, maybe we could just say “Hey, try with `&mut`!”.

Source

#### fn is_else_if_block(&self, expr: &Expr<'_>) -> bool

Returns whether the given expression is an `else if`.

Source

#### pub(crate) fn suggest_cast( &self, err: &mut Diag<'_>, expr: &Expr<'_>, checked_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, expected_ty_expr: Option<&'tcx Expr<'tcx>>, ) -> bool

Source

#### pub(crate) fn suggest_method_call_on_range_literal( &self, err: &mut Diag<'_>, expr: &Expr<'tcx>, checked_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, )

Identify when the user has written `foo..bar()` instead of `foo.bar()`.

Source

#### pub(crate) fn suggest_return_binding_for_missing_tail_expr( &self, err: &mut Diag<'_>, expr: &Expr<'_>, checked_ty: Ty<'tcx>, expected_ty: Ty<'tcx>, )

Identify when the type error is because `()` is found in a binding that was assigned a block without a tail expression.

Source

#### pub(crate) fn suggest_swapping_lhs_and_rhs( &self, err: &mut Diag<'_>, rhs_ty: Ty<'tcx>, lhs_ty: Ty<'tcx>, rhs_expr: &'tcx Expr<'tcx>, lhs_expr: &'tcx Expr<'tcx>, )

Source

#### pub(crate) fn typing_mode(&self) -> TypingMode<'tcx, CantBeErased>

Source

#### pub(crate) fn dcx(&self) -> DiagCtxtHandle<'a>

Source

#### pub(crate) fn cause( &self, span: Span, code: ObligationCauseCode<'tcx>, ) -> ObligationCause<'tcx>

Source

#### pub(crate) fn misc(&self, span: Span) -> ObligationCause<'tcx>

Source

#### pub(crate) fn sess(&self) -> &Session

Source

#### pub(crate) fn err_ctxt(&'a self) -> TypeErrCtxt<'a, 'tcx>

Creates an `TypeErrCtxt` with a reference to the in-progress `TypeckResults` which is used for diagnostics. Use `InferCtxtErrorExt::err_ctxt` to start one without a `TypeckResults`.

Source

#### pub(crate) fn confirm_method( &self, span: Span, self_expr: &'tcx Expr<'tcx>, call_expr: &'tcx Expr<'tcx>, unadjusted_self_ty: Ty<'tcx>, pick: &Pick<'tcx>, segment: &'tcx PathSegment<'tcx>, ) -> ConfirmResult<'tcx>

Source

#### pub(crate) fn confirm_method_for_diagnostic( &self, span: Span, self_expr: &'tcx Expr<'tcx>, call_expr: &'tcx Expr<'tcx>, unadjusted_self_ty: Ty<'tcx>, pick: &Pick<'tcx>, segment: &PathSegment<'tcx>, ) -> ConfirmResult<'tcx>

Source

#### pub(super) fn lint_edition_dependent_dot_call( &self, self_ty: Ty<'tcx>, segment: &PathSegment<'tcx>, span: Span, call_expr: &'tcx Expr<'tcx>, self_expr: &'tcx Expr<'tcx>, pick: &Pick<'tcx>, args: &'tcx [Expr<'tcx>], )

Source

#### pub(super) fn lint_fully_qualified_call_from_2018( &self, span: Span, method_name: Ident, self_ty: Ty<'tcx>, self_ty_span: Span, expr_id: HirId, pick: &Pick<'tcx>, )

Source

#### fn trait_path_or_bare_name( &self, span: Span, expr_hir_id: HirId, trait_def_id: DefId, ) -> String

Source

#### fn trait_path( &self, span: Span, expr_hir_id: HirId, trait_def_id: DefId, ) -> Option<String>

Source

#### fn adjust_expr( &self, pick: &Pick<'tcx>, expr: &Expr<'tcx>, outer: Span, ) -> (String, bool)

Creates a string version of the `expr` that includes explicit adjustments. Returns the string and also a bool indicating whether this is a precise suggestion.

Source

#### pub(crate) fn probe_for_return_type_for_diagnostic( &self, span: Span, mode: Mode, return_type: Ty<'tcx>, self_ty: Ty<'tcx>, scope_expr_id: HirId, candidate_filter: impl Fn(&AssocItem) -> bool, ) -> Vec<AssocItem>

This is used to offer suggestions to users. It returns methods that could have been called which have the desired return type. Some effort is made to rule out methods that, if called, would result in an error (basically, the same criteria we would use to decide if a method is a plausible fit for ambiguity purposes).

Source

#### pub(crate) fn probe_for_name( &self, mode: Mode, item_name: Ident, return_type: Option<Ty<'tcx>>, is_suggestion: IsSuggestion, self_ty: Ty<'tcx>, scope_expr_id: HirId, scope: ProbeScope, ) -> Result<Pick<'tcx>, MethodError<'tcx>>

Source

#### pub(crate) fn probe_for_name_many( &self, mode: Mode, item_name: Ident, return_type: Option<Ty<'tcx>>, is_suggestion: IsSuggestion, self_ty: Ty<'tcx>, scope_expr_id: HirId, scope: ProbeScope, ) -> Result<Vec<Candidate<'tcx>>, MethodError<'tcx>>

Source

#### pub(crate) fn probe_op<OP, R>( &'a self, span: Span, mode: Mode, method_name: Option<Ident>, return_type: Option<Ty<'tcx>>, is_suggestion: IsSuggestion, self_ty: Ty<'tcx>, scope_expr_id: HirId, scope: ProbeScope, op: OP, ) -> Result<R, MethodError<'tcx>>
where OP: FnOnce(ProbeContext<'_, 'tcx>) -> Result<R, MethodError<'tcx>>,

Source

#### fn is_slice_ty(&self, ty: Ty<'tcx>, span: Span) -> bool

Source

#### fn impl_into_iterator_should_be_iterator( &self, ty: Ty<'tcx>, span: Span, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, ) -> bool

Source

#### fn preferred_iterator_method( &self, source: SelfSource<'tcx>, rcvr_ty: Ty<'tcx>, ) -> Option<Symbol>

Source

#### pub(crate) fn report_method_error( &self, call_id: HirId, rcvr_ty: Ty<'tcx>, error: MethodError<'tcx>, expected: Expectation<'tcx>, trait_missing_method: bool, ) -> ErrorGuaranteed

Source

#### fn create_missing_writer_err( &self, rcvr_ty: Ty<'tcx>, rcvr_expr: &Expr<'tcx>, long_ty_path: Option<PathBuf>, ) -> Diag<'_>

Source

#### fn create_no_assoc_err( &self, rcvr_ty: Ty<'tcx>, item_ident: Ident, item_kind: &'static str, trait_missing_method: bool, source: SelfSource<'tcx>, is_method: bool, sugg_span: Span, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, ) -> Diag<'_>

Source

#### fn suggest_use_shadowed_binding_with_method( &self, self_source: SelfSource<'tcx>, method_name: Ident, ty: Ty<'tcx>, err: &mut Diag<'_>, )

Source

#### fn suggest_method_call_annotation( &self, err: &mut Diag<'_>, span: Span, rcvr_ty: Ty<'tcx>, item_ident: Ident, mode: Mode, source: SelfSource<'tcx>, expected: Expectation<'tcx>, )

Source

#### fn suggest_static_method_candidates( &self, err: &mut Diag<'_>, span: Span, rcvr_ty: Ty<'tcx>, item_ident: Ident, source: SelfSource<'tcx>, args: Option<&'tcx [Expr<'tcx>]>, sugg_span: Span, no_match_data: &NoMatchData<'tcx>, ) -> Vec<CandidateSource>

Source

#### fn suggest_unsatisfied_ty_or_trait( &self, err: &mut Diag<'_>, span: Span, rcvr_ty: Ty<'tcx>, item_ident: Ident, item_kind: &str, source: SelfSource<'tcx>, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, static_candidates: &[CandidateSource], ) -> Result<(bool, bool, bool, bool, SortedMap<Span, Vec<String>>), ()>

Source

#### fn suggest_surround_method_call( &self, err: &mut Diag<'_>, span: Span, rcvr_ty: Ty<'tcx>, item_ident: Ident, source: SelfSource<'tcx>, similar_candidate: &Option<AssocItem>, ) -> bool

Source

#### fn find_possible_candidates_for_method( &self, err: &mut Diag<'_>, span: Span, rcvr_ty: Ty<'tcx>, item_ident: Ident, item_kind: &str, mode: Mode, source: SelfSource<'tcx>, no_match_data: &NoMatchData<'tcx>, expected: Expectation<'tcx>, should_label_not_found: bool, custom_span_label: bool, )

Source

#### fn suggest_confusable_or_similarly_named_method( &self, err: &mut Diag<'_>, span: Span, rcvr_ty: Ty<'tcx>, item_ident: Ident, mode: Mode, args: Option<&'tcx [Expr<'tcx>]>, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, similar_candidate: Option<AssocItem>, )

Source

#### fn suggest_method_not_found_because_of_unsatisfied_bounds( &self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, item_ident: Ident, item_kind: &str, bound_spans: SortedMap<Span, Vec<String>>, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, )

Source

#### fn report_no_match_method_error( &self, span: Span, rcvr_ty: Ty<'tcx>, item_ident: Ident, expr_id: HirId, source: SelfSource<'tcx>, args: Option<&'tcx [Expr<'tcx>]>, sugg_span: Span, no_match_data: &mut NoMatchData<'tcx>, expected: Expectation<'tcx>, trait_missing_method: bool, within_macro_span: Option<Span>, ) -> ErrorGuaranteed

Source

#### fn set_not_found_span_label( &self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, item_ident: Ident, item_kind: &str, mode: Mode, source: SelfSource<'tcx>, span: Span, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, find_candidate_for_method: &mut bool, )

Source

#### fn suggest_enum_variant_for_method_call( &self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, item_ident: Ident, span: Span, source: SelfSource<'tcx>, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, )

Suggest similar enum variant when method call fails

Source

#### fn handle_unsatisfied_predicates( &self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, item_ident: Ident, item_kind: &str, span: Span, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, restrict_type_params: &mut bool, suggested_derive: &mut bool, unsatisfied_bounds: &mut bool, custom_span_label: &mut bool, bound_spans: &mut SortedMap<Span, Vec<String>>, )

Source

#### fn lookup_segments_chain_for_no_match_method( &self, err: &mut Diag<'_>, item_name: Ident, item_kind: &str, source: SelfSource<'tcx>, no_match_data: &NoMatchData<'tcx>, )

If an appropriate error source is not found, check method chain for possible candidates

Source

#### fn find_likely_intended_associated_item( &self, err: &mut Diag<'_>, similar_candidate: AssocItem, span: Span, args: Option<&'tcx [Expr<'tcx>]>, mode: Mode, )

Source

#### pub(crate) fn confusable_method_name( &self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, item_name: Ident, call_args: Option<Vec<Ty<'tcx>>>, ) -> Option<Symbol>

Source

#### fn note_candidates_on_method_error( &self, rcvr_ty: Ty<'tcx>, item_name: Ident, self_source: SelfSource<'tcx>, args: Option<&'tcx [Expr<'tcx>]>, span: Span, err: &mut Diag<'_>, sources: &mut Vec<CandidateSource>, sugg_span: Option<Span>, )

Source

#### fn find_builder_fn(&self, err: &mut Diag<'_>, rcvr_ty: Ty<'tcx>, expr_id: HirId)

Look at all the associated functions without receivers in the type’s inherent impls to look for builders that return `Self`, `Option<Self>` or `Result<Self, _>`.

Source

#### fn suggest_associated_call_syntax( &self, err: &mut Diag<'_>, static_candidates: &[CandidateSource], rcvr_ty: Ty<'tcx>, source: SelfSource<'tcx>, item_name: Ident, args: Option<&'tcx [Expr<'tcx>]>, sugg_span: Span, )

Suggest calling `Ty::method` if `.method()` isn’t found because the method doesn’t take a `self` receiver.

Source

#### fn suggest_calling_field_as_fn( &self, span: Span, rcvr_ty: Ty<'tcx>, expr: &Expr<'_>, item_name: Ident, err: &mut Diag<'_>, ) -> bool

Suggest calling a field with a type that implements the `Fn*` traits instead of a method with the same name as the field i.e. `(a.my_fn_ptr)(10)` instead of `a.my_fn_ptr(10)`.

Source

#### fn report_failed_method_call_on_range_end( &self, tcx: TyCtxt<'tcx>, actual: Ty<'tcx>, source: SelfSource<'tcx>, span: Span, item_name: Ident, ) -> Result<(), ErrorGuaranteed>

Suggest possible range with adding parentheses, for example: when encountering `0..1.map(|i| i + 1)` suggest `(0..1).map(|i| i + 1)`.

Source

#### fn report_failed_method_call_on_numerical_infer_var( &self, tcx: TyCtxt<'tcx>, actual: Ty<'tcx>, source: SelfSource<'_>, span: Span, item_kind: &str, item_name: Ident, long_ty_path: &mut Option<PathBuf>, ) -> Result<(), ErrorGuaranteed>

Source

#### pub(crate) fn suggest_assoc_method_call(&self, segs: &[PathSegment<'_>])

For code `rect::area(...)`, if `rect` is a local variable and `area` is a valid assoc method for it, we try to suggest `rect.area()`

Source

#### fn suggest_calling_method_on_field( &self, err: &mut Diag<'_>, source: SelfSource<'tcx>, span: Span, actual: Ty<'tcx>, item_name: Ident, return_type: Option<Ty<'tcx>>, )

Suggest calling a method on a field i.e. `a.field.bar()` instead of `a.bar()`

Source

#### fn suggest_unwrapping_inner_self( &self, err: &mut Diag<'_>, source: SelfSource<'tcx>, actual: Ty<'tcx>, item_name: Ident, )

Source

#### pub(crate) fn note_unmet_impls_on_type( &self, err: &mut Diag<'_>, errors: &[FulfillmentError<'tcx>], suggest_derive: bool, )

Source

#### fn consider_suggesting_derives_for_ty( &self, trait_pred: TraitPredicate<'tcx>, adt: AdtDef<'tcx>, ) -> Option<Vec<(String, Span, Symbol)>>

Checks if we can suggest a derive macro for the unmet trait bound. Returns Some(list_of_derives) if possible, or None if not.

Source

#### fn note_predicate_source_and_get_derives( &self, err: &mut Diag<'_>, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, ) -> Vec<(String, Span, Symbol)>

Source

#### pub(crate) fn suggest_derive( &self, err: &mut Diag<'_>, unsatisfied_predicates: &Vec<(Predicate<'tcx>, Option<Predicate<'tcx>>, Option<ObligationCause<'tcx>>)>, ) -> bool

Source

#### fn note_derefed_ty_has_method( &self, err: &mut Diag<'_>, self_source: SelfSource<'tcx>, rcvr_ty: Ty<'tcx>, item_name: Ident, expected: Expectation<'tcx>, )

Source

#### fn suggest_bounds_for_range_to_method( &self, err: &mut Diag<'_>, source: SelfSource<'tcx>, item_ident: Ident, )

Source

#### fn ty_to_value_string(&self, ty: Ty<'tcx>) -> String

Print out the type for use in value namespace.

Source

#### fn suggest_await_before_method( &self, err: &mut Diag<'_>, item_name: Ident, ty: Ty<'tcx>, call: &Expr<'_>, span: Span, return_type: Option<Ty<'tcx>>, )

Source

#### fn set_label_for_method_error( &self, err: &mut Diag<'_>, source: SelfSource<'tcx>, rcvr_ty: Ty<'tcx>, item_ident: Ident, expr_id: HirId, span: Span, sugg_span: Span, within_macro_span: Option<Span>, args: Option<&'tcx [Expr<'tcx>]>, )

Source

#### fn suggest_on_pointer_type( &self, err: &mut Diag<'_>, source: SelfSource<'tcx>, rcvr_ty: Ty<'tcx>, item_ident: Ident, )

Source

#### fn suggest_use_candidates<F>( &self, candidates: Vec<DefId>, handle_candidates: F, )
where F: FnOnce(Vec<String>, Vec<String>, Span),

Source

#### fn suggest_valid_traits( &self, err: &mut Diag<'_>, item_name: Ident, valid_out_of_scope_traits: Vec<DefId>, explain: bool, ) -> bool

Source

#### fn suggest_traits_to_import( &self, err: &mut Diag<'_>, span: Span, rcvr_ty: Ty<'tcx>, item_name: Ident, inputs_len: Option<usize>, source: SelfSource<'tcx>, valid_out_of_scope_traits: Vec<DefId>, static_candidates: &[CandidateSource], unsatisfied_bounds: bool, return_type: Option<Ty<'tcx>>, trait_missing_method: bool, )

Source

#### fn detect_and_explain_multiple_crate_versions_of_trait_item( &self, err: &mut Diag<'_>, item_def_id: DefId, hir_id: HirId, rcvr_ty: Option<Ty<'tcx>>, ) -> bool

Source

#### pub(crate) fn suggest_else_fn_with_closure( &self, err: &mut Diag<'_>, expr: &Expr<'_>, found: Ty<'tcx>, expected: Ty<'tcx>, ) -> bool

issue #102320, for `unwrap_or` with closure as argument, suggest `unwrap_or_else` FIXME: currently not working for suggesting `map_or_else`, see #102408

Source

#### fn type_derefs_to_local( &self, span: Span, rcvr_ty: Ty<'tcx>, source: SelfSource<'tcx>, ) -> bool

Checks whether there is a local type somewhere in the chain of autoderefs of `rcvr_ty`.

Source

#### fn suggest_hashmap_on_unsatisfied_hashset_buildhasher( &self, err: &mut Diag<'_>, pred: &TraitPredicate<'_>, adt: AdtDef<'_>, ) -> bool

Source

#### pub(crate) fn method_exists_for_diagnostic( &self, method_name: Ident, self_ty: Ty<'tcx>, call_expr_id: HirId, return_type: Option<Ty<'tcx>>, ) -> bool

Determines whether the type `self_ty` supports a visible method named `method_name` or not.

Source

#### pub(crate) fn suggest_method_call( &self, err: &mut Diag<'_>, msg: impl Into<DiagMessage> + Debug, method_name: Ident, self_ty: Ty<'tcx>, call_expr: &Expr<'tcx>, span: Option<Span>, )

Adds a suggestion to call the given method to the provided diagnostic.

Source

#### pub(crate) fn lookup_method( &self, self_ty: Ty<'tcx>, segment: &'tcx PathSegment<'tcx>, span: Span, call_expr: &'tcx Expr<'tcx>, self_expr: &'tcx Expr<'tcx>, args: &'tcx [Expr<'tcx>], ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>>

Performs method lookup. If lookup is successful, it will return the callee and store an appropriate adjustment for the self-expr. In some cases it may report an error (e.g., invoking the `drop` method).

##### §Arguments

Given a method call like `foo.bar::<T1,...Tn>(a, b + 1, ...)`:

- `self`: the surrounding `FnCtxt` (!)
- `self_ty`: the (unadjusted) type of the self expression (`foo`)
- `segment`: the name and generic arguments of the method (`bar::<T1, ...Tn>`)
- `span`: the span for the method call
- `call_expr`: the complete method call: (`foo.bar::<T1,...Tn>(...)`)
- `self_expr`: the self expression (`foo`)
- `args`: the expressions of the arguments (`a, b + 1, ...`)

Source

#### pub(crate) fn lookup_method_for_diagnostic( &self, self_ty: Ty<'tcx>, segment: &PathSegment<'tcx>, span: Span, call_expr: &'tcx Expr<'tcx>, self_expr: &'tcx Expr<'tcx>, ) -> Result<MethodCallee<'tcx>, MethodError<'tcx>>

Source

#### pub(crate) fn lookup_probe( &self, method_name: Ident, self_ty: Ty<'tcx>, call_expr: &Expr<'_>, scope: ProbeScope, ) -> Result<Pick<'tcx>, MethodError<'tcx>>

Source

#### pub(crate) fn lookup_probe_for_diagnostic( &self, method_name: Ident, self_ty: Ty<'tcx>, call_expr: &Expr<'_>, scope: ProbeScope, return_type: Option<Ty<'tcx>>, ) -> Result<Pick<'tcx>, MethodError<'tcx>>

Source

#### pub(crate) fn lookup_method_for_operator( &self, cause: ObligationCause<'tcx>, method_name: Symbol, trait_def_id: DefId, self_ty: Ty<'tcx>, opt_rhs_ty: Option<Ty<'tcx>>, treat_opaques: TreatNotYetDefinedOpaques, ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>>

`lookup_method_in_trait` is used for overloaded operators. It does a very narrow slice of what the normal probe/confirm path does. In particular, it doesn’t really do any probing: it simply constructs an obligation for a particular trait with the given self type and checks whether that trait is implemented.

Source

#### pub(crate) fn resolve_fully_qualified_call( &self, span: Span, method_name: Ident, self_ty: Ty<'tcx>, self_ty_span: Span, expr_id: HirId, ) -> Result<(DefKind, DefId), MethodError<'tcx>>

Performs a full-qualified function call (formerly “universal function call”) lookup. If lookup is successful, it will return the type of definition and the `DefId` of the found function definition.

##### §Arguments

Given a function call like `Foo::bar::<T1,...Tn>(...)`:

- `self`: the surrounding `FnCtxt` (!)
- `span`: the span of the call, excluding arguments (`Foo::bar::<T1, ...Tn>`)
- `method_name`: the identifier of the function within the container type (`bar`)
- `self_ty`: the type to search within (`Foo`)
- `self_ty_span` the span for the type being searched within (span of `Foo`)
- `expr_id`: the `hir::HirId` of the expression composing the entire call

Source

#### fn associated_value( &self, def_id: DefId, item_ident: Ident, ) -> Option<AssocItem>

Finds item with name `item_ident` defined in impl/trait `def_id` and return it, or `None`, if no such item was defined there.

Source

#### pub(crate) fn check_expr_assign_op( &self, expr: &'tcx Expr<'tcx>, op: AssignOp, lhs: &'tcx Expr<'tcx>, rhs: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Checks a `a <op>= b`

Source

#### pub(crate) fn check_expr_binop( &self, expr: &'tcx Expr<'tcx>, op: BinOp, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Checks a potentially overloaded binary operator.

Source

#### fn enforce_builtin_binop_types( &self, lhs_span: Span, lhs_ty: Ty<'tcx>, rhs_span: Span, rhs_ty: Ty<'tcx>, category: BinOpCategory, ) -> Ty<'tcx>

Source

#### fn check_overloaded_binop( &self, expr: &'tcx Expr<'tcx>, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, op: Op, expected: Expectation<'tcx>, ) -> (Ty<'tcx>, Ty<'tcx>, Ty<'tcx>)

Source

#### fn overloaded_binop_ret_ty( &self, expr: &'tcx Expr<'tcx>, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, op: Op, expected: Expectation<'tcx>, lhs_ty: Ty<'tcx>, result: Result<MethodCallee<'tcx>, Vec<FulfillmentError<'tcx>>>, rhs_ty: Ty<'tcx>, ) -> Ty<'tcx>

Source

#### fn report_binop_fulfillment_errors( &self, expr: &'tcx Expr<'tcx>, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, op: Op, expected: Expectation<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>, errors: Vec<FulfillmentError<'tcx>>, ) -> Ty<'tcx>

Source

#### fn suggest_deref_or_call_for_binop_error( &self, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, op: Op, expected: Expectation<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>, err: &mut Diag<'_>, is_compatible_after_call: impl Fn(Ty<'tcx>, Ty<'tcx>) -> bool, )

Source

#### fn suggest_raw_ptr_binop_arithmetic( &self, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, op: Op, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>, err: &mut Diag<'_>, )

Source

#### fn suggest_raw_ptr_assign_arithmetic( &self, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, op: Op, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>, lhs_name_str: &str, err: &mut Diag<'_>, )

Source

#### fn suggest_different_borrow( &self, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, op: Op, expected: Expectation<'tcx>, err: &mut Diag<'_>, lhs_adjusted_ty: Ty<'tcx>, lhs_new_mutbl: Option<Mutability>, rhs_adjusted_ty: Ty<'tcx>, rhs_new_mutbl: Option<Mutability>, )

Source

#### fn is_lhs_of_assign_stmt(&self, expr: &Expr<'_>) -> bool

Source

#### fn suggest_deref_binop( &self, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, op: Op, expected: Expectation<'tcx>, rhs_ty: Ty<'tcx>, err: &mut Diag<'_>, lhs_deref_ty: Ty<'tcx>, )

Source

#### fn check_str_addition( &self, lhs_expr: &'tcx Expr<'tcx>, rhs_expr: &'tcx Expr<'tcx>, lhs_ty: Ty<'tcx>, rhs_ty: Ty<'tcx>, err: &mut Diag<'_>, op: Op, ) -> bool

Provide actionable suggestions when trying to add two strings with incorrect types, like `&str + &str`, `String + String` and `&str + &String`.

If this function returns `true` it means a note was printed, so we don’t need to print the normal “implementation of `std::ops::Add` might be missing” note

Source

#### pub(crate) fn check_user_unop( &self, ex: &'tcx Expr<'tcx>, operand_ty: Ty<'tcx>, op: UnOp, expected: Expectation<'tcx>, ) -> Ty<'tcx>

Source

#### fn lookup_op_method( &self, (lhs_expr, lhs_ty): (&'tcx Expr<'tcx>, Ty<'tcx>), opt_rhs: Option<(&'tcx Expr<'tcx>, Ty<'tcx>)>, (opname, trait_did): (Symbol, Option<DefId>), span: Span, expected: Expectation<'tcx>, ) -> Result<MethodCallee<'tcx>, Vec<FulfillmentError<'tcx>>>

Source

#### fn consider_opaque_type_use( &self, opaque_type_key: OpaqueTypeKey<'tcx>, hidden_type: ProvisionalHiddenType<'tcx>, ) -> UsageKind<'tcx>

Source

#### pub(crate) fn detect_opaque_types_added_during_writeback(&self)

We may in theory add further uses of an opaque after cloning the opaque types storage during writeback when computing the defining uses.

Silently ignoring them is dangerous and could result in ICE or even in unsoundness, so we make sure we catch such cases here. There’s currently no known code where this actually happens, even with the new solver which does normalize types in writeback after cloning the opaque type storage.

FIXME(@lcnr): I believe this should be possible in theory and would like an actual test here. After playing around with this for an hour, I wasn’t able to do anything which didn’t already try to normalize the opaque before then, either allowing compilation to succeed or causing an ambiguity error.

Source

#### fn pattern_cause( &self, ti: &TopInfo<'tcx>, cause_span: Span, ) -> ObligationCause<'tcx>

Source

#### fn demand_eqtype_pat_diag( &'a self, cause_span: Span, expected: Ty<'tcx>, actual: Ty<'tcx>, ti: &TopInfo<'tcx>, ) -> Result<(), Diag<'a>>

Source

#### fn demand_eqtype_pat( &self, cause_span: Span, expected: Ty<'tcx>, actual: Ty<'tcx>, ti: &TopInfo<'tcx>, ) -> Result<(), ErrorGuaranteed>

Source

#### fn downgrade_mut_inside_shared(&self) -> bool

Experimental pattern feature: after matching against a shared reference, do we limit the default binding mode in subpatterns to be `ref` when it would otherwise be `ref mut`? This corresponds to Rule 3 of RFC 3627.

Source

#### fn ref_pat_matches_inherited_ref( &self, edition: Edition, ) -> InheritedRefMatchRule

Experimental pattern feature: when do reference patterns match against inherited references? This corresponds to variations on Rule 4 of RFC 3627.

Source

#### fn ref_pat_matches_mut_ref(&self) -> bool

Experimental pattern feature: do `&` patterns match against `&mut` references, treating them as if they were shared references? This corresponds to Rule 5 of RFC 3627.

Source

#### pub(crate) fn check_pat_top( &self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, span: Option<Span>, origin_expr: Option<&'tcx Expr<'tcx>>, decl_origin: Option<DeclOrigin<'tcx>>, )

Type check the given top level pattern against the `expected` type.

If a `Some(span)` is provided and `origin_expr` holds, then the `span` represents the scrutinee’s span. The scrutinee is found in e.g. `match scrutinee { ... }` and `let pat = scrutinee;`.

Otherwise, `Some(span)` represents the span of a type expression which originated the `expected` type.

Source

#### fn check_pat( &self, pat: &'tcx Pat<'tcx>, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, )

Type check the given `pat` against the `expected` type with the provided `binding_mode` (default binding mode).

Outside of this module, `check_pat_top` should always be used. Conversely, inside this module, `check_pat_top` should never be used.

Source

#### fn check_pat_inner( &self, pat: &'tcx Pat<'tcx>, opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>, adjust_mode: AdjustMode, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn adjust_pat_info( &self, inner_pinnedness: Pinnedness, inner_mutability: Mutability, pat_info: PatInfo<'tcx>, ) -> PatInfo<'tcx>

Source

#### fn check_deref_pattern( &self, pat: &'tcx Pat<'tcx>, opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>, adjust_mode: AdjustMode, expected: Ty<'tcx>, inner_ty: Ty<'tcx>, pat_adjust_kind: PatAdjust, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn calc_adjust_mode( &self, pat: &'tcx Pat<'tcx>, opt_path_res: Option<Result<ResolvedPat<'tcx>, ErrorGuaranteed>>, ) -> AdjustMode

How should the binding mode and expected type be adjusted?

When the pattern contains a path, `opt_path_res` must be `Some(path_res)`.

Source

#### fn should_peel_ref(&self, peel_kind: PeelKind, expected: Ty<'tcx>) -> bool

Assuming `expected` is a reference type, determine whether to peel it before matching.

Source

#### fn should_peel_smart_pointer( &self, peel_kind: PeelKind, expected: Ty<'tcx>, ) -> bool

Determine whether `expected` is a smart pointer type that should be peeled before matching.

Source

#### fn check_pat_expr_unadjusted(&self, lt: &'tcx PatExpr<'tcx>) -> Ty<'tcx>

Source

#### fn check_pat_lit( &self, span: Span, expr: &PatExpr<'tcx>, lit_kind: &LitKind, expected: Ty<'tcx>, ti: &TopInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_pat_range( &self, span: Span, lhs: Option<&'tcx PatExpr<'tcx>>, rhs: Option<&'tcx PatExpr<'tcx>>, expected: Ty<'tcx>, ti: &TopInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn endpoint_has_type(&self, err: &mut Diag<'_>, span: Span, ty: Ty<'_>)

Source

#### fn emit_err_pat_range( &self, span: Span, lhs: Option<(bool, Ty<'tcx>, Span)>, rhs: Option<(bool, Ty<'tcx>, Span)>, ) -> ErrorGuaranteed

Source

#### fn check_pat_ident( &self, pat: &'tcx Pat<'tcx>, user_bind_annot: BindingMode, var_id: HirId, ident: Ident, sub: Option<&'tcx Pat<'tcx>>, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_binding_alt_eq_ty( &self, ba: BindingMode, span: Span, var_id: HirId, ty: Ty<'tcx>, ti: &TopInfo<'tcx>, )

When a variable is bound several times in a `PatKind::Or`, it’ll resolve all of the subsequent bindings of the same name to the first usage. Verify that all of these bindings have the same type by comparing them all against the type of that first pat.

Source

#### fn suggest_adding_missing_ref_or_removing_ref( &self, err: &mut Diag<'_>, span: Span, expected: Ty<'tcx>, actual: Ty<'tcx>, ba: BindingMode, )

Source

#### fn borrow_pat_suggestion(&self, err: &mut Diag<'_>, pat: &Pat<'_>)

Precondition: pat is a `Ref(_)` pattern

Source

#### fn check_dereferenceable( &self, span: Span, expected: Ty<'tcx>, inner: &Pat<'_>, ) -> Result<(), ErrorGuaranteed>

Source

#### fn resolve_pat_struct( &self, pat: &'tcx Pat<'tcx>, qpath: &QPath<'tcx>, ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed>

Source

#### fn check_pat_struct( &self, pat: &'tcx Pat<'tcx>, fields: &'tcx [PatField<'tcx>], has_rest_pat: bool, pat_ty: Ty<'tcx>, variant: &'tcx VariantDef, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn resolve_pat_path( &self, path_id: HirId, span: Span, qpath: &'tcx QPath<'_>, ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed>

Source

#### fn check_pat_path( &self, pat_id_for_diag: HirId, span: Span, resolved: &ResolvedPat<'tcx>, expected: Ty<'tcx>, ti: &TopInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn maybe_suggest_range_literal( &self, e: &mut Diag<'_>, opt_def_id: Option<DefId>, ident: Ident, ) -> bool

Source

#### fn emit_bad_pat_path( &self, e: Diag<'_>, hir_id: HirId, pat_span: Span, resolved_pat: &ResolvedPat<'tcx>, )

Source

#### fn resolve_pat_tuple_struct( &self, pat: &'tcx Pat<'tcx>, qpath: &'tcx QPath<'tcx>, ) -> Result<ResolvedPat<'tcx>, ErrorGuaranteed>

Source

#### fn check_pat_tuple_struct( &self, pat: &'tcx Pat<'tcx>, qpath: &'tcx QPath<'tcx>, subpats: &'tcx [Pat<'tcx>], ddpos: DotDotPos, res: Res, pat_ty: Ty<'tcx>, variant: &'tcx VariantDef, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn emit_err_pat_wrong_number_of_fields( &self, pat_span: Span, res: Res, qpath: &QPath<'_>, subpats: &'tcx [Pat<'tcx>], fields: &'tcx [FieldDef], expected: Ty<'tcx>, had_err: Result<(), ErrorGuaranteed>, ) -> ErrorGuaranteed

Source

#### fn check_pat_tuple( &self, span: Span, elements: &'tcx [Pat<'tcx>], ddpos: DotDotPos, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_struct_pat_fields( &self, adt_ty: Ty<'tcx>, pat: &'tcx Pat<'tcx>, variant: &'tcx VariantDef, fields: &'tcx [PatField<'tcx>], has_rest_pat: bool, pat_info: PatInfo<'tcx>, ) -> Result<(), ErrorGuaranteed>

Source

#### fn error_tuple_variant_index_shorthand( &self, variant: &VariantDef, pat: &Pat<'_>, fields: &[PatField<'_>], ) -> Result<(), ErrorGuaranteed>

Source

#### fn error_foreign_non_exhaustive_spat( &self, pat: &Pat<'_>, descr: &str, no_fields: bool, )

Source

#### fn error_field_already_bound( &self, span: Span, ident: Ident, other_field: Span, ) -> ErrorGuaranteed

Source

#### fn error_inexistent_fields( &self, kind_name: &str, inexistent_fields: &[&PatField<'tcx>], unmentioned_fields: &mut Vec<(&'tcx FieldDef, Ident)>, pat: &'tcx Pat<'tcx>, variant: &VariantDef, args: GenericArgsRef<'tcx>, ) -> Diag<'a>

Source

#### fn error_tuple_variant_as_struct_pat( &self, pat: &Pat<'_>, fields: &'tcx [PatField<'tcx>], variant: &VariantDef, ) -> Result<(), ErrorGuaranteed>

Source

#### fn get_suggested_tuple_struct_pattern( &self, fields: &[PatField<'_>], variant: &VariantDef, ) -> String

Source

#### fn error_no_accessible_fields( &self, pat: &Pat<'_>, fields: &'tcx [PatField<'tcx>], ) -> Diag<'a>

Returns a diagnostic reporting a struct pattern which is missing an `..` due to inaccessible fields.

    error: pattern requires `..` due to inaccessible fields
      --> src/main.rs:10:9
       |
    LL |     let foo::Foo {} = foo::Foo::default();
       |         ^^^^^^^^^^^
       |
    help: add a `..`
       |
    LL |     let foo::Foo { .. } = foo::Foo::default();
       |                  ^^^^^^

Source

#### fn lint_non_exhaustive_omitted_patterns( &self, pat: &Pat<'_>, unmentioned_fields: &[(&FieldDef, Ident)], ty: Ty<'tcx>, )

Report that a pattern for a `#[non_exhaustive]` struct marked with `non_exhaustive_omitted_patterns` is not exhaustive enough.

Nb: the partner lint for enums lives in `compiler/rustc_mir_build/src/thir/pattern/usefulness.rs`.

Source

#### fn error_unmentioned_fields( &self, pat: &Pat<'_>, unmentioned_fields: &[(&FieldDef, Ident)], have_inaccessible_fields: bool, fields: &'tcx [PatField<'tcx>], ) -> Diag<'a>

Returns a diagnostic reporting a struct pattern which does not mention some fields.

    error[E0027]: pattern does not mention field `bar`
      --> src/main.rs:15:9
       |
    LL |     let foo::Foo {} = foo::Foo::new();
       |         ^^^^^^^^^^^ missing field `bar`

Source

#### fn check_pat_box( &self, span: Span, inner: &'tcx Pat<'tcx>, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn check_pat_deref( &self, span: Span, inner: &'tcx Pat<'tcx>, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn deref_pat_target(&self, span: Span, source_ty: Ty<'tcx>) -> Ty<'tcx>

Source

#### fn register_deref_mut_bounds_if_needed( &self, span: Span, inner: &'tcx Pat<'tcx>, derefed_tys: impl IntoIterator<Item = Ty<'tcx>>, )

Check if the interior of a deref pattern (either explicit or implicit) has any `ref mut` bindings, which would require `DerefMut` to be emitted in MIR building instead of just `Deref`. We do this after checking the inner pattern, since we want to make sure to account for `ref mut` binding modes inherited from implicitly dereferencing `&mut` refs.

Source

#### fn check_pat_ref( &self, pat: &'tcx Pat<'tcx>, inner: &'tcx Pat<'tcx>, pat_pinned: Pinnedness, pat_mutbl: Mutability, expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Source

#### fn new_ref_ty( &self, span: Span, pinnedness: Pinnedness, mutbl: Mutability, ty: Ty<'tcx>, ) -> Ty<'tcx>

Create a reference or pinned reference type with a fresh region variable.

Source

#### fn new_pinned_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>

Create a pinned type.

Source

#### fn error_inherited_ref_mutability_mismatch( &self, pat: &'tcx Pat<'tcx>, pat_prefix_span: Option<Span>, ) -> ErrorGuaranteed

Source

#### fn try_resolve_slice_ty_to_array_ty( &self, before: &'tcx [Pat<'tcx>], slice: Option<&'tcx Pat<'tcx>>, span: Span, ) -> Option<Ty<'tcx>>

Source

#### fn pat_is_irrefutable(&self, decl_origin: Option<DeclOrigin<'_>>) -> bool

Used to determines whether we can infer the expected type in the slice pattern to be of type array. This is only possible if we’re in an irrefutable pattern. If we were to allow this in refutable patterns we wouldn’t e.g. report ambiguity in the following situation:

ⓘ

    struct Zeroes;
       const ARR: [usize; 2] = [0; 2];
       const ARR2: [usize; 2] = [2; 2];

       impl Into<&'static [usize; 2]> for Zeroes {
           fn into(self) -> &'static [usize; 2] {
               &ARR
           }
       }

       impl Into<&'static [usize]> for Zeroes {
           fn into(self) -> &'static [usize] {
               &ARR2
           }
       }

       fn main() {
           let &[a, b]: &[usize] = Zeroes.into() else {
              ..
           };
       }

If we’re in an irrefutable pattern we prefer the array impl candidate given that the slice impl candidate would be rejected anyway (if no ambiguity existed).

Source

#### fn check_pat_slice( &self, span: Span, before: &'tcx [Pat<'tcx>], slice: Option<&'tcx Pat<'tcx>>, after: &'tcx [Pat<'tcx>], expected: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> Ty<'tcx>

Type check a slice pattern.

Syntactically, these look like `[pat_0, ..., pat_n]`. Semantically, we are type checking a pattern with structure:

ⓘ

    [before_0, ..., before_n, (slice, after_0, ... after_n)?]

The type of `slice`, if it is present, depends on the `expected` type. If `slice` is missing, then so is `after_i`. If `slice` is present, it can still represent 0 elements.

Source

#### fn check_array_pat_len( &self, span: Span, element_ty: Ty<'tcx>, arr_ty: Ty<'tcx>, slice: Option<&'tcx Pat<'tcx>>, len: Const<'tcx>, min_len: u64, ) -> (Option<Ty<'tcx>>, Ty<'tcx>)

Type check the length of an array pattern.

Returns both the type of the variable length pattern (or `None`), and the potentially inferred array type. We only return `None` for the slice type if `slice.is_none()`.

Source

#### fn error_scrutinee_inconsistent_length( &self, span: Span, min_len: u64, size: u64, ) -> ErrorGuaranteed

Source

#### fn error_scrutinee_with_rest_inconsistent_length( &self, span: Span, min_len: u64, size: u64, ) -> ErrorGuaranteed

Source

#### fn error_scrutinee_unfixed_length(&self, span: Span) -> ErrorGuaranteed

Source

#### fn error_expected_array_or_slice( &self, span: Span, expected_ty: Ty<'tcx>, pat_info: PatInfo<'tcx>, ) -> ErrorGuaranteed

Source

#### fn is_slice_or_array_or_vector(&self, ty: Ty<'tcx>) -> (bool, Ty<'tcx>)

Source

#### fn add_rust_2024_migration_desugared_pat( &self, pat_id: HirId, subpat: &'tcx Pat<'tcx>, final_char: char, def_br_mutbl: Mutability, )

Record a pattern that’s invalid under Rust 2024 match ergonomics, along with a problematic span, so that the pattern migration lint can desugar it during THIR construction.

Source

#### pub(crate) fn lookup_derefing( &self, expr: &Expr<'_>, oprnd_expr: &'tcx Expr<'tcx>, oprnd_ty: Ty<'tcx>, ) -> Option<Ty<'tcx>>

Type-check `*oprnd_expr` with `oprnd_expr` type-checked already.

Source

#### pub(crate) fn lookup_indexing( &self, expr: &Expr<'_>, base_expr: &'tcx Expr<'tcx>, base_ty: Ty<'tcx>, index_expr: &'tcx Expr<'tcx>, idx_ty: Ty<'tcx>, ) -> Option<(Ty<'tcx>, Ty<'tcx>)>

Type-check `*base_expr[index_expr]` with `base_expr` and `index_expr` type-checked already.

Source

#### fn negative_index( &self, ty: Ty<'tcx>, span: Span, base_expr: &Expr<'_>, ) -> Option<(Ty<'tcx>, Ty<'tcx>)>

Source

#### fn try_index_step( &self, expr: &Expr<'_>, base_expr: &Expr<'_>, autoderef: &Autoderef<'a, 'tcx>, index_ty: Ty<'tcx>, index_expr: &Expr<'_>, ) -> Option<(Ty<'tcx>, Ty<'tcx>)>

To type-check `base_expr[index_expr]`, we progressively autoderef (and otherwise adjust) `base_expr`, looking for a type which either supports builtin indexing or overloaded indexing. This loop implements one step in that search; the autoderef loop is implemented by `lookup_indexing`.

Source

#### pub(crate) fn try_overloaded_place_op( &self, span: Span, base_ty: Ty<'tcx>, opt_rhs_ty: Option<Ty<'tcx>>, op: PlaceOp, ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>>

Try to resolve an overloaded place op. We only deal with the immutable variant here (Deref/Index). In some contexts we would need the mutable variant (DerefMut/IndexMut); those would be later converted by `convert_place_derefs_to_mutable`.

Source

#### fn try_mutable_overloaded_place_op( &self, span: Span, base_ty: Ty<'tcx>, opt_rhs_ty: Option<Ty<'tcx>>, op: PlaceOp, ) -> Option<InferOk<'tcx, MethodCallee<'tcx>>>

Source

#### pub(crate) fn convert_place_derefs_to_mutable(&self, expr: &Expr<'_>)

Convert auto-derefs, indices, etc of an expression from `Deref` and `Index` into `DerefMut` and `IndexMut` respectively.

This is a second pass of typechecking derefs/indices. We need this because we do not always know whether a place needs to be mutable or not in the first pass. This happens whether there is an implicit mutable reborrow, e.g. when the type is used as the receiver of a method call.

Source

#### fn convert_place_op_to_mutable( &self, op: PlaceOp, expr: &Expr<'_>, base_expr: &Expr<'_>, )

Source

#### pub(crate) fn closure_analyze(&self, body: &'tcx Body<'tcx>)

Source

#### fn analyze_closure( &self, closure_hir_id: HirId, span: Span, body_id: BodyId, body: &'tcx Body<'tcx>, capture_clause: CaptureBy, )

Analysis starting point.

Source

#### fn coroutine_body_consumes_upvars( &self, coroutine_def_id: LocalDefId, body: &'tcx Body<'tcx>, ) -> bool

Determines whether the body of the coroutine uses its upvars in a way that consumes (i.e. moves) the value, which would force the coroutine to `FnOnce`. In a more detailed comment above, we care whether this happens, since if this happens, we want to force the coroutine to move all of the upvars it would’ve borrowed from the parent coroutine-closure.

This only really makes sense to be called on the child coroutine of a coroutine-closure.

Source

#### fn final_upvar_tys(&self, closure_id: LocalDefId) -> Vec<Ty<'tcx>>

Source

#### fn process_collected_capture_information( &self, capture_clause: CaptureBy, capture_information: &Vec<(Place<'tcx>, CaptureInfo)>, ) -> (Vec<(Place<'tcx>, CaptureInfo)>, ClosureKind, Option<(Span, Place<'tcx>)>)

Adjusts the closure capture information to ensure that the operations aren’t unsafe, and that the path can be captured with required capture kind (depending on use in closure, move closure etc.)

Returns the set of adjusted information along with the inferred closure kind and span associated with the closure kind inference.

Note that we always infer a minimal kind, even if we don’t always use that in the final result (i.e., sometimes we’ve taken the closure kind from the expectations instead, and for coroutines we don’t even implement the closure traits really).

If we inferred that the closure needs to be FnMut/FnOnce, last element of the returned tuple contains a `Some()` with the `Place` that caused us to do so.

Source

#### fn compute_min_captures( &self, closure_def_id: LocalDefId, capture_information: Vec<(Place<'tcx>, CaptureInfo)>, closure_span: Span, )

Analyzes the information collected by `InferBorrowKind` to compute the min number of Places (and corresponding capture kind) that we need to keep track of to support all the required captured paths.

Note: If this function is called multiple times for the same closure, it will update the existing min_capture map that is stored in TypeckResults.

Eg:

    #[derive(Debug)]
    struct Point { x: i32, y: i32 }

    let s = String::from("s");  // hir_id_s
    let mut p = Point { x: 2, y: -2 }; // his_id_p
    let c = || {
           println!("{s:?}");  // L1
           p.x += 10;  // L2
           println!("{}" , p.y); // L3
           println!("{p:?}"); // L4
           drop(s);   // L5
    };

and let hir_id_L1..5 be the expressions pointing to use of a captured variable on the lines L1..5 respectively.

InferBorrowKind results in a structure like this:

ⓘ

    {
          Place(base: hir_id_s, projections: [], ....) -> {
                                                               capture_kind_expr: hir_id_L5,
                                                               path_expr_id: hir_id_L5,
                                                               capture_kind: ByValue
                                                          },
          Place(base: hir_id_p, projections: [Field(0, 0)], ...) -> {
                                                                        capture_kind_expr: hir_id_L2,
                                                                        path_expr_id: hir_id_L2,
                                                                        capture_kind: ByValue
                                                                    },
          Place(base: hir_id_p, projections: [Field(1, 0)], ...) -> {
                                                                        capture_kind_expr: hir_id_L3,
                                                                        path_expr_id: hir_id_L3,
                                                                        capture_kind: ByValue
                                                                    },
          Place(base: hir_id_p, projections: [], ...) -> {
                                                             capture_kind_expr: hir_id_L4,
                                                             path_expr_id: hir_id_L4,
                                                             capture_kind: ByValue
                                                         },
    }

After the min capture analysis, we get:

ⓘ

    {
          hir_id_s -> [
               Place(base: hir_id_s, projections: [], ....) -> {
                                                                   capture_kind_expr: hir_id_L5,
                                                                   path_expr_id: hir_id_L5,
                                                                   capture_kind: ByValue
                                                               },
          ],
          hir_id_p -> [
               Place(base: hir_id_p, projections: [], ...) -> {
                                                                  capture_kind_expr: hir_id_L2,
                                                                  path_expr_id: hir_id_L4,
                                                                  capture_kind: ByValue
                                                              },
          ],
    }

Source

#### fn perform_2229_migration_analysis( &self, closure_def_id: LocalDefId, body_id: BodyId, capture_clause: CaptureBy, span: Span, )

Perform the migration analysis for RFC 2229, and emit lint `disjoint_capture_drop_reorder` if needed.

Source

#### fn compute_2229_migrations_reasons( &self, auto_trait_reasons: UnordSet<&'static str>, drop_order: bool, ) -> MigrationWarningReason

Combines all the reasons for 2229 migrations

Source

#### fn compute_2229_migrations_for_trait( &self, min_captures: Option<&RootVariableMinCaptureList<'tcx>>, var_hir_id: HirId, closure_clause: CaptureBy, ) -> Option<FxIndexMap<UpvarMigrationInfo, UnordSet<&'static str>>>

Figures out the list of root variables (and their types) that aren’t completely captured by the closure when `capture_disjoint_fields` is enabled and auto-traits differ between the root variable and the captured paths.

Returns a tuple containing a HashMap of CapturesInfo that maps to a HashSet of trait names if migration is needed for traits for the provided var_hir_id, otherwise returns None

Source

#### fn compute_2229_migrations_for_drop( &self, closure_def_id: LocalDefId, closure_span: Span, min_captures: Option<&RootVariableMinCaptureList<'tcx>>, closure_clause: CaptureBy, var_hir_id: HirId, ) -> Option<FxIndexSet<UpvarMigrationInfo>>

Figures out the list of root variables (and their types) that aren’t completely captured by the closure when `capture_disjoint_fields` is enabled and drop order of some path starting at that root variable might be affected.

The output list would include a root variable if:

- It would have been moved into the closure when `capture_disjoint_fields` wasn’t enabled, and
- It wasn’t completely captured by the closure, and
- One of the paths starting at this root variable, that is not captured needs Drop.

This function only returns a HashSet of CapturesInfo for significant drops. If there are no significant drops than None is returned

Source

#### fn compute_2229_migrations( &self, closure_def_id: LocalDefId, closure_span: Span, closure_clause: CaptureBy, min_captures: Option<&RootVariableMinCaptureList<'tcx>>, ) -> (Vec<NeededMigration>, MigrationWarningReason)

Figures out the list of root variables (and their types) that aren’t completely captured by the closure when `capture_disjoint_fields` is enabled and either drop order of some path starting at that root variable might be affected or auto-traits differ between the root variable and the captured paths.

The output list would include a root variable if:

- It would have been moved into the closure when `capture_disjoint_fields` wasn’t enabled, and
- It wasn’t completely captured by the closure, and
- One of the paths starting at this root variable, that is not captured needs Drop or
- One of the paths captured does not implement all the auto-traits its root variable implements.

Returns a tuple containing a vector of MigrationDiagnosticInfo, as well as a String containing the reason why root variables whose HirId is contained in the vector should be captured

Source

#### fn has_significant_drop_outside_of_captures( &self, closure_def_id: LocalDefId, closure_span: Span, base_path_ty: Ty<'tcx>, captured_by_move_projs: Vec<&[Projection<'tcx>]>, ) -> bool

This is a helper function to `compute_2229_migrations_precise_pass`. Provided the type of a root variable and a list of captured paths starting at this root variable (expressed using list of `Projection` slices), it returns true if there is a path that is not captured starting at this root variable that implements Drop.

The way this function works is at a given call it looks at type `base_path_ty` of some base path say P and then list of projection slices which represent the different captures moved into the closure starting off of P.

This will make more sense with an example:

ⓘ

    struct FancyInteger(i32); // This implements Drop

    struct Point { x: FancyInteger, y: FancyInteger }
    struct Color;

    struct Wrapper { p: Point, c: Color }

    fn f(w: Wrapper) {
      let c = || {
          // Closure captures w.p.x and w.c by move.
      };

      c();
    }

If `capture_disjoint_fields` wasn’t enabled the closure would’ve moved `w` instead of the precise paths. If we look closely `w.p.y` isn’t captured which implements Drop and therefore Drop ordering would change and we want this function to return true.

Call stack to figure out if we need to migrate for `w` would look as follows:

Our initial base path is just `w`, and the paths captured from it are `w[p, x]` and `w[c]`. Notation:

- Ty(place): Type of place
- `(a, b)`: Represents the function parameters `base_path_ty` and `captured_by_move_projs` respectively.

ⓘ

                     (Ty(w), [ &[p, x], &[c] ])
    //                              |
    //                 ----------------------------
    //                 |                          |
    //                 v                          v
           (Ty(w.p), [ &[x] ])          (Ty(w.c), [ &[] ]) // I(1)
    //                 |                          |
    //                 v                          v
           (Ty(w.p), [ &[x] ])                 false
    //                 |
    //                 |
    //       -------------------------------
    //       |                             |
    //       v                             v
        (Ty((w.p).x), [ &[] ])     (Ty((w.p).y), []) // IMP 2
    //       |                             |
    //       v                             v
           false              NeedsSignificantDrop(Ty(w.p.y))
    //                                     |
    //                                     v
                                         true

IMP 1 `(Ty(w.c), [ &[] ])`: Notice the single empty slice inside `captured_projs`. This implies that the `w.c` is completely captured by the closure. Since drop for this path will be called when the closure is dropped we don’t need to migrate for it.

IMP 2 `(Ty((w.p).y), [])`: Notice that `captured_projs` is empty. This implies that this path wasn’t captured by the closure. Also note that even though we didn’t capture this path, the function visits it, which is kind of the point of this function. We then return if the type of `w.p.y` implements Drop, which in this case is true.

Consider another example:

ⓘ

    struct X;
    impl Drop for X {}

    struct Y(X);
    impl Drop for Y {}

    fn foo() {
        let y = Y(X);
        let c = || move(y.0);
    }

Note that `y.0` is captured by the closure. When this function is called for `y`, it will return true, because even though all paths starting at `y` are captured, `y` itself implements Drop which will be affected since `y` isn’t completely captured.

Source

#### fn init_capture_kind_for_place( &self, place: &Place<'tcx>, capture_clause: CaptureBy, ) -> UpvarCapture

Source

#### fn place_for_root_variable( &self, closure_def_id: LocalDefId, var_hir_id: HirId, ) -> Place<'tcx>

Source

#### fn should_log_capture_analysis(&self, closure_def_id: LocalDefId) -> bool

Source

#### fn log_capture_analysis_first_pass( &self, closure_def_id: LocalDefId, capture_information: &Vec<(Place<'tcx>, CaptureInfo)>, closure_span: Span, )

Source

#### fn log_closure_min_capture_info( &self, closure_def_id: LocalDefId, closure_span: Span, )

Source

#### fn determine_capture_mutability( &self, typeck_results: &'a TypeckResults<'tcx>, place: &Place<'tcx>, ) -> Mutability

A captured place is mutable if

1. Projections don’t include a Deref of an immut-borrow, and
2. PlaceBase is mut or projections include a Deref of a mut-borrow.

Source

#### pub(crate) fn resolve_type_vars_in_body( &self, body: &'tcx Body<'tcx>, ) -> &'tcx TypeckResults<'tcx>

## Methods from Deref<Target = TypeckRootCtxt<'tcx>>§

Source

#### pub(crate) fn register_predicate(&self, obligation: PredicateObligation<'tcx>)

Source

#### pub(crate) fn register_predicates<I>(&self, obligations: I)
where I: IntoIterator<Item = PredicateObligation<'tcx>>,

Source

#### pub(crate) fn register_infer_ok_obligations<T>( &self, infer_ok: InferOk<'tcx, T>, ) -> T

## Methods from Deref<Target = InferCtxt<'tcx>>§

#### pub fn at<'a>( &'a self, cause: &'a ObligationCause<'tcx>, param_env: ParamEnv<'tcx>, ) -> At<'a, 'tcx>

#### pub fn fork(&self) -> InferCtxt<'tcx>

Forks the inference context, creating a new inference context with the same inference variables in the same state. This can be used to “branch off” many tests from the same common state.

#### pub fn fork_with_typing_mode( &self, typing_mode: TypingMode<TyCtxt<'tcx>>, ) -> InferCtxt<'tcx>

Forks the inference context, creating a new inference context with the same inference variables in the same state, except possibly changing the intercrate mode. This can be used to “branch off” many tests from the same common state. Used in negative coherence.

#### pub fn canonicalize_query<V>( &self, value: ParamEnvAnd<'tcx, V>, query_state: &mut OriginalQueryValues<'tcx>, ) -> CanonicalQueryInput<TyCtxt<'tcx>, ParamEnvAnd<'tcx, V>>
where V: TypeFoldable<TyCtxt<'tcx>>,

Canonicalizes a query value `V`. When we canonicalize a query, we not only canonicalize unbound inference variables, but we also replace all free regions whatsoever. So for example a query like `T: Trait<'static>` would be canonicalized to

    T: Trait<'?0>

with a mapping M that maps `'?0` to `'static`.

To get a good understanding of what is happening here, check out the chapter in the rustc dev guide.

#### pub fn canonicalize_response<V>(&self, value: V) -> Canonical<TyCtxt<'tcx>, V>
where V: TypeFoldable<TyCtxt<'tcx>>,

Canonicalizes a query response `V`. When we canonicalize a query response, we only canonicalize unbound inference variables, and we leave other free regions alone. So, continuing with the example from `canonicalize_query`, if there was an input query `T: Trait<'static>`, it would have been canonicalized to

    T: Trait<'?0>

with a mapping M that maps `'?0` to `'static`. But if we found that there exists only one possible impl of `Trait`, and it looks like

ⓘ

    impl<T> Trait<'static> for T { .. }

then we would prepare a query result R that (among other things) includes a mapping to `'?0 := 'static`. When canonicalizing this query result R, we would leave this reference to `'static` alone.

To get a good understanding of what is happening here, check out the chapter in the rustc dev guide.

#### pub fn canonicalize_user_type_annotation<V>( &self, value: V, ) -> Canonical<TyCtxt<'tcx>, V>
where V: TypeFoldable<TyCtxt<'tcx>>,

#### pub fn make_canonicalized_query_response<T>( &self, inference_vars: CanonicalVarValues<TyCtxt<'tcx>>, answer: T, fulfill_cx: &mut (dyn TraitEngine<'tcx, ScrubbedTraitError<'tcx>> + 'tcx), ) -> Result<&'tcx Canonical<TyCtxt<'tcx>, QueryResponse<'tcx, T>>, NoSolution>
where T: Debug + TypeFoldable<TyCtxt<'tcx>>, Canonical<TyCtxt<'tcx>, QueryResponse<'tcx, T>>: ArenaAllocatable<'tcx>,

This method is meant to be invoked as the final step of a canonical query implementation. It is given:

- the instantiated variables `inference_vars` created from the query key
- the result `answer` of the query
- a fulfillment context `fulfill_cx` that may contain various obligations which have yet to be proven.

Given this, the function will process the obligations pending in `fulfill_cx`:

- If all the obligations can be proven successfully, it will package up any resulting region obligations (extracted from `infcx`) along with the fully resolved value `answer` into a query result (which is then itself canonicalized).
- If some obligations can be neither proven nor disproven, then the same thing happens, but the resulting query is marked as ambiguous.
- Finally, if any of the obligations result in a hard error, then `Err(NoSolution)` is returned.

#### pub fn make_query_response_ignoring_pending_obligations<T>( &self, inference_vars: CanonicalVarValues<TyCtxt<'tcx>>, answer: T, prev_entries: OpaqueTypeStorageEntries, ) -> Canonical<TyCtxt<'tcx>, QueryResponse<'tcx, T>>
where T: Debug + TypeFoldable<TyCtxt<'tcx>>,

A version of `make_canonicalized_query_response` that does not pack in obligations, for contexts that want to drop pending obligations instead of treating them as an ambiguity (e.g. typeck “probing” contexts).

If you DO want to keep track of pending obligations (which include all region obligations, so this includes all cases that care about regions) with this function, you have to do it yourself, by e.g., having them be a part of the answer.

#### pub fn instantiate_query_response_and_region_obligations<R>( &self, cause: &ObligationCause<'tcx>, param_env: ParamEnv<'tcx>, original_values: &OriginalQueryValues<'tcx>, query_response: &Canonical<TyCtxt<'tcx>, QueryResponse<'tcx, R>>, ) -> Result<InferOk<'tcx, R>, TypeError<TyCtxt<'tcx>>>
where R: Debug + TypeFoldable<TyCtxt<'tcx>>,

Given the (canonicalized) result to a canonical query, instantiates the result so it can be used, plugging in the values from the canonical query. (Note that the result may have been ambiguous; you should check the certainty level of the query before applying this function.)

To get a good understanding of what is happening here, check out the chapter in the rustc dev guide.

#### pub fn instantiate_nll_query_response_and_region_obligations<R>( &self, cause: &ObligationCause<'tcx>, param_env: ParamEnv<'tcx>, original_values: &OriginalQueryValues<'tcx>, query_response: &Canonical<TyCtxt<'tcx>, QueryResponse<'tcx, R>>, output_query_region_constraints: &mut QueryRegionConstraints<'tcx>, ) -> Result<InferOk<'tcx, R>, TypeError<TyCtxt<'tcx>>>
where R: Debug + TypeFoldable<TyCtxt<'tcx>>,

An alternative to `instantiate_query_response_and_region_obligations` that is more efficient for NLL. NLL is a bit more advanced in the “transition to chalk” than the rest of the compiler. During the NLL type check, all of the “processing” of types and things happens in queries – the NLL checker itself is only interested in the region obligations (`'a: 'b` or `T: 'b`) that come out of these queries, which it wants to convert into MIR-based constraints and solve. Therefore, it is most convenient for the NLL Type Checker to directly consume the `QueryOutlivesConstraint` values that arise from doing a query. This is contrast to other parts of the compiler, which would prefer for those `QueryOutlivesConstraint` to be converted into the older infcx-style constraints (e.g., calls to `sub_regions` or `register_region_obligation`).

Therefore, `instantiate_nll_query_response_and_region_obligations` performs the same basic operations as `instantiate_query_response_and_region_obligations` but it returns its result differently:

- It creates an instantiation `S` that maps from the original query variables to the values computed in the query result. If any errors arise, they are propagated back as an `Err` result.
- In the case of a successful instantiation, we will append `QueryOutlivesConstraint` values onto the `output_query_region_constraints` vector for the solver to use (if an error arises, some values may also be pushed, but they should be ignored).
- It can happen (though it rarely does currently) that equating types and things will give rise to subobligations that must be processed. In this case, those subobligations are propagated back in the return value.
- Finally, the query result (of type `R`) is propagated back, after applying the instantiation `S`.

#### pub fn instantiate_canonical<T>( &self, span: Span, canonical: &Canonical<TyCtxt<'tcx>, T>, ) -> (T, CanonicalVarValues<TyCtxt<'tcx>>)
where T: TypeFoldable<TyCtxt<'tcx>>,

Creates an instantiation S for the canonical value with fresh inference variables and placeholders then applies it to the canonical value. Returns both the instantiated result and the instantiation S.

This can be invoked as part of constructing an inference context at the start of a query (see `InferCtxtBuilder::build_with_canonical`). It basically brings the canonical value “into scope” within your new infcx.

At the end of processing, the instantiation S (once canonicalized) then represents the values that you computed for each of the canonical inputs to your query.

#### pub fn instantiate_canonical_var( &self, span: Span, kind: CanonicalVarKind<TyCtxt<'tcx>>, previous_var_values: &[GenericArg<'tcx>], universe_map: impl Fn(UniverseIndex) -> UniverseIndex, ) -> GenericArg<'tcx>

Given the “info” about a canonical variable, creates a fresh variable for it. If this is an existentially quantified variable, then you’ll get a new inference variable; if it is a universally quantified variable, you get a placeholder.

FIXME(-Znext-solver): This is public because it’s used by the new trait solver which has a different canonicalization routine. We should somehow deduplicate all of this.

#### pub fn replace_opaque_types_with_inference_vars<T>( &self, value: T, body_id: LocalDefId, span: Span, param_env: ParamEnv<'tcx>, ) -> InferOk<'tcx, T>
where T: TypeFoldable<TyCtxt<'tcx>>,

This is a backwards compatibility hack to prevent breaking changes from lazy TAIT around RPIT handling.

#### pub fn handle_opaque_type( &self, a: Ty<'tcx>, b: Ty<'tcx>, span: Span, param_env: ParamEnv<'tcx>, ) -> Result<Vec<Goal<TyCtxt<'tcx>, Predicate<'tcx>>>, TypeError<TyCtxt<'tcx>>>

#### pub fn register_hidden_type_in_storage( &self, opaque_type_key: OpaqueTypeKey<TyCtxt<'tcx>>, hidden_ty: ProvisionalHiddenType<'tcx>, ) -> Option<Ty<'tcx>>

Insert a hidden type into the opaque type storage, making sure it hasn’t previously been defined. This does not emit any constraints and it’s the responsibility of the caller to make sure that the item bounds of the opaque are checked.

#### pub fn insert_hidden_type( &self, opaque_type_key: OpaqueTypeKey<TyCtxt<'tcx>>, span: Span, param_env: ParamEnv<'tcx>, hidden_ty: Ty<'tcx>, goals: &mut Vec<Goal<TyCtxt<'tcx>, Predicate<'tcx>>>, ) -> Result<(), TypeError<TyCtxt<'tcx>>>

Insert a hidden type into the opaque type storage, equating it with any previous entries if necessary.

This does not add the item bounds of the opaque as nested obligations. That is only necessary when normalizing the opaque itself, not when getting the opaque type constraints from somewhere else.

#### pub fn add_item_bounds_for_hidden_type( &self, def_id: DefId, args: &'tcx RawList<(), GenericArg<'tcx>>, param_env: ParamEnv<'tcx>, hidden_ty: Ty<'tcx>, goals: &mut Vec<Goal<TyCtxt<'tcx>, Predicate<'tcx>>>, )

#### pub fn register_outlives_constraint( &self, _: OutlivesPredicate<TyCtxt<'tcx>, GenericArg<'tcx>>, vis: VisibleForLeakCheck, cause: &ObligationCause<'tcx>, )

#### pub fn register_region_eq_constraint( &self, _: RegionEqPredicate<TyCtxt<'tcx>>, vis: VisibleForLeakCheck, cause: &ObligationCause<'tcx>, )

#### pub fn register_region_outlives_constraint( &self, _: OutlivesPredicate<TyCtxt<'tcx>, Region<'tcx>>, vis: VisibleForLeakCheck, cause: &ObligationCause<'tcx>, )

#### pub fn register_type_outlives_constraint_inner( &self, obligation: TypeOutlivesConstraint<'tcx>, )

Registers that the given region obligation must be resolved from within the scope of `body_id`. These regions are enqueued and later processed by regionck, when full type information is available (see `region_obligations` field for more information).

#### pub fn register_type_outlives_constraint( &self, sup_type: Ty<'tcx>, sub_region: Region<'tcx>, cause: &ObligationCause<'tcx>, )

#### pub fn take_registered_region_obligations( &self, ) -> Vec<TypeOutlivesConstraint<'tcx>>

Trait queries just want to pass back type obligations “as is”

#### pub fn clone_registered_region_obligations( &self, ) -> Vec<TypeOutlivesConstraint<'tcx>>

#### pub fn register_region_assumption( &self, assumption: OutlivesPredicate<TyCtxt<'tcx>, GenericArg<'tcx>>, )

#### pub fn take_registered_region_assumptions( &self, ) -> Vec<OutlivesPredicate<TyCtxt<'tcx>, GenericArg<'tcx>>>

#### pub fn destructure_solver_region_constraints_for_regionck( &self, outlives_env: &OutlivesEnvironment<'tcx>, span: Span, )

#### pub fn destructure_solver_region_constraints_for_borrowck( &self, conversion: impl TypeOutlivesDelegate<'tcx>, known_type_outlives: &[Binder<TyCtxt<'tcx>, OutlivesPredicate<TyCtxt<'tcx>, Ty<'tcx>>>], region_outlives: TransitiveRelation<RegionVid>, span: Span, )

#### pub fn destructure_solver_region_constraints( &self, assumptions: Assumptions<TyCtxt<'tcx>>, conversion: impl TypeOutlivesDelegate<'tcx>, span: Span, )

#### pub fn process_registered_region_obligations( &self, outlives_env: &OutlivesEnvironment<'tcx>, deeply_normalize_ty: impl FnMut(Binder<TyCtxt<'tcx>, OutlivesPredicate<TyCtxt<'tcx>, Ty<'tcx>>>, SubregionOrigin<'tcx>) -> Result<Binder<TyCtxt<'tcx>, OutlivesPredicate<TyCtxt<'tcx>, Ty<'tcx>>>, NoSolution>, span: Span, ) -> Result<(), (Binder<TyCtxt<'tcx>, OutlivesPredicate<TyCtxt<'tcx>, Ty<'tcx>>>, SubregionOrigin<'tcx>)>

Process the region obligations that must be proven (during `regionck`) for the given `body_id`, given information about the region bounds in scope and so forth.

See the `region_obligations` field of `InferCtxt` for some comments about how this function fits into the overall expected flow of the inferencer. The key point is that it is invoked after all type-inference variables have been bound – right before lexical region resolution.

#### pub fn resolve_regions_with_normalize( &self, outlives_env: &OutlivesEnvironment<'tcx>, deeply_normalize_ty: impl Fn(Binder<TyCtxt<'tcx>, OutlivesPredicate<TyCtxt<'tcx>, Ty<'tcx>>>, SubregionOrigin<'tcx>) -> Result<Binder<TyCtxt<'tcx>, OutlivesPredicate<TyCtxt<'tcx>, Ty<'tcx>>>, NoSolution>, span: Span, ) -> Vec<RegionResolutionError<'tcx>>

Process the region constraints and return any errors that result. After this, no more unification operations should be done – or the compiler will panic – but it is legal to use `resolve_vars_if_possible` as well as `fully_resolve`.

If you are in a crate that has access to `rustc_trait_selection`, then it’s probably better to use `resolve_regions`, which knows how to normalize registered region obligations.

#### pub fn take_and_reset_region_constraints(&self) -> RegionConstraintData<'tcx>

Obtains (and clears) the current set of region constraints. The inference context is still usable: further unifications will simply add new constraints.

This method is not meant to be used with normal lexical region resolution. Rather, it is used in the NLL mode as a kind of interim hack: basically we run normal type-check and generate region constraints as normal, but then we take them and translate them into the form that the NLL solver understands. See the NLL module for mode details.

#### pub fn with_region_constraints<R>( &self, op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, ) -> R

Gives temporary access to the region constraint data.

#### pub fn projection_term_to_infer( &self, param_env: ParamEnv<'tcx>, alias_term: AliasTerm<TyCtxt<'tcx>>, cause: ObligationCause<'tcx>, recursion_depth: usize, obligations: &mut ThinVec<Obligation<'tcx, Predicate<'tcx>>>, ) -> Term<'tcx>

Instead of normalizing an associated type projection, this function generates an inference variable and registers an obligation that this inference variable must be the result of the given projection. This allows us to proceed with projections while they cannot be resolved yet due to missing information or simply due to the lack of access to the trait resolution machinery.

#### pub fn instantiate_ty_var<R>( &self, relation: &mut R, target_is_expected: bool, target_vid: TyVid, instantiation_variance: Variance, source_ty: Ty<'tcx>, ) -> Result<(), TypeError<TyCtxt<'tcx>>>
where R: PredicateEmittingRelation<InferCtxt<'tcx>>,

The idea is that we should ensure that the type variable `target_vid` is equal to, a subtype of, or a supertype of `source_ty`.

For this, we will instantiate `target_vid` with a generalized version of `source_ty`. Generalization introduces other inference variables wherever subtyping could occur. This also does the occurs checks, detecting whether instantiating `target_vid` would result in a cyclic type. We eagerly error in this case.

This is not expected to be used anywhere except for an implementation of `TypeRelation`. Do not use this, and instead please use `At::eq`, for all other usecases (i.e. setting the value of a type var).

#### pub fn enter_forall_and_leak_universe<T>( &self, binder: Binder<TyCtxt<'tcx>, T>, ) -> T
where T: TypeFoldable<TyCtxt<'tcx>>,

Replaces all bound variables (lifetimes, types, and constants) bound by `binder` with placeholder variables in a new universe. This means that the new placeholders can only be named by inference variables created after this method has been called.

This is the first step of checking subtyping when higher-ranked things are involved. For more details visit the relevant sections of the rustc dev guide.

`fn enter_forall` should be preferred over this method.

#### pub fn enter_forall<T, U>( &self, forall: Binder<TyCtxt<'tcx>, T>, f: impl FnOnce(T) -> U, ) -> U
where T: TypeFoldable<TyCtxt<'tcx>>,

Replaces all bound variables (lifetimes, types, and constants) bound by `binder` with placeholder variables in a new universe and then calls the closure `f` with the instantiated value. The new placeholders can only be named by inference variables created inside of the closure `f` or afterwards.

This is the first step of checking subtyping when higher-ranked things are involved. For more details visit the relevant sections of the rustc dev guide.

This method should be preferred over `fn enter_forall_and_leak_universe`.

#### pub fn leak_check( &self, outer_universe: UniverseIndex, only_consider_snapshot: Option<&CombinedSnapshot<'tcx>>, ) -> Result<(), TypeError<TyCtxt<'tcx>>>

See RegionConstraintCollector::leak_check. We only check placeholder leaking into `outer_universe`, i.e. placeholders which cannot be named by that universe.

#### pub fn fudge_inference_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
where F: FnOnce() -> Result<T, E>, T: TypeFoldable<TyCtxt<'tcx>>, E: Debug,

This rather funky routine is used while processing expected types. What happens here is that we want to propagate a coercion through the return type of a fn to its argument. Consider the type of `Option::Some`, which is basically `for<T> fn(T) -> Option<T>`. So if we have an expression `Some(&[1, 2, 3])`, and that has the expected type `Option<&[u32]>`, we would like to type check `&[1, 2, 3]` with the expectation of `&[u32]`. This will cause us to coerce from `&[u32; 3]` to `&[u32]` and make the users life more pleasant.

The way we do this is using `fudge_inference_if_ok`. What the routine actually does is to start a snapshot and execute the closure `f`. In our example above, what this closure will do is to unify the expectation (`Option<&[u32]>`) with the actual return type (`Option<?T>`, where `?T` represents the variable instantiated for `T`). This will cause `?T` to be unified with `&?a [u32]`, where `?a` is a fresh lifetime variable. The input type (`?T`) is then returned by `f()`.

At this point, `fudge_inference_if_ok` will normalize all type variables, converting `?T` to `&?a [u32]` and end the snapshot. The problem is that we can’t just return this type out, because it references the region variable `?a`, and that region variable was popped when we popped the snapshot.

So what we do is to keep a list (`region_vars`, in the code below) of region variables created during the snapshot (here, `?a`). We fold the return value and replace any such regions with a new region variable (e.g., `?b`) and return the result (`&?b [u32]`). This can then be used as the expectation for the fn argument.

The important point here is that, for soundness purposes, the regions in question are not particularly important. We will use the expected types to guide coercions, but we will still type-check the resulting types from those coercions against the actual types (`?T`, `Option<?T>`) – and remember that after the snapshot is popped, the variable `?T` is no longer unified.

#### pub fn in_snapshot(&self) -> bool

#### pub fn num_open_snapshots(&self) -> usize

#### pub fn commit_if_ok<T, E, F>(&self, f: F) -> Result<T, E>
where F: FnOnce(&CombinedSnapshot<'tcx>) -> Result<T, E>,

Execute `f` and commit the bindings if closure `f` returns `Ok(_)`.

#### pub fn probe<R, F>(&self, f: F) -> R
where F: FnOnce(&CombinedSnapshot<'tcx>) -> R,

Execute `f` then unroll any bindings it creates.

#### pub fn region_constraints_added_in_snapshot( &self, snapshot: &CombinedSnapshot<'tcx>, ) -> bool

Scan the constraints produced since `snapshot` and check whether we added any region constraints.

#### pub fn opaque_types_added_in_snapshot( &self, snapshot: &CombinedSnapshot<'tcx>, ) -> bool

#### pub fn dcx(&self) -> DiagCtxtHandle<'_>

#### pub fn next_trait_solver(&self) -> bool

#### pub fn typing_mode_raw(&self) -> TypingMode<TyCtxt<'tcx>>

This method is deliberately called `..._raw`, since the output may possibly include `TypingMode::ErasedNotCoherence`. `ErasedNotCoherence` is an implementation detail of the next trait solver, see its docs for more information.

`InferCtxt` has two uses: the trait solver calls some methods on it, because the `InferCtxt` works as a kind of store for for example type unification information. `InferCtxt` is also often used outside the trait solver during typeck. There, we don’t care about the `ErasedNotCoherence` case and should never encounter it. To make sure these two uses are never confused, we want to statically encode this information.

The `FnCtxt`, for example, is only used in the outside-trait-solver case. It has a non-raw version of the `typing_mode` method available that asserts `ErasedNotCoherence` is impossible, and returns a `TypingMode` where `ErasedNotCoherence` is made uninhabited using the `CantBeErased` enum. That way you don’t even have to match on the variant and can safely ignore it.

Prefer non-raw apis if available. e.g.,

- On the `FnCtxt`
- on the `SelectionCtxt`

#### pub fn disable_trait_solver_fast_paths(&self) -> bool

#### pub fn type_var_origin(&self, vid: TyVid) -> TypeVariableOrigin

Returns the origin of the type variable identified by `vid`.

No attempt is made to resolve `vid` to its root variable.

#### pub fn float_var_origin(&self, vid: FloatVid) -> FloatVariableOrigin

Returns the origin of the float type variable identified by `vid`.

No attempt is made to resolve `vid` to its root variable.

#### pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin>

Returns the origin of the const variable identified by `vid`

#### pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>>

#### pub fn sub_regions( &self, origin: SubregionOrigin<'tcx>, a: Region<'tcx>, b: Region<'tcx>, vis: VisibleForLeakCheck, )

#### pub fn equate_regions( &self, origin: SubregionOrigin<'tcx>, a: Region<'tcx>, b: Region<'tcx>, vis: VisibleForLeakCheck, )

#### pub fn coerce_predicate( &self, cause: &ObligationCause<'tcx>, param_env: ParamEnv<'tcx>, predicate: Binder<TyCtxt<'tcx>, CoercePredicate<TyCtxt<'tcx>>>, ) -> Result<Result<InferOk<'tcx, ()>, TypeError<TyCtxt<'tcx>>>, (TyVid, TyVid)>

Processes a `Coerce` predicate from the fulfillment context. This is NOT the preferred way to handle coercion, which is to invoke `FnCtxt::coerce` or a similar method (see `coercion.rs`).

This method here is actually a fallback that winds up being invoked when `FnCtxt::coerce` encounters unresolved type variables and records a coercion predicate. Presently, this method is equivalent to `subtype_predicate` – that is, “coercing” `a` to `b` winds up actually requiring `a <: b`. This is of course a valid coercion, but it’s not as flexible as `FnCtxt::coerce` would be.

(We may refactor this in the future, but there are a number of practical obstacles. Among other things, `FnCtxt::coerce` presently records adjustments that are required on the HIR in order to perform the coercion, and we don’t currently have a way to manage that.)

#### pub fn subtype_predicate( &self, cause: &ObligationCause<'tcx>, param_env: ParamEnv<'tcx>, predicate: Binder<TyCtxt<'tcx>, SubtypePredicate<TyCtxt<'tcx>>>, ) -> Result<Result<InferOk<'tcx, ()>, TypeError<TyCtxt<'tcx>>>, (TyVid, TyVid)>

#### pub fn num_ty_vars(&self) -> usize

Number of type variables created so far.

#### pub fn next_ty_vid(&self, span: Span) -> TyVid

#### pub fn next_ty_vid_with_origin(&self, origin: TypeVariableOrigin) -> TyVid

#### pub fn next_ty_vid_in_universe( &self, span: Span, universe: UniverseIndex, ) -> TyVid

#### pub fn next_ty_var(&self, span: Span) -> Ty<'tcx>

#### pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx>

#### pub fn next_ty_var_in_universe( &self, span: Span, universe: UniverseIndex, ) -> Ty<'tcx>

#### pub fn next_const_var(&self, span: Span) -> Const<'tcx>

#### pub fn next_const_var_with_origin( &self, origin: ConstVariableOrigin, ) -> Const<'tcx>

#### pub fn next_const_var_in_universe( &self, span: Span, universe: UniverseIndex, ) -> Const<'tcx>

#### pub fn next_int_var(&self) -> Ty<'tcx>

#### pub fn next_float_var(&self, span: Span, lint_id: Option<HirId>) -> Ty<'tcx>

#### pub fn next_region_var( &self, origin: RegionVariableOrigin<'tcx>, ) -> Region<'tcx>

Creates a fresh region variable with the next available index. The variable will be created in the maximum universe created thus far, allowing it to name any region created thus far.

#### pub fn next_region_var_in_universe( &self, origin: RegionVariableOrigin<'tcx>, universe: UniverseIndex, ) -> Region<'tcx>

Creates a fresh region variable with the next available index in the given universe; typically, you can use `next_region_var` and just use the maximal universe.

#### pub fn next_term_var_of_kind(&self, term: Term<'tcx>, span: Span) -> Term<'tcx>

#### pub fn universe_of_region(&self, r: Region<'tcx>) -> UniverseIndex

Return the universe that the region `r` was created in. For most regions (e.g., `'static`, named regions from the user, etc) this is the root universe U0. For inference variables or placeholders, however, it will return the universe which they are associated.

#### pub fn num_region_vars(&self) -> usize

Number of region variables created so far.

#### pub fn next_nll_region_var( &self, origin: NllRegionVariableOrigin<'tcx>, ) -> Region<'tcx>

Just a convenient wrapper of `next_region_var` for using during NLL.

#### pub fn next_nll_region_var_in_universe( &self, origin: NllRegionVariableOrigin<'tcx>, universe: UniverseIndex, ) -> Region<'tcx>

Just a convenient wrapper of `next_region_var` for using during NLL.

#### pub fn var_for_def( &self, span: Span, param: &GenericParamDef, ) -> GenericArg<'tcx>

#### pub fn fresh_args_for_item( &self, span: Span, def_id: DefId, ) -> &'tcx RawList<(), GenericArg<'tcx>>

Given a set of generics defined on a type or impl, returns the generic parameters mapping each type/region parameter to a fresh inference variable.

#### pub fn tainted_by_errors(&self) -> Option<ErrorGuaranteed>

Returns `true` if errors have been reported since this infcx was created. This is sometimes used as a heuristic to skip reporting errors that often occur as a result of earlier errors, but where it’s hard to be 100% sure (e.g., unresolved inference variables, regionck errors).

#### pub fn set_tainted_by_errors(&self, e: ErrorGuaranteed)

Set the “tainted by errors” flag to true. We call this when we observe an error from a prior pass.

#### pub fn region_var_origin(&self, vid: RegionVid) -> RegionVariableOrigin<'tcx>

#### pub fn get_region_var_infos( &self, ) -> IndexVec<RegionVid, RegionVariableInfo<'tcx>>

Clone the list of variable regions. This is used only during NLL processing to put the set of region variables into the NLL region context.

#### pub fn has_opaque_types_in_storage(&self) -> bool

#### pub fn take_opaque_types( &self, ) -> Vec<(OpaqueTypeKey<TyCtxt<'tcx>>, ProvisionalHiddenType<'tcx>)>

#### pub fn clone_opaque_types( &self, ) -> Vec<(OpaqueTypeKey<TyCtxt<'tcx>>, ProvisionalHiddenType<'tcx>)>

#### pub fn has_opaques_with_sub_unified_hidden_type(&self, ty_vid: TyVid) -> bool

#### pub fn opaques_with_sub_unified_hidden_type( &self, ty_vid: TyVid, ) -> Vec<AliasTy<TyCtxt<'tcx>>>

Searches for an opaque type key whose hidden type is related to `ty_vid`.

This only checks for a subtype relation, it does not require equality.

#### pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool

#### pub fn push_hir_typeck_potentially_region_dependent_goal( &self, goal: Obligation<'tcx, Predicate<'tcx>>, )

#### pub fn take_hir_typeck_potentially_region_dependent_goals( &self, ) -> Vec<Obligation<'tcx, Predicate<'tcx>>>

#### pub fn ty_to_string(&self, t: Ty<'tcx>) -> String

#### pub fn try_resolve_ty_var(&self, vid: TyVid) -> Result<Ty<'tcx>, UniverseIndex>

If `TyVar(vid)` resolves to a type, return that type. Else, return the universe index of `TyVar(vid)`.

#### pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx>

#### pub fn shallow_resolve_const(&self, ct: Const<'tcx>) -> Const<'tcx>

#### pub fn shallow_resolve_term(&self, term: Term<'tcx>) -> Term<'tcx>

#### pub fn root_var(&self, var: TyVid) -> TyVid

#### pub fn sub_unify_ty_vids_raw(&self, a: TyVid, b: TyVid)

#### pub fn sub_unification_table_root_var(&self, var: TyVid) -> TyVid

#### pub fn root_float_var(&self, var: FloatVid) -> FloatVid

#### pub fn root_const_var(&self, var: ConstVid) -> ConstVid

#### pub fn opportunistic_resolve_int_var(&self, vid: IntVid) -> Ty<'tcx>

Resolves an int var to a rigid int type, if it was constrained to one, or else the root int var in the unification table.

#### pub fn opportunistic_resolve_float_var(&self, vid: FloatVid) -> Ty<'tcx>

Resolves a float var to a rigid int type, if it was constrained to one, or else the root float var in the unification table.

#### pub fn resolve_vars_if_possible<T>(&self, value: T) -> T
where T: TypeFoldable<TyCtxt<'tcx>>,

Where possible, replaces type/const variables in `value` with their final value. Note that region variables are unaffected. If a type/const variable has not been unified, it is left as is. This is an idempotent operation that does not affect inference state in any way and so you can do it at will.

#### pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
where T: TypeFoldable<TyCtxt<'tcx>>,

#### pub fn try_resolve_const_var( &self, vid: ConstVid, ) -> Result<Const<'tcx>, UniverseIndex>

#### pub fn fully_resolve<T>(&self, value: T) -> Result<T, FixupError>
where T: TypeFoldable<TyCtxt<'tcx>>,

Attempts to resolve all type/region/const variables in `value`. Region inference must have been run already (e.g., by calling `resolve_regions_and_report_errors`). If some variable was never unified, an `Err` results.

This method is idempotent, but it not typically not invoked except during the writeback phase.

#### pub fn instantiate_binder_with_fresh_vars<T>( &self, span: Span, lbrct: BoundRegionConversionTime, value: Binder<TyCtxt<'tcx>, T>, ) -> T
where T: TypeFoldable<TyCtxt<'tcx>> + Copy,

#### pub fn closure_kind(&self, closure_ty: Ty<'tcx>) -> Option<ClosureKind>

Obtains the latest type of the given closure; this may be a closure in the current function, in which case its `ClosureKind` may not yet be known.

#### pub fn universe(&self) -> UniverseIndex

#### pub fn create_next_universe(&self) -> UniverseIndex

Creates and return a fresh universe that extends all previous universes. Updates `self.universe` to that new universe.

#### pub fn typing_env(&self, param_env: ParamEnv<'tcx>) -> TypingEnv<'tcx>

Extract `ty::TypingMode` of this inference context to get a `TypingEnv` which contains the necessary information to use the trait system without using canonicalization or carrying this inference context around.

#### pub fn pseudo_canonicalize_query<V>( &self, param_env: ParamEnv<'tcx>, value: V, ) -> PseudoCanonicalInput<'tcx, V>
where V: TypeVisitable<TyCtxt<'tcx>>,

Similar to [`Self::canonicalize_query`], except that it returns a `PseudoCanonicalInput` and requires both the `value` and the `param_env` to not contain any inference variables or placeholders.

#### pub fn is_ty_infer_var_definitely_unchanged(&self) -> impl Fn(TyOrConstInferVar)

The returned function is used in a fast path. If it returns `true` the variable is unchanged, `false` indicates that the status is unknown.

#### pub fn ty_or_const_infer_var_changed( &self, infer_var: TyOrConstInferVar, ) -> bool

`ty_or_const_infer_var_changed` is equivalent to one of these two:

- `shallow_resolve(ty) != ty` (where `ty.kind = ty::Infer(_)`)
- `shallow_resolve(ct) != ct` (where `ct.kind = ty::ConstKind::Infer(_)`)

However, `ty_or_const_infer_var_changed` is more efficient. It’s always inlined, despite being large, because it has only two call sites that are extremely hot (both in `traits::fulfill`’s checking of `stalled_on` inference variables), and it handles both `Ty` and `ty::Const` without having to resort to storing full `GenericArg`s in `stalled_on`.

#### pub fn attach_obligation_inspector( &self, inspector: fn(&InferCtxt<'tcx>, &Obligation<'tcx, Predicate<'tcx>>, Result<Certainty, NoSolution>), )

Attach a callback to be invoked on each root obligation evaluated in the new trait solver.

#### pub fn find_block_span(&self, block: &'tcx Block<'tcx>) -> Span

Given a `hir::Block`, get the span of its last expression or statement, peeling off any inner blocks.

#### pub fn find_block_span_from_hir_id(&self, hir_id: HirId) -> Span

Given a `hir::HirId` for a block (or an expr of a block), get the span of its last expression or statement, peeling off any inner blocks.

## Trait Implementations§

Source§

### impl<'a, 'tcx> Deref for Coerce<'a, 'tcx>

Source§

#### type Target = FnCtxt<'a, 'tcx>

The resulting type after dereferencing.
Source§

#### fn deref(&self) -> &Self::Target

Dereferences the value.

## Auto Trait Implementations§

§

### impl<'a, 'tcx> !DynSend for Coerce<'a, 'tcx>

§

### impl<'a, 'tcx> !DynSync for Coerce<'a, 'tcx>

§

### impl<'a, 'tcx> Freeze for Coerce<'a, 'tcx>

§

### impl<'a, 'tcx> !RefUnwindSafe for Coerce<'a, 'tcx>

§

### impl<'a, 'tcx> !Send for Coerce<'a, 'tcx>

§

### impl<'a, 'tcx> !Sync for Coerce<'a, 'tcx>

§

### impl<'a, 'tcx> Unpin for Coerce<'a, 'tcx>

§

### impl<'a, 'tcx> UnsafeUnpin for Coerce<'a, 'tcx>

§

### impl<'a, 'tcx> !UnwindSafe for Coerce<'a, 'tcx>

## Blanket Implementations§

Source§

### impl<T> Aligned for T

Source§

#### const ALIGN: Alignment

Alignment of `Self`.
Source§

### impl<T> Any for T
where T: 'static + ?Sized,

Source§

#### fn type_id(&self) -> TypeId

Gets the `TypeId` of `self`. Read more
Source§

### impl<T> Borrow<T> for T
where T: ?Sized,

Source§

#### fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

### impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

#### fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

### impl<T, R> CollectAndApply<T, R> for T

Source§

#### fn collect_and_apply<I, F>(iter: I, f: F) -> R
where I: Iterator<Item = T>, F: FnOnce(&[T]) -> R,

Equivalent to `f(&iter.collect::<Vec<_>>())`.

Source§

#### type Output = R

Source§

### impl<T> From<T> for T

Source§

#### fn from(t: T) -> T

Returns the argument unchanged.

Source§

### impl<T> Instrument for T

Source§

#### fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided `Span`, returning an `Instrumented` wrapper. Read more
Source§

#### fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current `Span`, returning an `Instrumented` wrapper. Read more
Source§

### impl<T, U> Into<U> for T
where U: From<T>,

Source§

#### fn into(self) -> U

Calls `U::from(self)`.

That is, this conversion is whatever the implementation of `From<T> for U` chooses to do.

Source§

### impl<T> IntoEither for T

Source§

#### fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts `self` into a `Left` variant of `Either<Self, Self>` if `into_left` is `true`. Converts `self` into a `Right` variant of `Either<Self, Self>` otherwise. Read more
Source§

#### fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts `self` into a `Left` variant of `Either<Self, Self>` if `into_left(&self)` returns `true`. Converts `self` into a `Right` variant of `Either<Self, Self>` otherwise. Read more
Source§

### impl<K> IntoQueryKey<K> for K

Source§

#### fn into_query_key(self) -> K

Argument conversion from `Self` to `K`. This should always be a very cheap conversion, e.g. `LocalDefId::to_def_id`.
Source§

### impl<T> MaybeResult<T> for T

Source§

#### type Error = !

Source§

#### fn from(_: Result<T, <T as MaybeResult<T>>::Error>) -> T

Source§

#### fn to_result(self) -> Result<T, <T as MaybeResult<T>>::Error>

Source§

### impl<T> Pointable for T

Source§

#### const ALIGN: usize

The alignment of pointer.
Source§

#### type Init = T

The type for initializers.
Source§

#### unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

#### unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

#### unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

#### unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

### impl<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

#### type Target = T

🔬This is a nightly-only experimental API. (`arbitrary_self_types`)
The target type on which the method may be called.
Source§

### impl<T> Same for T

Source§

#### type Output = T

Should always be `Self`
Source§

### impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

#### type Error = Infallible

The type returned in the event of a conversion error.
Source§

#### fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

### impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

#### type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

#### fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

### impl<I, T, U> Upcast<I, U> for T
where U: UpcastFrom<I, T>,

Source§

#### fn upcast(self, interner: I) -> U

Source§

### impl<I, T> UpcastFrom<I, T> for T

Source§

#### fn upcast_from(from: T, _tcx: I) -> T

Source§

### impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

#### fn vzip(self) -> V

Source§

### impl<T> WithSubscriber for T

Source§

#### fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more
Source§

#### fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more
Source§

### impl<T> ErasedDestructor for T
where T: 'static,

## Layout§

Note: Most layout information is completely unstable and may even differ between compilations. The only exception is types with certain `repr(...)` attributes. Please see the Rust Reference's “Type Layout” chapter for details on type layout guarantees.

Size: 40 bytes