2019-06-15 01:28:38 +02:00
|
|
|
//! Type checking expressions.
|
|
|
|
|
//!
|
|
|
|
|
//! See `mod.rs` for more context on type checking in general.
|
|
|
|
|
|
|
|
|
|
use crate::astconv::AstConv as _;
|
2022-04-13 16:38:16 -07:00
|
|
|
use crate::check::cast::{self, CastCheckResult};
|
2019-06-15 01:28:38 +02:00
|
|
|
use crate::check::coercion::CoerceMany;
|
|
|
|
|
use crate::check::fatally_break_rust;
|
2021-03-29 19:53:48 -07:00
|
|
|
use crate::check::method::SelfSource;
|
2019-06-15 01:28:38 +02:00
|
|
|
use crate::check::Expectation::{self, ExpectCastableToType, ExpectHasType, NoExpectation};
|
2022-04-13 16:38:16 -07:00
|
|
|
use crate::check::{
|
|
|
|
|
report_unexpected_variant_res, BreakableCtxt, Diverges, DynamicCoerceMany, FnCtxt, Needs,
|
|
|
|
|
TupleArgumentsFlag::DontTupleArguments,
|
|
|
|
|
};
|
2020-08-27 20:09:22 +10:00
|
|
|
use crate::errors::{
|
|
|
|
|
FieldMultiplySpecifiedInInitializer, FunctionalRecordUpdateOnNonStruct,
|
|
|
|
|
YieldExprOutsideOfGenerator,
|
|
|
|
|
};
|
2019-12-31 21:25:16 +01:00
|
|
|
use crate::type_error_struct;
|
2019-06-15 01:28:38 +02:00
|
|
|
|
2020-08-27 20:09:22 +10:00
|
|
|
use crate::errors::{AddressOfTemporaryTaken, ReturnStmtOutsideOfFnBody, StructExprNonExhaustive};
|
2020-04-27 23:26:11 +05:30
|
|
|
use rustc_ast as ast;
|
2019-12-24 05:02:53 +01:00
|
|
|
use rustc_data_structures::fx::FxHashMap;
|
2020-07-24 17:00:10 +09:00
|
|
|
use rustc_data_structures::stack::ensure_sufficient_stack;
|
2022-06-20 16:29:05 +09:00
|
|
|
use rustc_errors::{
|
|
|
|
|
pluralize, struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, DiagnosticId,
|
2022-08-16 00:16:14 +09:00
|
|
|
ErrorGuaranteed, StashKey,
|
2022-06-20 16:29:05 +09:00
|
|
|
};
|
2020-01-05 02:37:57 +01:00
|
|
|
use rustc_hir as hir;
|
|
|
|
|
use rustc_hir::def::{CtorKind, DefKind, Res};
|
|
|
|
|
use rustc_hir::def_id::DefId;
|
2021-10-02 13:12:33 +01:00
|
|
|
use rustc_hir::intravisit::Visitor;
|
2022-03-14 11:46:12 -07:00
|
|
|
use rustc_hir::lang_items::LangItem;
|
2022-07-11 23:39:53 +04:00
|
|
|
use rustc_hir::{Closure, ExprKind, HirId, QPath};
|
2020-01-06 23:12:31 +01:00
|
|
|
use rustc_infer::infer;
|
|
|
|
|
use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
|
2021-10-19 11:08:12 +08:00
|
|
|
use rustc_infer::infer::InferOk;
|
2022-06-06 23:20:13 -07:00
|
|
|
use rustc_infer::traits::ObligationCause;
|
2022-01-24 13:13:29 +01:00
|
|
|
use rustc_middle::middle::stability;
|
2020-06-15 21:59:09 +01:00
|
|
|
use rustc_middle::ty::adjustment::{Adjust, Adjustment, AllowTwoPhase};
|
2022-06-11 09:57:33 -07:00
|
|
|
use rustc_middle::ty::error::TypeError::FieldMisMatch;
|
2021-01-28 18:26:31 +01:00
|
|
|
use rustc_middle::ty::subst::SubstsRef;
|
2022-08-27 20:59:07 +00:00
|
|
|
use rustc_middle::ty::{self, AdtKind, Ty, TypeVisitable};
|
2022-09-30 01:38:15 +00:00
|
|
|
use rustc_session::errors::ExprParenthesesNeeded;
|
2021-10-29 20:08:30 +08:00
|
|
|
use rustc_session::parse::feature_err;
|
2019-12-31 20:15:40 +03:00
|
|
|
use rustc_span::hygiene::DesugaringKind;
|
Move lev_distance to rustc_ast, make non-generic
rustc_ast currently has a few dependencies on rustc_lexer. Ideally, an AST
would not have any dependency its lexer, for minimizing unnecessarily
design-time dependencies. Breaking this dependency would also have practical
benefits, since modifying rustc_lexer would not trigger a rebuild of rustc_ast.
This commit does not remove the rustc_ast --> rustc_lexer dependency,
but it does remove one of the sources of this dependency, which is the
code that handles fuzzy matching between symbol names for making suggestions
in diagnostics. Since that code depends only on Symbol, it is easy to move
it to rustc_span. It might even be best to move it to a separate crate,
since other tools such as Cargo use the same algorithm, and have simply
contain a duplicate of the code.
This changes the signature of find_best_match_for_name so that it is no
longer generic over its input. I checked the optimized binaries, and this
function was duplicated at nearly every call site, because most call sites
used short-lived iterator chains, generic over Map and such. But there's
no good reason for a function like this to be generic, since all it does
is immediately convert the generic input (the Iterator impl) to a concrete
Vec<Symbol>. This has all of the costs of generics (duplicated method bodies)
with no benefit.
Changing find_best_match_for_name to be non-generic removed about 10KB of
code from the optimized binary. I know it's a drop in the bucket, but we have
to start reducing binary size, and beginning to tame over-use of generics
is part of that.
2020-11-12 11:24:10 -08:00
|
|
|
use rustc_span::lev_distance::find_best_match_for_name;
|
2022-07-12 13:59:51 +09:00
|
|
|
use rustc_span::source_map::{Span, Spanned};
|
2020-04-19 13:00:18 +02:00
|
|
|
use rustc_span::symbol::{kw, sym, Ident, Symbol};
|
2022-04-14 12:07:36 +00:00
|
|
|
use rustc_target::spec::abi::Abi::RustIntrinsic;
|
2022-03-05 01:57:43 -08:00
|
|
|
use rustc_trait_selection::infer::InferCtxtExt;
|
2020-10-23 10:54:34 -07:00
|
|
|
use rustc_trait_selection::traits::{self, ObligationCauseCode};
|
2019-06-15 01:28:38 +02:00
|
|
|
|
|
|
|
|
impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|
2019-11-30 15:08:22 +01:00
|
|
|
fn check_expr_eq_type(&self, expr: &'tcx hir::Expr<'tcx>, expected: Ty<'tcx>) {
|
2019-06-15 02:58:32 +02:00
|
|
|
let ty = self.check_expr_with_hint(expr, expected);
|
|
|
|
|
self.demand_eqtype(expr.span, expected, ty);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub fn check_expr_has_type_or_error(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:58:32 +02:00
|
|
|
expected: Ty<'tcx>,
|
2022-06-11 09:57:33 -07:00
|
|
|
extend_err: impl FnMut(&mut Diagnostic),
|
2019-06-15 02:58:32 +02:00
|
|
|
) -> Ty<'tcx> {
|
2019-09-26 17:16:34 -07:00
|
|
|
self.check_expr_meets_expectation_or_error(expr, ExpectHasType(expected), extend_err)
|
2019-06-15 02:58:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn check_expr_meets_expectation_or_error(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:58:32 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2022-06-11 09:57:33 -07:00
|
|
|
mut extend_err: impl FnMut(&mut Diagnostic),
|
2019-06-15 02:58:32 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let expected_ty = expected.to_option(&self).unwrap_or(self.tcx.types.bool);
|
|
|
|
|
let mut ty = self.check_expr_with_expectation(expr, expected);
|
|
|
|
|
|
|
|
|
|
// While we don't allow *arbitrary* coercions here, we *do* allow
|
|
|
|
|
// coercions from ! to `expected`.
|
|
|
|
|
if ty.is_never() {
|
2022-04-24 02:00:12 -06:00
|
|
|
if let Some(adjustments) = self.typeck_results.borrow().adjustments().get(expr.hir_id) {
|
|
|
|
|
self.tcx().sess.delay_span_bug(
|
|
|
|
|
expr.span,
|
|
|
|
|
"expression with never type wound up being adjusted",
|
|
|
|
|
);
|
|
|
|
|
return if let [Adjustment { kind: Adjust::NeverToAny, target }] = &adjustments[..] {
|
|
|
|
|
target.to_owned()
|
|
|
|
|
} else {
|
|
|
|
|
self.tcx().ty_error()
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2020-11-23 09:06:37 -05:00
|
|
|
let adj_ty = self.next_ty_var(TypeVariableOrigin {
|
2019-06-15 02:58:32 +02:00
|
|
|
kind: TypeVariableOriginKind::AdjustmentType,
|
|
|
|
|
span: expr.span,
|
2019-12-22 17:42:04 -05:00
|
|
|
});
|
2019-06-15 02:58:32 +02:00
|
|
|
self.apply_adjustments(
|
2019-12-22 17:42:04 -05:00
|
|
|
expr,
|
2019-06-15 02:58:32 +02:00
|
|
|
vec![Adjustment { kind: Adjust::NeverToAny, target: adj_ty }],
|
|
|
|
|
);
|
|
|
|
|
ty = adj_ty;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if let Some(mut err) = self.demand_suptype_diag(expr.span, expected_ty, ty) {
|
2019-10-08 08:42:26 -07:00
|
|
|
let expr = expr.peel_drop_temps();
|
2020-06-09 11:45:40 -07:00
|
|
|
self.suggest_deref_ref_or_into(&mut err, expr, expected_ty, ty, None);
|
2019-09-26 17:16:34 -07:00
|
|
|
extend_err(&mut err);
|
2021-09-16 23:31:16 -04:00
|
|
|
err.emit();
|
2019-06-15 02:58:32 +02:00
|
|
|
}
|
|
|
|
|
ty
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub(super) fn check_expr_coercable_to_type(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:58:32 +02:00
|
|
|
expected: Ty<'tcx>,
|
2020-06-09 11:45:40 -07:00
|
|
|
expected_ty_expr: Option<&'tcx hir::Expr<'tcx>>,
|
2019-06-15 02:58:32 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let ty = self.check_expr_with_hint(expr, expected);
|
|
|
|
|
// checks don't need two phase
|
2020-06-09 11:45:40 -07:00
|
|
|
self.demand_coerce(expr, ty, expected, expected_ty_expr, AllowTwoPhase::No)
|
2019-06-15 02:58:32 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
pub(super) fn check_expr_with_hint(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:58:32 +02:00
|
|
|
expected: Ty<'tcx>,
|
|
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
self.check_expr_with_expectation(expr, ExpectHasType(expected))
|
|
|
|
|
}
|
|
|
|
|
|
2020-06-15 21:59:09 +01:00
|
|
|
fn check_expr_with_expectation_and_needs(
|
2019-06-15 02:58:32 +02:00
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:58:32 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2020-06-15 21:59:09 +01:00
|
|
|
needs: Needs,
|
2019-06-15 02:58:32 +02:00
|
|
|
) -> Ty<'tcx> {
|
2020-06-15 21:59:09 +01:00
|
|
|
let ty = self.check_expr_with_expectation(expr, expected);
|
|
|
|
|
|
|
|
|
|
// If the expression is used in a place whether mutable place is required
|
|
|
|
|
// e.g. LHS of assignment, perform the conversion.
|
|
|
|
|
if let Needs::MutPlace = needs {
|
|
|
|
|
self.convert_place_derefs_to_mutable(expr);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
ty
|
2019-06-15 02:58:32 +02:00
|
|
|
}
|
|
|
|
|
|
2019-11-30 15:08:22 +01:00
|
|
|
pub(super) fn check_expr(&self, expr: &'tcx hir::Expr<'tcx>) -> Ty<'tcx> {
|
2019-06-15 02:58:32 +02:00
|
|
|
self.check_expr_with_expectation(expr, NoExpectation)
|
|
|
|
|
}
|
|
|
|
|
|
2019-11-30 15:08:22 +01:00
|
|
|
pub(super) fn check_expr_with_needs(
|
|
|
|
|
&self,
|
|
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
needs: Needs,
|
|
|
|
|
) -> Ty<'tcx> {
|
2019-06-15 02:58:32 +02:00
|
|
|
self.check_expr_with_expectation_and_needs(expr, NoExpectation, needs)
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-15 02:51:45 +02:00
|
|
|
/// Invariant:
|
|
|
|
|
/// If an expression has any sub-expressions that result in a type error,
|
|
|
|
|
/// inspecting that expression's type with `ty.references_error()` will return
|
|
|
|
|
/// true. Likewise, if an expression is known to diverge, inspecting its
|
|
|
|
|
/// type with `ty::type_is_bot` will return true (n.b.: since Rust is
|
|
|
|
|
/// strict, _|_ can appear in the type of an expression that does not,
|
|
|
|
|
/// itself, diverge: for example, fn() -> _|_.)
|
|
|
|
|
/// Note that inspecting a type's structure *directly* may expose the fact
|
|
|
|
|
/// that there are actually multiple representations for `Error`, so avoid
|
|
|
|
|
/// that when err needs to be handled differently.
|
2021-08-20 13:36:04 +00:00
|
|
|
#[instrument(skip(self, expr), level = "debug")]
|
2020-06-15 21:59:09 +01:00
|
|
|
pub(super) fn check_expr_with_expectation(
|
2019-06-15 02:51:45 +02:00
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:51:45 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2021-09-14 10:52:36 +00:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
self.check_expr_with_expectation_and_args(expr, expected, &[])
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Same as `check_expr_with_expectation`, but allows us to pass in the arguments of a
|
|
|
|
|
/// `ExprKind::Call` when evaluating its callee when it is an `ExprKind::Path`.
|
|
|
|
|
pub(super) fn check_expr_with_expectation_and_args(
|
|
|
|
|
&self,
|
|
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
expected: Expectation<'tcx>,
|
|
|
|
|
args: &'tcx [hir::Expr<'tcx>],
|
2019-06-15 02:51:45 +02:00
|
|
|
) -> Ty<'tcx> {
|
2021-08-23 19:14:06 +00:00
|
|
|
if self.tcx().sess.verbose() {
|
|
|
|
|
// make this code only run with -Zverbose because it is probably slow
|
|
|
|
|
if let Ok(lint_str) = self.tcx.sess.source_map().span_to_snippet(expr.span) {
|
2021-08-31 00:54:48 +02:00
|
|
|
if !lint_str.contains('\n') {
|
2022-04-15 15:56:32 +09:00
|
|
|
debug!("expr text: {lint_str}");
|
2021-08-23 19:14:06 +00:00
|
|
|
} else {
|
|
|
|
|
let mut lines = lint_str.lines();
|
|
|
|
|
if let Some(line0) = lines.next() {
|
|
|
|
|
let remaining_lines = lines.count();
|
2022-04-15 15:56:32 +09:00
|
|
|
debug!("expr text: {line0}");
|
|
|
|
|
debug!("expr text: ...(and {remaining_lines} more lines)");
|
2021-08-23 19:14:06 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-08-23 22:21:21 +00:00
|
|
|
}
|
2019-06-15 02:51:45 +02:00
|
|
|
|
2019-09-19 01:20:18 +03:00
|
|
|
// True if `expr` is a `Try::from_ok(())` that is a result of desugaring a try block
|
|
|
|
|
// without the final expr (e.g. `try { return; }`). We don't want to generate an
|
|
|
|
|
// unreachable_code lint for it since warnings for autogenerated code are confusing.
|
2019-10-01 20:04:41 +03:00
|
|
|
let is_try_block_generated_unit_expr = match expr.kind {
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Call(_, args) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {
|
2019-09-19 01:20:18 +03:00
|
|
|
args.len() == 1 && args[0].span.is_desugaring(DesugaringKind::TryBlock)
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2019-09-19 01:20:18 +03:00
|
|
|
|
|
|
|
|
_ => false,
|
2019-09-18 18:08:56 +03:00
|
|
|
};
|
|
|
|
|
|
2019-06-15 02:51:45 +02:00
|
|
|
// Warn for expressions after diverging siblings.
|
2019-09-19 01:20:18 +03:00
|
|
|
if !is_try_block_generated_unit_expr {
|
2019-09-18 18:08:56 +03:00
|
|
|
self.warn_if_unreachable(expr.hir_id, expr.span, "expression");
|
|
|
|
|
}
|
2019-06-15 02:51:45 +02:00
|
|
|
|
|
|
|
|
// Hide the outer diverging and has_errors flags.
|
2020-01-21 17:37:11 +01:00
|
|
|
let old_diverges = self.diverges.replace(Diverges::Maybe);
|
|
|
|
|
let old_has_errors = self.has_errors.replace(false);
|
2019-06-15 02:51:45 +02:00
|
|
|
|
2021-09-14 10:52:36 +00:00
|
|
|
let ty = ensure_sufficient_stack(|| match &expr.kind {
|
|
|
|
|
hir::ExprKind::Path(
|
|
|
|
|
qpath @ hir::QPath::Resolved(..) | qpath @ hir::QPath::TypeRelative(..),
|
|
|
|
|
) => self.check_expr_path(qpath, expr, args),
|
|
|
|
|
_ => self.check_expr_kind(expr, expected),
|
|
|
|
|
});
|
2019-06-15 02:51:45 +02:00
|
|
|
|
|
|
|
|
// Warn for non-block expressions with diverging children.
|
2019-09-19 01:20:18 +03:00
|
|
|
match expr.kind {
|
2021-08-08 11:49:13 -03:00
|
|
|
ExprKind::Block(..)
|
|
|
|
|
| ExprKind::If(..)
|
|
|
|
|
| ExprKind::Let(..)
|
|
|
|
|
| ExprKind::Loop(..)
|
|
|
|
|
| ExprKind::Match(..) => {}
|
2019-09-19 01:20:18 +03:00
|
|
|
// If `expr` is a result of desugaring the try block and is an ok-wrapped
|
|
|
|
|
// diverging expression (e.g. it arose from desugaring of `try { return }`),
|
|
|
|
|
// we skip issuing a warning because it is autogenerated code.
|
|
|
|
|
ExprKind::Call(..) if expr.span.is_desugaring(DesugaringKind::TryBlock) => {}
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Call(callee, _) => self.warn_if_unreachable(expr.hir_id, callee.span, "call"),
|
2021-12-01 11:17:50 -06:00
|
|
|
ExprKind::MethodCall(segment, ..) => {
|
|
|
|
|
self.warn_if_unreachable(expr.hir_id, segment.ident.span, "call")
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2019-09-19 01:20:18 +03:00
|
|
|
_ => self.warn_if_unreachable(expr.hir_id, expr.span, "expression"),
|
2019-06-15 02:51:45 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Any expression that produces a value of type `!` must have diverged
|
|
|
|
|
if ty.is_never() {
|
2019-09-18 20:04:01 -04:00
|
|
|
self.diverges.set(self.diverges.get() | Diverges::always(expr.span));
|
2019-06-15 02:51:45 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Record the type, which applies it effects.
|
|
|
|
|
// We need to do this after the warning above, so that
|
|
|
|
|
// we don't warn for the diverging expression itself.
|
|
|
|
|
self.write_ty(expr.hir_id, ty);
|
|
|
|
|
|
|
|
|
|
// Combine the diverging and has_error flags.
|
|
|
|
|
self.diverges.set(self.diverges.get() | old_diverges);
|
|
|
|
|
self.has_errors.set(self.has_errors.get() | old_has_errors);
|
|
|
|
|
|
2019-06-17 19:01:41 +02:00
|
|
|
debug!("type of {} is...", self.tcx.hir().node_to_string(expr.hir_id));
|
2019-06-15 02:51:45 +02:00
|
|
|
debug!("... {:?}, expected is {:?}", ty, expected);
|
|
|
|
|
|
|
|
|
|
ty
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-20 13:36:04 +00:00
|
|
|
#[instrument(skip(self, expr), level = "debug")]
|
2022-07-01 22:16:05 +00:00
|
|
|
fn check_expr_kind(
|
2019-06-15 01:28:38 +02:00
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 01:28:38 +02:00
|
|
|
expected: Expectation<'tcx>,
|
|
|
|
|
) -> Ty<'tcx> {
|
2021-08-20 13:36:04 +00:00
|
|
|
trace!("expr={:#?}", expr);
|
2019-06-15 01:28:38 +02:00
|
|
|
|
|
|
|
|
let tcx = self.tcx;
|
2019-09-26 14:39:48 +01:00
|
|
|
match expr.kind {
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Box(subexpr) => self.check_expr_box(subexpr, expected),
|
2019-06-15 01:28:38 +02:00
|
|
|
ExprKind::Lit(ref lit) => self.check_lit(&lit, expected),
|
2022-04-26 13:59:08 -07:00
|
|
|
ExprKind::Binary(op, lhs, rhs) => self.check_binop(expr, op, lhs, rhs, expected),
|
2022-02-23 08:11:17 -05:00
|
|
|
ExprKind::Assign(lhs, rhs, span) => {
|
2019-12-23 12:39:48 +00:00
|
|
|
self.check_expr_assign(expr, expected, lhs, rhs, span)
|
2019-12-22 21:08:53 +00:00
|
|
|
}
|
2022-04-26 13:59:08 -07:00
|
|
|
ExprKind::AssignOp(op, lhs, rhs) => {
|
|
|
|
|
self.check_binop_assign(expr, op, lhs, rhs, expected)
|
|
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Unary(unop, oprnd) => self.check_expr_unary(unop, oprnd, expected, expr),
|
|
|
|
|
ExprKind::AddrOf(kind, mutbl, oprnd) => {
|
2019-11-23 14:15:49 +00:00
|
|
|
self.check_expr_addr_of(kind, mutbl, oprnd, expected, expr)
|
2019-06-15 01:28:38 +02:00
|
|
|
}
|
2021-11-16 20:07:23 +00:00
|
|
|
ExprKind::Path(QPath::LangItem(lang_item, _, hir_id)) => {
|
|
|
|
|
self.check_lang_item_path(lang_item, expr, hir_id)
|
2020-08-04 14:34:24 +01:00
|
|
|
}
|
2021-09-14 10:52:36 +00:00
|
|
|
ExprKind::Path(ref qpath) => self.check_expr_path(qpath, expr, &[]),
|
2022-04-14 12:07:36 +00:00
|
|
|
ExprKind::InlineAsm(asm) => {
|
2022-05-25 14:01:06 +00:00
|
|
|
// We defer some asm checks as we may not have resolved the input and output types yet (they may still be infer vars).
|
2022-04-14 12:07:36 +00:00
|
|
|
self.deferred_asm_checks.borrow_mut().push((asm, expr.hir_id));
|
|
|
|
|
self.check_expr_asm(asm)
|
|
|
|
|
}
|
2019-06-15 01:28:38 +02:00
|
|
|
ExprKind::Break(destination, ref expr_opt) => {
|
2019-07-06 03:35:19 +09:00
|
|
|
self.check_expr_break(destination, expr_opt.as_deref(), expr)
|
2019-06-15 01:28:38 +02:00
|
|
|
}
|
|
|
|
|
ExprKind::Continue(destination) => {
|
|
|
|
|
if destination.target_id.is_ok() {
|
|
|
|
|
tcx.types.never
|
|
|
|
|
} else {
|
|
|
|
|
// There was an error; make type-check fail.
|
2020-05-05 23:02:09 -05:00
|
|
|
tcx.ty_error()
|
2019-06-15 01:28:38 +02:00
|
|
|
}
|
|
|
|
|
}
|
2019-07-06 03:35:19 +09:00
|
|
|
ExprKind::Ret(ref expr_opt) => self.check_expr_return(expr_opt.as_deref(), expr),
|
2021-10-13 16:39:06 +11:00
|
|
|
ExprKind::Let(let_expr) => self.check_expr_let(let_expr),
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Loop(body, _, source, _) => {
|
2019-06-15 02:22:52 +02:00
|
|
|
self.check_expr_loop(body, source, expected, expr)
|
2019-06-15 01:28:38 +02:00
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Match(discrim, arms, match_src) => {
|
2019-06-15 01:28:38 +02:00
|
|
|
self.check_match(expr, &discrim, arms, expected, match_src)
|
|
|
|
|
}
|
2022-07-11 23:39:53 +04:00
|
|
|
ExprKind::Closure(&Closure { capture_clause, fn_decl, body, movability, .. }) => {
|
2022-06-11 21:25:25 +02:00
|
|
|
self.check_expr_closure(expr, capture_clause, &fn_decl, body, movability, expected)
|
2019-06-15 01:28:38 +02:00
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Block(body, _) => self.check_block_with_expected(&body, expected),
|
|
|
|
|
ExprKind::Call(callee, args) => self.check_call(expr, &callee, args, expected),
|
2022-09-01 13:27:31 +09:00
|
|
|
ExprKind::MethodCall(segment, receiver, args, _) => {
|
|
|
|
|
self.check_method_call(expr, segment, receiver, args, expected)
|
2019-06-15 01:28:38 +02:00
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Cast(e, t) => self.check_expr_cast(e, t, expr),
|
|
|
|
|
ExprKind::Type(e, t) => {
|
2019-06-15 01:28:38 +02:00
|
|
|
let ty = self.to_ty_saving_user_provided_ty(&t);
|
|
|
|
|
self.check_expr_eq_type(&e, ty);
|
|
|
|
|
ty
|
|
|
|
|
}
|
2021-02-07 23:05:15 +01:00
|
|
|
ExprKind::If(cond, then_expr, opt_else_expr) => {
|
|
|
|
|
self.check_then_else(cond, then_expr, opt_else_expr, expr.span, expected)
|
|
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::DropTemps(e) => self.check_expr_with_expectation(e, expected),
|
|
|
|
|
ExprKind::Array(args) => self.check_expr_array(args, expected, expr),
|
2021-10-02 13:12:33 +01:00
|
|
|
ExprKind::ConstBlock(ref anon_const) => {
|
|
|
|
|
self.check_expr_const_block(anon_const, expected, expr)
|
|
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Repeat(element, ref count) => {
|
2019-06-15 02:36:07 +02:00
|
|
|
self.check_expr_repeat(element, count, expected, expr)
|
2019-06-15 01:28:38 +02:00
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Tup(elts) => self.check_expr_tuple(elts, expected, expr),
|
|
|
|
|
ExprKind::Struct(qpath, fields, ref base_expr) => {
|
2019-06-15 01:28:38 +02:00
|
|
|
self.check_expr_struct(expr, expected, qpath, fields, base_expr)
|
|
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
ExprKind::Field(base, field) => self.check_field(expr, &base, field),
|
|
|
|
|
ExprKind::Index(base, idx) => self.check_expr_index(base, idx, expr),
|
|
|
|
|
ExprKind::Yield(value, ref src) => self.check_expr_yield(value, expr, src),
|
2020-05-05 23:02:09 -05:00
|
|
|
hir::ExprKind::Err => tcx.ty_error(),
|
2019-06-15 01:28:38 +02:00
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 01:36:09 +02:00
|
|
|
|
2019-11-30 15:08:22 +01:00
|
|
|
fn check_expr_box(&self, expr: &'tcx hir::Expr<'tcx>, expected: Expectation<'tcx>) -> Ty<'tcx> {
|
2020-08-03 00:49:11 +02:00
|
|
|
let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| match ty.kind() {
|
2019-06-15 01:36:09 +02:00
|
|
|
ty::Adt(def, _) if def.is_box() => Expectation::rvalue_hint(self, ty.boxed_ty()),
|
|
|
|
|
_ => NoExpectation,
|
|
|
|
|
});
|
|
|
|
|
let referent_ty = self.check_expr_with_expectation(expr, expected_inner);
|
2021-08-20 16:25:52 +02:00
|
|
|
self.require_type_is_sized(referent_ty, expr.span, traits::SizedBoxType);
|
2019-06-15 01:36:09 +02:00
|
|
|
self.tcx.mk_box(referent_ty)
|
|
|
|
|
}
|
2019-06-15 01:45:39 +02:00
|
|
|
|
|
|
|
|
fn check_expr_unary(
|
|
|
|
|
&self,
|
|
|
|
|
unop: hir::UnOp,
|
2019-11-30 15:08:22 +01:00
|
|
|
oprnd: &'tcx hir::Expr<'tcx>,
|
2019-06-15 01:45:39 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 01:45:39 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let tcx = self.tcx;
|
|
|
|
|
let expected_inner = match unop {
|
2021-02-09 11:15:53 +03:00
|
|
|
hir::UnOp::Not | hir::UnOp::Neg => expected,
|
|
|
|
|
hir::UnOp::Deref => NoExpectation,
|
2019-06-15 01:45:39 +02:00
|
|
|
};
|
2020-06-15 21:59:09 +01:00
|
|
|
let mut oprnd_t = self.check_expr_with_expectation(&oprnd, expected_inner);
|
2019-06-15 01:45:39 +02:00
|
|
|
|
|
|
|
|
if !oprnd_t.references_error() {
|
|
|
|
|
oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
|
|
|
|
|
match unop {
|
2021-02-09 11:15:53 +03:00
|
|
|
hir::UnOp::Deref => {
|
2020-06-15 21:59:09 +01:00
|
|
|
if let Some(ty) = self.lookup_derefing(expr, oprnd, oprnd_t) {
|
|
|
|
|
oprnd_t = ty;
|
2019-06-15 01:45:39 +02:00
|
|
|
} else {
|
|
|
|
|
let mut err = type_error_struct!(
|
|
|
|
|
tcx.sess,
|
|
|
|
|
expr.span,
|
|
|
|
|
oprnd_t,
|
|
|
|
|
E0614,
|
2022-04-15 15:56:32 +09:00
|
|
|
"type `{oprnd_t}` cannot be dereferenced",
|
2019-06-15 01:45:39 +02:00
|
|
|
);
|
|
|
|
|
let sp = tcx.sess.source_map().start_point(expr.span);
|
|
|
|
|
if let Some(sp) =
|
|
|
|
|
tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp)
|
|
|
|
|
{
|
2022-09-30 01:38:15 +00:00
|
|
|
err.subdiagnostic(ExprParenthesesNeeded::surrounding(*sp));
|
2019-06-15 01:45:39 +02:00
|
|
|
}
|
|
|
|
|
err.emit();
|
2020-05-05 23:02:09 -05:00
|
|
|
oprnd_t = tcx.ty_error();
|
2019-06-15 01:45:39 +02:00
|
|
|
}
|
|
|
|
|
}
|
2021-02-09 11:15:53 +03:00
|
|
|
hir::UnOp::Not => {
|
2022-04-26 13:59:08 -07:00
|
|
|
let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
|
2019-06-15 01:45:39 +02:00
|
|
|
// If it's builtin, we can reuse the type, this helps inference.
|
2020-08-03 00:49:11 +02:00
|
|
|
if !(oprnd_t.is_integral() || *oprnd_t.kind() == ty::Bool) {
|
2019-06-15 01:45:39 +02:00
|
|
|
oprnd_t = result;
|
|
|
|
|
}
|
|
|
|
|
}
|
2021-02-09 11:15:53 +03:00
|
|
|
hir::UnOp::Neg => {
|
2022-04-26 13:59:08 -07:00
|
|
|
let result = self.check_user_unop(expr, oprnd_t, unop, expected_inner);
|
2019-06-15 01:45:39 +02:00
|
|
|
// If it's builtin, we can reuse the type, this helps inference.
|
|
|
|
|
if !oprnd_t.is_numeric() {
|
|
|
|
|
oprnd_t = result;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
oprnd_t
|
|
|
|
|
}
|
2019-06-15 01:50:33 +02:00
|
|
|
|
|
|
|
|
fn check_expr_addr_of(
|
|
|
|
|
&self,
|
2019-11-23 14:15:49 +00:00
|
|
|
kind: hir::BorrowKind,
|
2019-06-15 01:50:33 +02:00
|
|
|
mutbl: hir::Mutability,
|
2019-11-30 15:08:22 +01:00
|
|
|
oprnd: &'tcx hir::Expr<'tcx>,
|
2019-06-15 01:50:33 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 01:50:33 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
|
2020-08-03 00:49:11 +02:00
|
|
|
match ty.kind() {
|
2019-06-15 01:50:33 +02:00
|
|
|
ty::Ref(_, ty, _) | ty::RawPtr(ty::TypeAndMut { ty, .. }) => {
|
2019-11-23 14:15:49 +00:00
|
|
|
if oprnd.is_syntactic_place_expr() {
|
2019-06-15 01:50:33 +02:00
|
|
|
// Places may legitimately have unsized types.
|
|
|
|
|
// For example, dereferences of a fat pointer and
|
|
|
|
|
// the last field of a struct can be unsized.
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 14:13:38 +11:00
|
|
|
ExpectHasType(*ty)
|
2019-06-15 01:50:33 +02:00
|
|
|
} else {
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 14:13:38 +11:00
|
|
|
Expectation::rvalue_hint(self, *ty)
|
2019-06-15 01:50:33 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
_ => NoExpectation,
|
|
|
|
|
}
|
|
|
|
|
});
|
2020-06-15 21:59:09 +01:00
|
|
|
let ty =
|
|
|
|
|
self.check_expr_with_expectation_and_needs(&oprnd, hint, Needs::maybe_mut_place(mutbl));
|
2019-06-15 01:50:33 +02:00
|
|
|
|
2020-03-06 19:28:44 +01:00
|
|
|
let tm = ty::TypeAndMut { ty, mutbl };
|
2019-11-23 14:15:49 +00:00
|
|
|
match kind {
|
2020-05-05 23:02:09 -05:00
|
|
|
_ if tm.ty.references_error() => self.tcx.ty_error(),
|
2019-11-23 14:15:49 +00:00
|
|
|
hir::BorrowKind::Raw => {
|
|
|
|
|
self.check_named_place_expr(oprnd);
|
|
|
|
|
self.tcx.mk_ptr(tm)
|
|
|
|
|
}
|
|
|
|
|
hir::BorrowKind::Ref => {
|
|
|
|
|
// Note: at this point, we cannot say what the best lifetime
|
|
|
|
|
// is to use for resulting pointer. We want to use the
|
|
|
|
|
// shortest lifetime possible so as to avoid spurious borrowck
|
|
|
|
|
// errors. Moreover, the longest lifetime will depend on the
|
|
|
|
|
// precise details of the value whose address is being taken
|
|
|
|
|
// (and how long it is valid), which we don't know yet until
|
|
|
|
|
// type inference is complete.
|
|
|
|
|
//
|
|
|
|
|
// Therefore, here we simply generate a region variable. The
|
|
|
|
|
// region inferencer will then select a suitable value.
|
|
|
|
|
// Finally, borrowck will infer the value of the region again,
|
|
|
|
|
// this time with enough precision to check that the value
|
|
|
|
|
// whose address was taken can actually be made to live as long
|
|
|
|
|
// as it needs to live.
|
|
|
|
|
let region = self.next_region_var(infer::AddrOfRegion(expr.span));
|
|
|
|
|
self.tcx.mk_ref(region, tm)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// 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.
|
2019-11-30 15:08:22 +01:00
|
|
|
fn check_named_place_expr(&self, oprnd: &'tcx hir::Expr<'tcx>) {
|
2019-11-23 14:15:49 +00:00
|
|
|
let is_named = oprnd.is_place_expr(|base| {
|
|
|
|
|
// Allow raw borrows if there are any deref adjustments.
|
|
|
|
|
//
|
|
|
|
|
// const VAL: (i32,) = (0,);
|
|
|
|
|
// const REF: &(i32,) = &(0,);
|
|
|
|
|
//
|
|
|
|
|
// &raw const VAL.0; // ERROR
|
|
|
|
|
// &raw const REF.0; // OK, same as &raw const (*REF).0;
|
2019-06-15 01:50:33 +02:00
|
|
|
//
|
2019-11-23 14:15:49 +00:00
|
|
|
// This is maybe too permissive, since it allows
|
|
|
|
|
// `let u = &raw const Box::new((1,)).0`, which creates an
|
|
|
|
|
// immediately dangling raw pointer.
|
2020-09-18 19:11:06 +02:00
|
|
|
self.typeck_results
|
|
|
|
|
.borrow()
|
|
|
|
|
.adjustments()
|
|
|
|
|
.get(base.hir_id)
|
|
|
|
|
.map_or(false, |x| x.iter().any(|adj| matches!(adj.kind, Adjust::Deref(_))))
|
2019-11-23 14:15:49 +00:00
|
|
|
});
|
|
|
|
|
if !is_named {
|
2022-01-27 09:44:25 +00:00
|
|
|
self.tcx.sess.emit_err(AddressOfTemporaryTaken { span: oprnd.span });
|
2019-06-15 01:50:33 +02:00
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 01:56:10 +02:00
|
|
|
|
2020-08-04 14:34:24 +01:00
|
|
|
fn check_lang_item_path(
|
|
|
|
|
&self,
|
|
|
|
|
lang_item: hir::LangItem,
|
|
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2021-11-16 20:07:23 +00:00
|
|
|
hir_id: Option<hir::HirId>,
|
2020-08-04 14:34:24 +01:00
|
|
|
) -> Ty<'tcx> {
|
2021-11-16 20:07:23 +00:00
|
|
|
self.resolve_lang_item_path(lang_item, expr.span, expr.hir_id, hir_id).1
|
2020-08-04 14:34:24 +01:00
|
|
|
}
|
|
|
|
|
|
2021-09-14 10:52:36 +00:00
|
|
|
pub(crate) fn check_expr_path(
|
2021-03-29 19:53:48 -07:00
|
|
|
&self,
|
|
|
|
|
qpath: &'tcx hir::QPath<'tcx>,
|
|
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2021-09-14 10:52:36 +00:00
|
|
|
args: &'tcx [hir::Expr<'tcx>],
|
2021-03-29 19:53:48 -07:00
|
|
|
) -> Ty<'tcx> {
|
2019-06-15 01:56:10 +02:00
|
|
|
let tcx = self.tcx;
|
2021-05-27 23:39:07 -04:00
|
|
|
let (res, opt_ty, segs) =
|
|
|
|
|
self.resolve_ty_and_res_fully_qualified_call(qpath, expr.hir_id, expr.span);
|
2019-06-15 01:56:10 +02:00
|
|
|
let ty = match res {
|
|
|
|
|
Res::Err => {
|
|
|
|
|
self.set_tainted_by_errors();
|
2020-05-05 23:02:09 -05:00
|
|
|
tcx.ty_error()
|
2019-06-15 01:56:10 +02:00
|
|
|
}
|
|
|
|
|
Res::Def(DefKind::Ctor(_, CtorKind::Fictive), _) => {
|
2022-07-16 21:03:30 -07:00
|
|
|
report_unexpected_variant_res(tcx, res, qpath, expr.span);
|
2020-05-05 23:02:09 -05:00
|
|
|
tcx.ty_error()
|
2019-06-15 01:56:10 +02:00
|
|
|
}
|
|
|
|
|
_ => self.instantiate_value_path(segs, opt_ty, res, expr.span, expr.hir_id).0,
|
|
|
|
|
};
|
|
|
|
|
|
2022-04-14 12:07:36 +00:00
|
|
|
if let ty::FnDef(did, ..) = *ty.kind() {
|
2019-06-15 01:56:10 +02:00
|
|
|
let fn_sig = ty.fn_sig(tcx);
|
2022-04-14 12:07:36 +00:00
|
|
|
if tcx.fn_sig(did).abi() == RustIntrinsic && tcx.item_name(did) == sym::transmute {
|
|
|
|
|
let from = fn_sig.inputs().skip_binder()[0];
|
|
|
|
|
let to = fn_sig.output().skip_binder();
|
2022-05-25 14:01:06 +00:00
|
|
|
// We defer the transmute to the end of typeck, once all inference vars have
|
|
|
|
|
// been resolved or we errored. This is important as we can only check transmute
|
|
|
|
|
// on concrete types, but the output type may not be known yet (it would only
|
|
|
|
|
// be known if explicitly specified via turbofish).
|
2022-10-03 13:49:31 +02:00
|
|
|
self.deferred_transmute_checks.borrow_mut().push((from, to, expr.hir_id));
|
2022-04-14 12:07:36 +00:00
|
|
|
}
|
2020-10-16 17:46:59 -03:00
|
|
|
if !tcx.features().unsized_fn_params {
|
2019-06-15 01:56:10 +02:00
|
|
|
// We want to remove some Sized bounds from std functions,
|
|
|
|
|
// but don't want to expose the removal to stable Rust.
|
|
|
|
|
// i.e., we don't want to allow
|
|
|
|
|
//
|
|
|
|
|
// ```rust
|
|
|
|
|
// drop as fn(str);
|
|
|
|
|
// ```
|
|
|
|
|
//
|
|
|
|
|
// to work in stable even if the Sized bound on `drop` is relaxed.
|
|
|
|
|
for i in 0..fn_sig.inputs().skip_binder().len() {
|
|
|
|
|
// We just want to check sizedness, so instead of introducing
|
|
|
|
|
// placeholder lifetimes with probing, we just replace higher lifetimes
|
|
|
|
|
// with fresh vars.
|
2022-08-24 18:36:44 +00:00
|
|
|
let span = args.get(i).map(|a| a.span).unwrap_or(expr.span);
|
2022-06-02 12:48:56 +02:00
|
|
|
let input = self.replace_bound_vars_with_fresh_vars(
|
|
|
|
|
span,
|
|
|
|
|
infer::LateBoundRegionConversionTime::FnCall,
|
|
|
|
|
fn_sig.input(i),
|
|
|
|
|
);
|
2022-08-24 18:36:44 +00:00
|
|
|
self.require_type_is_sized_deferred(
|
|
|
|
|
input,
|
2021-09-14 10:52:36 +00:00
|
|
|
span,
|
2022-08-24 18:36:44 +00:00
|
|
|
traits::SizedArgumentType(None),
|
2019-06-15 01:56:10 +02:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
// Here we want to prevent struct constructors from returning unsized types.
|
|
|
|
|
// There were two cases this happened: fn pointer coercion in stable
|
2019-11-26 22:19:54 -05:00
|
|
|
// and usual function call in presence of unsized_locals.
|
2019-06-15 01:56:10 +02:00
|
|
|
// Also, as we just want to check sizedness, instead of introducing
|
|
|
|
|
// placeholder lifetimes with probing, we just replace higher lifetimes
|
|
|
|
|
// with fresh vars.
|
2022-06-02 12:48:56 +02:00
|
|
|
let output = self.replace_bound_vars_with_fresh_vars(
|
|
|
|
|
expr.span,
|
|
|
|
|
infer::LateBoundRegionConversionTime::FnCall,
|
|
|
|
|
fn_sig.output(),
|
|
|
|
|
);
|
2022-08-24 18:36:44 +00:00
|
|
|
self.require_type_is_sized_deferred(output, expr.span, traits::SizedReturnType);
|
2019-06-15 01:56:10 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// We always require that the type provided as the value for
|
|
|
|
|
// a type parameter outlives the moment of instantiation.
|
2020-07-17 08:47:04 +00:00
|
|
|
let substs = self.typeck_results.borrow().node_substs(expr.hir_id);
|
2019-06-15 01:56:10 +02:00
|
|
|
self.add_wf_bounds(substs, expr);
|
|
|
|
|
|
|
|
|
|
ty
|
|
|
|
|
}
|
2019-06-15 02:06:02 +02:00
|
|
|
|
|
|
|
|
fn check_expr_break(
|
|
|
|
|
&self,
|
|
|
|
|
destination: hir::Destination,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr_opt: Option<&'tcx hir::Expr<'tcx>>,
|
|
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:06:02 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let tcx = self.tcx;
|
|
|
|
|
if let Ok(target_id) = destination.target_id {
|
|
|
|
|
let (e_ty, cause);
|
2021-02-08 22:02:35 -05:00
|
|
|
if let Some(e) = expr_opt {
|
2019-06-15 02:06:02 +02:00
|
|
|
// If this is a break with a value, we need to type-check
|
|
|
|
|
// the expression. Get an expected type from the loop context.
|
|
|
|
|
let opt_coerce_to = {
|
2019-11-29 12:11:12 +03:00
|
|
|
// We should release `enclosing_breakables` before the `check_expr_with_hint`
|
|
|
|
|
// below, so can't move this block of code to the enclosing scope and share
|
2022-03-30 15:14:15 -04:00
|
|
|
// `ctxt` with the second `enclosing_breakables` borrow below.
|
2019-06-15 02:06:02 +02:00
|
|
|
let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
|
2019-11-29 12:11:12 +03:00
|
|
|
match enclosing_breakables.opt_find_breakable(target_id) {
|
|
|
|
|
Some(ctxt) => ctxt.coerce.as_ref().map(|coerce| coerce.expected_ty()),
|
|
|
|
|
None => {
|
|
|
|
|
// Avoid ICE when `break` is inside a closure (#65383).
|
2020-05-05 23:02:09 -05:00
|
|
|
return tcx.ty_error_with_message(
|
2019-11-29 12:11:12 +03:00
|
|
|
expr.span,
|
|
|
|
|
"break was outside loop, but no error was emitted",
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 02:06:02 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// If the loop context is not a `loop { }`, then break with
|
|
|
|
|
// a value is illegal, and `opt_coerce_to` will be `None`.
|
|
|
|
|
// Just set expectation to error in that case.
|
2020-05-05 23:02:09 -05:00
|
|
|
let coerce_to = opt_coerce_to.unwrap_or_else(|| tcx.ty_error());
|
2019-06-15 02:06:02 +02:00
|
|
|
|
|
|
|
|
// Recurse without `enclosing_breakables` borrowed.
|
|
|
|
|
e_ty = self.check_expr_with_hint(e, coerce_to);
|
|
|
|
|
cause = self.misc(e.span);
|
|
|
|
|
} else {
|
|
|
|
|
// Otherwise, this is a break *without* a value. That's
|
|
|
|
|
// always legal, and is equivalent to `break ()`.
|
|
|
|
|
e_ty = tcx.mk_unit();
|
|
|
|
|
cause = self.misc(expr.span);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Now that we have type-checked `expr_opt`, borrow
|
|
|
|
|
// the `enclosing_loops` field and let's coerce the
|
|
|
|
|
// type of `expr_opt` into what is expected.
|
|
|
|
|
let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
|
2022-02-19 00:44:45 +01:00
|
|
|
let Some(ctxt) = enclosing_breakables.opt_find_breakable(target_id) else {
|
|
|
|
|
// Avoid ICE when `break` is inside a closure (#65383).
|
|
|
|
|
return tcx.ty_error_with_message(
|
|
|
|
|
expr.span,
|
|
|
|
|
"break was outside loop, but no error was emitted",
|
|
|
|
|
);
|
2019-10-17 13:16:24 -07:00
|
|
|
};
|
|
|
|
|
|
2019-06-15 02:06:02 +02:00
|
|
|
if let Some(ref mut coerce) = ctxt.coerce {
|
|
|
|
|
if let Some(ref e) = expr_opt {
|
|
|
|
|
coerce.coerce(self, &cause, e, e_ty);
|
|
|
|
|
} else {
|
|
|
|
|
assert!(e_ty.is_unit());
|
2019-08-06 14:20:39 -07:00
|
|
|
let ty = coerce.expected_ty();
|
2019-11-04 18:47:02 -08:00
|
|
|
coerce.coerce_forced_unit(
|
|
|
|
|
self,
|
|
|
|
|
&cause,
|
|
|
|
|
&mut |mut err| {
|
|
|
|
|
self.suggest_mismatched_types_on_tail(
|
2021-04-06 19:23:22 -07:00
|
|
|
&mut err, expr, ty, e_ty, target_id,
|
2019-10-23 22:45:15 -07:00
|
|
|
);
|
|
|
|
|
if let Some(val) = ty_kind_suggestion(ty) {
|
|
|
|
|
let label = destination
|
2019-12-22 17:42:04 -05:00
|
|
|
.label
|
2019-10-23 22:45:15 -07:00
|
|
|
.map(|l| format!(" {}", l.ident))
|
|
|
|
|
.unwrap_or_else(String::new);
|
|
|
|
|
err.span_suggestion(
|
2019-10-17 13:16:24 -07:00
|
|
|
expr.span,
|
2019-10-23 22:45:15 -07:00
|
|
|
"give it a value of the expected type",
|
2022-04-15 15:56:32 +09:00
|
|
|
format!("break{label} {val}"),
|
2019-10-23 22:45:15 -07:00
|
|
|
Applicability::HasPlaceholders,
|
2019-08-06 14:20:39 -07:00
|
|
|
);
|
2019-12-22 17:42:04 -05:00
|
|
|
}
|
2019-08-06 14:20:39 -07:00
|
|
|
},
|
|
|
|
|
false,
|
2019-12-22 17:42:04 -05:00
|
|
|
);
|
2019-06-15 02:06:02 +02:00
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
// If `ctxt.coerce` is `None`, we can just ignore
|
2019-10-17 13:16:24 -07:00
|
|
|
// the type of the expression. This is because
|
2019-06-15 02:06:02 +02:00
|
|
|
// either this was a break *without* a value, in
|
|
|
|
|
// which case it is always a legal type (`()`), or
|
|
|
|
|
// else an error would have been flagged by the
|
|
|
|
|
// `loops` pass for using break with an expression
|
|
|
|
|
// where you are not supposed to.
|
2022-01-22 18:49:12 -06:00
|
|
|
assert!(expr_opt.is_none() || self.tcx.sess.has_errors().is_some());
|
2019-06-15 02:06:02 +02:00
|
|
|
}
|
|
|
|
|
|
2020-09-29 01:03:02 +01:00
|
|
|
// If we encountered a `break`, then (no surprise) it may be possible to break from the
|
|
|
|
|
// loop... unless the value being returned from the loop diverges itself, e.g.
|
|
|
|
|
// `break return 5` or `break loop {}`.
|
2020-10-22 23:12:46 +01:00
|
|
|
ctxt.may_break |= !self.diverges.get().is_always();
|
2019-06-15 02:06:02 +02:00
|
|
|
|
|
|
|
|
// the type of a `break` is always `!`, since it diverges
|
|
|
|
|
tcx.types.never
|
|
|
|
|
} else {
|
|
|
|
|
// Otherwise, we failed to find the enclosing loop;
|
|
|
|
|
// this can only happen if the `break` was not
|
|
|
|
|
// inside a loop at all, which is caught by the
|
|
|
|
|
// loop-checking pass.
|
2020-05-05 23:02:09 -05:00
|
|
|
let err = self.tcx.ty_error_with_message(
|
|
|
|
|
expr.span,
|
|
|
|
|
"break was outside loop, but no error was emitted",
|
|
|
|
|
);
|
2019-06-15 02:06:02 +02:00
|
|
|
|
|
|
|
|
// We still need to assign a type to the inner expression to
|
|
|
|
|
// prevent the ICE in #43162.
|
2021-02-08 22:02:35 -05:00
|
|
|
if let Some(e) = expr_opt {
|
2020-05-05 23:02:09 -05:00
|
|
|
self.check_expr_with_hint(e, err);
|
2019-06-15 02:06:02 +02:00
|
|
|
|
|
|
|
|
// ... except when we try to 'break rust;'.
|
|
|
|
|
// ICE this expression in particular (see #43162).
|
2021-02-08 22:02:35 -05:00
|
|
|
if let ExprKind::Path(QPath::Resolved(_, path)) = e.kind {
|
2019-06-15 02:06:02 +02:00
|
|
|
if path.segments.len() == 1 && path.segments[0].ident.name == sym::rust {
|
|
|
|
|
fatally_break_rust(self.tcx.sess);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-05-05 23:02:09 -05:00
|
|
|
|
2019-06-15 02:06:02 +02:00
|
|
|
// There was an error; make type-check fail.
|
2020-05-05 23:02:09 -05:00
|
|
|
err
|
2019-06-15 02:06:02 +02:00
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 02:10:12 +02:00
|
|
|
|
|
|
|
|
fn check_expr_return(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr_opt: Option<&'tcx hir::Expr<'tcx>>,
|
|
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:10:12 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
if self.ret_coercion.is_none() {
|
2021-06-11 01:20:00 +02:00
|
|
|
let mut err = ReturnStmtOutsideOfFnBody {
|
|
|
|
|
span: expr.span,
|
|
|
|
|
encl_body_span: None,
|
|
|
|
|
encl_fn_span: None,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let encl_item_id = self.tcx.hir().get_parent_item(expr.hir_id);
|
|
|
|
|
|
2021-06-30 18:27:07 +02:00
|
|
|
if let Some(hir::Node::Item(hir::Item {
|
|
|
|
|
kind: hir::ItemKind::Fn(..),
|
|
|
|
|
span: encl_fn_span,
|
|
|
|
|
..
|
|
|
|
|
}))
|
|
|
|
|
| Some(hir::Node::TraitItem(hir::TraitItem {
|
|
|
|
|
kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)),
|
|
|
|
|
span: encl_fn_span,
|
|
|
|
|
..
|
|
|
|
|
}))
|
|
|
|
|
| Some(hir::Node::ImplItem(hir::ImplItem {
|
|
|
|
|
kind: hir::ImplItemKind::Fn(..),
|
|
|
|
|
span: encl_fn_span,
|
|
|
|
|
..
|
2022-09-20 14:11:23 +09:00
|
|
|
})) = self.tcx.hir().find_by_def_id(encl_item_id.def_id)
|
2021-06-30 18:27:07 +02:00
|
|
|
{
|
|
|
|
|
// We are inside a function body, so reporting "return statement
|
|
|
|
|
// outside of function body" needs an explanation.
|
|
|
|
|
|
|
|
|
|
let encl_body_owner_id = self.tcx.hir().enclosing_body_owner(expr.hir_id);
|
|
|
|
|
|
|
|
|
|
// If this didn't hold, we would not have to report an error in
|
|
|
|
|
// the first place.
|
2022-09-20 14:11:23 +09:00
|
|
|
assert_ne!(encl_item_id.def_id, encl_body_owner_id);
|
2021-06-30 18:27:07 +02:00
|
|
|
|
|
|
|
|
let encl_body_id = self.tcx.hir().body_owned_by(encl_body_owner_id);
|
|
|
|
|
let encl_body = self.tcx.hir().body(encl_body_id);
|
|
|
|
|
|
|
|
|
|
err.encl_body_span = Some(encl_body.value.span);
|
|
|
|
|
err.encl_fn_span = Some(*encl_fn_span);
|
2021-06-11 01:20:00 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
self.tcx.sess.emit_err(err);
|
|
|
|
|
|
|
|
|
|
if let Some(e) = expr_opt {
|
|
|
|
|
// We still have to type-check `e` (issue #86188), but calling
|
|
|
|
|
// `check_return_expr` only works inside fn bodies.
|
|
|
|
|
self.check_expr(e);
|
|
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
} else if let Some(e) = expr_opt {
|
2021-01-23 11:47:38 +01:00
|
|
|
if self.ret_coercion_span.get().is_none() {
|
|
|
|
|
self.ret_coercion_span.set(Some(e.span));
|
2019-06-15 02:10:12 +02:00
|
|
|
}
|
2021-09-16 16:53:40 -05:00
|
|
|
self.check_return_expr(e, true);
|
2019-06-15 02:10:12 +02:00
|
|
|
} else {
|
|
|
|
|
let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
|
2021-01-23 11:47:38 +01:00
|
|
|
if self.ret_coercion_span.get().is_none() {
|
|
|
|
|
self.ret_coercion_span.set(Some(expr.span));
|
2019-06-15 02:10:12 +02:00
|
|
|
}
|
|
|
|
|
let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
|
|
|
|
|
if let Some((fn_decl, _)) = self.get_fn_decl(expr.hir_id) {
|
|
|
|
|
coercion.coerce_forced_unit(
|
|
|
|
|
self,
|
|
|
|
|
&cause,
|
|
|
|
|
&mut |db| {
|
2020-03-23 11:32:07 +01:00
|
|
|
let span = fn_decl.output.span();
|
|
|
|
|
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
|
|
|
|
|
db.span_label(
|
|
|
|
|
span,
|
2022-04-15 15:56:32 +09:00
|
|
|
format!("expected `{snippet}` because of this return type"),
|
2020-03-23 11:32:07 +01:00
|
|
|
);
|
|
|
|
|
}
|
2019-06-15 02:10:12 +02:00
|
|
|
},
|
|
|
|
|
true,
|
|
|
|
|
);
|
|
|
|
|
} else {
|
|
|
|
|
coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
self.tcx.types.never
|
|
|
|
|
}
|
2019-06-15 02:10:56 +02:00
|
|
|
|
2022-03-30 15:14:15 -04:00
|
|
|
/// `explicit_return` is `true` if we're checking an explicit `return expr`,
|
2021-09-16 16:53:40 -05:00
|
|
|
/// and `false` if we're checking a trailing expression.
|
|
|
|
|
pub(super) fn check_return_expr(
|
|
|
|
|
&self,
|
|
|
|
|
return_expr: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
explicit_return: bool,
|
|
|
|
|
) {
|
2019-06-15 03:01:05 +02:00
|
|
|
let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
|
|
|
|
|
span_bug!(return_expr.span, "check_return_expr called outside fn body")
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
let ret_ty = ret_coercion.borrow().expected_ty();
|
2021-01-05 16:46:50 +01:00
|
|
|
let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
|
2021-09-16 16:53:40 -05:00
|
|
|
let mut span = return_expr.span;
|
|
|
|
|
// Use the span of the trailing expression for our cause,
|
|
|
|
|
// not the span of the entire function
|
|
|
|
|
if !explicit_return {
|
2022-02-26 07:43:47 -03:00
|
|
|
if let ExprKind::Block(body, _) = return_expr.kind && let Some(last_expr) = body.expr {
|
|
|
|
|
span = last_expr.span;
|
2021-09-16 16:53:40 -05:00
|
|
|
}
|
|
|
|
|
}
|
2019-09-24 11:05:49 -07:00
|
|
|
ret_coercion.borrow_mut().coerce(
|
|
|
|
|
self,
|
2021-09-16 16:53:40 -05:00
|
|
|
&self.cause(span, ObligationCauseCode::ReturnValue(return_expr.hir_id)),
|
2019-09-24 11:05:49 -07:00
|
|
|
return_expr,
|
|
|
|
|
return_expr_ty,
|
|
|
|
|
);
|
2022-06-06 23:20:13 -07:00
|
|
|
|
|
|
|
|
if self.return_type_has_opaque {
|
|
|
|
|
// Point any obligations that were registered due to opaque type
|
|
|
|
|
// inference at the return expression.
|
|
|
|
|
self.select_obligations_where_possible(false, |errors| {
|
|
|
|
|
self.point_at_return_for_opaque_ty_error(errors, span, return_expr_ty);
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn point_at_return_for_opaque_ty_error(
|
|
|
|
|
&self,
|
|
|
|
|
errors: &mut Vec<traits::FulfillmentError<'tcx>>,
|
|
|
|
|
span: Span,
|
|
|
|
|
return_expr_ty: Ty<'tcx>,
|
|
|
|
|
) {
|
|
|
|
|
// Don't point at the whole block if it's empty
|
|
|
|
|
if span == self.tcx.hir().span(self.body_id) {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
for err in errors {
|
|
|
|
|
let cause = &mut err.obligation.cause;
|
|
|
|
|
if let ObligationCauseCode::OpaqueReturnType(None) = cause.code() {
|
|
|
|
|
let new_cause = ObligationCause::new(
|
|
|
|
|
cause.span,
|
|
|
|
|
cause.body_id,
|
|
|
|
|
ObligationCauseCode::OpaqueReturnType(Some((return_expr_ty, span))),
|
|
|
|
|
);
|
|
|
|
|
*cause = new_cause;
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 03:01:05 +02:00
|
|
|
}
|
|
|
|
|
|
2019-12-22 20:14:08 +00:00
|
|
|
pub(crate) fn check_lhs_assignable(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
lhs: &'tcx hir::Expr<'tcx>,
|
2019-12-22 20:14:08 +00:00
|
|
|
err_code: &'static str,
|
2021-05-06 19:09:35 -07:00
|
|
|
op_span: Span,
|
2022-08-10 03:39:41 +00:00
|
|
|
adjust_err: impl FnOnce(&mut Diagnostic),
|
2019-12-22 20:14:08 +00:00
|
|
|
) {
|
2020-11-04 16:32:52 +00:00
|
|
|
if lhs.is_syntactic_place_expr() {
|
|
|
|
|
return;
|
2019-12-22 20:14:08 +00:00
|
|
|
}
|
2020-11-04 16:32:52 +00:00
|
|
|
|
2022-09-18 11:46:56 -04:00
|
|
|
// FIXME: Make this use Diagnostic once error codes can be dynamically set.
|
2020-11-04 16:32:52 +00:00
|
|
|
let mut err = self.tcx.sess.struct_span_err_with_code(
|
2021-05-06 19:09:35 -07:00
|
|
|
op_span,
|
2020-11-04 16:32:52 +00:00
|
|
|
"invalid left-hand side of assignment",
|
|
|
|
|
DiagnosticId::Error(err_code.into()),
|
|
|
|
|
);
|
|
|
|
|
err.span_label(lhs.span, "cannot assign to this expression");
|
2021-05-06 19:09:35 -07:00
|
|
|
|
2022-02-21 19:49:15 -08:00
|
|
|
self.comes_from_while_condition(lhs.hir_id, |expr| {
|
|
|
|
|
err.span_suggestion_verbose(
|
|
|
|
|
expr.span.shrink_to_lo(),
|
|
|
|
|
"you might have meant to use pattern destructuring",
|
2022-06-13 15:48:40 +09:00
|
|
|
"let ",
|
2022-02-21 19:49:15 -08:00
|
|
|
Applicability::MachineApplicable,
|
|
|
|
|
);
|
|
|
|
|
});
|
|
|
|
|
|
2022-03-04 21:59:13 -08:00
|
|
|
adjust_err(&mut err);
|
|
|
|
|
|
2022-02-21 19:49:15 -08:00
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check if an expression `original_expr_id` comes from the condition of a while loop,
|
|
|
|
|
// as opposed from the body of a while loop, which we can naively check by iterating
|
|
|
|
|
// parents until we find a loop...
|
|
|
|
|
pub(super) fn comes_from_while_condition(
|
|
|
|
|
&self,
|
|
|
|
|
original_expr_id: HirId,
|
|
|
|
|
then: impl FnOnce(&hir::Expr<'_>),
|
|
|
|
|
) {
|
|
|
|
|
let mut parent = self.tcx.hir().get_parent_node(original_expr_id);
|
2021-05-06 19:09:35 -07:00
|
|
|
while let Some(node) = self.tcx.hir().find(parent) {
|
|
|
|
|
match node {
|
|
|
|
|
hir::Node::Expr(hir::Expr {
|
|
|
|
|
kind:
|
|
|
|
|
hir::ExprKind::Loop(
|
|
|
|
|
hir::Block {
|
|
|
|
|
expr:
|
|
|
|
|
Some(hir::Expr {
|
|
|
|
|
kind:
|
|
|
|
|
hir::ExprKind::Match(expr, ..) | hir::ExprKind::If(expr, ..),
|
|
|
|
|
..
|
|
|
|
|
}),
|
|
|
|
|
..
|
|
|
|
|
},
|
|
|
|
|
_,
|
|
|
|
|
hir::LoopSource::While,
|
|
|
|
|
_,
|
|
|
|
|
),
|
|
|
|
|
..
|
|
|
|
|
}) => {
|
2022-02-21 19:49:15 -08:00
|
|
|
// Check if our original expression is a child of the condition of a while loop
|
|
|
|
|
let expr_is_ancestor = std::iter::successors(Some(original_expr_id), |id| {
|
2022-02-01 23:27:04 -08:00
|
|
|
self.tcx.hir().find_parent_node(*id)
|
|
|
|
|
})
|
|
|
|
|
.take_while(|id| *id != parent)
|
|
|
|
|
.any(|id| id == expr.hir_id);
|
|
|
|
|
// if it is, then we have a situation like `while Some(0) = value.get(0) {`,
|
|
|
|
|
// where `while let` was more likely intended.
|
|
|
|
|
if expr_is_ancestor {
|
2022-02-21 19:49:15 -08:00
|
|
|
then(expr);
|
2022-02-01 23:27:04 -08:00
|
|
|
}
|
2021-05-06 19:09:35 -07:00
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
hir::Node::Item(_)
|
|
|
|
|
| hir::Node::ImplItem(_)
|
|
|
|
|
| hir::Node::TraitItem(_)
|
|
|
|
|
| hir::Node::Crate(_) => break,
|
|
|
|
|
_ => {
|
|
|
|
|
parent = self.tcx.hir().get_parent_node(parent);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-12-22 20:14:08 +00:00
|
|
|
}
|
|
|
|
|
|
2021-01-01 15:38:11 -03:00
|
|
|
// A generic function for checking the 'then' and 'else' clauses in an 'if'
|
|
|
|
|
// or 'if-else' expression.
|
|
|
|
|
fn check_then_else(
|
|
|
|
|
&self,
|
|
|
|
|
cond_expr: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
then_expr: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
opt_else_expr: Option<&'tcx hir::Expr<'tcx>>,
|
|
|
|
|
sp: Span,
|
|
|
|
|
orig_expected: Expectation<'tcx>,
|
|
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let cond_ty = self.check_expr_has_type_or_error(cond_expr, self.tcx.types.bool, |_| {});
|
|
|
|
|
|
2021-08-08 11:49:13 -03:00
|
|
|
self.warn_if_unreachable(
|
|
|
|
|
cond_expr.hir_id,
|
|
|
|
|
then_expr.span,
|
|
|
|
|
"block in `if` or `while` expression",
|
|
|
|
|
);
|
2021-01-01 15:38:11 -03:00
|
|
|
|
|
|
|
|
let cond_diverges = self.diverges.get();
|
|
|
|
|
self.diverges.set(Diverges::Maybe);
|
|
|
|
|
|
|
|
|
|
let expected = orig_expected.adjust_for_branches(self);
|
|
|
|
|
let then_ty = self.check_expr_with_expectation(then_expr, expected);
|
|
|
|
|
let then_diverges = self.diverges.get();
|
|
|
|
|
self.diverges.set(Diverges::Maybe);
|
|
|
|
|
|
|
|
|
|
// We've already taken the expected type's preferences
|
|
|
|
|
// into account when typing the `then` branch. To figure
|
|
|
|
|
// out the initial shot at a LUB, we thus only consider
|
|
|
|
|
// `expected` if it represents a *hard* constraint
|
|
|
|
|
// (`only_has_type`); otherwise, we just go with a
|
|
|
|
|
// fresh type variable.
|
|
|
|
|
let coerce_to_ty = expected.coercion_target_type(self, sp);
|
|
|
|
|
let mut coerce: DynamicCoerceMany<'_> = CoerceMany::new(coerce_to_ty);
|
|
|
|
|
|
|
|
|
|
coerce.coerce(self, &self.misc(sp), then_expr, then_ty);
|
|
|
|
|
|
|
|
|
|
if let Some(else_expr) = opt_else_expr {
|
2022-06-02 22:39:47 +08:00
|
|
|
let else_ty = self.check_expr_with_expectation(else_expr, expected);
|
2021-01-01 15:38:11 -03:00
|
|
|
let else_diverges = self.diverges.get();
|
|
|
|
|
|
2022-08-01 20:22:50 +09:00
|
|
|
let opt_suggest_box_span = self.opt_suggest_box_span(then_ty, else_ty, orig_expected);
|
2022-07-23 14:42:54 +02:00
|
|
|
let if_cause = self.if_cause(
|
|
|
|
|
sp,
|
|
|
|
|
cond_expr.span,
|
|
|
|
|
then_expr,
|
|
|
|
|
else_expr,
|
|
|
|
|
then_ty,
|
|
|
|
|
else_ty,
|
|
|
|
|
opt_suggest_box_span,
|
|
|
|
|
);
|
2021-01-01 15:38:11 -03:00
|
|
|
|
|
|
|
|
coerce.coerce(self, &if_cause, else_expr, else_ty);
|
|
|
|
|
|
|
|
|
|
// We won't diverge unless both branches do (or the condition does).
|
|
|
|
|
self.diverges.set(cond_diverges | then_diverges & else_diverges);
|
|
|
|
|
} else {
|
2021-08-08 11:49:13 -03:00
|
|
|
self.if_fallback_coercion(sp, then_expr, &mut coerce);
|
2021-01-01 15:38:11 -03:00
|
|
|
|
|
|
|
|
// If the condition is false we can't diverge.
|
|
|
|
|
self.diverges.set(cond_diverges);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let result_ty = coerce.complete(self);
|
|
|
|
|
if cond_ty.references_error() { self.tcx.ty_error() } else { result_ty }
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-15 02:10:56 +02:00
|
|
|
/// Type check assignment expression `expr` of form `lhs = rhs`.
|
2021-01-01 15:38:11 -03:00
|
|
|
/// The expected type is `()` and is passed to the function for the purposes of diagnostics.
|
2019-06-15 02:10:56 +02:00
|
|
|
fn check_expr_assign(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:10:56 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2019-11-30 15:08:22 +01:00
|
|
|
lhs: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
rhs: &'tcx hir::Expr<'tcx>,
|
2022-02-23 08:11:17 -05:00
|
|
|
span: Span,
|
2019-06-15 02:10:56 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let expected_ty = expected.coercion_target_type(self, expr.span);
|
|
|
|
|
if expected_ty == self.tcx.types.bool {
|
|
|
|
|
// 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 { .. }`.
|
|
|
|
|
let actual_ty = self.tcx.mk_unit();
|
|
|
|
|
let mut err = self.demand_suptype_diag(expr.span, expected_ty, actual_ty).unwrap();
|
2020-08-25 20:28:25 -07:00
|
|
|
let lhs_ty = self.check_expr(&lhs);
|
|
|
|
|
let rhs_ty = self.check_expr(&rhs);
|
2020-09-27 18:58:56 -07:00
|
|
|
let (applicability, eq) = if self.can_coerce(rhs_ty, lhs_ty) {
|
|
|
|
|
(Applicability::MachineApplicable, true)
|
2022-10-05 22:51:22 +09:00
|
|
|
} else if let ExprKind::Binary(
|
|
|
|
|
Spanned { node: hir::BinOpKind::And | hir::BinOpKind::Or, .. },
|
|
|
|
|
_,
|
|
|
|
|
rhs_expr,
|
|
|
|
|
) = lhs.kind
|
|
|
|
|
{
|
|
|
|
|
let actual_lhs_ty = self.check_expr(&rhs_expr);
|
|
|
|
|
(Applicability::MaybeIncorrect, self.can_coerce(rhs_ty, actual_lhs_ty))
|
2020-09-27 18:58:56 -07:00
|
|
|
} else {
|
|
|
|
|
(Applicability::MaybeIncorrect, false)
|
|
|
|
|
};
|
2022-06-07 20:53:02 -07:00
|
|
|
if !lhs.is_syntactic_place_expr()
|
|
|
|
|
&& lhs.is_approximately_pattern()
|
|
|
|
|
&& !matches!(lhs.kind, hir::ExprKind::Lit(_))
|
|
|
|
|
{
|
2020-09-27 18:58:56 -07:00
|
|
|
// Do not suggest `if let x = y` as `==` is way more likely to be the intention.
|
2021-08-08 11:49:13 -03:00
|
|
|
let hir = self.tcx.hir();
|
|
|
|
|
if let hir::Node::Expr(hir::Expr { kind: ExprKind::If { .. }, .. }) =
|
|
|
|
|
hir.get(hir.get_parent_node(hir.get_parent_node(expr.hir_id)))
|
|
|
|
|
{
|
2020-09-27 18:58:56 -07:00
|
|
|
err.span_suggestion_verbose(
|
|
|
|
|
expr.span.shrink_to_lo(),
|
|
|
|
|
"you might have meant to use pattern matching",
|
2022-06-13 15:48:40 +09:00
|
|
|
"let ",
|
2020-09-27 18:58:56 -07:00
|
|
|
applicability,
|
|
|
|
|
);
|
2021-05-06 19:09:35 -07:00
|
|
|
};
|
2020-09-27 18:58:56 -07:00
|
|
|
}
|
|
|
|
|
if eq {
|
2020-08-25 20:28:25 -07:00
|
|
|
err.span_suggestion_verbose(
|
2022-10-05 22:46:44 +09:00
|
|
|
span.shrink_to_hi(),
|
2020-08-25 20:28:25 -07:00
|
|
|
"you might have meant to compare for equality",
|
2022-10-05 22:46:44 +09:00
|
|
|
'=',
|
2020-09-27 18:58:56 -07:00
|
|
|
applicability,
|
2020-08-25 20:28:25 -07:00
|
|
|
);
|
2019-06-15 02:10:56 +02:00
|
|
|
}
|
2020-08-25 20:28:25 -07:00
|
|
|
|
2021-08-27 18:28:22 -05:00
|
|
|
// If the assignment expression itself is ill-formed, don't
|
|
|
|
|
// bother emitting another error
|
|
|
|
|
if lhs_ty.references_error() || rhs_ty.references_error() {
|
|
|
|
|
err.delay_as_bug()
|
2020-08-25 20:28:25 -07:00
|
|
|
} else {
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
return self.tcx.ty_error();
|
2019-06-15 02:10:56 +02:00
|
|
|
}
|
|
|
|
|
|
2020-08-25 20:28:25 -07:00
|
|
|
let lhs_ty = self.check_expr_with_needs(&lhs, Needs::MutPlace);
|
2022-03-04 21:59:13 -08:00
|
|
|
|
2022-08-10 03:39:41 +00:00
|
|
|
let suggest_deref_binop = |err: &mut Diagnostic, rhs_ty: Ty<'tcx>| {
|
2022-03-05 01:57:43 -08:00
|
|
|
if let Some(lhs_deref_ty) = self.deref_once_mutably_for_diagnostic(lhs_ty) {
|
|
|
|
|
// Can only assign if the type is sized, so if `DerefMut` yields a type that is
|
|
|
|
|
// unsized, do not suggest dereferencing it.
|
|
|
|
|
let lhs_deref_ty_is_sized = self
|
|
|
|
|
.infcx
|
|
|
|
|
.type_implements_trait(
|
|
|
|
|
self.tcx.lang_items().sized_trait().unwrap(),
|
|
|
|
|
lhs_deref_ty,
|
|
|
|
|
ty::List::empty(),
|
|
|
|
|
self.param_env,
|
|
|
|
|
)
|
|
|
|
|
.may_apply();
|
|
|
|
|
if lhs_deref_ty_is_sized && self.can_coerce(rhs_ty, lhs_deref_ty) {
|
2022-03-04 21:59:13 -08:00
|
|
|
err.span_suggestion_verbose(
|
|
|
|
|
lhs.span.shrink_to_lo(),
|
2022-03-05 01:57:43 -08:00
|
|
|
"consider dereferencing here to assign to the mutably borrowed value",
|
2022-06-13 15:48:40 +09:00
|
|
|
"*",
|
2022-03-04 21:59:13 -08:00
|
|
|
Applicability::MachineApplicable,
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
2022-03-05 01:57:43 -08:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
self.check_lhs_assignable(lhs, "E0070", span, |err| {
|
|
|
|
|
let rhs_ty = self.check_expr(&rhs);
|
|
|
|
|
suggest_deref_binop(err, rhs_ty);
|
2022-03-04 21:59:13 -08:00
|
|
|
});
|
|
|
|
|
|
2022-03-05 01:57:43 -08:00
|
|
|
// This is (basically) inlined `check_expr_coercable_to_type`, but we want
|
|
|
|
|
// to suggest an additional fixup here in `suggest_deref_binop`.
|
|
|
|
|
let rhs_ty = self.check_expr_with_hint(&rhs, lhs_ty);
|
|
|
|
|
if let (_, Some(mut diag)) =
|
|
|
|
|
self.demand_coerce_diag(rhs, rhs_ty, lhs_ty, Some(lhs), AllowTwoPhase::No)
|
|
|
|
|
{
|
|
|
|
|
suggest_deref_binop(&mut diag, rhs_ty);
|
|
|
|
|
diag.emit();
|
|
|
|
|
}
|
2020-08-25 20:28:25 -07:00
|
|
|
|
2019-06-15 02:10:56 +02:00
|
|
|
self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
|
|
|
|
|
|
|
|
|
|
if lhs_ty.references_error() || rhs_ty.references_error() {
|
2020-05-05 23:02:09 -05:00
|
|
|
self.tcx.ty_error()
|
2019-06-15 02:10:56 +02:00
|
|
|
} else {
|
|
|
|
|
self.tcx.mk_unit()
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 02:19:23 +02:00
|
|
|
|
2022-05-09 20:35:58 +08:00
|
|
|
pub(super) fn check_expr_let(&self, let_expr: &'tcx hir::Let<'tcx>) -> Ty<'tcx> {
|
2021-10-13 16:39:06 +11:00
|
|
|
// for let statements, this is done in check_stmt
|
|
|
|
|
let init = let_expr.init;
|
|
|
|
|
self.warn_if_unreachable(init.hir_id, init.span, "block in `let` expression");
|
|
|
|
|
// otherwise check exactly as a let statement
|
|
|
|
|
self.check_decl(let_expr.into());
|
|
|
|
|
// but return a bool, for this is a boolean expression
|
2021-08-08 11:49:13 -03:00
|
|
|
self.tcx.types.bool
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-15 02:22:52 +02:00
|
|
|
fn check_expr_loop(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
body: &'tcx hir::Block<'tcx>,
|
2019-06-15 02:22:52 +02:00
|
|
|
source: hir::LoopSource,
|
|
|
|
|
expected: Expectation<'tcx>,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:22:52 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let coerce = match source {
|
|
|
|
|
// you can only use break with a value from a normal `loop { }`
|
|
|
|
|
hir::LoopSource::Loop => {
|
|
|
|
|
let coerce_to = expected.coercion_target_type(self, body.span);
|
|
|
|
|
Some(CoerceMany::new(coerce_to))
|
|
|
|
|
}
|
|
|
|
|
|
2021-08-08 11:49:13 -03:00
|
|
|
hir::LoopSource::While | hir::LoopSource::ForLoop => None,
|
2019-06-15 02:22:52 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let ctxt = BreakableCtxt {
|
|
|
|
|
coerce,
|
|
|
|
|
may_break: false, // Will get updated if/when we find a `break`.
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let (ctxt, ()) = self.with_breakable_ctxt(expr.hir_id, ctxt, || {
|
|
|
|
|
self.check_block_no_value(&body);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if ctxt.may_break {
|
|
|
|
|
// No way to know whether it's diverging because
|
|
|
|
|
// of a `break` or an outer `break` or `return`.
|
|
|
|
|
self.diverges.set(Diverges::Maybe);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If we permit break with a value, then result type is
|
|
|
|
|
// the LUB of the breaks (possibly ! if none); else, it
|
|
|
|
|
// is nil. This makes sense because infinite loops
|
|
|
|
|
// (which would have type !) are only possible iff we
|
|
|
|
|
// permit break with a value [1].
|
|
|
|
|
if ctxt.coerce.is_none() && !ctxt.may_break {
|
|
|
|
|
// [1]
|
|
|
|
|
self.tcx.sess.delay_span_bug(body.span, "no coercion, but loop may not break");
|
|
|
|
|
}
|
|
|
|
|
ctxt.coerce.map(|c| c.complete(self)).unwrap_or_else(|| self.tcx.mk_unit())
|
|
|
|
|
}
|
2019-06-15 02:25:37 +02:00
|
|
|
|
2019-06-15 03:11:36 +02:00
|
|
|
/// Checks a method call.
|
|
|
|
|
fn check_method_call(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-12-01 16:08:58 +01:00
|
|
|
segment: &hir::PathSegment<'_>,
|
2022-09-02 22:48:14 +09:00
|
|
|
rcvr: &'tcx hir::Expr<'tcx>,
|
2019-11-30 15:08:22 +01:00
|
|
|
args: &'tcx [hir::Expr<'tcx>],
|
2019-06-15 03:11:36 +02:00
|
|
|
expected: Expectation<'tcx>,
|
|
|
|
|
) -> Ty<'tcx> {
|
2020-06-15 21:59:09 +01:00
|
|
|
let rcvr_t = self.check_expr(&rcvr);
|
2019-06-15 03:11:36 +02:00
|
|
|
// no need to check for bot/err -- callee does that
|
2022-09-02 22:48:14 +09:00
|
|
|
let rcvr_t = self.structurally_resolved_type(rcvr.span, rcvr_t);
|
2021-12-01 11:17:50 -06:00
|
|
|
let span = segment.ident.span;
|
2019-06-15 03:11:36 +02:00
|
|
|
|
2021-06-14 22:43:19 -04:00
|
|
|
let method = match self.lookup_method(rcvr_t, segment, span, expr, rcvr, args) {
|
2019-06-15 03:11:36 +02:00
|
|
|
Ok(method) => {
|
2019-12-10 09:01:06 -08:00
|
|
|
// We could add a "consider `foo::<params>`" suggestion here, but I wasn't able to
|
2022-03-30 15:14:15 -04:00
|
|
|
// trigger this codepath causing `structurally_resolved_type` to emit an error.
|
2019-12-10 09:01:06 -08:00
|
|
|
|
2019-06-15 03:11:36 +02:00
|
|
|
self.write_method_call(expr.hir_id, method);
|
|
|
|
|
Ok(method)
|
|
|
|
|
}
|
|
|
|
|
Err(error) => {
|
2020-12-29 20:28:08 -05:00
|
|
|
if segment.ident.name != kw::Empty {
|
2021-03-29 19:53:48 -07:00
|
|
|
if let Some(mut err) = self.report_method_error(
|
|
|
|
|
span,
|
|
|
|
|
rcvr_t,
|
|
|
|
|
segment.ident,
|
2022-09-02 22:48:14 +09:00
|
|
|
SelfSource::MethodCall(rcvr),
|
2021-03-29 19:53:48 -07:00
|
|
|
error,
|
2022-09-02 22:48:14 +09:00
|
|
|
Some((rcvr, args)),
|
2021-03-29 19:53:48 -07:00
|
|
|
) {
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
2019-06-15 03:11:36 +02:00
|
|
|
}
|
|
|
|
|
Err(())
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Call the generic checker.
|
2022-09-01 13:27:31 +09:00
|
|
|
self.check_method_argument_types(span, expr, method, &args, DontTupleArguments, expected)
|
2019-06-15 03:11:36 +02:00
|
|
|
}
|
|
|
|
|
|
2019-06-15 02:25:37 +02:00
|
|
|
fn check_expr_cast(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
e: &'tcx hir::Expr<'tcx>,
|
2019-12-01 16:08:58 +01:00
|
|
|
t: &'tcx hir::Ty<'tcx>,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:25:37 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
// Find the type of `e`. Supply hints based on the type we are casting to,
|
|
|
|
|
// if appropriate.
|
|
|
|
|
let t_cast = self.to_ty_saving_user_provided_ty(t);
|
2020-10-24 02:21:18 +02:00
|
|
|
let t_cast = self.resolve_vars_if_possible(t_cast);
|
2019-06-15 02:25:37 +02:00
|
|
|
let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
|
2021-08-23 19:07:14 +00:00
|
|
|
let t_expr = self.resolve_vars_if_possible(t_expr);
|
2019-06-15 02:25:37 +02:00
|
|
|
|
|
|
|
|
// Eagerly check for some obvious errors.
|
|
|
|
|
if t_expr.references_error() || t_cast.references_error() {
|
2020-05-05 23:02:09 -05:00
|
|
|
self.tcx.ty_error()
|
2019-06-15 02:25:37 +02:00
|
|
|
} else {
|
|
|
|
|
// Defer other checks until we're done type checking.
|
|
|
|
|
let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
|
2022-04-13 16:38:16 -07:00
|
|
|
match cast::check_cast(self, e, t_expr, t_cast, t.span, expr.span) {
|
|
|
|
|
CastCheckResult::Ok => t_cast,
|
|
|
|
|
CastCheckResult::Deferred(cast_check) => {
|
2021-08-23 19:14:06 +00:00
|
|
|
debug!(
|
|
|
|
|
"check_expr_cast: deferring cast from {:?} to {:?}: {:?}",
|
2021-08-23 22:21:21 +00:00
|
|
|
t_cast, t_expr, cast_check,
|
2021-08-23 19:14:06 +00:00
|
|
|
);
|
2019-06-15 02:25:37 +02:00
|
|
|
deferred_cast_checks.push(cast_check);
|
|
|
|
|
t_cast
|
|
|
|
|
}
|
2022-04-13 16:38:16 -07:00
|
|
|
CastCheckResult::Err(ErrorGuaranteed { .. }) => self.tcx.ty_error(),
|
2019-06-15 02:25:37 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 02:31:20 +02:00
|
|
|
|
|
|
|
|
fn check_expr_array(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
args: &'tcx [hir::Expr<'tcx>],
|
2019-06-15 02:31:20 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:31:20 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let element_ty = if !args.is_empty() {
|
2020-04-11 15:53:10 +08:00
|
|
|
let coerce_to = expected
|
|
|
|
|
.to_option(self)
|
2020-08-03 00:49:11 +02:00
|
|
|
.and_then(|uty| match *uty.kind() {
|
2020-04-11 15:53:10 +08:00
|
|
|
ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
|
|
|
|
|
_ => None,
|
2019-06-15 02:31:20 +02:00
|
|
|
})
|
2020-04-11 15:53:10 +08:00
|
|
|
.unwrap_or_else(|| {
|
|
|
|
|
self.next_ty_var(TypeVariableOrigin {
|
|
|
|
|
kind: TypeVariableOriginKind::TypeInference,
|
|
|
|
|
span: expr.span,
|
|
|
|
|
})
|
|
|
|
|
});
|
2019-06-15 02:31:20 +02:00
|
|
|
let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
|
|
|
|
|
assert_eq!(self.diverges.get(), Diverges::Maybe);
|
|
|
|
|
for e in args {
|
|
|
|
|
let e_ty = self.check_expr_with_hint(e, coerce_to);
|
|
|
|
|
let cause = self.misc(e.span);
|
|
|
|
|
coerce.coerce(self, &cause, e, e_ty);
|
|
|
|
|
}
|
|
|
|
|
coerce.complete(self)
|
|
|
|
|
} else {
|
|
|
|
|
self.next_ty_var(TypeVariableOrigin {
|
|
|
|
|
kind: TypeVariableOriginKind::TypeInference,
|
|
|
|
|
span: expr.span,
|
|
|
|
|
})
|
|
|
|
|
};
|
2022-08-16 00:16:14 +09:00
|
|
|
let array_len = args.len() as u64;
|
|
|
|
|
self.suggest_array_len(expr, array_len);
|
|
|
|
|
self.tcx.mk_array(element_ty, array_len)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn suggest_array_len(&self, expr: &'tcx hir::Expr<'tcx>, array_len: u64) {
|
2022-09-07 02:37:18 +09:00
|
|
|
let parent_node = self.tcx.hir().parent_iter(expr.hir_id).find(|(_, node)| {
|
|
|
|
|
!matches!(node, hir::Node::Expr(hir::Expr { kind: hir::ExprKind::AddrOf(..), .. }))
|
|
|
|
|
});
|
|
|
|
|
let Some((_,
|
|
|
|
|
hir::Node::Local(hir::Local { ty: Some(ty), .. })
|
|
|
|
|
| hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(ty, _), .. }))
|
|
|
|
|
) = parent_node else {
|
|
|
|
|
return
|
|
|
|
|
};
|
|
|
|
|
if let hir::TyKind::Array(_, length) = ty.peel_refs().kind
|
|
|
|
|
&& let hir::ArrayLen::Body(hir::AnonConst { hir_id, .. }) = length
|
|
|
|
|
&& let Some(span) = self.tcx.hir().opt_span(hir_id)
|
|
|
|
|
{
|
|
|
|
|
match self.tcx.sess.diagnostic().steal_diagnostic(span, StashKey::UnderscoreForArrayLengths) {
|
|
|
|
|
Some(mut err) => {
|
|
|
|
|
err.span_suggestion(
|
|
|
|
|
span,
|
|
|
|
|
"consider specifying the array length",
|
|
|
|
|
array_len,
|
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
|
|
|
|
err.emit();
|
2022-08-16 00:16:14 +09:00
|
|
|
}
|
2022-09-07 02:37:18 +09:00
|
|
|
None => ()
|
2022-08-16 00:16:14 +09:00
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 02:31:20 +02:00
|
|
|
}
|
2019-06-15 02:36:07 +02:00
|
|
|
|
2021-10-02 13:12:33 +01:00
|
|
|
fn check_expr_const_block(
|
|
|
|
|
&self,
|
|
|
|
|
anon_const: &'tcx hir::AnonConst,
|
|
|
|
|
expected: Expectation<'tcx>,
|
|
|
|
|
_expr: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let body = self.tcx.hir().body(anon_const.body);
|
|
|
|
|
|
|
|
|
|
// Create a new function context.
|
2022-01-14 03:39:29 -08:00
|
|
|
let fcx = FnCtxt::new(self, self.param_env.with_const(), body.value.hir_id);
|
2021-10-02 13:12:33 +01:00
|
|
|
crate::check::GatherLocalsVisitor::new(&fcx).visit_body(body);
|
|
|
|
|
|
|
|
|
|
let ty = fcx.check_expr_with_expectation(&body.value, expected);
|
|
|
|
|
fcx.require_type_is_sized(ty, body.value.span, traits::ConstSized);
|
|
|
|
|
fcx.write_ty(anon_const.hir_id, ty);
|
|
|
|
|
ty
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-15 02:36:07 +02:00
|
|
|
fn check_expr_repeat(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
element: &'tcx hir::Expr<'tcx>,
|
2021-12-23 10:01:51 +01:00
|
|
|
count: &'tcx hir::ArrayLen,
|
2019-06-15 02:36:07 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2022-08-16 00:16:14 +09:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:36:07 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let tcx = self.tcx;
|
2021-12-23 10:01:51 +01:00
|
|
|
let count = self.array_length_to_const(count);
|
2022-08-16 00:16:14 +09:00
|
|
|
if let Some(count) = count.try_eval_usize(tcx, self.param_env) {
|
|
|
|
|
self.suggest_array_len(expr, count);
|
|
|
|
|
}
|
2019-06-15 02:36:07 +02:00
|
|
|
|
|
|
|
|
let uty = match expected {
|
2020-08-03 00:49:11 +02:00
|
|
|
ExpectHasType(uty) => match *uty.kind() {
|
2019-06-15 02:36:07 +02:00
|
|
|
ty::Array(ty, _) | ty::Slice(ty) => Some(ty),
|
|
|
|
|
_ => None,
|
|
|
|
|
},
|
|
|
|
|
_ => None,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
let (element_ty, t) = match uty {
|
|
|
|
|
Some(uty) => {
|
2020-06-09 11:45:40 -07:00
|
|
|
self.check_expr_coercable_to_type(&element, uty, None);
|
2019-06-15 02:36:07 +02:00
|
|
|
(uty, uty)
|
|
|
|
|
}
|
|
|
|
|
None => {
|
|
|
|
|
let ty = self.next_ty_var(TypeVariableOrigin {
|
|
|
|
|
kind: TypeVariableOriginKind::MiscVariable,
|
|
|
|
|
span: element.span,
|
|
|
|
|
});
|
2019-09-26 17:16:34 -07:00
|
|
|
let element_ty = self.check_expr_has_type_or_error(&element, ty, |_| {});
|
2019-06-15 02:36:07 +02:00
|
|
|
(element_ty, ty)
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
if element_ty.references_error() {
|
2020-05-05 23:02:09 -05:00
|
|
|
return tcx.ty_error();
|
2020-03-10 01:51:08 +08:00
|
|
|
}
|
2020-03-14 15:30:35 +01:00
|
|
|
|
2022-04-29 18:49:02 +00:00
|
|
|
self.check_repeat_element_needs_copy_bound(element, count, element_ty);
|
|
|
|
|
|
|
|
|
|
tcx.mk_ty(ty::Array(t, count))
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn check_repeat_element_needs_copy_bound(
|
|
|
|
|
&self,
|
|
|
|
|
element: &hir::Expr<'_>,
|
|
|
|
|
count: ty::Const<'tcx>,
|
|
|
|
|
element_ty: Ty<'tcx>,
|
|
|
|
|
) {
|
|
|
|
|
let tcx = self.tcx;
|
2022-04-29 18:56:57 +00:00
|
|
|
// Actual constants as the repeat element get inserted repeatedly instead of getting copied via Copy.
|
|
|
|
|
match &element.kind {
|
|
|
|
|
hir::ExprKind::ConstBlock(..) => return,
|
2022-04-11 16:38:48 +00:00
|
|
|
hir::ExprKind::Path(qpath) => {
|
|
|
|
|
let res = self.typeck_results.borrow().qpath_res(qpath, element.hir_id);
|
2022-04-29 18:56:57 +00:00
|
|
|
if let Res::Def(DefKind::Const | DefKind::AssocConst | DefKind::AnonConst, _) = res
|
|
|
|
|
{
|
|
|
|
|
return;
|
|
|
|
|
}
|
2022-04-11 16:38:48 +00:00
|
|
|
}
|
2022-04-29 18:56:57 +00:00
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
// If someone calls a const fn, they can extract that call out into a separate constant (or a const
|
|
|
|
|
// block in the future), so we check that to tell them that in the diagnostic. Does not affect typeck.
|
|
|
|
|
let is_const_fn = match element.kind {
|
|
|
|
|
hir::ExprKind::Call(func, _args) => match *self.node_ty(func.hir_id).kind() {
|
|
|
|
|
ty::FnDef(def_id, _) => tcx.is_const_fn(def_id),
|
|
|
|
|
_ => false,
|
|
|
|
|
},
|
2022-04-11 16:38:48 +00:00
|
|
|
_ => false,
|
|
|
|
|
};
|
|
|
|
|
|
2022-04-29 18:56:57 +00:00
|
|
|
// If the length is 0, we don't create any elements, so we don't copy any. If the length is 1, we
|
|
|
|
|
// don't copy that one element, we move it. Only check for Copy if the length is larger.
|
|
|
|
|
if count.try_eval_usize(tcx, self.param_env).map_or(true, |len| len > 1) {
|
|
|
|
|
let lang_item = self.tcx.require_lang_item(LangItem::Copy, None);
|
|
|
|
|
let code = traits::ObligationCauseCode::RepeatElementCopy { is_const_fn };
|
|
|
|
|
self.require_type_meets(element_ty, element.span, code, lang_item);
|
2022-04-11 16:38:48 +00:00
|
|
|
}
|
2019-06-15 02:36:07 +02:00
|
|
|
}
|
2019-06-15 02:39:23 +02:00
|
|
|
|
|
|
|
|
fn check_expr_tuple(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
elts: &'tcx [hir::Expr<'tcx>],
|
2019-06-15 02:39:23 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:39:23 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
let flds = expected.only_has_type(self).and_then(|ty| {
|
2019-10-19 12:04:16 +13:00
|
|
|
let ty = self.resolve_vars_with_obligations(ty);
|
2020-08-03 00:49:11 +02:00
|
|
|
match ty.kind() {
|
2021-02-08 22:02:35 -05:00
|
|
|
ty::Tuple(flds) => Some(&flds[..]),
|
2019-06-15 02:39:23 +02:00
|
|
|
_ => None,
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2020-03-22 00:20:58 +01:00
|
|
|
let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds {
|
2021-02-08 22:02:35 -05:00
|
|
|
Some(fs) if i < fs.len() => {
|
2022-02-07 16:06:31 +01:00
|
|
|
let ety = fs[i];
|
2020-06-09 11:45:40 -07:00
|
|
|
self.check_expr_coercable_to_type(&e, ety, None);
|
2020-03-22 00:20:58 +01:00
|
|
|
ety
|
|
|
|
|
}
|
|
|
|
|
_ => self.check_expr_with_expectation(&e, NoExpectation),
|
2019-06-15 02:39:23 +02:00
|
|
|
});
|
|
|
|
|
let tuple = self.tcx.mk_tup(elt_ts_iter);
|
|
|
|
|
if tuple.references_error() {
|
2020-05-05 23:02:09 -05:00
|
|
|
self.tcx.ty_error()
|
2019-06-15 02:39:23 +02:00
|
|
|
} else {
|
|
|
|
|
self.require_type_is_sized(tuple, expr.span, traits::TupleInitializerSized);
|
|
|
|
|
tuple
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 02:43:02 +02:00
|
|
|
|
|
|
|
|
fn check_expr_struct(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &hir::Expr<'_>,
|
2019-06-15 02:43:02 +02:00
|
|
|
expected: Expectation<'tcx>,
|
2019-12-01 16:08:58 +01:00
|
|
|
qpath: &QPath<'_>,
|
2021-03-16 00:36:07 +03:00
|
|
|
fields: &'tcx [hir::ExprField<'tcx>],
|
2019-11-30 15:08:22 +01:00
|
|
|
base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
|
2019-06-15 02:43:02 +02:00
|
|
|
) -> Ty<'tcx> {
|
|
|
|
|
// Find the relevant variant
|
2022-02-15 05:58:25 +01:00
|
|
|
let Some((variant, adt_ty)) = self.check_struct_path(qpath, expr.hir_id) else {
|
2019-06-15 02:43:02 +02:00
|
|
|
self.check_struct_fields_on_error(fields, base_expr);
|
2020-05-05 23:02:09 -05:00
|
|
|
return self.tcx.ty_error();
|
2019-06-15 02:43:02 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Prohibit struct expressions when non-exhaustive flag is set.
|
|
|
|
|
let adt = adt_ty.ty_adt_def().expect("`check_struct_path` returned non-ADT type");
|
2022-03-05 07:28:41 +11:00
|
|
|
if !adt.did().is_local() && variant.is_field_list_non_exhaustive() {
|
2020-08-27 20:09:22 +10:00
|
|
|
self.tcx
|
|
|
|
|
.sess
|
|
|
|
|
.emit_err(StructExprNonExhaustive { span: expr.span, what: adt.variant_descr() });
|
2019-06-15 02:43:02 +02:00
|
|
|
}
|
|
|
|
|
|
2021-10-29 11:16:28 +08:00
|
|
|
self.check_expr_struct_fields(
|
2019-06-15 02:43:02 +02:00
|
|
|
adt_ty,
|
|
|
|
|
expected,
|
|
|
|
|
expr.hir_id,
|
2020-08-04 14:34:24 +01:00
|
|
|
qpath.span(),
|
2019-06-15 02:43:02 +02:00
|
|
|
variant,
|
|
|
|
|
fields,
|
2021-10-29 11:16:28 +08:00
|
|
|
base_expr,
|
2021-09-01 20:11:05 -07:00
|
|
|
expr.span,
|
2019-06-15 02:43:02 +02:00
|
|
|
);
|
2021-10-29 11:16:28 +08:00
|
|
|
|
2019-06-15 02:43:02 +02:00
|
|
|
self.require_type_is_sized(adt_ty, expr.span, traits::StructInitializerSized);
|
|
|
|
|
adt_ty
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn check_expr_struct_fields(
|
|
|
|
|
&self,
|
|
|
|
|
adt_ty: Ty<'tcx>,
|
|
|
|
|
expected: Expectation<'tcx>,
|
|
|
|
|
expr_id: hir::HirId,
|
|
|
|
|
span: Span,
|
|
|
|
|
variant: &'tcx ty::VariantDef,
|
2021-03-16 00:36:07 +03:00
|
|
|
ast_fields: &'tcx [hir::ExprField<'tcx>],
|
2021-10-29 11:16:28 +08:00
|
|
|
base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
|
2021-09-01 20:11:05 -07:00
|
|
|
expr_span: Span,
|
2021-10-29 11:16:28 +08:00
|
|
|
) {
|
2019-06-15 03:32:16 +02:00
|
|
|
let tcx = self.tcx;
|
|
|
|
|
|
Implementation for 65853
This attempts to bring better error messages to invalid method calls, by applying some heuristics to identify common mistakes.
The algorithm is inspired by Levenshtein distance and longest common sub-sequence. In essence, we treat the types of the function, and the types of the arguments you provided as two "words" and compute the edits to get from one to the other.
We then modify that algorithm to detect 4 cases:
- A function input is missing
- An extra argument was provided
- The type of an argument is straight up invalid
- Two arguments have been swapped
- A subset of the arguments have been shuffled
(We detect the last two as separate cases so that we can detect two swaps, instead of 4 parameters permuted.)
It helps to understand this argument by paying special attention to terminology: "inputs" refers to the inputs being *expected* by the function, and "arguments" refers to what has been provided at the call site.
The basic sketch of the algorithm is as follows:
- Construct a boolean grid, with a row for each argument, and a column for each input. The cell [i, j] is true if the i'th argument could satisfy the j'th input.
- If we find an argument that could satisfy no inputs, provided for an input that can't be satisfied by any other argument, we consider this an "invalid type".
- Extra arguments are those that can't satisfy any input, provided for an input that *could* be satisfied by another argument.
- Missing inputs are inputs that can't be satisfied by any argument, where the provided argument could satisfy another input
- Swapped / Permuted arguments are identified with a cycle detection algorithm.
As each issue is found, we remove the relevant inputs / arguments and check for more issues. If we find no issues, we match up any "valid" arguments, and start again.
Note that there's a lot of extra complexity:
- We try to stay efficient on the happy path, only computing the diagonal until we find a problem, and then filling in the rest of the matrix.
- Closure arguments are wrapped in a tuple and need to be unwrapped
- We need to resolve closure types after the rest, to allow the most specific type constraints
- We need to handle imported C functions that might be variadic in their inputs.
I tried to document a lot of this in comments in the code and keep the naming clear.
2022-01-21 23:50:54 -05:00
|
|
|
let expected_inputs =
|
|
|
|
|
self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty]);
|
|
|
|
|
let adt_ty_hint = if let Some(expected_inputs) = expected_inputs {
|
|
|
|
|
expected_inputs.get(0).cloned().unwrap_or(adt_ty)
|
|
|
|
|
} else {
|
|
|
|
|
adt_ty
|
|
|
|
|
};
|
2019-06-15 03:32:16 +02:00
|
|
|
// re-link the regions that EIfEO can erase.
|
|
|
|
|
self.demand_eqtype(span, adt_ty_hint, adt_ty);
|
|
|
|
|
|
2022-06-11 10:35:36 -07:00
|
|
|
let ty::Adt(adt, substs) = adt_ty.kind() else {
|
|
|
|
|
span_bug!(span, "non-ADT passed to check_expr_struct_fields");
|
2019-06-15 03:32:16 +02:00
|
|
|
};
|
2022-06-11 10:35:36 -07:00
|
|
|
let adt_kind = adt.adt_kind();
|
2019-06-15 03:32:16 +02:00
|
|
|
|
|
|
|
|
let mut remaining_fields = variant
|
|
|
|
|
.fields
|
|
|
|
|
.iter()
|
|
|
|
|
.enumerate()
|
2022-01-02 22:37:05 -05:00
|
|
|
.map(|(i, field)| (field.ident(tcx).normalize_to_macros_2_0(), (i, field)))
|
2019-06-15 03:32:16 +02:00
|
|
|
.collect::<FxHashMap<_, _>>();
|
|
|
|
|
|
|
|
|
|
let mut seen_fields = FxHashMap::default();
|
|
|
|
|
|
|
|
|
|
let mut error_happened = false;
|
|
|
|
|
|
|
|
|
|
// Type-check each field.
|
2022-08-09 07:04:37 +00:00
|
|
|
for (idx, field) in ast_fields.iter().enumerate() {
|
2019-06-15 03:32:16 +02:00
|
|
|
let ident = tcx.adjust_ident(field.ident, variant.def_id);
|
|
|
|
|
let field_type = if let Some((i, v_field)) = remaining_fields.remove(&ident) {
|
|
|
|
|
seen_fields.insert(ident, field.span);
|
|
|
|
|
self.write_field_index(field.hir_id, i);
|
|
|
|
|
|
|
|
|
|
// We don't look at stability attributes on
|
|
|
|
|
// struct-like enums (yet...), but it's definitely not
|
|
|
|
|
// a bug to have constructed one.
|
|
|
|
|
if adt_kind != AdtKind::Enum {
|
2021-05-07 10:41:04 +08:00
|
|
|
tcx.check_stability(v_field.did, Some(expr_id), field.span, None);
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
self.field_ty(field.span, v_field, substs)
|
|
|
|
|
} else {
|
|
|
|
|
error_happened = true;
|
|
|
|
|
if let Some(prev_span) = seen_fields.get(&ident) {
|
2020-08-27 20:09:22 +10:00
|
|
|
tcx.sess.emit_err(FieldMultiplySpecifiedInInitializer {
|
|
|
|
|
span: field.ident.span,
|
|
|
|
|
prev_span: *prev_span,
|
|
|
|
|
ident,
|
|
|
|
|
});
|
2019-06-15 03:32:16 +02:00
|
|
|
} else {
|
2021-09-01 20:11:05 -07:00
|
|
|
self.report_unknown_field(
|
2022-06-11 10:35:36 -07:00
|
|
|
adt_ty,
|
|
|
|
|
variant,
|
|
|
|
|
field,
|
|
|
|
|
ast_fields,
|
|
|
|
|
adt.variant_descr(),
|
|
|
|
|
expr_span,
|
2021-09-01 20:11:05 -07:00
|
|
|
);
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
|
|
|
|
|
2020-05-05 23:02:09 -05:00
|
|
|
tcx.ty_error()
|
2019-06-15 03:32:16 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// Make sure to give a type to the field even if there's
|
|
|
|
|
// an error, so we can continue type-checking.
|
2022-08-09 07:04:37 +00:00
|
|
|
let ty = self.check_expr_with_hint(&field.expr, field_type);
|
|
|
|
|
let (_, diag) =
|
|
|
|
|
self.demand_coerce_diag(&field.expr, ty, field_type, None, AllowTwoPhase::No);
|
|
|
|
|
|
|
|
|
|
if let Some(mut diag) = diag {
|
|
|
|
|
if idx == ast_fields.len() - 1 && remaining_fields.is_empty() {
|
|
|
|
|
self.suggest_fru_from_range(field, variant, substs, &mut diag);
|
|
|
|
|
}
|
|
|
|
|
diag.emit();
|
|
|
|
|
}
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Make sure the programmer specified correct number of fields.
|
2022-06-11 10:35:36 -07:00
|
|
|
if adt_kind == AdtKind::Union {
|
2019-06-15 03:32:16 +02:00
|
|
|
if ast_fields.len() != 1 {
|
2021-08-02 16:33:37 +02:00
|
|
|
struct_span_err!(
|
|
|
|
|
tcx.sess,
|
|
|
|
|
span,
|
|
|
|
|
E0784,
|
|
|
|
|
"union expressions should have exactly one field",
|
|
|
|
|
)
|
|
|
|
|
.emit();
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
2021-10-29 11:16:28 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If check_expr_struct_fields hit an error, do not attempt to populate
|
|
|
|
|
// the fields with the base_expr. This could cause us to hit errors later
|
|
|
|
|
// when certain fields are assumed to exist that in fact do not.
|
|
|
|
|
if error_happened {
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if let Some(base_expr) = base_expr {
|
2021-11-05 09:30:49 +08:00
|
|
|
// FIXME: We are currently creating two branches here in order to maintain
|
|
|
|
|
// consistency. But they should be merged as much as possible.
|
|
|
|
|
let fru_tys = if self.tcx.features().type_changing_struct_update {
|
2022-06-11 13:21:38 -07:00
|
|
|
if adt.is_struct() {
|
|
|
|
|
// Make some fresh substitutions for our ADT type.
|
|
|
|
|
let fresh_substs = self.fresh_substs_for_item(base_expr.span, adt.did());
|
|
|
|
|
// We do subtyping on the FRU fields first, so we can
|
|
|
|
|
// learn exactly what types we expect the base expr
|
|
|
|
|
// needs constrained to be compatible with the struct
|
|
|
|
|
// type we expect from the expectation value.
|
|
|
|
|
let fru_tys = variant
|
|
|
|
|
.fields
|
|
|
|
|
.iter()
|
|
|
|
|
.map(|f| {
|
|
|
|
|
let fru_ty = self.normalize_associated_types_in(
|
|
|
|
|
expr_span,
|
|
|
|
|
self.field_ty(base_expr.span, f, fresh_substs),
|
|
|
|
|
);
|
|
|
|
|
let ident = self.tcx.adjust_ident(f.ident(self.tcx), variant.def_id);
|
|
|
|
|
if let Some(_) = remaining_fields.remove(&ident) {
|
|
|
|
|
let target_ty = self.field_ty(base_expr.span, f, substs);
|
|
|
|
|
let cause = self.misc(base_expr.span);
|
|
|
|
|
match self.at(&cause, self.param_env).sup(target_ty, fru_ty) {
|
|
|
|
|
Ok(InferOk { obligations, value: () }) => {
|
|
|
|
|
self.register_predicates(obligations)
|
|
|
|
|
}
|
|
|
|
|
Err(_) => {
|
|
|
|
|
// This should never happen, since we're just subtyping the
|
|
|
|
|
// remaining_fields, but it's fine to emit this, I guess.
|
|
|
|
|
self.report_mismatched_types(
|
|
|
|
|
&cause,
|
|
|
|
|
target_ty,
|
|
|
|
|
fru_ty,
|
|
|
|
|
FieldMisMatch(variant.name, ident.name),
|
|
|
|
|
)
|
|
|
|
|
.emit();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
self.resolve_vars_if_possible(fru_ty)
|
|
|
|
|
})
|
|
|
|
|
.collect();
|
|
|
|
|
// The use of fresh substs that we have subtyped against
|
|
|
|
|
// our base ADT type's fields allows us to guide inference
|
|
|
|
|
// along so that, e.g.
|
2022-06-11 09:57:33 -07:00
|
|
|
// ```
|
2022-06-11 13:21:38 -07:00
|
|
|
// MyStruct<'a, F1, F2, const C: usize> {
|
|
|
|
|
// f: F1,
|
|
|
|
|
// // Other fields that reference `'a`, `F2`, and `C`
|
|
|
|
|
// }
|
|
|
|
|
//
|
|
|
|
|
// let x = MyStruct {
|
|
|
|
|
// f: 1usize,
|
|
|
|
|
// ..other_struct
|
2022-06-11 09:57:33 -07:00
|
|
|
// };
|
|
|
|
|
// ```
|
2022-06-11 13:21:38 -07:00
|
|
|
// will have the `other_struct` expression constrained to
|
|
|
|
|
// `MyStruct<'a, _, F2, C>`, as opposed to just `_`...
|
|
|
|
|
// This is important to allow coercions to happen in
|
|
|
|
|
// `other_struct` itself. See `coerce-in-base-expr.rs`.
|
2022-06-11 09:57:33 -07:00
|
|
|
let fresh_base_ty = self.tcx.mk_adt(*adt, fresh_substs);
|
2022-06-11 13:21:38 -07:00
|
|
|
self.check_expr_has_type_or_error(
|
2022-06-11 09:57:33 -07:00
|
|
|
base_expr,
|
2022-06-11 13:21:38 -07:00
|
|
|
self.resolve_vars_if_possible(fresh_base_ty),
|
|
|
|
|
|_| {},
|
2022-06-11 09:57:33 -07:00
|
|
|
);
|
2022-06-11 13:21:38 -07:00
|
|
|
fru_tys
|
2022-06-11 09:57:33 -07:00
|
|
|
} else {
|
|
|
|
|
// Check the base_expr, regardless of a bad expected adt_ty, so we can get
|
|
|
|
|
// type errors on that expression, too.
|
|
|
|
|
self.check_expr(base_expr);
|
|
|
|
|
self.tcx
|
|
|
|
|
.sess
|
|
|
|
|
.emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
|
|
|
|
|
return;
|
2021-10-29 20:08:30 +08:00
|
|
|
}
|
2021-10-29 11:16:28 +08:00
|
|
|
} else {
|
2021-11-05 09:30:49 +08:00
|
|
|
self.check_expr_has_type_or_error(base_expr, adt_ty, |_| {
|
2022-02-25 20:20:26 -08:00
|
|
|
let base_ty = self.typeck_results.borrow().expr_ty(*base_expr);
|
2021-11-05 09:30:49 +08:00
|
|
|
let same_adt = match (adt_ty.kind(), base_ty.kind()) {
|
|
|
|
|
(ty::Adt(adt, _), ty::Adt(base_adt, _)) if adt == base_adt => true,
|
|
|
|
|
_ => false,
|
|
|
|
|
};
|
|
|
|
|
if self.tcx.sess.is_nightly_build() && same_adt {
|
|
|
|
|
feature_err(
|
|
|
|
|
&self.tcx.sess.parse_sess,
|
|
|
|
|
sym::type_changing_struct_update,
|
|
|
|
|
base_expr.span,
|
|
|
|
|
"type changing struct updating is experimental",
|
|
|
|
|
)
|
|
|
|
|
.emit();
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
match adt_ty.kind() {
|
|
|
|
|
ty::Adt(adt, substs) if adt.is_struct() => variant
|
|
|
|
|
.fields
|
|
|
|
|
.iter()
|
|
|
|
|
.map(|f| {
|
|
|
|
|
self.normalize_associated_types_in(expr_span, f.ty(self.tcx, substs))
|
|
|
|
|
})
|
|
|
|
|
.collect(),
|
|
|
|
|
_ => {
|
2022-01-27 09:44:25 +00:00
|
|
|
self.tcx
|
2021-11-05 09:30:49 +08:00
|
|
|
.sess
|
|
|
|
|
.emit_err(FunctionalRecordUpdateOnNonStruct { span: base_expr.span });
|
2022-01-27 09:44:25 +00:00
|
|
|
return;
|
2021-11-05 09:30:49 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
self.typeck_results.borrow_mut().fru_field_types_mut().insert(expr_id, fru_tys);
|
2022-06-11 10:35:36 -07:00
|
|
|
} else if adt_kind != AdtKind::Union && !remaining_fields.is_empty() {
|
2022-06-20 16:29:05 +09:00
|
|
|
debug!(?remaining_fields);
|
|
|
|
|
let private_fields: Vec<&ty::FieldDef> = variant
|
|
|
|
|
.fields
|
|
|
|
|
.iter()
|
2022-08-28 00:10:06 +03:00
|
|
|
.filter(|field| !field.vis.is_accessible_from(tcx.parent_module(expr_id), tcx))
|
2022-06-20 16:29:05 +09:00
|
|
|
.collect();
|
2019-06-15 03:32:16 +02:00
|
|
|
|
2022-06-22 12:01:41 +09:00
|
|
|
if !private_fields.is_empty() {
|
2022-06-20 16:29:05 +09:00
|
|
|
self.report_private_fields(adt_ty, span, private_fields, ast_fields);
|
2019-06-15 03:32:16 +02:00
|
|
|
} else {
|
2022-03-14 11:46:12 -07:00
|
|
|
self.report_missing_fields(
|
|
|
|
|
adt_ty,
|
|
|
|
|
span,
|
|
|
|
|
remaining_fields,
|
|
|
|
|
variant,
|
|
|
|
|
ast_fields,
|
|
|
|
|
substs,
|
|
|
|
|
);
|
2020-09-09 15:42:37 +01:00
|
|
|
}
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn check_struct_fields_on_error(
|
|
|
|
|
&self,
|
2021-03-16 00:36:07 +03:00
|
|
|
fields: &'tcx [hir::ExprField<'tcx>],
|
2019-11-30 15:08:22 +01:00
|
|
|
base_expr: &'tcx Option<&'tcx hir::Expr<'tcx>>,
|
2019-06-15 03:32:16 +02:00
|
|
|
) {
|
|
|
|
|
for field in fields {
|
|
|
|
|
self.check_expr(&field.expr);
|
|
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
if let Some(base) = *base_expr {
|
2019-06-15 03:32:16 +02:00
|
|
|
self.check_expr(&base);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2020-09-09 15:42:37 +01:00
|
|
|
/// Report an error for a struct field expression when there are fields which aren't provided.
|
|
|
|
|
///
|
2020-10-04 19:08:40 -07:00
|
|
|
/// ```text
|
2020-09-09 15:42:37 +01:00
|
|
|
/// 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 previous error
|
|
|
|
|
/// ```
|
2020-12-11 19:52:51 -08:00
|
|
|
fn report_missing_fields(
|
2020-09-09 15:42:37 +01:00
|
|
|
&self,
|
|
|
|
|
adt_ty: Ty<'tcx>,
|
|
|
|
|
span: Span,
|
|
|
|
|
remaining_fields: FxHashMap<Ident, (usize, &ty::FieldDef)>,
|
2022-03-14 11:46:12 -07:00
|
|
|
variant: &'tcx ty::VariantDef,
|
|
|
|
|
ast_fields: &'tcx [hir::ExprField<'tcx>],
|
|
|
|
|
substs: SubstsRef<'tcx>,
|
2020-09-09 15:42:37 +01:00
|
|
|
) {
|
|
|
|
|
let len = remaining_fields.len();
|
|
|
|
|
|
2022-02-03 21:44:47 +01:00
|
|
|
let mut displayable_field_names: Vec<&str> =
|
|
|
|
|
remaining_fields.keys().map(|ident| ident.as_str()).collect();
|
|
|
|
|
// sorting &str primitives here, sort_unstable is ok
|
|
|
|
|
displayable_field_names.sort_unstable();
|
2020-09-09 15:42:37 +01:00
|
|
|
|
2021-02-20 18:32:02 +01:00
|
|
|
let mut truncated_fields_error = String::new();
|
|
|
|
|
let remaining_fields_names = match &displayable_field_names[..] {
|
|
|
|
|
[field1] => format!("`{}`", field1),
|
2022-04-15 15:56:32 +09:00
|
|
|
[field1, field2] => format!("`{field1}` and `{field2}`"),
|
|
|
|
|
[field1, field2, field3] => format!("`{field1}`, `{field2}` and `{field3}`"),
|
2021-02-20 18:32:02 +01:00
|
|
|
_ => {
|
|
|
|
|
truncated_fields_error =
|
|
|
|
|
format!(" and {} other field{}", len - 3, pluralize!(len - 3));
|
|
|
|
|
displayable_field_names
|
|
|
|
|
.iter()
|
|
|
|
|
.take(3)
|
2022-04-15 15:56:32 +09:00
|
|
|
.map(|n| format!("`{n}`"))
|
2021-02-20 18:32:02 +01:00
|
|
|
.collect::<Vec<_>>()
|
|
|
|
|
.join(", ")
|
|
|
|
|
}
|
2020-09-09 15:42:37 +01:00
|
|
|
};
|
|
|
|
|
|
2022-03-14 11:46:12 -07:00
|
|
|
let mut err = struct_span_err!(
|
2021-02-20 18:32:02 +01:00
|
|
|
self.tcx.sess,
|
2020-09-09 15:42:37 +01:00
|
|
|
span,
|
|
|
|
|
E0063,
|
|
|
|
|
"missing field{} {}{} in initializer of `{}`",
|
2021-02-20 18:32:02 +01:00
|
|
|
pluralize!(len),
|
2020-09-09 15:42:37 +01:00
|
|
|
remaining_fields_names,
|
|
|
|
|
truncated_fields_error,
|
|
|
|
|
adt_ty
|
2022-03-14 11:46:12 -07:00
|
|
|
);
|
2022-04-15 15:56:32 +09:00
|
|
|
err.span_label(span, format!("missing {remaining_fields_names}{truncated_fields_error}"));
|
2022-03-14 11:46:12 -07:00
|
|
|
|
2022-08-09 07:04:37 +00:00
|
|
|
if let Some(last) = ast_fields.last() {
|
|
|
|
|
self.suggest_fru_from_range(last, variant, substs, &mut err);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// If the last field is a range literal, but it isn't supposed to be, then they probably
|
|
|
|
|
/// meant to use functional update syntax.
|
|
|
|
|
fn suggest_fru_from_range(
|
|
|
|
|
&self,
|
|
|
|
|
last_expr_field: &hir::ExprField<'tcx>,
|
|
|
|
|
variant: &ty::VariantDef,
|
|
|
|
|
substs: SubstsRef<'tcx>,
|
|
|
|
|
err: &mut Diagnostic,
|
|
|
|
|
) {
|
2022-03-14 11:46:12 -07:00
|
|
|
// I don't use 'is_range_literal' because only double-sided, half-open ranges count.
|
2022-08-09 07:04:37 +00:00
|
|
|
if let ExprKind::Struct(
|
2022-03-14 11:46:12 -07:00
|
|
|
QPath::LangItem(LangItem::Range, ..),
|
|
|
|
|
&[ref range_start, ref range_end],
|
|
|
|
|
_,
|
2022-08-09 07:04:37 +00:00
|
|
|
) = last_expr_field.expr.kind
|
|
|
|
|
&& let variant_field =
|
|
|
|
|
variant.fields.iter().find(|field| field.ident(self.tcx) == last_expr_field.ident)
|
|
|
|
|
&& let range_def_id = self.tcx.lang_items().range_struct()
|
|
|
|
|
&& variant_field
|
|
|
|
|
.and_then(|field| field.ty(self.tcx, substs).ty_adt_def())
|
|
|
|
|
.map(|adt| adt.did())
|
|
|
|
|
!= range_def_id
|
2022-03-14 11:46:12 -07:00
|
|
|
{
|
|
|
|
|
let instead = self
|
|
|
|
|
.tcx
|
|
|
|
|
.sess
|
|
|
|
|
.source_map()
|
|
|
|
|
.span_to_snippet(range_end.expr.span)
|
|
|
|
|
.map(|s| format!(" from `{s}`"))
|
2022-07-20 11:48:11 +02:00
|
|
|
.unwrap_or_default();
|
2022-03-14 11:46:12 -07:00
|
|
|
err.span_suggestion(
|
|
|
|
|
range_start.span.shrink_to_hi(),
|
|
|
|
|
&format!("to set the remaining fields{instead}, separate the last named field with a comma"),
|
2022-06-13 15:48:40 +09:00
|
|
|
",",
|
2022-03-14 11:46:12 -07:00
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
|
|
|
|
}
|
2020-09-09 15:42:37 +01:00
|
|
|
}
|
|
|
|
|
|
2021-08-10 16:17:45 +02:00
|
|
|
/// Report an error for a struct field expression when there are invisible fields.
|
2020-09-09 15:42:37 +01:00
|
|
|
///
|
2020-10-04 19:08:40 -07:00
|
|
|
/// ```text
|
2022-06-20 16:29:05 +09:00
|
|
|
/// error: cannot construct `Foo` with struct literal syntax due to private fields
|
2020-09-09 15:42:37 +01:00
|
|
|
/// --> src/main.rs:8:5
|
|
|
|
|
/// |
|
|
|
|
|
/// 8 | foo::Foo {};
|
|
|
|
|
/// | ^^^^^^^^
|
|
|
|
|
///
|
|
|
|
|
/// error: aborting due to previous error
|
|
|
|
|
/// ```
|
2022-06-20 16:29:05 +09:00
|
|
|
fn report_private_fields(
|
|
|
|
|
&self,
|
|
|
|
|
adt_ty: Ty<'tcx>,
|
|
|
|
|
span: Span,
|
|
|
|
|
private_fields: Vec<&ty::FieldDef>,
|
|
|
|
|
used_fields: &'tcx [hir::ExprField<'tcx>],
|
|
|
|
|
) {
|
2022-06-22 12:01:41 +09:00
|
|
|
let mut err = self.tcx.sess.struct_span_err(
|
2020-09-09 15:42:37 +01:00
|
|
|
span,
|
|
|
|
|
&format!(
|
2022-06-22 12:01:41 +09:00
|
|
|
"cannot construct `{adt_ty}` with struct literal syntax due to private fields",
|
2020-09-09 15:42:37 +01:00
|
|
|
),
|
|
|
|
|
);
|
2022-06-22 12:01:41 +09:00
|
|
|
let (used_private_fields, remaining_private_fields): (
|
|
|
|
|
Vec<(Symbol, Span, bool)>,
|
|
|
|
|
Vec<(Symbol, Span, bool)>,
|
|
|
|
|
) = private_fields
|
|
|
|
|
.iter()
|
|
|
|
|
.map(|field| {
|
|
|
|
|
match used_fields.iter().find(|used_field| field.name == used_field.ident.name) {
|
|
|
|
|
Some(used_field) => (field.name, used_field.span, true),
|
|
|
|
|
None => (field.name, self.tcx.def_span(field.did), false),
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.partition(|field| field.2);
|
|
|
|
|
err.span_labels(used_private_fields.iter().map(|(_, span, _)| *span), "private field");
|
2022-06-22 14:56:40 +09:00
|
|
|
if !remaining_private_fields.is_empty() {
|
|
|
|
|
let remaining_private_fields_len = remaining_private_fields.len();
|
|
|
|
|
let names = match &remaining_private_fields
|
|
|
|
|
.iter()
|
2022-07-17 04:09:20 +09:00
|
|
|
.map(|(name, _, _)| name)
|
2022-06-22 14:56:40 +09:00
|
|
|
.collect::<Vec<_>>()[..]
|
|
|
|
|
{
|
|
|
|
|
_ if remaining_private_fields_len > 6 => String::new(),
|
|
|
|
|
[name] => format!("`{name}` "),
|
|
|
|
|
[names @ .., last] => {
|
|
|
|
|
let names = names.iter().map(|name| format!("`{name}`")).collect::<Vec<_>>();
|
|
|
|
|
format!("{} and `{last}` ", names.join(", "))
|
|
|
|
|
}
|
|
|
|
|
[] => unreachable!(),
|
|
|
|
|
};
|
|
|
|
|
err.note(format!(
|
|
|
|
|
"... and other private field{s} {names}that {were} not provided",
|
|
|
|
|
s = pluralize!(remaining_private_fields_len),
|
|
|
|
|
were = pluralize!("was", remaining_private_fields_len),
|
|
|
|
|
));
|
|
|
|
|
}
|
2022-06-20 16:29:05 +09:00
|
|
|
err.emit();
|
2020-09-09 15:42:37 +01:00
|
|
|
}
|
|
|
|
|
|
2019-06-15 03:32:16 +02:00
|
|
|
fn report_unknown_field(
|
|
|
|
|
&self,
|
|
|
|
|
ty: Ty<'tcx>,
|
|
|
|
|
variant: &'tcx ty::VariantDef,
|
2021-03-16 00:36:07 +03:00
|
|
|
field: &hir::ExprField<'_>,
|
|
|
|
|
skip_fields: &[hir::ExprField<'_>],
|
2019-06-15 03:32:16 +02:00
|
|
|
kind_name: &str,
|
2021-09-01 20:11:05 -07:00
|
|
|
expr_span: Span,
|
2019-06-15 03:32:16 +02:00
|
|
|
) {
|
2020-08-25 11:50:36 +02:00
|
|
|
if variant.is_recovered() {
|
2020-02-29 14:19:48 +01:00
|
|
|
self.set_tainted_by_errors();
|
2019-06-15 03:32:16 +02:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
let mut err = self.type_error_struct_with_diag(
|
|
|
|
|
field.ident.span,
|
2020-08-03 00:49:11 +02:00
|
|
|
|actual| match ty.kind() {
|
2019-06-15 03:32:16 +02:00
|
|
|
ty::Adt(adt, ..) if adt.is_enum() => struct_span_err!(
|
|
|
|
|
self.tcx.sess,
|
|
|
|
|
field.ident.span,
|
|
|
|
|
E0559,
|
|
|
|
|
"{} `{}::{}` has no field named `{}`",
|
|
|
|
|
kind_name,
|
|
|
|
|
actual,
|
2022-01-02 22:37:05 -05:00
|
|
|
variant.name,
|
2019-06-15 03:32:16 +02:00
|
|
|
field.ident
|
|
|
|
|
),
|
|
|
|
|
_ => struct_span_err!(
|
|
|
|
|
self.tcx.sess,
|
|
|
|
|
field.ident.span,
|
|
|
|
|
E0560,
|
|
|
|
|
"{} `{}` has no field named `{}`",
|
|
|
|
|
kind_name,
|
|
|
|
|
actual,
|
|
|
|
|
field.ident
|
2019-12-22 17:42:04 -05:00
|
|
|
),
|
2019-06-15 03:32:16 +02:00
|
|
|
},
|
|
|
|
|
ty,
|
|
|
|
|
);
|
2022-01-02 22:37:05 -05:00
|
|
|
|
|
|
|
|
let variant_ident_span = self.tcx.def_ident_span(variant.def_id).unwrap();
|
2019-06-17 20:04:26 +02:00
|
|
|
match variant.ctor_kind {
|
2021-01-02 11:06:30 +01:00
|
|
|
CtorKind::Fn => match ty.kind() {
|
|
|
|
|
ty::Adt(adt, ..) if adt.is_enum() => {
|
|
|
|
|
err.span_label(
|
2022-01-02 22:37:05 -05:00
|
|
|
variant_ident_span,
|
2021-01-02 11:06:30 +01:00
|
|
|
format!(
|
|
|
|
|
"`{adt}::{variant}` defined here",
|
|
|
|
|
adt = ty,
|
2022-01-02 22:37:05 -05:00
|
|
|
variant = variant.name,
|
2021-01-02 11:06:30 +01:00
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
err.span_label(field.ident.span, "field does not exist");
|
2021-09-01 20:20:46 -07:00
|
|
|
err.span_suggestion_verbose(
|
2021-09-01 20:11:05 -07:00
|
|
|
expr_span,
|
2021-02-03 21:29:00 -08:00
|
|
|
&format!(
|
|
|
|
|
"`{adt}::{variant}` is a tuple {kind_name}, use the appropriate syntax",
|
|
|
|
|
adt = ty,
|
2022-01-02 22:37:05 -05:00
|
|
|
variant = variant.name,
|
2021-02-03 21:29:00 -08:00
|
|
|
),
|
2021-01-02 11:06:30 +01:00
|
|
|
format!(
|
2021-02-03 21:29:00 -08:00
|
|
|
"{adt}::{variant}(/* fields */)",
|
2021-01-02 11:06:30 +01:00
|
|
|
adt = ty,
|
2022-01-02 22:37:05 -05:00
|
|
|
variant = variant.name,
|
2021-01-02 11:06:30 +01:00
|
|
|
),
|
2021-02-03 21:29:00 -08:00
|
|
|
Applicability::HasPlaceholders,
|
2021-01-02 11:06:30 +01:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
_ => {
|
2022-01-02 22:37:05 -05:00
|
|
|
err.span_label(variant_ident_span, format!("`{adt}` defined here", adt = ty));
|
2021-01-02 11:06:30 +01:00
|
|
|
err.span_label(field.ident.span, "field does not exist");
|
2021-09-01 20:20:46 -07:00
|
|
|
err.span_suggestion_verbose(
|
2021-09-01 20:11:05 -07:00
|
|
|
expr_span,
|
2021-02-03 21:29:00 -08:00
|
|
|
&format!(
|
|
|
|
|
"`{adt}` is a tuple {kind_name}, use the appropriate syntax",
|
2021-01-02 11:06:30 +01:00
|
|
|
adt = ty,
|
2021-02-03 21:29:00 -08:00
|
|
|
kind_name = kind_name,
|
2021-01-02 11:06:30 +01:00
|
|
|
),
|
2021-02-03 21:29:00 -08:00
|
|
|
format!("{adt}(/* fields */)", adt = ty),
|
|
|
|
|
Applicability::HasPlaceholders,
|
2021-01-02 11:06:30 +01:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
},
|
2019-06-17 20:04:26 +02:00
|
|
|
_ => {
|
|
|
|
|
// prevent all specified fields from being suggested
|
2021-02-08 22:02:35 -05:00
|
|
|
let skip_fields = skip_fields.iter().map(|x| x.ident.name);
|
2022-01-24 13:13:29 +01:00
|
|
|
if let Some(field_name) = self.suggest_field_name(
|
|
|
|
|
variant,
|
|
|
|
|
field.ident.name,
|
|
|
|
|
skip_fields.collect(),
|
|
|
|
|
expr_span,
|
|
|
|
|
) {
|
2019-06-17 20:04:26 +02:00
|
|
|
err.span_suggestion(
|
|
|
|
|
field.ident.span,
|
|
|
|
|
"a field with a similar name exists",
|
2022-06-13 15:48:40 +09:00
|
|
|
field_name,
|
2019-06-17 20:04:26 +02:00
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
|
|
|
|
} else {
|
2020-08-03 00:49:11 +02:00
|
|
|
match ty.kind() {
|
2019-06-17 20:04:26 +02:00
|
|
|
ty::Adt(adt, ..) => {
|
|
|
|
|
if adt.is_enum() {
|
2019-06-18 22:05:27 +02:00
|
|
|
err.span_label(
|
|
|
|
|
field.ident.span,
|
2022-01-02 22:37:05 -05:00
|
|
|
format!("`{}::{}` does not have this field", ty, variant.name),
|
2019-06-18 22:05:27 +02:00
|
|
|
);
|
2019-06-17 20:04:26 +02:00
|
|
|
} else {
|
2019-06-18 22:05:27 +02:00
|
|
|
err.span_label(
|
|
|
|
|
field.ident.span,
|
2022-04-15 15:56:32 +09:00
|
|
|
format!("`{ty}` does not have this field"),
|
2019-06-18 22:05:27 +02:00
|
|
|
);
|
2019-06-17 20:04:26 +02:00
|
|
|
}
|
2022-01-24 13:13:29 +01:00
|
|
|
let available_field_names =
|
|
|
|
|
self.available_field_names(variant, expr_span);
|
2019-06-17 20:04:26 +02:00
|
|
|
if !available_field_names.is_empty() {
|
|
|
|
|
err.note(&format!(
|
|
|
|
|
"available fields are: {}",
|
|
|
|
|
self.name_series_display(available_field_names)
|
|
|
|
|
));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
_ => bug!("non-ADT passed to report_unknown_field"),
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
2019-06-17 20:04:26 +02:00
|
|
|
};
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
2019-06-17 20:04:26 +02:00
|
|
|
}
|
2019-06-15 03:32:16 +02:00
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-24 13:13:29 +01:00
|
|
|
// Return a hint about the closest match in field names
|
2019-06-15 03:32:16 +02:00
|
|
|
fn suggest_field_name(
|
2022-01-24 13:13:29 +01:00
|
|
|
&self,
|
2019-06-15 03:32:16 +02:00
|
|
|
variant: &'tcx ty::VariantDef,
|
2020-07-08 20:03:37 +10:00
|
|
|
field: Symbol,
|
2019-09-03 15:48:14 +10:00
|
|
|
skip: Vec<Symbol>,
|
2022-01-24 13:13:29 +01:00
|
|
|
// The span where stability will be checked
|
|
|
|
|
span: Span,
|
2019-06-15 03:32:16 +02:00
|
|
|
) -> Option<Symbol> {
|
Move lev_distance to rustc_ast, make non-generic
rustc_ast currently has a few dependencies on rustc_lexer. Ideally, an AST
would not have any dependency its lexer, for minimizing unnecessarily
design-time dependencies. Breaking this dependency would also have practical
benefits, since modifying rustc_lexer would not trigger a rebuild of rustc_ast.
This commit does not remove the rustc_ast --> rustc_lexer dependency,
but it does remove one of the sources of this dependency, which is the
code that handles fuzzy matching between symbol names for making suggestions
in diagnostics. Since that code depends only on Symbol, it is easy to move
it to rustc_span. It might even be best to move it to a separate crate,
since other tools such as Cargo use the same algorithm, and have simply
contain a duplicate of the code.
This changes the signature of find_best_match_for_name so that it is no
longer generic over its input. I checked the optimized binaries, and this
function was duplicated at nearly every call site, because most call sites
used short-lived iterator chains, generic over Map and such. But there's
no good reason for a function like this to be generic, since all it does
is immediately convert the generic input (the Iterator impl) to a concrete
Vec<Symbol>. This has all of the costs of generics (duplicated method bodies)
with no benefit.
Changing find_best_match_for_name to be non-generic removed about 10KB of
code from the optimized binary. I know it's a drop in the bucket, but we have
to start reducing binary size, and beginning to tame over-use of generics
is part of that.
2020-11-12 11:24:10 -08:00
|
|
|
let names = variant
|
|
|
|
|
.fields
|
|
|
|
|
.iter()
|
|
|
|
|
.filter_map(|field| {
|
|
|
|
|
// ignore already set fields and private fields from non-local crates
|
2022-01-24 13:13:29 +01:00
|
|
|
// and unstable fields.
|
2022-01-02 22:37:05 -05:00
|
|
|
if skip.iter().any(|&x| x == field.name)
|
2021-11-07 19:53:26 -08:00
|
|
|
|| (!variant.def_id.is_local() && !field.vis.is_public())
|
2022-01-24 13:13:29 +01:00
|
|
|
|| matches!(
|
|
|
|
|
self.tcx.eval_stability(field.did, None, span, None),
|
|
|
|
|
stability::EvalResult::Deny { .. }
|
|
|
|
|
)
|
Move lev_distance to rustc_ast, make non-generic
rustc_ast currently has a few dependencies on rustc_lexer. Ideally, an AST
would not have any dependency its lexer, for minimizing unnecessarily
design-time dependencies. Breaking this dependency would also have practical
benefits, since modifying rustc_lexer would not trigger a rebuild of rustc_ast.
This commit does not remove the rustc_ast --> rustc_lexer dependency,
but it does remove one of the sources of this dependency, which is the
code that handles fuzzy matching between symbol names for making suggestions
in diagnostics. Since that code depends only on Symbol, it is easy to move
it to rustc_span. It might even be best to move it to a separate crate,
since other tools such as Cargo use the same algorithm, and have simply
contain a duplicate of the code.
This changes the signature of find_best_match_for_name so that it is no
longer generic over its input. I checked the optimized binaries, and this
function was duplicated at nearly every call site, because most call sites
used short-lived iterator chains, generic over Map and such. But there's
no good reason for a function like this to be generic, since all it does
is immediately convert the generic input (the Iterator impl) to a concrete
Vec<Symbol>. This has all of the costs of generics (duplicated method bodies)
with no benefit.
Changing find_best_match_for_name to be non-generic removed about 10KB of
code from the optimized binary. I know it's a drop in the bucket, but we have
to start reducing binary size, and beginning to tame over-use of generics
is part of that.
2020-11-12 11:24:10 -08:00
|
|
|
{
|
|
|
|
|
None
|
|
|
|
|
} else {
|
2022-01-02 22:37:05 -05:00
|
|
|
Some(field.name)
|
Move lev_distance to rustc_ast, make non-generic
rustc_ast currently has a few dependencies on rustc_lexer. Ideally, an AST
would not have any dependency its lexer, for minimizing unnecessarily
design-time dependencies. Breaking this dependency would also have practical
benefits, since modifying rustc_lexer would not trigger a rebuild of rustc_ast.
This commit does not remove the rustc_ast --> rustc_lexer dependency,
but it does remove one of the sources of this dependency, which is the
code that handles fuzzy matching between symbol names for making suggestions
in diagnostics. Since that code depends only on Symbol, it is easy to move
it to rustc_span. It might even be best to move it to a separate crate,
since other tools such as Cargo use the same algorithm, and have simply
contain a duplicate of the code.
This changes the signature of find_best_match_for_name so that it is no
longer generic over its input. I checked the optimized binaries, and this
function was duplicated at nearly every call site, because most call sites
used short-lived iterator chains, generic over Map and such. But there's
no good reason for a function like this to be generic, since all it does
is immediately convert the generic input (the Iterator impl) to a concrete
Vec<Symbol>. This has all of the costs of generics (duplicated method bodies)
with no benefit.
Changing find_best_match_for_name to be non-generic removed about 10KB of
code from the optimized binary. I know it's a drop in the bucket, but we have
to start reducing binary size, and beginning to tame over-use of generics
is part of that.
2020-11-12 11:24:10 -08:00
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
.collect::<Vec<Symbol>>();
|
2019-06-15 03:32:16 +02:00
|
|
|
|
Move lev_distance to rustc_ast, make non-generic
rustc_ast currently has a few dependencies on rustc_lexer. Ideally, an AST
would not have any dependency its lexer, for minimizing unnecessarily
design-time dependencies. Breaking this dependency would also have practical
benefits, since modifying rustc_lexer would not trigger a rebuild of rustc_ast.
This commit does not remove the rustc_ast --> rustc_lexer dependency,
but it does remove one of the sources of this dependency, which is the
code that handles fuzzy matching between symbol names for making suggestions
in diagnostics. Since that code depends only on Symbol, it is easy to move
it to rustc_span. It might even be best to move it to a separate crate,
since other tools such as Cargo use the same algorithm, and have simply
contain a duplicate of the code.
This changes the signature of find_best_match_for_name so that it is no
longer generic over its input. I checked the optimized binaries, and this
function was duplicated at nearly every call site, because most call sites
used short-lived iterator chains, generic over Map and such. But there's
no good reason for a function like this to be generic, since all it does
is immediately convert the generic input (the Iterator impl) to a concrete
Vec<Symbol>. This has all of the costs of generics (duplicated method bodies)
with no benefit.
Changing find_best_match_for_name to be non-generic removed about 10KB of
code from the optimized binary. I know it's a drop in the bucket, but we have
to start reducing binary size, and beginning to tame over-use of generics
is part of that.
2020-11-12 11:24:10 -08:00
|
|
|
find_best_match_for_name(&names, field, None)
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
|
|
|
|
|
2022-01-24 13:13:29 +01:00
|
|
|
fn available_field_names(
|
|
|
|
|
&self,
|
|
|
|
|
variant: &'tcx ty::VariantDef,
|
|
|
|
|
access_span: Span,
|
|
|
|
|
) -> Vec<Symbol> {
|
2019-06-15 03:32:16 +02:00
|
|
|
variant
|
|
|
|
|
.fields
|
|
|
|
|
.iter()
|
|
|
|
|
.filter(|field| {
|
|
|
|
|
let def_scope = self
|
|
|
|
|
.tcx
|
2022-01-02 22:37:05 -05:00
|
|
|
.adjust_ident_and_get_scope(field.ident(self.tcx), variant.def_id, self.body_id)
|
2019-06-15 03:32:16 +02:00
|
|
|
.1;
|
|
|
|
|
field.vis.is_accessible_from(def_scope, self.tcx)
|
2022-01-24 13:13:29 +01:00
|
|
|
&& !matches!(
|
|
|
|
|
self.tcx.eval_stability(field.did, None, access_span, None),
|
|
|
|
|
stability::EvalResult::Deny { .. }
|
|
|
|
|
)
|
2019-06-15 03:32:16 +02:00
|
|
|
})
|
2022-01-22 15:47:02 -05:00
|
|
|
.filter(|field| !self.tcx.is_doc_hidden(field.did))
|
2022-01-02 22:37:05 -05:00
|
|
|
.map(|field| field.name)
|
2019-06-15 03:32:16 +02:00
|
|
|
.collect()
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-19 13:00:18 +02:00
|
|
|
fn name_series_display(&self, names: Vec<Symbol>) -> String {
|
2019-06-15 03:32:16 +02:00
|
|
|
// dynamic limit, to never omit just one field
|
|
|
|
|
let limit = if names.len() == 6 { 6 } else { 5 };
|
|
|
|
|
let mut display =
|
|
|
|
|
names.iter().take(limit).map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
|
|
|
|
|
if names.len() > limit {
|
|
|
|
|
display = format!("{} ... and {} others", display, names.len() - limit);
|
|
|
|
|
}
|
|
|
|
|
display
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Check field access expressions
|
|
|
|
|
fn check_field(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
base: &'tcx hir::Expr<'tcx>,
|
2020-04-19 13:00:18 +02:00
|
|
|
field: Ident,
|
2019-06-15 03:32:16 +02:00
|
|
|
) -> Ty<'tcx> {
|
2021-01-28 18:26:31 +01:00
|
|
|
debug!("check_field(expr: {:?}, base: {:?}, field: {:?})", expr, base, field);
|
2022-08-27 20:56:14 +00:00
|
|
|
let base_ty = self.check_expr(base);
|
|
|
|
|
let base_ty = self.structurally_resolved_type(base.span, base_ty);
|
2019-06-15 03:32:16 +02:00
|
|
|
let mut private_candidate = None;
|
2022-08-27 20:56:14 +00:00
|
|
|
let mut autoderef = self.autoderef(expr.span, base_ty);
|
|
|
|
|
while let Some((deref_base_ty, _)) = autoderef.next() {
|
|
|
|
|
debug!("deref_base_ty: {:?}", deref_base_ty);
|
|
|
|
|
match deref_base_ty.kind() {
|
2019-06-15 03:32:16 +02:00
|
|
|
ty::Adt(base_def, substs) if !base_def.is_enum() => {
|
2022-08-27 20:56:14 +00:00
|
|
|
debug!("struct named {:?}", deref_base_ty);
|
2019-06-15 03:32:16 +02:00
|
|
|
let (ident, def_scope) =
|
2022-03-05 07:28:41 +11:00
|
|
|
self.tcx.adjust_ident_and_get_scope(field, base_def.did(), self.body_id);
|
2019-06-15 03:32:16 +02:00
|
|
|
let fields = &base_def.non_enum_variant().fields;
|
2022-01-02 22:37:05 -05:00
|
|
|
if let Some(index) = fields
|
|
|
|
|
.iter()
|
|
|
|
|
.position(|f| f.ident(self.tcx).normalize_to_macros_2_0() == ident)
|
2020-03-14 01:36:46 +03:00
|
|
|
{
|
2019-06-15 03:32:16 +02:00
|
|
|
let field = &fields[index];
|
|
|
|
|
let field_ty = self.field_ty(expr.span, field, substs);
|
|
|
|
|
// Save the index of all fields regardless of their visibility in case
|
|
|
|
|
// of error recovery.
|
|
|
|
|
self.write_field_index(expr.hir_id, index);
|
2021-11-02 17:20:21 +00:00
|
|
|
let adjustments = self.adjust_steps(&autoderef);
|
2019-06-15 03:32:16 +02:00
|
|
|
if field.vis.is_accessible_from(def_scope, self.tcx) {
|
|
|
|
|
self.apply_adjustments(base, adjustments);
|
2020-06-20 18:29:13 +08:00
|
|
|
self.register_predicates(autoderef.into_obligations());
|
2019-06-15 03:32:16 +02:00
|
|
|
|
2021-05-07 10:41:04 +08:00
|
|
|
self.tcx.check_stability(field.did, Some(expr.hir_id), expr.span, None);
|
2019-06-15 03:32:16 +02:00
|
|
|
return field_ty;
|
|
|
|
|
}
|
2022-03-05 07:28:41 +11:00
|
|
|
private_candidate = Some((adjustments, base_def.did(), field_ty));
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
|
|
|
|
}
|
2021-02-08 22:02:35 -05:00
|
|
|
ty::Tuple(tys) => {
|
2019-06-15 03:32:16 +02:00
|
|
|
let fstr = field.as_str();
|
|
|
|
|
if let Ok(index) = fstr.parse::<usize>() {
|
|
|
|
|
if fstr == index.to_string() {
|
2022-02-07 16:06:31 +01:00
|
|
|
if let Some(&field_ty) = tys.get(index) {
|
2020-06-20 18:29:13 +08:00
|
|
|
let adjustments = self.adjust_steps(&autoderef);
|
2019-06-15 03:32:16 +02:00
|
|
|
self.apply_adjustments(base, adjustments);
|
2020-06-20 18:29:13 +08:00
|
|
|
self.register_predicates(autoderef.into_obligations());
|
2019-06-15 03:32:16 +02:00
|
|
|
|
|
|
|
|
self.write_field_index(expr.hir_id, index);
|
2022-02-07 16:06:31 +01:00
|
|
|
return field_ty;
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-06-20 18:29:13 +08:00
|
|
|
self.structurally_resolved_type(autoderef.span(), autoderef.final_ty(false));
|
2019-06-15 03:32:16 +02:00
|
|
|
|
2021-11-02 17:20:21 +00:00
|
|
|
if let Some((adjustments, did, field_ty)) = private_candidate {
|
|
|
|
|
// (#90483) apply adjustments to avoid ExprUseVisitor from
|
|
|
|
|
// creating erroneous projection.
|
|
|
|
|
self.apply_adjustments(base, adjustments);
|
2022-08-27 20:56:14 +00:00
|
|
|
self.ban_private_field_access(expr, base_ty, field, did);
|
2019-08-14 00:50:39 +02:00
|
|
|
return field_ty;
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-29 20:28:08 -05:00
|
|
|
if field.name == kw::Empty {
|
2022-08-27 20:56:14 +00:00
|
|
|
} else if self.method_exists(field, base_ty, expr.hir_id, true) {
|
|
|
|
|
self.ban_take_value_of_method(expr, base_ty, field);
|
|
|
|
|
} else if !base_ty.is_primitive_ty() {
|
|
|
|
|
self.ban_nonexisting_field(field, base, expr, base_ty);
|
2019-08-14 00:50:39 +02:00
|
|
|
} else {
|
2022-07-06 20:09:39 +09:00
|
|
|
let field_name = field.to_string();
|
|
|
|
|
let mut err = type_error_struct!(
|
2019-08-14 00:50:39 +02:00
|
|
|
self.tcx().sess,
|
|
|
|
|
field.span,
|
2022-08-27 20:56:14 +00:00
|
|
|
base_ty,
|
2019-08-14 00:50:39 +02:00
|
|
|
E0610,
|
2022-08-27 20:56:14 +00:00
|
|
|
"`{base_ty}` is a primitive type and therefore doesn't have fields",
|
2022-07-06 20:09:39 +09:00
|
|
|
);
|
2022-08-16 10:50:04 +08:00
|
|
|
let is_valid_suffix = |field: &str| {
|
2022-07-12 13:59:51 +09:00
|
|
|
if field == "f32" || field == "f64" {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
let mut chars = field.chars().peekable();
|
|
|
|
|
match chars.peek() {
|
|
|
|
|
Some('e') | Some('E') => {
|
|
|
|
|
chars.next();
|
|
|
|
|
if let Some(c) = chars.peek()
|
|
|
|
|
&& !c.is_numeric() && *c != '-' && *c != '+'
|
|
|
|
|
{
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
while let Some(c) = chars.peek() {
|
|
|
|
|
if !c.is_numeric() {
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
chars.next();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
_ => (),
|
|
|
|
|
}
|
|
|
|
|
let suffix = chars.collect::<String>();
|
|
|
|
|
suffix.is_empty() || suffix == "f32" || suffix == "f64"
|
|
|
|
|
};
|
2022-08-16 19:12:36 +08:00
|
|
|
let maybe_partial_suffix = |field: &str| -> Option<&str> {
|
|
|
|
|
let first_chars = ['f', 'l'];
|
|
|
|
|
if field.len() >= 1
|
|
|
|
|
&& field.to_lowercase().starts_with(first_chars)
|
2022-08-16 10:50:04 +08:00
|
|
|
&& field[1..].chars().all(|c| c.is_ascii_digit())
|
2022-08-16 19:12:36 +08:00
|
|
|
{
|
|
|
|
|
if field.to_lowercase().starts_with(['f']) { Some("f32") } else { Some("f64") }
|
|
|
|
|
} else {
|
|
|
|
|
None
|
|
|
|
|
}
|
2022-08-16 10:50:04 +08:00
|
|
|
};
|
2022-08-27 20:56:14 +00:00
|
|
|
if let ty::Infer(ty::IntVar(_)) = base_ty.kind()
|
2022-07-12 13:59:51 +09:00
|
|
|
&& let ExprKind::Lit(Spanned {
|
|
|
|
|
node: ast::LitKind::Int(_, ast::LitIntType::Unsuffixed),
|
|
|
|
|
..
|
|
|
|
|
}) = base.kind
|
|
|
|
|
&& !base.span.from_expansion()
|
2022-07-06 20:09:39 +09:00
|
|
|
{
|
2022-08-16 10:50:04 +08:00
|
|
|
if is_valid_suffix(&field_name) {
|
|
|
|
|
err.span_suggestion_verbose(
|
|
|
|
|
field.span.shrink_to_lo(),
|
2022-08-16 19:12:36 +08:00
|
|
|
"if intended to be a floating point literal, consider adding a `0` after the period",
|
2022-08-16 10:50:04 +08:00
|
|
|
'0',
|
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
2022-08-16 19:12:36 +08:00
|
|
|
} else if let Some(correct_suffix) = maybe_partial_suffix(&field_name) {
|
2022-08-16 10:50:04 +08:00
|
|
|
err.span_suggestion_verbose(
|
|
|
|
|
field.span,
|
2022-08-16 19:12:36 +08:00
|
|
|
format!("if intended to be a floating point literal, consider adding a `0` after the period and a `{correct_suffix}` suffix"),
|
|
|
|
|
format!("0{correct_suffix}"),
|
2022-08-16 10:50:04 +08:00
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
|
|
|
|
}
|
2022-07-06 20:09:39 +09:00
|
|
|
}
|
|
|
|
|
err.emit();
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
2019-08-14 00:50:39 +02:00
|
|
|
|
2020-05-05 23:02:09 -05:00
|
|
|
self.tcx().ty_error()
|
2019-06-15 03:32:16 +02:00
|
|
|
}
|
|
|
|
|
|
2020-08-16 20:25:22 +08:00
|
|
|
fn suggest_await_on_field_access(
|
|
|
|
|
&self,
|
2022-01-23 20:41:46 +00:00
|
|
|
err: &mut Diagnostic,
|
2020-08-16 20:25:22 +08:00
|
|
|
field_ident: Ident,
|
|
|
|
|
base: &'tcx hir::Expr<'tcx>,
|
2020-10-23 10:54:34 -07:00
|
|
|
ty: Ty<'tcx>,
|
2020-08-16 20:25:22 +08:00
|
|
|
) {
|
2022-07-22 18:49:35 +00:00
|
|
|
let output_ty = match self.get_impl_future_output_ty(ty) {
|
2020-10-24 02:21:18 +02:00
|
|
|
Some(output_ty) => self.resolve_vars_if_possible(output_ty),
|
2020-10-23 10:54:34 -07:00
|
|
|
_ => return,
|
|
|
|
|
};
|
|
|
|
|
let mut add_label = true;
|
2021-12-21 22:08:47 +00:00
|
|
|
if let ty::Adt(def, _) = output_ty.skip_binder().kind() {
|
2020-10-23 10:54:34 -07:00
|
|
|
// no field access on enum type
|
|
|
|
|
if !def.is_enum() {
|
2022-01-02 22:37:05 -05:00
|
|
|
if def
|
|
|
|
|
.non_enum_variant()
|
|
|
|
|
.fields
|
|
|
|
|
.iter()
|
|
|
|
|
.any(|field| field.ident(self.tcx) == field_ident)
|
|
|
|
|
{
|
2020-10-23 10:54:34 -07:00
|
|
|
add_label = false;
|
|
|
|
|
err.span_label(
|
|
|
|
|
field_ident.span,
|
|
|
|
|
"field not available in `impl Future`, but it is available in its `Output`",
|
|
|
|
|
);
|
|
|
|
|
err.span_suggestion_verbose(
|
|
|
|
|
base.span.shrink_to_hi(),
|
|
|
|
|
"consider `await`ing on the `Future` and access the field of its `Output`",
|
2022-06-13 15:48:40 +09:00
|
|
|
".await",
|
2020-10-23 10:54:34 -07:00
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
2020-08-16 20:25:22 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-10-23 10:54:34 -07:00
|
|
|
if add_label {
|
2022-04-15 15:56:32 +09:00
|
|
|
err.span_label(field_ident.span, &format!("field not found in `{ty}`"));
|
2020-10-23 10:54:34 -07:00
|
|
|
}
|
2020-08-16 20:25:22 +08:00
|
|
|
}
|
|
|
|
|
|
2019-09-28 15:26:00 +03:00
|
|
|
fn ban_nonexisting_field(
|
|
|
|
|
&self,
|
2022-08-27 20:56:14 +00:00
|
|
|
ident: Ident,
|
2019-11-30 15:08:22 +01:00
|
|
|
base: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2022-08-27 20:56:14 +00:00
|
|
|
base_ty: Ty<'tcx>,
|
2019-09-28 15:26:00 +03:00
|
|
|
) {
|
2020-08-16 20:25:22 +08:00
|
|
|
debug!(
|
2022-08-27 20:56:14 +00:00
|
|
|
"ban_nonexisting_field: field={:?}, base={:?}, expr={:?}, base_ty={:?}",
|
|
|
|
|
ident, base, expr, base_ty
|
2020-08-16 20:25:22 +08:00
|
|
|
);
|
2022-08-27 20:56:14 +00:00
|
|
|
let mut err = self.no_such_field_err(ident, base_ty, base.hir_id);
|
2019-09-28 15:26:00 +03:00
|
|
|
|
2022-08-27 20:56:14 +00:00
|
|
|
match *base_ty.peel_refs().kind() {
|
2019-09-28 15:26:00 +03:00
|
|
|
ty::Array(_, len) => {
|
2022-08-27 20:56:14 +00:00
|
|
|
self.maybe_suggest_array_indexing(&mut err, expr, base, ident, len);
|
2019-09-28 15:26:00 +03:00
|
|
|
}
|
|
|
|
|
ty::RawPtr(..) => {
|
2022-08-27 20:56:14 +00:00
|
|
|
self.suggest_first_deref_field(&mut err, expr, base, ident);
|
2019-09-28 15:26:00 +03:00
|
|
|
}
|
|
|
|
|
ty::Adt(def, _) if !def.is_enum() => {
|
2022-08-27 20:56:14 +00:00
|
|
|
self.suggest_fields_on_recordish(&mut err, def, ident, expr.span);
|
2019-09-28 15:26:00 +03:00
|
|
|
}
|
|
|
|
|
ty::Param(param_ty) => {
|
|
|
|
|
self.point_at_param_definition(&mut err, param_ty);
|
|
|
|
|
}
|
2020-10-23 10:54:34 -07:00
|
|
|
ty::Opaque(_, _) => {
|
2022-08-27 20:56:14 +00:00
|
|
|
self.suggest_await_on_field_access(&mut err, ident, base, base_ty.peel_refs());
|
2022-04-26 17:04:44 -04:00
|
|
|
}
|
2019-09-28 15:26:00 +03:00
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
|
2022-08-27 20:59:07 +00:00
|
|
|
self.suggest_fn_call(&mut err, base, base_ty, |output_ty| {
|
|
|
|
|
if let ty::Adt(def, _) = output_ty.kind() && !def.is_enum() {
|
|
|
|
|
def.non_enum_variant().fields.iter().any(|field| {
|
|
|
|
|
field.ident(self.tcx) == ident
|
2022-09-20 14:11:23 +09:00
|
|
|
&& field.vis.is_accessible_from(expr.hir_id.owner.def_id, self.tcx)
|
2022-08-27 20:59:07 +00:00
|
|
|
})
|
|
|
|
|
} else if let ty::Tuple(tys) = output_ty.kind()
|
|
|
|
|
&& let Ok(idx) = ident.as_str().parse::<usize>()
|
|
|
|
|
{
|
|
|
|
|
idx < tys.len()
|
|
|
|
|
} else {
|
|
|
|
|
false
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2022-08-27 20:56:14 +00:00
|
|
|
if ident.name == kw::Await {
|
2019-09-28 15:26:00 +03:00
|
|
|
// We know by construction that `<expr>.await` is either on Rust 2015
|
|
|
|
|
// or results in `ExprKind::Await`. Suggest switching the edition to 2018.
|
2020-12-30 14:33:46 +01:00
|
|
|
err.note("to `.await` a `Future`, switch to Rust 2018 or later");
|
2022-03-07 10:50:47 -07:00
|
|
|
err.help_use_latest_edition();
|
2019-09-28 15:26:00 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
|
2019-08-13 23:54:20 +02:00
|
|
|
fn ban_private_field_access(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &hir::Expr<'_>,
|
2019-08-13 23:54:20 +02:00
|
|
|
expr_t: Ty<'tcx>,
|
2020-04-19 13:00:18 +02:00
|
|
|
field: Ident,
|
2019-08-13 23:59:22 +02:00
|
|
|
base_did: DefId,
|
2019-08-13 23:54:20 +02:00
|
|
|
) {
|
2019-08-13 23:59:22 +02:00
|
|
|
let struct_path = self.tcx().def_path_str(base_did);
|
2020-04-17 21:55:17 +03:00
|
|
|
let kind_name = self.tcx().def_kind(base_did).descr(base_did);
|
2019-08-13 23:54:20 +02:00
|
|
|
let mut err = struct_span_err!(
|
|
|
|
|
self.tcx().sess,
|
2020-03-22 11:18:06 -07:00
|
|
|
field.span,
|
2019-08-13 23:54:20 +02:00
|
|
|
E0616,
|
2022-04-15 15:56:32 +09:00
|
|
|
"field `{field}` of {kind_name} `{struct_path}` is private",
|
2019-08-13 23:54:20 +02:00
|
|
|
);
|
2020-03-22 11:18:06 -07:00
|
|
|
err.span_label(field.span, "private field");
|
2019-08-13 23:54:20 +02:00
|
|
|
// Also check if an accessible method exists, which is often what is meant.
|
|
|
|
|
if self.method_exists(field, expr_t, expr.hir_id, false) && !self.expr_in_place(expr.hir_id)
|
|
|
|
|
{
|
|
|
|
|
self.suggest_method_call(
|
|
|
|
|
&mut err,
|
2022-04-15 15:56:32 +09:00
|
|
|
&format!("a method `{field}` also exists, call it with parentheses"),
|
2019-08-13 23:54:20 +02:00
|
|
|
field,
|
|
|
|
|
expr_t,
|
2020-02-08 20:02:54 -08:00
|
|
|
expr,
|
2021-09-17 22:18:05 +02:00
|
|
|
None,
|
2019-08-13 23:54:20 +02:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
|
2020-04-19 13:00:18 +02:00
|
|
|
fn ban_take_value_of_method(&self, expr: &hir::Expr<'_>, expr_t: Ty<'tcx>, field: Ident) {
|
2019-08-13 23:59:22 +02:00
|
|
|
let mut err = type_error_struct!(
|
|
|
|
|
self.tcx().sess,
|
|
|
|
|
field.span,
|
|
|
|
|
expr_t,
|
|
|
|
|
E0615,
|
2022-04-15 15:56:32 +09:00
|
|
|
"attempted to take value of method `{field}` on type `{expr_t}`",
|
2019-08-13 23:59:22 +02:00
|
|
|
);
|
2020-03-22 11:18:06 -07:00
|
|
|
err.span_label(field.span, "method, not a field");
|
2021-09-10 18:48:25 -07:00
|
|
|
let expr_is_call =
|
|
|
|
|
if let hir::Node::Expr(hir::Expr { kind: ExprKind::Call(callee, _args), .. }) =
|
|
|
|
|
self.tcx.hir().get(self.tcx.hir().get_parent_node(expr.hir_id))
|
|
|
|
|
{
|
|
|
|
|
expr.hir_id == callee.hir_id
|
|
|
|
|
} else {
|
|
|
|
|
false
|
|
|
|
|
};
|
2021-09-10 18:16:58 -07:00
|
|
|
let expr_snippet =
|
2022-07-20 11:48:11 +02:00
|
|
|
self.tcx.sess.source_map().span_to_snippet(expr.span).unwrap_or_default();
|
2021-10-07 22:31:33 +02:00
|
|
|
let is_wrapped = expr_snippet.starts_with('(') && expr_snippet.ends_with(')');
|
2021-09-17 22:18:05 +02:00
|
|
|
let after_open = expr.span.lo() + rustc_span::BytePos(1);
|
|
|
|
|
let before_close = expr.span.hi() - rustc_span::BytePos(1);
|
|
|
|
|
|
|
|
|
|
if expr_is_call && is_wrapped {
|
2021-09-12 19:51:09 -07:00
|
|
|
err.multipart_suggestion(
|
2021-09-10 18:16:58 -07:00
|
|
|
"remove wrapping parentheses to call the method",
|
2021-09-12 19:51:09 -07:00
|
|
|
vec![
|
|
|
|
|
(expr.span.with_hi(after_open), String::new()),
|
|
|
|
|
(expr.span.with_lo(before_close), String::new()),
|
|
|
|
|
],
|
2021-09-10 18:16:58 -07:00
|
|
|
Applicability::MachineApplicable,
|
|
|
|
|
);
|
|
|
|
|
} else if !self.expr_in_place(expr.hir_id) {
|
2021-09-17 22:18:05 +02:00
|
|
|
// Suggest call parentheses inside the wrapping parentheses
|
|
|
|
|
let span = if is_wrapped {
|
|
|
|
|
expr.span.with_lo(after_open).with_hi(before_close)
|
|
|
|
|
} else {
|
|
|
|
|
expr.span
|
|
|
|
|
};
|
2019-08-13 23:59:22 +02:00
|
|
|
self.suggest_method_call(
|
|
|
|
|
&mut err,
|
|
|
|
|
"use parentheses to call the method",
|
|
|
|
|
field,
|
|
|
|
|
expr_t,
|
2020-02-08 20:02:54 -08:00
|
|
|
expr,
|
2021-09-17 22:18:05 +02:00
|
|
|
Some(span),
|
2019-08-13 23:59:22 +02:00
|
|
|
);
|
2022-08-05 18:14:15 +09:00
|
|
|
} else if let ty::RawPtr(ty_and_mut) = expr_t.kind()
|
|
|
|
|
&& let ty::Adt(adt_def, _) = ty_and_mut.ty.kind()
|
|
|
|
|
&& let ExprKind::Field(base_expr, _) = expr.kind
|
|
|
|
|
&& adt_def.variants().len() == 1
|
|
|
|
|
&& adt_def
|
|
|
|
|
.variants()
|
|
|
|
|
.iter()
|
|
|
|
|
.next()
|
|
|
|
|
.unwrap()
|
|
|
|
|
.fields
|
|
|
|
|
.iter()
|
|
|
|
|
.any(|f| f.ident(self.tcx) == field)
|
|
|
|
|
{
|
|
|
|
|
err.multipart_suggestion(
|
|
|
|
|
"to access the field, dereference first",
|
|
|
|
|
vec![
|
|
|
|
|
(base_expr.span.shrink_to_lo(), "(*".to_string()),
|
|
|
|
|
(base_expr.span.shrink_to_hi(), ")".to_string()),
|
|
|
|
|
],
|
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
2019-08-13 23:59:22 +02:00
|
|
|
} else {
|
2022-08-05 18:14:15 +09:00
|
|
|
err.help("methods are immutable and cannot be assigned to");
|
2019-08-13 23:59:22 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
|
2022-01-23 20:41:46 +00:00
|
|
|
fn point_at_param_definition(&self, err: &mut Diagnostic, param: ty::ParamTy) {
|
2020-03-18 20:27:59 +02:00
|
|
|
let generics = self.tcx.generics_of(self.body_id.owner.to_def_id());
|
2019-09-28 14:39:19 +03:00
|
|
|
let generic_param = generics.type_param(¶m, self.tcx);
|
2021-11-18 13:25:27 +08:00
|
|
|
if let ty::GenericParamDefKind::Type { synthetic: true, .. } = generic_param.kind {
|
2019-09-28 14:39:19 +03:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
let param_def_id = generic_param.def_id;
|
2020-04-12 13:45:41 +01:00
|
|
|
let param_hir_id = match param_def_id.as_local() {
|
2020-08-12 12:22:56 +02:00
|
|
|
Some(x) => self.tcx.hir().local_def_id_to_hir_id(x),
|
2019-09-26 18:14:27 +03:00
|
|
|
None => return,
|
|
|
|
|
};
|
|
|
|
|
let param_span = self.tcx.hir().span(param_hir_id);
|
2022-04-08 23:06:20 +02:00
|
|
|
let param_name = self.tcx.hir().ty_param_name(param_def_id.expect_local());
|
2019-09-26 18:14:27 +03:00
|
|
|
|
2022-04-15 15:56:32 +09:00
|
|
|
err.span_label(param_span, &format!("type parameter '{param_name}' declared here"));
|
2019-09-26 18:14:27 +03:00
|
|
|
}
|
|
|
|
|
|
2019-08-14 00:40:44 +02:00
|
|
|
fn suggest_fields_on_recordish(
|
|
|
|
|
&self,
|
2022-01-23 20:41:46 +00:00
|
|
|
err: &mut Diagnostic,
|
2022-03-05 07:28:41 +11:00
|
|
|
def: ty::AdtDef<'tcx>,
|
2020-04-19 13:00:18 +02:00
|
|
|
field: Ident,
|
2022-01-24 13:13:29 +01:00
|
|
|
access_span: Span,
|
2019-08-14 00:40:44 +02:00
|
|
|
) {
|
|
|
|
|
if let Some(suggested_field_name) =
|
2022-01-24 13:13:29 +01:00
|
|
|
self.suggest_field_name(def.non_enum_variant(), field.name, vec![], access_span)
|
2019-08-14 00:40:44 +02:00
|
|
|
{
|
|
|
|
|
err.span_suggestion(
|
|
|
|
|
field.span,
|
|
|
|
|
"a field with a similar name exists",
|
2022-06-13 15:48:40 +09:00
|
|
|
suggested_field_name,
|
2019-08-14 00:40:44 +02:00
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
|
|
|
|
} else {
|
|
|
|
|
err.span_label(field.span, "unknown field");
|
|
|
|
|
let struct_variant_def = def.non_enum_variant();
|
2022-01-24 13:13:29 +01:00
|
|
|
let field_names = self.available_field_names(struct_variant_def, access_span);
|
2019-08-14 00:40:44 +02:00
|
|
|
if !field_names.is_empty() {
|
2019-09-01 02:22:42 -07:00
|
|
|
err.note(&format!(
|
|
|
|
|
"available fields are: {}",
|
|
|
|
|
self.name_series_display(field_names),
|
|
|
|
|
));
|
2019-08-14 00:40:44 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-08-14 00:30:06 +02:00
|
|
|
fn maybe_suggest_array_indexing(
|
|
|
|
|
&self,
|
2022-01-23 20:41:46 +00:00
|
|
|
err: &mut Diagnostic,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &hir::Expr<'_>,
|
|
|
|
|
base: &hir::Expr<'_>,
|
2020-04-19 13:00:18 +02:00
|
|
|
field: Ident,
|
2022-02-02 14:24:45 +11:00
|
|
|
len: ty::Const<'tcx>,
|
2019-08-14 00:30:06 +02:00
|
|
|
) {
|
|
|
|
|
if let (Some(len), Ok(user_index)) =
|
|
|
|
|
(len.try_eval_usize(self.tcx, self.param_env), field.as_str().parse::<u64>())
|
2022-04-15 15:56:32 +09:00
|
|
|
&& let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span)
|
2019-08-14 00:30:06 +02:00
|
|
|
{
|
2022-04-15 15:56:32 +09:00
|
|
|
let help = "instead of using tuple indexing, use array indexing";
|
|
|
|
|
let suggestion = format!("{base}[{field}]");
|
|
|
|
|
let applicability = if len < user_index {
|
|
|
|
|
Applicability::MachineApplicable
|
|
|
|
|
} else {
|
|
|
|
|
Applicability::MaybeIncorrect
|
|
|
|
|
};
|
|
|
|
|
err.span_suggestion(expr.span, help, suggestion, applicability);
|
2019-08-14 00:30:06 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-08-14 00:31:08 +02:00
|
|
|
fn suggest_first_deref_field(
|
|
|
|
|
&self,
|
2022-01-23 20:41:46 +00:00
|
|
|
err: &mut Diagnostic,
|
2019-11-30 15:08:22 +01:00
|
|
|
expr: &hir::Expr<'_>,
|
|
|
|
|
base: &hir::Expr<'_>,
|
2020-04-19 13:00:18 +02:00
|
|
|
field: Ident,
|
2019-08-14 00:31:08 +02:00
|
|
|
) {
|
2020-03-24 02:44:41 +01:00
|
|
|
if let Ok(base) = self.tcx.sess.source_map().span_to_snippet(base.span) {
|
2022-04-15 15:56:32 +09:00
|
|
|
let msg = format!("`{base}` is a raw pointer; try dereferencing it");
|
|
|
|
|
let suggestion = format!("(*{base}).{field}");
|
2020-03-24 02:44:41 +01:00
|
|
|
err.span_suggestion(expr.span, &msg, suggestion, Applicability::MaybeIncorrect);
|
|
|
|
|
}
|
2019-08-14 00:31:08 +02:00
|
|
|
}
|
|
|
|
|
|
2021-01-28 18:26:31 +01:00
|
|
|
fn no_such_field_err(
|
2019-06-15 03:32:16 +02:00
|
|
|
&self,
|
2021-01-28 18:26:31 +01:00
|
|
|
field: Ident,
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 14:13:38 +11:00
|
|
|
expr_t: Ty<'tcx>,
|
2022-01-18 17:09:17 +01:00
|
|
|
id: HirId,
|
2022-01-23 12:34:26 -06:00
|
|
|
) -> DiagnosticBuilder<'_, ErrorGuaranteed> {
|
2021-01-28 18:26:31 +01:00
|
|
|
let span = field.span;
|
|
|
|
|
debug!("no_such_field_err(span: {:?}, field: {:?}, expr_t: {:?})", span, field, expr_t);
|
|
|
|
|
|
|
|
|
|
let mut err = type_error_struct!(
|
2019-06-15 03:32:16 +02:00
|
|
|
self.tcx().sess,
|
2021-01-28 18:26:31 +01:00
|
|
|
field.span,
|
2019-06-15 03:32:16 +02:00
|
|
|
expr_t,
|
|
|
|
|
E0609,
|
2022-04-15 15:56:32 +09:00
|
|
|
"no field `{field}` on type `{expr_t}`",
|
2021-01-28 18:26:31 +01:00
|
|
|
);
|
|
|
|
|
|
|
|
|
|
// try to add a suggestion in case the field is a nested field of a field of the Adt
|
2022-08-03 06:42:19 +00:00
|
|
|
let mod_id = self.tcx.parent_module(id).to_def_id();
|
|
|
|
|
if let Some((fields, substs)) =
|
|
|
|
|
self.get_field_candidates_considering_privacy(span, expr_t, mod_id)
|
|
|
|
|
{
|
2022-08-23 01:58:33 +00:00
|
|
|
let candidate_fields: Vec<_> = fields
|
|
|
|
|
.filter_map(|candidate_field| {
|
|
|
|
|
self.check_for_nested_field_satisfying(
|
|
|
|
|
span,
|
|
|
|
|
&|candidate_field, _| candidate_field.ident(self.tcx()) == field,
|
|
|
|
|
candidate_field,
|
|
|
|
|
substs,
|
|
|
|
|
vec![],
|
|
|
|
|
mod_id,
|
|
|
|
|
)
|
|
|
|
|
})
|
|
|
|
|
.map(|mut field_path| {
|
2022-04-24 16:45:39 -07:00
|
|
|
field_path.pop();
|
2022-08-23 01:58:33 +00:00
|
|
|
field_path
|
2021-01-28 18:26:31 +01:00
|
|
|
.iter()
|
|
|
|
|
.map(|id| id.name.to_ident_string())
|
|
|
|
|
.collect::<Vec<String>>()
|
2022-08-23 01:58:33 +00:00
|
|
|
.join(".")
|
|
|
|
|
})
|
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
|
|
|
|
|
let len = candidate_fields.len();
|
|
|
|
|
if len > 0 {
|
|
|
|
|
err.span_suggestions(
|
|
|
|
|
field.span.shrink_to_lo(),
|
|
|
|
|
format!(
|
|
|
|
|
"{} of the expressions' fields {} a field of the same name",
|
|
|
|
|
if len > 1 { "some" } else { "one" },
|
|
|
|
|
if len > 1 { "have" } else { "has" },
|
|
|
|
|
),
|
|
|
|
|
candidate_fields.iter().map(|path| format!("{path}.")),
|
|
|
|
|
Applicability::MaybeIncorrect,
|
|
|
|
|
);
|
2021-01-28 18:26:31 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
err
|
|
|
|
|
}
|
|
|
|
|
|
2022-08-03 06:42:19 +00:00
|
|
|
pub(crate) fn get_field_candidates_considering_privacy(
|
2021-01-28 18:26:31 +01:00
|
|
|
&self,
|
|
|
|
|
span: Span,
|
2022-08-03 06:42:19 +00:00
|
|
|
base_ty: Ty<'tcx>,
|
|
|
|
|
mod_id: DefId,
|
|
|
|
|
) -> Option<(impl Iterator<Item = &'tcx ty::FieldDef> + 'tcx, SubstsRef<'tcx>)> {
|
|
|
|
|
debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_ty);
|
2021-01-28 18:26:31 +01:00
|
|
|
|
2022-08-03 06:42:19 +00:00
|
|
|
for (base_t, _) in self.autoderef(span, base_ty) {
|
2021-01-28 18:26:31 +01:00
|
|
|
match base_t.kind() {
|
|
|
|
|
ty::Adt(base_def, substs) if !base_def.is_enum() => {
|
2022-08-03 06:42:19 +00:00
|
|
|
let tcx = self.tcx;
|
2021-01-28 18:26:31 +01:00
|
|
|
let fields = &base_def.non_enum_variant().fields;
|
2022-08-03 07:01:18 +00:00
|
|
|
// Some struct, e.g. some that impl `Deref`, have all private fields
|
|
|
|
|
// because you're expected to deref them to access the _real_ fields.
|
|
|
|
|
// This, for example, will help us suggest accessing a field through a `Box<T>`.
|
|
|
|
|
if fields.iter().all(|field| !field.vis.is_accessible_from(mod_id, tcx)) {
|
|
|
|
|
continue;
|
2021-01-28 18:26:31 +01:00
|
|
|
}
|
2022-08-03 06:42:19 +00:00
|
|
|
return Some((
|
2022-08-03 07:01:18 +00:00
|
|
|
fields
|
2022-08-03 06:42:19 +00:00
|
|
|
.iter()
|
|
|
|
|
.filter(move |field| field.vis.is_accessible_from(mod_id, tcx))
|
|
|
|
|
// For compile-time reasons put a limit on number of fields we search
|
|
|
|
|
.take(100),
|
|
|
|
|
substs,
|
|
|
|
|
));
|
2021-01-28 18:26:31 +01:00
|
|
|
}
|
|
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
None
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// This method is called after we have encountered a missing field error to recursively
|
|
|
|
|
/// search for the field
|
2022-05-20 19:51:09 -04:00
|
|
|
pub(crate) fn check_for_nested_field_satisfying(
|
2021-01-28 18:26:31 +01:00
|
|
|
&self,
|
|
|
|
|
span: Span,
|
2022-04-24 16:45:39 -07:00
|
|
|
matches: &impl Fn(&ty::FieldDef, Ty<'tcx>) -> bool,
|
2021-01-28 18:26:31 +01:00
|
|
|
candidate_field: &ty::FieldDef,
|
|
|
|
|
subst: SubstsRef<'tcx>,
|
|
|
|
|
mut field_path: Vec<Ident>,
|
2022-08-03 06:42:19 +00:00
|
|
|
mod_id: DefId,
|
2021-01-28 18:26:31 +01:00
|
|
|
) -> Option<Vec<Ident>> {
|
|
|
|
|
debug!(
|
2022-04-24 16:45:39 -07:00
|
|
|
"check_for_nested_field_satisfying(span: {:?}, candidate_field: {:?}, field_path: {:?}",
|
2021-01-28 18:26:31 +01:00
|
|
|
span, candidate_field, field_path
|
|
|
|
|
);
|
|
|
|
|
|
2022-04-24 16:45:39 -07:00
|
|
|
if field_path.len() > 3 {
|
2021-01-28 18:26:31 +01:00
|
|
|
// For compile-time reasons and to avoid infinite recursion we only check for fields
|
|
|
|
|
// up to a depth of three
|
|
|
|
|
None
|
|
|
|
|
} else {
|
2022-01-02 22:37:05 -05:00
|
|
|
field_path.push(candidate_field.ident(self.tcx).normalize_to_macros_2_0());
|
2021-01-28 18:26:31 +01:00
|
|
|
let field_ty = candidate_field.ty(self.tcx, subst);
|
2022-08-03 06:28:45 +00:00
|
|
|
if matches(candidate_field, field_ty) {
|
|
|
|
|
return Some(field_path);
|
2022-08-03 06:42:19 +00:00
|
|
|
} else if let Some((nested_fields, subst)) =
|
|
|
|
|
self.get_field_candidates_considering_privacy(span, field_ty, mod_id)
|
|
|
|
|
{
|
2022-08-03 06:28:45 +00:00
|
|
|
// recursively search fields of `candidate_field` if it's a ty::Adt
|
|
|
|
|
for field in nested_fields {
|
2022-08-03 06:42:19 +00:00
|
|
|
if let Some(field_path) = self.check_for_nested_field_satisfying(
|
|
|
|
|
span,
|
|
|
|
|
matches,
|
|
|
|
|
field,
|
|
|
|
|
subst,
|
|
|
|
|
field_path.clone(),
|
|
|
|
|
mod_id,
|
|
|
|
|
) {
|
|
|
|
|
return Some(field_path);
|
2021-01-28 18:26:31 +01:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
None
|
|
|
|
|
}
|
2019-06-15 02:43:02 +02:00
|
|
|
}
|
2019-06-15 02:46:47 +02:00
|
|
|
|
|
|
|
|
fn check_expr_index(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
base: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
idx: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-15 02:46:47 +02:00
|
|
|
) -> Ty<'tcx> {
|
2020-06-15 21:59:09 +01:00
|
|
|
let base_t = self.check_expr(&base);
|
2019-06-15 02:46:47 +02:00
|
|
|
let idx_t = self.check_expr(&idx);
|
|
|
|
|
|
|
|
|
|
if base_t.references_error() {
|
|
|
|
|
base_t
|
|
|
|
|
} else if idx_t.references_error() {
|
|
|
|
|
idx_t
|
|
|
|
|
} else {
|
|
|
|
|
let base_t = self.structurally_resolved_type(base.span, base_t);
|
2021-09-25 18:23:07 +00:00
|
|
|
match self.lookup_indexing(expr, base, base_t, idx, idx_t) {
|
2019-06-15 02:46:47 +02:00
|
|
|
Some((index_ty, element_ty)) => {
|
|
|
|
|
// two-phase not needed because index_ty is never mutable
|
2020-06-09 11:45:40 -07:00
|
|
|
self.demand_coerce(idx, idx_t, index_ty, None, AllowTwoPhase::No);
|
2022-07-24 22:26:44 +09:00
|
|
|
self.select_obligations_where_possible(false, |errors| {
|
2022-07-29 14:12:17 +09:00
|
|
|
self.point_at_index_if_possible(errors, idx.span)
|
2022-07-24 22:26:44 +09:00
|
|
|
});
|
2019-06-15 02:46:47 +02:00
|
|
|
element_ty
|
|
|
|
|
}
|
|
|
|
|
None => {
|
|
|
|
|
let mut err = type_error_struct!(
|
|
|
|
|
self.tcx.sess,
|
|
|
|
|
expr.span,
|
|
|
|
|
base_t,
|
|
|
|
|
E0608,
|
2022-04-15 15:56:32 +09:00
|
|
|
"cannot index into a value of type `{base_t}`",
|
2019-06-15 02:46:47 +02:00
|
|
|
);
|
|
|
|
|
// Try to give some advice about indexing tuples.
|
2020-08-03 00:49:11 +02:00
|
|
|
if let ty::Tuple(..) = base_t.kind() {
|
2019-06-15 02:46:47 +02:00
|
|
|
let mut needs_note = true;
|
|
|
|
|
// If the index is an integer, we can show the actual
|
|
|
|
|
// fixed expression:
|
2019-09-26 14:39:48 +01:00
|
|
|
if let ExprKind::Lit(ref lit) = idx.kind {
|
2019-06-15 02:46:47 +02:00
|
|
|
if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
|
|
|
|
|
let snip = self.tcx.sess.source_map().span_to_snippet(base.span);
|
|
|
|
|
if let Ok(snip) = snip {
|
|
|
|
|
err.span_suggestion(
|
|
|
|
|
expr.span,
|
|
|
|
|
"to access tuple elements, use",
|
2022-04-15 15:56:32 +09:00
|
|
|
format!("{snip}.{i}"),
|
2019-06-15 02:46:47 +02:00
|
|
|
Applicability::MachineApplicable,
|
|
|
|
|
);
|
|
|
|
|
needs_note = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if needs_note {
|
|
|
|
|
err.help(
|
|
|
|
|
"to access tuple elements, use tuple indexing \
|
|
|
|
|
syntax (e.g., `tuple.0`)",
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
err.emit();
|
2020-05-05 23:02:09 -05:00
|
|
|
self.tcx.ty_error()
|
2019-06-15 02:46:47 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 02:48:59 +02:00
|
|
|
|
2022-07-29 14:12:17 +09:00
|
|
|
fn point_at_index_if_possible(
|
|
|
|
|
&self,
|
|
|
|
|
errors: &mut Vec<traits::FulfillmentError<'tcx>>,
|
|
|
|
|
span: Span,
|
|
|
|
|
) {
|
|
|
|
|
for error in errors {
|
|
|
|
|
match error.obligation.predicate.kind().skip_binder() {
|
|
|
|
|
ty::PredicateKind::Trait(predicate)
|
|
|
|
|
if self.tcx.is_diagnostic_item(sym::SliceIndex, predicate.trait_ref.def_id) => {
|
|
|
|
|
}
|
|
|
|
|
_ => continue,
|
|
|
|
|
}
|
|
|
|
|
error.obligation.cause.span = span;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2019-06-26 13:48:41 +01:00
|
|
|
fn check_expr_yield(
|
|
|
|
|
&self,
|
2019-11-30 15:08:22 +01:00
|
|
|
value: &'tcx hir::Expr<'tcx>,
|
|
|
|
|
expr: &'tcx hir::Expr<'tcx>,
|
2019-06-26 13:48:41 +01:00
|
|
|
src: &'tcx hir::YieldSource,
|
|
|
|
|
) -> Ty<'tcx> {
|
2020-01-25 02:27:51 +01:00
|
|
|
match self.resume_yield_tys {
|
|
|
|
|
Some((resume_ty, yield_ty)) => {
|
2020-06-09 11:45:40 -07:00
|
|
|
self.check_expr_coercable_to_type(&value, yield_ty, None);
|
2020-01-25 02:27:51 +01:00
|
|
|
|
|
|
|
|
resume_ty
|
2019-06-15 02:48:59 +02:00
|
|
|
}
|
2019-06-26 13:48:41 +01:00
|
|
|
// Given that this `yield` expression was generated as a result of lowering a `.await`,
|
|
|
|
|
// we know that the yield type must be `()`; however, the context won't contain this
|
|
|
|
|
// information. Hence, we check the source of the yield expression here and check its
|
|
|
|
|
// value's type against `()` (this check should always hold).
|
2020-04-01 18:53:00 -07:00
|
|
|
None if src.is_await() => {
|
2020-06-09 11:45:40 -07:00
|
|
|
self.check_expr_coercable_to_type(&value, self.tcx.mk_unit(), None);
|
2020-01-25 02:27:51 +01:00
|
|
|
self.tcx.mk_unit()
|
2019-06-26 13:48:41 +01:00
|
|
|
}
|
|
|
|
|
_ => {
|
2020-08-27 20:09:22 +10:00
|
|
|
self.tcx.sess.emit_err(YieldExprOutsideOfGenerator { span: expr.span });
|
2021-02-17 20:44:00 -08:00
|
|
|
// Avoid expressions without types during writeback (#78653).
|
|
|
|
|
self.check_expr(value);
|
2020-01-25 02:27:51 +01:00
|
|
|
self.tcx.mk_unit()
|
2019-06-15 02:48:59 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-02-13 11:00:55 +00:00
|
|
|
|
|
|
|
|
fn check_expr_asm_operand(&self, expr: &'tcx hir::Expr<'tcx>, is_input: bool) {
|
|
|
|
|
let needs = if is_input { Needs::None } else { Needs::MutPlace };
|
|
|
|
|
let ty = self.check_expr_with_needs(expr, needs);
|
|
|
|
|
self.require_type_is_sized(ty, expr.span, traits::InlineAsmSized);
|
|
|
|
|
|
|
|
|
|
if !is_input && !expr.is_syntactic_place_expr() {
|
|
|
|
|
let mut err = self.tcx.sess.struct_span_err(expr.span, "invalid asm output");
|
|
|
|
|
err.span_label(expr.span, "cannot assign to this expression");
|
|
|
|
|
err.emit();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If this is an input value, we require its type to be fully resolved
|
|
|
|
|
// at this point. This allows us to provide helpful coercions which help
|
2020-07-07 11:12:44 -04:00
|
|
|
// pass the type candidate list in a later pass.
|
2020-02-13 11:00:55 +00:00
|
|
|
//
|
|
|
|
|
// We don't require output types to be resolved at this point, which
|
|
|
|
|
// allows them to be inferred based on how they are used later in the
|
|
|
|
|
// function.
|
|
|
|
|
if is_input {
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 14:13:38 +11:00
|
|
|
let ty = self.structurally_resolved_type(expr.span, ty);
|
2020-08-03 00:49:11 +02:00
|
|
|
match *ty.kind() {
|
2020-02-13 11:00:55 +00:00
|
|
|
ty::FnDef(..) => {
|
|
|
|
|
let fnptr_ty = self.tcx.mk_fn_ptr(ty.fn_sig(self.tcx));
|
2020-06-09 11:45:40 -07:00
|
|
|
self.demand_coerce(expr, ty, fnptr_ty, None, AllowTwoPhase::No);
|
2020-02-13 11:00:55 +00:00
|
|
|
}
|
|
|
|
|
ty::Ref(_, base_ty, mutbl) => {
|
|
|
|
|
let ptr_ty = self.tcx.mk_ptr(ty::TypeAndMut { ty: base_ty, mutbl });
|
2020-06-09 11:45:40 -07:00
|
|
|
self.demand_coerce(expr, ty, ptr_ty, None, AllowTwoPhase::No);
|
2020-02-13 11:00:55 +00:00
|
|
|
}
|
|
|
|
|
_ => {}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn check_expr_asm(&self, asm: &'tcx hir::InlineAsm<'tcx>) -> Ty<'tcx> {
|
2020-11-27 00:00:00 +00:00
|
|
|
for (op, _op_sp) in asm.operands {
|
2020-02-13 11:00:55 +00:00
|
|
|
match op {
|
2021-04-06 05:50:55 +01:00
|
|
|
hir::InlineAsmOperand::In { expr, .. } => {
|
2020-02-13 11:00:55 +00:00
|
|
|
self.check_expr_asm_operand(expr, true);
|
|
|
|
|
}
|
2021-08-16 17:30:23 +02:00
|
|
|
hir::InlineAsmOperand::Out { expr: Some(expr), .. }
|
|
|
|
|
| hir::InlineAsmOperand::InOut { expr, .. } => {
|
2020-02-13 11:00:55 +00:00
|
|
|
self.check_expr_asm_operand(expr, false);
|
|
|
|
|
}
|
2021-08-16 17:30:23 +02:00
|
|
|
hir::InlineAsmOperand::Out { expr: None, .. } => {}
|
2020-02-13 11:00:55 +00:00
|
|
|
hir::InlineAsmOperand::SplitInOut { in_expr, out_expr, .. } => {
|
|
|
|
|
self.check_expr_asm_operand(in_expr, true);
|
|
|
|
|
if let Some(out_expr) = out_expr {
|
|
|
|
|
self.check_expr_asm_operand(out_expr, false);
|
|
|
|
|
}
|
|
|
|
|
}
|
2022-05-07 02:56:46 +01:00
|
|
|
// `AnonConst`s have their own body and is type-checked separately.
|
|
|
|
|
// As they don't flow into the type system we don't need them to
|
|
|
|
|
// be well-formed.
|
|
|
|
|
hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::SymFn { .. } => {}
|
2022-03-01 00:50:56 +00:00
|
|
|
hir::InlineAsmOperand::SymStatic { .. } => {}
|
2020-02-13 11:00:55 +00:00
|
|
|
}
|
|
|
|
|
}
|
2020-05-06 14:46:01 +01:00
|
|
|
if asm.options.contains(ast::InlineAsmOptions::NORETURN) {
|
2020-02-13 11:00:55 +00:00
|
|
|
self.tcx.types.never
|
|
|
|
|
} else {
|
|
|
|
|
self.tcx.mk_unit()
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-06-15 01:28:38 +02:00
|
|
|
}
|
2019-10-23 22:45:15 -07:00
|
|
|
|
2019-10-30 12:55:38 -07:00
|
|
|
pub(super) fn ty_kind_suggestion(ty: Ty<'_>) -> Option<&'static str> {
|
2020-08-03 00:49:11 +02:00
|
|
|
Some(match ty.kind() {
|
2019-10-23 22:45:15 -07:00
|
|
|
ty::Bool => "true",
|
|
|
|
|
ty::Char => "'a'",
|
|
|
|
|
ty::Int(_) | ty::Uint(_) => "42",
|
|
|
|
|
ty::Float(_) => "3.14159",
|
2020-05-05 23:02:09 -05:00
|
|
|
ty::Error(_) | ty::Never => return None,
|
2019-10-23 22:45:15 -07:00
|
|
|
_ => "value",
|
|
|
|
|
})
|
|
|
|
|
}
|