rustc_trait_selection::error_reporting

Struct TypeErrCtxt

Source
pub struct TypeErrCtxt<'a, 'tcx> {
    pub infcx: &'a InferCtxt<'tcx>,
    pub sub_relations: RefCell<SubRelations>,
    pub typeck_results: Option<Ref<'a, TypeckResults<'tcx>>>,
    pub fallback_has_occurred: bool,
    pub normalize_fn_sig: Box<dyn Fn(PolyFnSig<'tcx>) -> PolyFnSig<'tcx> + 'a>,
    pub autoderef_steps: Box<dyn Fn(Ty<'tcx>) -> Vec<(Ty<'tcx>, PredicateObligations<'tcx>)> + 'a>,
}
Expand description

A helper for building type related errors. The typeck_results field is only populated during an in-progress typeck. Get an instance by calling InferCtxt::err_ctxt or FnCtxt::err_ctxt.

You must only create this if you intend to actually emit an error (or perhaps a warning, though preferably not.) It provides a lot of utility methods which should not be used during the happy path.

Fields§

§infcx: &'a InferCtxt<'tcx>§sub_relations: RefCell<SubRelations>§typeck_results: Option<Ref<'a, TypeckResults<'tcx>>>§fallback_has_occurred: bool§normalize_fn_sig: Box<dyn Fn(PolyFnSig<'tcx>) -> PolyFnSig<'tcx> + 'a>§autoderef_steps: Box<dyn Fn(Ty<'tcx>) -> Vec<(Ty<'tcx>, PredicateObligations<'tcx>)> + 'a>

Implementations§

Source§

impl<'tcx> TypeErrCtxt<'_, 'tcx>

Source

pub fn note_and_explain_type_err( &self, diag: &mut Diag<'_>, err: TypeError<'tcx>, cause: &ObligationCause<'tcx>, sp: Span, body_owner_def_id: DefId, )

Source

fn suggest_constraint( &self, diag: &mut Diag<'_>, msg: impl Fn() -> String, body_owner_def_id: DefId, proj_ty: AliasTy<'tcx>, ty: Ty<'tcx>, ) -> bool

Source

fn expected_projection( &self, diag: &mut Diag<'_>, proj_ty: AliasTy<'tcx>, values: ExpectedFound<Ty<'tcx>>, body_owner_def_id: DefId, cause_code: &ObligationCauseCode<'_>, )

An associated type was expected and a different type was found.

We perform a few different checks to see what we can suggest:

  • In the current item, look for associated functions that return the expected type and suggest calling them. (Not a structured suggestion.)
  • If any of the item’s generic bounds can be constrained, we suggest constraining the associated type to the found type.
  • If the associated type has a default type and was expected inside of a trait, we mention that this is disallowed.
  • If all other things fail, and the error is not because of a mismatch between the trait and the impl, we provide a generic help to constrain the assoc type or call an assoc fn that returns the type.
Source

fn suggest_constraining_opaque_associated_type( &self, diag: &mut Diag<'_>, msg: impl Fn() -> String, proj_ty: AliasTy<'tcx>, ty: Ty<'tcx>, ) -> bool

When the expected impl Trait is not defined in the current item, it will come from a return type. This can occur when dealing with TryStream (#71035).

Source

fn point_at_methods_that_satisfy_associated_type( &self, diag: &mut Diag<'_>, assoc_container_id: DefId, current_method_ident: Option<Symbol>, proj_ty_item_def_id: DefId, expected: Ty<'tcx>, ) -> bool

Source

fn point_at_associated_type( &self, diag: &mut Diag<'_>, body_owner_def_id: DefId, found: Ty<'tcx>, ) -> bool

Source

fn constrain_generic_bound_associated_type_structured_suggestion( &self, diag: &mut Diag<'_>, trait_ref: TraitRef<'tcx>, bounds: GenericBounds<'_>, assoc: AssocItem, assoc_args: &[GenericArg<'tcx>], ty: Ty<'tcx>, msg: impl Fn() -> String, is_bound_surely_present: bool, ) -> bool

Given a slice of hir::GenericBounds, if any of them corresponds to the trait_ref requirement, provide a structured suggestion to constrain it to a given type ty.

is_bound_surely_present indicates whether we know the bound we’re looking for is inside bounds. If that’s the case then we can consider bounds containing only one trait bound as the one we’re looking for. This can help in cases where the associated type is defined on a supertrait of the one present in the bounds.

Source

fn constrain_associated_type_structured_suggestion( &self, diag: &mut Diag<'_>, span: Span, assoc: AssocItem, assoc_args: &[GenericArg<'tcx>], ty: Ty<'tcx>, msg: impl Fn() -> String, ) -> bool

Given a span corresponding to a bound, provide a structured suggestion to set an associated type to a given type ty.

Source

pub fn format_generic_args(&self, args: &[GenericArg<'tcx>]) -> String

Source§

impl<'tcx> TypeErrCtxt<'_, 'tcx>

Source

pub(super) fn suggest_remove_semi_or_return_binding( &self, first_id: Option<HirId>, first_ty: Ty<'tcx>, first_span: Span, second_id: Option<HirId>, second_ty: Ty<'tcx>, second_span: Span, ) -> Option<SuggestRemoveSemiOrReturnBinding>

Source

pub(super) fn suggest_tuple_pattern( &self, cause: &ObligationCause<'tcx>, exp_found: &ExpectedFound<Ty<'tcx>>, diag: &mut Diag<'_>, )

Source

pub(super) fn suggest_await_on_expect_found( &self, cause: &ObligationCause<'tcx>, exp_span: Span, exp_found: &ExpectedFound<Ty<'tcx>>, diag: &mut Diag<'_>, )

A possible error is to forget to add .await when using futures:

async fn make_u32() -> u32 {
    22
}

fn take_u32(x: u32) {}

async fn foo() {
    let x = make_u32();
    take_u32(x);
}

This routine checks if the found type T implements Future<Output=U> where U is the expected type. If this is the case, and we are inside of an async body, it suggests adding .await to the tail of the expression.

Source

pub(super) fn suggest_accessing_field_where_appropriate( &self, cause: &ObligationCause<'tcx>, exp_found: &ExpectedFound<Ty<'tcx>>, diag: &mut Diag<'_>, )

Source

pub(super) fn suggest_turning_stmt_into_expr( &self, cause: &ObligationCause<'tcx>, exp_found: &ExpectedFound<Ty<'tcx>>, diag: &mut Diag<'_>, )

Source

pub fn consider_removing_semicolon( &self, blk: &'tcx Block<'tcx>, expected_ty: Ty<'tcx>, diag: &mut Diag<'_>, ) -> bool

A common error is to add an extra semicolon:

fn foo() -> usize {
    22;
}

This routine checks if the final statement in a block is an expression with an explicit semicolon whose type is compatible with expected_ty. If so, it suggests removing the semicolon.

Source

pub(super) fn suggest_function_pointers( &self, cause: &ObligationCause<'tcx>, span: Span, exp_found: &ExpectedFound<Ty<'tcx>>, diag: &mut Diag<'_>, )

Source

pub fn should_suggest_as_ref_kind( &self, expected: Ty<'tcx>, found: Ty<'tcx>, ) -> Option<SuggestAsRefKind>

Source

pub fn should_suggest_as_ref( &self, expected: Ty<'tcx>, found: Ty<'tcx>, ) -> Option<&str>

Source

pub(super) fn suggest_let_for_letchains( &self, cause: &ObligationCause<'_>, span: Span, ) -> Option<TypeErrorAdditionalDiags>

Try to find code with pattern if Some(..) = expr use a visitor to mark the if which its span contains given error span, and then try to find a assignment in the cond part, which span is equal with error span

Source

pub(super) fn suggest_for_all_lifetime_closure( &self, span: Span, hir: Node<'_>, exp_found: &ExpectedFound<TraitRef<'tcx>>, diag: &mut Diag<'_>, )

For “one type is more general than the other” errors on closures, suggest changing the lifetime of the parameters to accept all lifetimes.

Source§

impl<'tcx> TypeErrCtxt<'_, 'tcx>

Source

pub fn could_remove_semicolon( &self, blk: &'tcx Block<'tcx>, expected_ty: Ty<'tcx>, ) -> Option<(Span, StatementAsExpression)>

Be helpful when the user wrote {... expr; } and taking the ; off is enough to fix the error.

Source

pub fn consider_returning_binding_diag( &self, blk: &'tcx Block<'tcx>, expected_ty: Ty<'tcx>, ) -> Option<SuggestRemoveSemiOrReturnBinding>

Suggest returning a local binding with a compatible type if the block has no return expression.

Source

pub fn consider_returning_binding( &self, blk: &'tcx Block<'tcx>, expected_ty: Ty<'tcx>, err: &mut Diag<'_>, ) -> bool

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

pub fn extract_inference_diagnostics_data( &self, arg: GenericArg<'tcx>, highlight: Option<RegionHighlightMode<'tcx>>, ) -> InferenceDiagnosticsData

Extracts data used by diagnostic for either types or constants which were stuck during inference.

Source

fn bad_inference_failure_err( &self, span: Span, arg_data: InferenceDiagnosticsData, error_code: TypeAnnotationNeeded, ) -> Diag<'a>

Used as a fallback in TypeErrCtxt::emit_inference_failure_err in case we weren’t able to get a better error.

Source

pub fn emit_inference_failure_err( &self, body_def_id: LocalDefId, failure_span: Span, arg: GenericArg<'tcx>, error_code: TypeAnnotationNeeded, should_label_span: bool, ) -> Diag<'a>

Source

fn detect_old_time_crate_version( &self, span: Option<Span>, kind: &InferSourceKind<'_>, infer_subdiags: &mut Vec<SourceKindSubdiag<'_>>, ) -> bool

Detect the inference regression on crate time <= 0.3.35 and emit a more targeted error. https://github.com/rust-lang/rust/issues/127343

Source§

impl<'cx, 'tcx> TypeErrCtxt<'cx, 'tcx>

Source

pub fn try_report_nice_region_error( &'cx self, generic_param_scope: LocalDefId, error: &RegionResolutionError<'tcx>, ) -> Option<ErrorGuaranteed>

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

pub fn report_region_errors( &self, generic_param_scope: LocalDefId, errors: &[RegionResolutionError<'tcx>], ) -> ErrorGuaranteed

Source

fn process_errors( &self, errors: &[RegionResolutionError<'tcx>], ) -> Vec<RegionResolutionError<'tcx>>

Source

pub(super) fn note_region_origin( &self, err: &mut Diag<'_>, origin: &SubregionOrigin<'tcx>, )

Source

pub(super) fn report_concrete_failure( &self, generic_param_scope: LocalDefId, origin: SubregionOrigin<'tcx>, sub: Region<'tcx>, sup: Region<'tcx>, ) -> Diag<'a>

Source

pub fn suggest_copy_trait_method_bounds( &self, trait_item_def_id: DefId, impl_item_def_id: LocalDefId, err: &mut Diag<'_>, )

Source

pub(super) fn report_placeholder_failure( &self, generic_param_scope: LocalDefId, placeholder_origin: SubregionOrigin<'tcx>, sub: Region<'tcx>, sup: Region<'tcx>, ) -> Diag<'a>

Source

pub fn report_generic_bound_failure( &self, generic_param_scope: LocalDefId, span: Span, origin: Option<SubregionOrigin<'tcx>>, bound_kind: GenericKind<'tcx>, sub: Region<'tcx>, ) -> ErrorGuaranteed

Source

pub fn construct_generic_bound_failure( &self, generic_param_scope: LocalDefId, span: Span, origin: Option<SubregionOrigin<'tcx>>, bound_kind: GenericKind<'tcx>, sub: Region<'tcx>, ) -> Diag<'a>

Source

pub fn suggest_name_region( &self, generic_param_scope: LocalDefId, lifetime: Region<'tcx>, add_lt_suggs: &mut Vec<(Span, String)>, ) -> String

Source

fn report_sub_sup_conflict( &self, generic_param_scope: LocalDefId, var_origin: RegionVariableOrigin, sub_origin: SubregionOrigin<'tcx>, sub_region: Region<'tcx>, sup_origin: SubregionOrigin<'tcx>, sup_region: Region<'tcx>, ) -> ErrorGuaranteed

Source

fn report_inference_failure(&self, var_origin: RegionVariableOrigin) -> Diag<'_>

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

pub fn type_error_struct_with_diag<M>( &self, sp: Span, mk_diag: M, actual_ty: Ty<'tcx>, ) -> Diag<'a>
where M: FnOnce(String) -> Diag<'a>,

Source

pub fn report_mismatched_types( &self, cause: &ObligationCause<'tcx>, param_env: ParamEnv<'tcx>, expected: Ty<'tcx>, actual: Ty<'tcx>, err: TypeError<'tcx>, ) -> Diag<'a>

Source

pub fn report_mismatched_consts( &self, cause: &ObligationCause<'tcx>, param_env: ParamEnv<'tcx>, expected: Const<'tcx>, actual: Const<'tcx>, err: TypeError<'tcx>, ) -> Diag<'a>

Source

pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>>

Source

fn check_and_note_conflicting_crates( &self, err: &mut Diag<'_>, terr: TypeError<'tcx>, )

Adds a note if the types come from similarly named crates

Source

fn note_error_origin( &self, err: &mut Diag<'_>, cause: &ObligationCause<'tcx>, exp_found: Option<ExpectedFound<Ty<'tcx>>>, terr: TypeError<'tcx>, )

Source

fn highlight_outer( &self, value: &mut DiagStyledString, other_value: &mut DiagStyledString, name: String, sub: GenericArgsRef<'tcx>, pos: usize, other_ty: Ty<'tcx>, )

Given that other_ty is the same as a type argument for name in sub, populate value highlighting name and every type argument that isn’t at pos (which is other_ty), and populate other_value with other_ty.

Foo<Bar<Qux>>
^^^^--------^ this is highlighted
|   |
|   this type argument is exactly the same as the other type, not highlighted
this is highlighted
Bar<Qux>
-------- this type is the same as a type argument in the other type, not highlighted
Source

fn cmp_type_arg( &self, t1_out: &mut DiagStyledString, t2_out: &mut DiagStyledString, path: String, sub: &'tcx [GenericArg<'tcx>], other_path: String, other_ty: Ty<'tcx>, ) -> Option<()>

If other_ty is the same as a type argument present in sub, highlight path in t1_out, as that is the difference to the other type.

For the following code:

let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();

The type error output will behave in the following way:

Foo<Bar<Qux>>
^^^^--------^ this is highlighted
|   |
|   this type argument is exactly the same as the other type, not highlighted
this is highlighted
Bar<Qux>
-------- this type is the same as a type argument in the other type, not highlighted
Source

fn push_comma( &self, value: &mut DiagStyledString, other_value: &mut DiagStyledString, len: usize, pos: usize, )

Adds a , to the type representation only if it is appropriate.

Source

fn cmp_fn_sig( &self, sig1: &PolyFnSig<'tcx>, sig2: &PolyFnSig<'tcx>, ) -> (DiagStyledString, DiagStyledString)

Given two fn signatures highlight only sub-parts that are different.

Source

pub fn cmp_traits( &self, def_id1: DefId, args1: &[GenericArg<'tcx>], def_id2: DefId, args2: &[GenericArg<'tcx>], ) -> (DiagStyledString, DiagStyledString)

Source

pub fn cmp( &self, t1: Ty<'tcx>, t2: Ty<'tcx>, ) -> (DiagStyledString, DiagStyledString)

Compares two given types, eliding parts that are the same between them and highlighting relevant differences, and return two representation of those types for highlighted printing.

Source

pub fn note_type_err( &self, diag: &mut Diag<'_>, cause: &ObligationCause<'tcx>, secondary_span: Option<(Span, Cow<'static, str>, bool)>, values: Option<ParamEnvAnd<'tcx, ValuePairs<'tcx>>>, terr: TypeError<'tcx>, prefer_label: bool, )

Extend a type error with extra labels pointing at “non-trivial” types, like closures and the return type of async fns.

secondary_span gives the caller the opportunity to expand diag with a span_label.

swap_secondary_and_primary is used to make projection errors in particular nicer by using the message in secondary_span as the primary label, and apply the message that would otherwise be used for the primary label on the secondary_span Span. This applies on E0271, like tests/ui/issues/issue-39970.stderr.

Source

pub fn type_error_additional_suggestions( &self, trace: &TypeTrace<'tcx>, terr: TypeError<'tcx>, ) -> Vec<TypeErrorAdditionalDiags>

Source

fn suggest_specify_actual_length( &self, terr: TypeError<'tcx>, trace: &TypeTrace<'tcx>, span: Span, ) -> Option<TypeErrorAdditionalDiags>

Source

pub fn report_and_explain_type_error( &self, trace: TypeTrace<'tcx>, param_env: ParamEnv<'tcx>, terr: TypeError<'tcx>, ) -> Diag<'a>

Source

fn suggest_wrap_to_build_a_tuple( &self, span: Span, found: Ty<'tcx>, expected_fields: &List<Ty<'tcx>>, ) -> Option<TypeErrorAdditionalDiags>

Source

fn values_str( &self, values: ValuePairs<'tcx>, ) -> Option<(DiagStyledString, DiagStyledString, Option<PathBuf>)>

Source

fn expected_found_str_term( &self, exp_found: ExpectedFound<Term<'tcx>>, ) -> Option<(DiagStyledString, DiagStyledString, Option<PathBuf>)>

Source

fn expected_found_str<T: Display + TypeFoldable<TyCtxt<'tcx>>>( &self, exp_found: ExpectedFound<T>, ) -> Option<(DiagStyledString, DiagStyledString, Option<PathBuf>)>

Returns a string of the form “expected {}, found {}”.

Source

pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool

Determine whether an error associated with the given span and definition should be treated as being caused by the implicit From conversion within ? desugaring.

Source

pub fn same_type_modulo_infer<T: Relate<TyCtxt<'tcx>>>( &self, a: T, b: T, ) -> bool

Structurally compares two types, modulo any inference variables.

Returns true if two types are equal, or if one type is an inference variable compatible with the other type. A TyVar inference type is compatible with any type, and an IntVar or FloatVar inference type are compatible with themselves or their concrete types (Int and Float types, respectively). When comparing two ADTs, these rules apply recursively.

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

pub(super) fn maybe_report_ambiguity( &self, obligation: &PredicateObligation<'tcx>, ) -> ErrorGuaranteed

Source

fn annotate_source_of_ambiguity( &self, err: &mut Diag<'_>, ambiguities: &[CandidateSource], predicate: Predicate<'tcx>, )

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

pub fn report_selection_error( &self, obligation: PredicateObligation<'tcx>, root_obligation: &PredicateObligation<'tcx>, error: &SelectionError<'tcx>, ) -> ErrorGuaranteed

The root_obligation parameter should be the root_obligation field from a FulfillmentError. If no FulfillmentError is available, then it should be the same as obligation.

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

pub(super) fn apply_do_not_recommend( &self, obligation: &mut PredicateObligation<'tcx>, ) -> bool

Source

fn emit_specialized_closure_kind_error( &self, obligation: &PredicateObligation<'tcx>, trait_ref: PolyTraitRef<'tcx>, ) -> Option<ErrorGuaranteed>

Source

fn fn_arg_obligation( &self, obligation: &PredicateObligation<'tcx>, ) -> Result<(), ErrorGuaranteed>

Source

fn try_conversion_context( &self, obligation: &PredicateObligation<'tcx>, trait_ref: TraitRef<'tcx>, err: &mut Diag<'_>, ) -> bool

When the E of the resulting Result<T, E> in an expression foo().bar().baz()?, identify those method chain sub-expressions that could or could not have been annotated with ?.

Source

fn report_const_param_not_wf( &self, ty: Ty<'tcx>, obligation: &PredicateObligation<'tcx>, ) -> Diag<'a>

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

fn can_match_trait( &self, goal: TraitPredicate<'tcx>, assumption: PolyTraitPredicate<'tcx>, ) -> bool

Source

fn can_match_projection( &self, goal: ProjectionPredicate<'tcx>, assumption: PolyProjectionPredicate<'tcx>, ) -> bool

Source

pub(super) fn error_implies( &self, cond: Predicate<'tcx>, error: Predicate<'tcx>, ) -> bool

Source

pub(super) fn report_projection_error( &self, obligation: &PredicateObligation<'tcx>, error: &MismatchedProjectionTypes<'tcx>, ) -> ErrorGuaranteed

Source

fn maybe_detailed_projection_msg( &self, projection_term: AliasTerm<'tcx>, normalized_ty: Term<'tcx>, expected_ty: Term<'tcx>, ) -> Option<String>

Source

pub fn fuzzy_match_tys( &self, a: Ty<'tcx>, b: Ty<'tcx>, ignoring_lifetimes: bool, ) -> Option<CandidateSimilarity>

Source

pub(super) fn describe_closure(&self, kind: ClosureKind) -> &'static str

Source

pub(super) fn find_similar_impl_candidates( &self, trait_pred: PolyTraitPredicate<'tcx>, ) -> Vec<ImplCandidate<'tcx>>

Source

pub(super) fn report_similar_impl_candidates( &self, impl_candidates: &[ImplCandidate<'tcx>], trait_ref: PolyTraitRef<'tcx>, body_def_id: LocalDefId, err: &mut Diag<'_>, other: bool, param_env: ParamEnv<'tcx>, ) -> bool

Source

fn report_similar_impl_candidates_for_root_obligation( &self, obligation: &PredicateObligation<'tcx>, trait_predicate: Binder<'tcx, TraitPredicate<'tcx>>, body_def_id: LocalDefId, err: &mut Diag<'_>, )

Source

fn get_parent_trait_ref( &self, code: &ObligationCauseCode<'tcx>, ) -> Option<(Ty<'tcx>, Option<Span>)>

Gets the parent trait chain start

Source

fn note_version_mismatch( &self, err: &mut Diag<'_>, trait_ref: PolyTraitRef<'tcx>, ) -> bool

If the Self type of the unsatisfied trait trait_ref implements a trait with the same path as trait_ref, a help message about a probable version mismatch is added to err

Source

pub(super) fn mk_trait_obligation_with_new_self_ty( &self, param_env: ParamEnv<'tcx>, trait_ref_and_ty: Binder<'tcx, (TraitPredicate<'tcx>, Ty<'tcx>)>, ) -> PredicateObligation<'tcx>

Creates a PredicateObligation with new_self_ty replacing the existing type in the trait_ref.

For this to work, new_self_ty must have no escaping bound variables.

Source

fn predicate_can_apply( &self, param_env: ParamEnv<'tcx>, pred: PolyTraitPredicate<'tcx>, ) -> bool

Returns true if the trait predicate may apply for some assignment to the type parameters.

Source

pub fn note_obligation_cause( &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, )

Source

pub(super) fn is_recursive_obligation( &self, obligated_types: &mut Vec<Ty<'tcx>>, cause_code: &ObligationCauseCode<'tcx>, ) -> bool

Source

fn get_standard_error_message( &self, trait_predicate: PolyTraitPredicate<'tcx>, message: Option<String>, predicate_constness: Option<BoundConstness>, append_const_msg: Option<AppendConstMessage>, post_message: String, ) -> String

Source

fn get_safe_transmute_error_and_reason( &self, obligation: PredicateObligation<'tcx>, trait_ref: PolyTraitRef<'tcx>, span: Span, ) -> GetSafeTransmuteErrorAndReason

Source

fn add_tuple_trait_message( &self, obligation_cause_code: &ObligationCauseCode<'tcx>, err: &mut Diag<'_>, )

Source

fn try_to_add_help_message( &self, root_obligation: &PredicateObligation<'tcx>, obligation: &PredicateObligation<'tcx>, trait_predicate: PolyTraitPredicate<'tcx>, err: &mut Diag<'_>, span: Span, is_fn_trait: bool, suggested: bool, unsatisfied_const: bool, )

Source

fn add_help_message_for_fn_trait( &self, trait_ref: PolyTraitRef<'tcx>, err: &mut Diag<'_>, implemented_kind: ClosureKind, params: Binder<'tcx, Ty<'tcx>>, )

Source

fn maybe_add_note_for_unsatisfied_const( &self, _trait_predicate: PolyTraitPredicate<'tcx>, _err: &mut Diag<'_>, _span: Span, ) -> UnsatisfiedConst

Source

fn report_closure_error( &self, obligation: &PredicateObligation<'tcx>, closure_def_id: DefId, found_kind: ClosureKind, kind: ClosureKind, trait_prefix: &'static str, ) -> Diag<'a>

Source

fn report_cyclic_signature_error( &self, obligation: &PredicateObligation<'tcx>, found_trait_ref: TraitRef<'tcx>, expected_trait_ref: TraitRef<'tcx>, terr: TypeError<'tcx>, ) -> Diag<'a>

Source

fn report_opaque_type_auto_trait_leakage( &self, obligation: &PredicateObligation<'tcx>, def_id: DefId, ) -> ErrorGuaranteed

Source

fn report_signature_mismatch_error( &self, obligation: &PredicateObligation<'tcx>, span: Span, found_trait_ref: TraitRef<'tcx>, expected_trait_ref: TraitRef<'tcx>, ) -> Result<Diag<'a>, ErrorGuaranteed>

Source

pub fn get_fn_like_arguments( &self, node: Node<'_>, ) -> Option<(Span, Option<Span>, Vec<ArgKind>)>

Given some node representing a fn-like thing in the HIR map, returns a span and ArgKind information that describes the arguments it expects. This can be supplied to report_arg_count_mismatch.

Source

pub fn report_arg_count_mismatch( &self, span: Span, found_span: Option<Span>, expected_args: Vec<ArgKind>, found_args: Vec<ArgKind>, is_closure: bool, closure_arg_span: Option<Span>, ) -> Diag<'a>

Reports an error when the number of arguments needed by a trait match doesn’t match the number that the expression provides.

Source

pub fn type_implements_fn_trait( &self, param_env: ParamEnv<'tcx>, ty: Binder<'tcx, Ty<'tcx>>, polarity: PredicatePolarity, ) -> Result<(ClosureKind, Binder<'tcx, Ty<'tcx>>), ()>

Checks if the type implements one of Fn, FnMut, or FnOnce in that order, and returns the generic type corresponding to the argument of that trait (corresponding to the closure arguments).

Source

fn report_not_const_evaluatable_error( &self, obligation: &PredicateObligation<'tcx>, span: Span, ) -> Result<Diag<'a>, ErrorGuaranteed>

Source§

impl<'tcx> TypeErrCtxt<'_, 'tcx>

Source

fn impl_similar_to( &self, trait_ref: PolyTraitRef<'tcx>, obligation: &PredicateObligation<'tcx>, ) -> Option<(DefId, GenericArgsRef<'tcx>)>

Source

fn describe_enclosure(&self, def_id: LocalDefId) -> Option<&'static str>

Used to set on_unimplemented’s ItemContext to be the enclosing (async) block/function/closure

Source

pub fn on_unimplemented_note( &self, trait_pred: PolyTraitPredicate<'tcx>, obligation: &PredicateObligation<'tcx>, long_ty_file: &mut Option<PathBuf>, ) -> OnUnimplementedNote

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

pub fn report_overflow_error( &self, cause: OverflowCause<'tcx>, span: Span, suggest_increasing_limit: bool, mutate: impl FnOnce(&mut Diag<'_>), ) -> !

Reports that an overflow has occurred and halts compilation. We halt compilation unconditionally because it is important that overflows never be masked – they basically represent computations whose result could not be truly determined and thus we can’t say if the program type checks or not – and they are unusual occurrences in any case.

Source

pub fn build_overflow_error( &self, cause: OverflowCause<'tcx>, span: Span, suggest_increasing_limit: bool, ) -> Diag<'a>

Source

pub fn report_overflow_obligation<T>( &self, obligation: &Obligation<'tcx, T>, suggest_increasing_limit: bool, ) -> !
where T: Upcast<TyCtxt<'tcx>, Predicate<'tcx>> + Clone,

Reports that an overflow has occurred and halts compilation. We halt compilation unconditionally because it is important that overflows never be masked – they basically represent computations whose result could not be truly determined and thus we can’t say if the program type checks or not – and they are unusual occurrences in any case.

Source

pub fn report_overflow_obligation_cycle( &self, cycle: &[PredicateObligation<'tcx>], ) -> !

Reports that a cycle was detected which led to overflow and halts compilation. This is equivalent to report_overflow_obligation except that we can give a more helpful error message (and, in particular, we do not suggest increasing the overflow limit, which is not going to help).

Source

pub fn report_overflow_no_abort( &self, obligation: PredicateObligation<'tcx>, suggest_increasing_limit: bool, ) -> ErrorGuaranteed

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

pub fn suggest_restricting_param_bound( &self, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, associated_ty: Option<(&'static str, Ty<'tcx>)>, body_id: LocalDefId, )

Source

pub(super) fn suggest_dereferences( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, ) -> bool

When after several dereferencing, the reference satisfies the trait bound. This function provides dereference suggestion for this specific situation.

Source

fn get_closure_name( &self, def_id: DefId, err: &mut Diag<'_>, msg: Cow<'static, str>, ) -> Option<Symbol>

Given a closure’s DefId, return the given name of the closure.

This doesn’t account for reassignments, but it’s only used for suggestions.

Source

pub(super) fn suggest_fn_call( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, ) -> bool

We tried to apply the bound to an fn or closure. Check whether calling it would evaluate to a type that would satisfy the trait bound. If it would, suggest calling it: bar(foo)bar(foo()). This case is very likely to be hit if foo is async.

Source

pub(super) fn check_for_binding_assigned_block_without_tail_expression( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, )

Source

pub(super) fn suggest_add_clone_to_arg( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, ) -> bool

Source

pub fn extract_callable_info( &self, body_id: LocalDefId, param_env: ParamEnv<'tcx>, found: 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(super) fn suggest_add_reference_to_arg( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, poly_trait_pred: PolyTraitPredicate<'tcx>, has_custom_message: bool, ) -> bool

Source

pub(super) fn suggest_borrowing_for_object_cast( &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, self_ty: Ty<'tcx>, target_ty: Ty<'tcx>, )

Source

pub(super) fn suggest_remove_reference( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, ) -> bool

Whenever references are used by mistake, like for (i, e) in &vec.iter().enumerate(), suggest removing these references until we reach a type that implements the trait.

Source

pub(super) fn suggest_remove_await( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, )

Source

pub(super) fn suggest_change_mut( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, )

Check if the trait bound is implemented for a different mutability and note it in the final error.

Source

pub(super) fn suggest_semicolon_removal( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, span: Span, trait_pred: PolyTraitPredicate<'tcx>, ) -> bool

Source

pub(super) fn return_type_span( &self, obligation: &PredicateObligation<'tcx>, ) -> Option<Span>

Source

pub(super) fn suggest_impl_trait( &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, trait_pred: PolyTraitPredicate<'tcx>, ) -> bool

If all conditions are met to identify a returned dyn Trait, suggest using impl Trait if applicable and signal that the error has been expanded appropriately and needs to be emitted.

Source

pub(super) fn point_at_returns_when_relevant( &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, )

Source

pub(super) fn report_closure_arg_mismatch( &self, span: Span, found_span: Option<Span>, found: TraitRef<'tcx>, expected: TraitRef<'tcx>, cause: &ObligationCauseCode<'tcx>, found_node: Option<Node<'_>>, param_env: ParamEnv<'tcx>, ) -> Diag<'a>

Source

fn note_conflicting_fn_args( &self, err: &mut Diag<'_>, cause: &ObligationCauseCode<'tcx>, expected: Ty<'tcx>, found: Ty<'tcx>, param_env: ParamEnv<'tcx>, )

Source

fn note_conflicting_closure_bounds( &self, cause: &ObligationCauseCode<'tcx>, err: &mut Diag<'_>, )

Source

pub(super) fn suggest_fully_qualified_path( &self, err: &mut Diag<'_>, item_def_id: DefId, span: Span, trait_ref: DefId, )

Source

pub fn maybe_note_obligation_cause_for_async_await<G: EmissionGuarantee>( &self, err: &mut Diag<'_, G>, obligation: &PredicateObligation<'tcx>, ) -> bool

Adds an async-await specific note to the diagnostic when the future does not implement an auto trait because of a captured type.

note: future does not implement `Qux` as this value is used across an await
  --> $DIR/issue-64130-3-other.rs:17:5
   |
LL |     let x = Foo;
   |         - has type `Foo`
LL |     baz().await;
   |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
LL | }
   | - `x` is later dropped here

When the diagnostic does not implement Send or Sync specifically, then the diagnostic is “replaced” with a different message and a more specific error.

error: future cannot be sent between threads safely
  --> $DIR/issue-64130-2-send.rs:21:5
   |
LL | fn is_send<T: Send>(t: T) { }
   |               ---- required by this bound in `is_send`
...
LL |     is_send(bar());
   |     ^^^^^^^ future returned by `bar` is not send
   |
   = help: within `impl std::future::Future`, the trait `std::marker::Send` is not
           implemented for `Foo`
note: future is not send as this value is used across an await
  --> $DIR/issue-64130-2-send.rs:15:5
   |
LL |     let x = Foo;
   |         - has type `Foo`
LL |     baz().await;
   |     ^^^^^^^^^^^ await occurs here, with `x` maybe used later
LL | }
   | - `x` is later dropped here

Returns true if an async-await specific note was added to the diagnostic.

Source

fn note_obligation_cause_for_async_await<G: EmissionGuarantee>( &self, err: &mut Diag<'_, G>, interior_or_upvar_span: CoroutineInteriorOrUpvar, is_async: bool, outer_coroutine: Option<DefId>, trait_pred: TraitPredicate<'tcx>, target_ty: Ty<'tcx>, obligation: &PredicateObligation<'tcx>, next_code: Option<&ObligationCauseCode<'tcx>>, )

Unconditionally adds the diagnostic note described in maybe_note_obligation_cause_for_async_await’s documentation comment.

Source

pub(super) fn note_obligation_cause_code<G: EmissionGuarantee, T>( &self, body_id: LocalDefId, err: &mut Diag<'_, G>, predicate: T, param_env: ParamEnv<'tcx>, cause_code: &ObligationCauseCode<'tcx>, obligated_types: &mut Vec<Ty<'tcx>>, seen_requirements: &mut FxHashSet<DefId>, long_ty_file: &mut Option<PathBuf>, )
where T: Upcast<TyCtxt<'tcx>, Predicate<'tcx>>,

Source

pub(super) fn suggest_await_before_try( &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, trait_pred: PolyTraitPredicate<'tcx>, span: Span, )

Source

pub(super) fn suggest_floating_point_literal( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_ref: PolyTraitRef<'tcx>, )

Source

pub fn suggest_derive( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, )

Source

pub(super) fn suggest_dereferencing_index( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, )

Source

fn note_function_argument_obligation<G: EmissionGuarantee>( &self, body_id: LocalDefId, err: &mut Diag<'_, G>, arg_hir_id: HirId, parent_code: &ObligationCauseCode<'tcx>, param_env: ParamEnv<'tcx>, failed_pred: Predicate<'tcx>, call_hir_id: HirId, )

Source

fn suggest_option_method_if_applicable<G: EmissionGuarantee>( &self, failed_pred: Predicate<'tcx>, param_env: ParamEnv<'tcx>, err: &mut Diag<'_, G>, expr: &Expr<'_>, )

Source

fn look_for_iterator_item_mistakes<G: EmissionGuarantee>( &self, assocs_in_this_method: &[Option<(Span, (DefId, Ty<'tcx>))>], typeck_results: &TypeckResults<'tcx>, type_diffs: &[TypeError<'tcx>], param_env: ParamEnv<'tcx>, path_segment: &PathSegment<'_>, args: &[Expr<'_>], err: &mut Diag<'_, G>, )

Source

fn point_at_chain<G: EmissionGuarantee>( &self, expr: &Expr<'_>, typeck_results: &TypeckResults<'tcx>, type_diffs: Vec<TypeError<'tcx>>, param_env: ParamEnv<'tcx>, err: &mut Diag<'_, G>, )

Source

fn probe_assoc_types_at_expr( &self, type_diffs: &[TypeError<'tcx>], span: Span, prev_ty: Ty<'tcx>, body_id: HirId, param_env: ParamEnv<'tcx>, ) -> Vec<Option<(Span, (DefId, Ty<'tcx>))>>

Source

pub(super) fn suggest_convert_to_slice( &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, trait_ref: PolyTraitRef<'tcx>, candidate_impls: &[ImplCandidate<'tcx>], span: Span, )

If the type that failed selection is an array or a reference to an array, but the trait is implemented for slices, suggest that the user converts the array into a slice.

Source

pub(super) fn suggest_tuple_wrapping( &self, err: &mut Diag<'_>, root_obligation: &PredicateObligation<'tcx>, obligation: &PredicateObligation<'tcx>, )

If the type failed selection but the trait is implemented for (T,), suggest that the user creates a unary tuple

This is a common gotcha when using libraries that emulate variadic functions with traits for tuples.

Source

pub(super) fn explain_hrtb_projection( &self, diag: &mut Diag<'_>, pred: PolyTraitPredicate<'tcx>, param_env: ParamEnv<'tcx>, cause: &ObligationCause<'tcx>, )

Source

pub(super) fn suggest_desugaring_async_fn_in_trait( &self, err: &mut Diag<'_>, trait_ref: PolyTraitRef<'tcx>, )

Source

pub fn ty_kind_suggestion( &self, param_env: ParamEnv<'tcx>, ty: Ty<'tcx>, ) -> Option<String>

Source

pub(super) fn suggest_add_result_as_return_type( &self, obligation: &PredicateObligation<'tcx>, err: &mut Diag<'_>, trait_pred: PolyTraitPredicate<'tcx>, )

Source

pub(super) fn suggest_unsized_bound_if_applicable( &self, err: &mut Diag<'_>, obligation: &PredicateObligation<'tcx>, )

Source

fn suggest_indirection_for_unsized( &self, err: &mut Diag<'_>, item: &Item<'tcx>, param: &GenericParam<'tcx>, ) -> bool

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

pub fn report_extra_impl_obligation( &self, error_span: Span, impl_item_def_id: LocalDefId, trait_item_def_id: DefId, requirement: &dyn Display, ) -> Diag<'a>

Source§

impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx>

Source

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

Source

pub fn err_ctxt(&self) -> !

👎Deprecated: you already have a TypeErrCtxt

This is just to avoid a potential footgun of accidentally dropping typeck_results by calling InferCtxt::err_ctxt

Methods from Deref<Target = InferCtxt<'tcx>>§

Source

pub fn at<'a>( &'a self, cause: &'a ObligationCause<'tcx>, param_env: ParamEnv<'tcx>, ) -> At<'a, 'tcx>

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn canonicalize_user_type_annotation<V>( &self, value: V, ) -> Canonical<TyCtxt<'tcx>, V>
where V: TypeFoldable<TyCtxt<'tcx>>,

Source

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.
Source

pub fn make_query_response_ignoring_pending_obligations<T>( &self, inference_vars: CanonicalVarValues<TyCtxt<'tcx>>, answer: T, ) -> 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.

Source

pub fn clone_opaque_types_for_query_response( &self, ) -> Vec<(OpaqueTypeKey<TyCtxt<'tcx>>, Ty<'tcx>)>

Used by the new solver as that one takes the opaque types at the end of a probe to deal with multiple candidates without having to recompute them.

Source

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.

Source

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.
Source

pub fn query_outlives_constraint_to_obligation( &self, _: (OutlivesPredicate<TyCtxt<'tcx>, GenericArg<'tcx>>, ConstraintCategory<'tcx>), cause: ObligationCause<'tcx>, param_env: ParamEnv<'tcx>, ) -> Obligation<'tcx, Predicate<'tcx>>

Source

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.

Source

pub fn instantiate_canonical_var( &self, span: Span, cv_info: CanonicalVarInfo<TyCtxt<'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.

Source

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.

Source

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>>>

Source

pub fn register_member_constraints( &self, opaque_type_key: OpaqueTypeKey<TyCtxt<'tcx>>, concrete_ty: Ty<'tcx>, span: Span, )

Given the map opaque_types containing the opaque impl Trait types whose underlying, hidden types are being inferred, this method adds constraints to the regions appearing in those underlying hidden types to ensure that they at least do not refer to random scopes within the current function. These constraints are not (quite) sufficient to guarantee that the regions are actually legal values; that final condition is imposed after region inference is done.

§The Problem

Let’s work through an example to explain how it works. Assume the current function is as follows:

fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)

Here, we have two impl Trait types whose values are being inferred (the impl Bar<'a> and the impl Bar<'b>). Conceptually, this is sugar for a setup where we define underlying opaque types (Foo1, Foo2) and then, in the return type of foo, we reference those definitions:

type Foo1<'x> = impl Bar<'x>;
type Foo2<'x> = impl Bar<'x>;
fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
                   //  ^^^^ ^^
                   //  |    |
                   //  |    args
                   //  def_id

As indicating in the comments above, each of those references is (in the compiler) basically generic parameters (args) applied to the type of a suitable def_id (which identifies Foo1 or Foo2).

Now, at this point in compilation, what we have done is to replace each of the references (Foo1<'a>, Foo2<'b>) with fresh inference variables C1 and C2. We wish to use the values of these variables to infer the underlying types of Foo1 and Foo2. That is, this gives rise to higher-order (pattern) unification constraints like:

for<'a> (Foo1<'a> = C1)
for<'b> (Foo1<'b> = C2)

For these equation to be satisfiable, the types C1 and C2 can only refer to a limited set of regions. For example, C1 can only refer to 'static and 'a, and C2 can only refer to 'static and 'b. The job of this function is to impose that constraint.

Up to this point, C1 and C2 are basically just random type inference variables, and hence they may contain arbitrary regions. In fact, it is fairly likely that they do! Consider this possible definition of foo:

fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
        (&*x, &*y)
    }

Here, the values for the concrete types of the two impl traits will include inference variables:

&'0 i32
&'1 i32

Ordinarily, the subtyping rules would ensure that these are sufficiently large. But since impl Bar<'a> isn’t a specific type per se, we don’t get such constraints by default. This is where this function comes into play. It adds extra constraints to ensure that all the regions which appear in the inferred type are regions that could validly appear.

This is actually a bit of a tricky constraint in general. We want to say that each variable (e.g., '0) can only take on values that were supplied as arguments to the opaque type (e.g., 'a for Foo1<'a>) or 'static, which is always in scope. We don’t have a constraint quite of this kind in the current region checker.

§The Solution

We generally prefer to make <= constraints, since they integrate best into the region solver. To do that, we find the “minimum” of all the arguments that appear in the args: that is, some region which is less than all the others. In the case of Foo1<'a>, that would be 'a (it’s the only choice, after all). Then we apply that as a least bound to the variables (e.g., 'a <= '0).

In some cases, there is no minimum. Consider this example:

fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }

Here we would report a more complex “in constraint”, like 'r in ['a, 'b, 'static] (where 'r is some region appearing in the hidden type).

§Constrain regions, not the hidden concrete type

Note that generating constraints on each region Rc is not the same as generating an outlives constraint on Tc itself. For example, if we had a function like this:

fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
  (x, y)
}

// Equivalent to:
type FooReturn<'a, T> = impl Foo<'a>;
fn foo<'a, T>(x: &'a u32, y: T) -> FooReturn<'a, T> {
  (x, y)
}

then the hidden type Tc would be (&'0 u32, T) (where '0 is an inference variable). If we generated a constraint that Tc: 'a, then this would incorrectly require that T: 'a – but this is not necessary, because the opaque type we create will be allowed to reference T. So we only generate a constraint that '0: 'a.

Source

pub fn inject_new_hidden_type_unchecked( &self, opaque_type_key: OpaqueTypeKey<TyCtxt<'tcx>>, hidden_ty: OpaqueHiddenType<'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.

Source

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.

Source

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>>>, )

Source

pub fn register_region_obligation(&self, obligation: RegionObligation<'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).

Source

pub fn register_region_obligation_with_cause( &self, sup_type: Ty<'tcx>, sub_region: Region<'tcx>, cause: &ObligationCause<'tcx>, )

Source

pub fn take_registered_region_obligations(&self) -> Vec<RegionObligation<'tcx>>

Trait queries just want to pass back type obligations “as is”

Source

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>, ) -> 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.

Source

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>, ) -> 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.

Source

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.

Source

pub fn with_region_constraints<R>( &self, op: impl FnOnce(&RegionConstraintData<'tcx>) -> R, ) -> R

Gives temporary access to the region constraint data.

Source

pub fn projection_ty_to_infer( &self, param_env: ParamEnv<'tcx>, projection_ty: AliasTy<TyCtxt<'tcx>>, cause: ObligationCause<'tcx>, recursion_depth: usize, obligations: &mut ThinVec<Obligation<'tcx, Predicate<'tcx>>>, ) -> Ty<'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.

Source

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>>>

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).

Source

pub fn enter_forall_and_leak_universe<T>( &self, binder: Binder<TyCtxt<'tcx>, T>, ) -> T
where T: TypeFoldable<TyCtxt<'tcx>> + Copy,

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.

Source

pub fn enter_forall<T, U>( &self, forall: Binder<TyCtxt<'tcx>, T>, f: impl FnOnce(T) -> U, ) -> U
where T: TypeFoldable<TyCtxt<'tcx>> + Copy,

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.

Source

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.

Source

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>>,

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.

Source

pub fn in_snapshot(&self) -> bool

Source

pub fn num_open_snapshots(&self) -> usize

Source

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(_).

Source

pub fn probe<R, F>(&self, f: F) -> R
where F: FnOnce(&CombinedSnapshot<'tcx>) -> R,

Execute f then unroll any bindings it creates.

Source

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.

Source

pub fn opaque_types_added_in_snapshot( &self, snapshot: &CombinedSnapshot<'tcx>, ) -> bool

Source

pub fn dcx(&self) -> DiagCtxtHandle<'_>

Source

pub fn next_trait_solver(&self) -> bool

Source

pub fn typing_mode(&self) -> TypingMode<TyCtxt<'tcx>>

Source

pub fn freshen<T>(&self, t: T) -> T
where T: TypeFoldable<TyCtxt<'tcx>>,

Source

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.

Source

pub fn const_var_origin(&self, vid: ConstVid) -> Option<ConstVariableOrigin>

Returns the origin of the const variable identified by vid

Source

pub fn freshener<'b>(&'b self) -> TypeFreshener<'b, 'tcx>

Source

pub fn unresolved_variables(&self) -> Vec<Ty<'tcx>>

Source

pub fn sub_regions( &self, origin: SubregionOrigin<'tcx>, a: Region<'tcx>, b: Region<'tcx>, )

Source

pub fn member_constraint( &self, key: OpaqueTypeKey<TyCtxt<'tcx>>, definition_span: Span, hidden_ty: Ty<'tcx>, region: Region<'tcx>, in_regions: Arc<Vec<Region<'tcx>>>, )

Require that the region r be equal to one of the regions in the set regions.

Source

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.)

Source

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)>

Source

pub fn region_outlives_predicate( &self, cause: &ObligationCause<'tcx>, predicate: Binder<TyCtxt<'tcx>, OutlivesPredicate<TyCtxt<'tcx>, Region<'tcx>>>, )

Source

pub fn num_ty_vars(&self) -> usize

Number of type variables created so far.

Source

pub fn next_ty_var(&self, span: Span) -> Ty<'tcx>

Source

pub fn next_ty_var_with_origin(&self, origin: TypeVariableOrigin) -> Ty<'tcx>

Source

pub fn next_ty_var_id_in_universe( &self, span: Span, universe: UniverseIndex, ) -> TyVid

Source

pub fn next_ty_var_in_universe( &self, span: Span, universe: UniverseIndex, ) -> Ty<'tcx>

Source

pub fn next_const_var(&self, span: Span) -> Const<'tcx>

Source

pub fn next_const_var_with_origin( &self, origin: ConstVariableOrigin, ) -> Const<'tcx>

Source

pub fn next_const_var_in_universe( &self, span: Span, universe: UniverseIndex, ) -> Const<'tcx>

Source

pub fn next_int_var(&self) -> Ty<'tcx>

Source

pub fn next_float_var(&self) -> Ty<'tcx>

Source

pub fn next_region_var(&self, origin: RegionVariableOrigin) -> 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.

Source

pub fn next_region_var_in_universe( &self, origin: RegionVariableOrigin, 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.

Source

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.

Source

pub fn num_region_vars(&self) -> usize

Number of region variables created so far.

Source

pub fn next_nll_region_var( &self, origin: NllRegionVariableOrigin, ) -> Region<'tcx>

Just a convenient wrapper of next_region_var for using during NLL.

Source

pub fn next_nll_region_var_in_universe( &self, origin: NllRegionVariableOrigin, universe: UniverseIndex, ) -> Region<'tcx>

Just a convenient wrapper of next_region_var for using during NLL.

Source

pub fn var_for_def( &self, span: Span, param: &GenericParamDef, ) -> GenericArg<'tcx>

Source

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.

Source

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).

Source

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.

Source

pub fn region_var_origin(&self, vid: RegionVid) -> RegionVariableOrigin

Source

pub fn get_region_var_origins(&self) -> IndexVec<RegionVid, RegionVariableInfo>

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.

Source

pub fn take_opaque_types( &self, ) -> IndexMap<OpaqueTypeKey<TyCtxt<'tcx>>, OpaqueTypeDecl<'tcx>, BuildHasherDefault<FxHasher>>

Source

pub fn clone_opaque_types( &self, ) -> IndexMap<OpaqueTypeKey<TyCtxt<'tcx>>, OpaqueTypeDecl<'tcx>, BuildHasherDefault<FxHasher>>

Source

pub fn can_define_opaque_ty(&self, id: impl Into<DefId>) -> bool

Source

pub fn ty_to_string(&self, t: Ty<'tcx>) -> String

Source

pub fn probe_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).

Source

pub fn shallow_resolve(&self, ty: Ty<'tcx>) -> Ty<'tcx>

Source

pub fn shallow_resolve_const(&self, ct: Const<'tcx>) -> Const<'tcx>

Source

pub fn root_var(&self, var: TyVid) -> TyVid

Source

pub fn root_const_var(&self, var: ConstVid) -> ConstVid

Source

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.

Source

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.

Source

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.

Source

pub fn resolve_numeric_literals_with_default<T>(&self, value: T) -> T
where T: TypeFoldable<TyCtxt<'tcx>>,

Source

pub fn probe_const_var( &self, vid: ConstVid, ) -> Result<Const<'tcx>, UniverseIndex>

Source

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.

Source

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,

Source

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.

Source

pub fn universe(&self) -> UniverseIndex

Source

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.

Source

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.

Source

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.

Source

pub fn is_ty_infer_var_definitely_unchanged<'a>( &'a self, ) -> impl Fn(TyOrConstInferVar) + Captures<'tcx> + 'a

The returned function is used in a fast path. If it returns true the variable is unchanged, false indicates that the status is unknown.

Source

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 GenericArgs in stalled_on.

Source

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.

Source

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.

Source

pub fn find_block_span_from_hir_id(&self, hir_id: HirId) -> Span

Given a hir::HirId for a block, get the span of its last expression or statement, peeling off any inner blocks.

Trait Implementations§

Source§

impl<'tcx> Deref for TypeErrCtxt<'_, 'tcx>

Source§

type Target = InferCtxt<'tcx>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &InferCtxt<'tcx>

Dereferences the value.

Auto Trait Implementations§

§

impl<'a, 'tcx> !DynSend for TypeErrCtxt<'a, 'tcx>

§

impl<'a, 'tcx> !DynSync for TypeErrCtxt<'a, 'tcx>

§

impl<'a, 'tcx> !Freeze for TypeErrCtxt<'a, 'tcx>

§

impl<'a, 'tcx> !RefUnwindSafe for TypeErrCtxt<'a, 'tcx>

§

impl<'a, 'tcx> !Send for TypeErrCtxt<'a, 'tcx>

§

impl<'a, 'tcx> !Sync for TypeErrCtxt<'a, 'tcx>

§

impl<'a, 'tcx> Unpin for TypeErrCtxt<'a, 'tcx>

§

impl<'a, 'tcx> !UnwindSafe for TypeErrCtxt<'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> Filterable for T

Source§

fn filterable( self, filter_name: &'static str, ) -> RequestFilterDataProvider<T, fn(_: DataRequest<'_>) -> bool>

Creates a filterable data provider with the given name for debugging. Read more
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<P> IntoQueryParam<P> for P

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<Tcx, T> Value<Tcx> for T
where Tcx: DepContext,

Source§

default fn from_cycle_error( tcx: Tcx, cycle_error: &CycleError, _guar: ErrorGuaranteed, ) -> T

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<'a, T> Captures<'a> for T
where T: ?Sized,

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: 128 bytes