Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rollup of 7 pull requests #135267

Closed
wants to merge 20 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
872aa75
Add Tests
veera-sivarajan Jul 23, 2024
98cc345
Suggest Semicolon in Incorrect Repeat Expressions
veera-sivarajan Jul 29, 2024
4bc6b76
Escape all `*` in rustc's SUMMARY.md
tbu- Dec 21, 2024
8630234
Add new `{x86_64,i686}-win7-windows-gnu` targets
tbu- Jan 6, 2025
ceabc95
Add more comments to some of the test steps
Zalathar Jan 8, 2025
63040a9
Make `lit_to_mir_constant` infallible
oli-obk Dec 5, 2024
109b067
Use error constant instead of explicit error handling
oli-obk Jan 7, 2025
aebc703
Used pthread name functions returning result for FreeBSD and DragonFly
YohDeadfall Nov 4, 2024
9cc3013
Always take the `Ok` path in `lit_to_const` and produce error constan…
oli-obk Jan 7, 2025
9c879a0
Remove the now-useless `Result` from `lit_to_const`
oli-obk Jan 7, 2025
c92ed62
Use option combinators instead of manual if/return
oli-obk Jan 8, 2025
61bda87
Move `mod cargo` below the import statements
onur-ozkan Jan 8, 2025
c64f859
Implement const Destruct in old solver
compiler-errors Dec 29, 2024
a66278f
Rollup merge of #128110 - veera-sivarajan:bugfix-80173, r=cjgillot
matthiaskrgr Jan 8, 2025
3dc2ff1
Rollup merge of #132607 - YohDeadfall:pthread-name-fn-with-result, r=…
matthiaskrgr Jan 8, 2025
dc6c865
Rollup merge of #134609 - tbu-:pr_win7_gnu, r=davidtwco
matthiaskrgr Jan 8, 2025
614e17b
Rollup merge of #134875 - compiler-errors:const-destruct-old-solver, …
matthiaskrgr Jan 8, 2025
b4ea2b2
Rollup merge of #135195 - oli-obk:push-toyoyrupruko, r=lcnr
matthiaskrgr Jan 8, 2025
e701aa5
Rollup merge of #135231 - Zalathar:test-step-notes, r=jieyouxu
matthiaskrgr Jan 8, 2025
5b7e3d7
Rollup merge of #135256 - onur-ozkan:weird-mod-position, r=clubby789,…
matthiaskrgr Jan 8, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion compiler/rustc_hir/src/hir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use rustc_ast::token::CommentKind;
use rustc_ast::util::parser::{AssocOp, ExprPrecedence};
use rustc_ast::{
self as ast, AttrId, AttrStyle, DelimArgs, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece,
IntTy, Label, LitKind, MetaItemInner, MetaItemLit, TraitObjectSyntax, UintTy,
IntTy, Label, LitIntType, LitKind, MetaItemInner, MetaItemLit, TraitObjectSyntax, UintTy,
};
pub use rustc_ast::{
BinOp, BinOpKind, BindingMode, BorrowKind, BoundConstness, BoundPolarity, ByRef, CaptureBy,
Expand Down Expand Up @@ -2074,6 +2074,18 @@ impl Expr<'_> {
}
}

/// Check if expression is an integer literal that can be used
/// where `usize` is expected.
pub fn is_size_lit(&self) -> bool {
matches!(
self.kind,
ExprKind::Lit(Lit {
node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
..
})
)
}

/// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
/// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
/// silent, only signaling the ownership system. By doing this, suggestions that check the
Expand Down
34 changes: 7 additions & 27 deletions compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ use rustc_hir::{self as hir, AnonConst, GenericArg, GenericArgs, HirId};
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
use rustc_infer::traits::ObligationCause;
use rustc_middle::middle::stability::AllowUnstable;
use rustc_middle::mir::interpret::{LitToConstError, LitToConstInput};
use rustc_middle::mir::interpret::LitToConstInput;
use rustc_middle::ty::fold::fold_regions;
use rustc_middle::ty::print::PrintPolyTraitRefExt as _;
use rustc_middle::ty::{
Expand Down Expand Up @@ -2262,25 +2262,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
_ => None,
};

if let Some(lit_input) = lit_input {
// If an error occurred, ignore that it's a literal and leave reporting the error up to
// mir.
match tcx.at(expr.span).lit_to_const(lit_input) {
Ok(c) => return Some(c),
Err(_) if lit_input.ty.has_aliases() => {
// allow the `ty` to be an alias type, though we cannot handle it here
return None;
}
Err(e) => {
tcx.dcx().span_delayed_bug(
expr.span,
format!("try_lower_anon_const_lit: couldn't lit_to_const {e:?}"),
);
}
}
}

None
lit_input
// Allow the `ty` to be an alias type, though we cannot handle it here, we just go through
// the more expensive anon const code path.
.filter(|l| !l.ty.has_aliases())
.map(|l| tcx.at(expr.span).lit_to_const(l))
}

fn lower_delegation_ty(&self, idx: hir::InferDelegationKind) -> Ty<'tcx> {
Expand Down Expand Up @@ -2460,13 +2446,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
hir::ExprKind::Lit(lit) => {
let lit_input =
LitToConstInput { lit: &lit.node, ty, neg: neg.is_some() };
let ct = match tcx.lit_to_const(lit_input) {
Ok(c) => c,
Err(LitToConstError::Reported(err)) => {
ty::Const::new_error(tcx, err)
}
Err(LitToConstError::TypeError) => todo!(),
};
let ct = tcx.lit_to_const(lit_input);
(ct, ty)
}

Expand Down
2 changes: 2 additions & 0 deletions compiler/rustc_hir_typeck/messages.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,8 @@ hir_typeck_remove_semi_for_coerce_ret = the `match` arms can conform to this ret
hir_typeck_remove_semi_for_coerce_semi = the `match` is a statement because of this semicolon, consider removing it
hir_typeck_remove_semi_for_coerce_suggestion = remove this semicolon

hir_typeck_replace_comma_with_semicolon = replace the comma with a semicolon to create {$descr}

hir_typeck_return_stmt_outside_of_fn_body =
{$statement_kind} statement outside of function body
.encl_body_label = the {$statement_kind} is part of this body...
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_hir_typeck/src/demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
if expr_ty == expected {
return;
}

self.annotate_alternative_method_deref(err, expr, error);
self.explain_self_literal(err, expr, expected, expr_ty);

Expand All @@ -39,6 +38,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
|| self.suggest_missing_unwrap_expect(err, expr, expected, expr_ty)
|| self.suggest_remove_last_method_call(err, expr, expected)
|| self.suggest_associated_const(err, expr, expected)
|| self.suggest_semicolon_in_repeat_expr(err, expr, expr_ty)
|| self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr)
|| self.suggest_option_to_bool(err, expr, expr_ty, expected)
|| self.suggest_compatible_variants(err, expr, expected, expr_ty)
Expand Down
13 changes: 13 additions & 0 deletions compiler/rustc_hir_typeck/src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,3 +846,16 @@ pub(crate) struct PassFnItemToVariadicFunction {
pub sugg_span: Span,
pub replace: String,
}

#[derive(Subdiagnostic)]
#[suggestion(
hir_typeck_replace_comma_with_semicolon,
applicability = "machine-applicable",
style = "verbose",
code = "; "
)]
pub(crate) struct ReplaceCommaWithSemicolon {
#[primary_span]
pub comma_span: Span,
pub descr: &'static str,
}
90 changes: 82 additions & 8 deletions compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1320,14 +1320,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let span = expr.span.shrink_to_hi();
let subdiag = if self.type_is_copy_modulo_regions(self.param_env, ty) {
errors::OptionResultRefMismatch::Copied { span, def_path }
} else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
&& rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
self,
self.param_env,
ty,
clone_did,
)
{
} else if self.type_is_clone_modulo_regions(self.param_env, ty) {
errors::OptionResultRefMismatch::Cloned { span, def_path }
} else {
return false;
Expand Down Expand Up @@ -2182,6 +2175,87 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
}
}

/// Suggest replacing comma with semicolon in incorrect repeat expressions
/// like `["_", 10]` or `vec![String::new(), 10]`.
pub(crate) fn suggest_semicolon_in_repeat_expr(
&self,
err: &mut Diag<'_>,
expr: &hir::Expr<'_>,
expr_ty: Ty<'tcx>,
) -> bool {
// Check if `expr` is contained in array of two elements
if let hir::Node::Expr(array_expr) = self.tcx.parent_hir_node(expr.hir_id)
&& let hir::ExprKind::Array(elements) = array_expr.kind
&& let [first, second] = &elements[..]
&& second.hir_id == expr.hir_id
{
// Span between the two elements of the array
let comma_span = first.span.between(second.span);

// Check if `expr` is a constant value of type `usize`.
// This can only detect const variable declarations and
// calls to const functions.

// Checking this here instead of rustc_hir::hir because
// this check needs access to `self.tcx` but rustc_hir
// has no access to `TyCtxt`.
let expr_is_const_usize = expr_ty.is_usize()
&& match expr.kind {
ExprKind::Path(QPath::Resolved(
None,
Path { res: Res::Def(DefKind::Const, _), .. },
)) => true,
ExprKind::Call(
Expr {
kind:
ExprKind::Path(QPath::Resolved(
None,
Path { res: Res::Def(DefKind::Fn, fn_def_id), .. },
)),
..
},
_,
) => self.tcx.is_const_fn(*fn_def_id),
_ => false,
};

// Type of the first element is guaranteed to be checked
// when execution reaches here because `mismatched types`
// error occurs only when type of second element of array
// is not the same as type of first element.
let first_ty = self.typeck_results.borrow().expr_ty(first);

// `array_expr` is from a macro `vec!["a", 10]` if
// 1. array expression's span is imported from a macro
// 2. first element of array implements `Clone` trait
// 3. second element is an integer literal or is an expression of `usize` like type
if self.tcx.sess.source_map().is_imported(array_expr.span)
&& self.type_is_clone_modulo_regions(self.param_env, first_ty)
&& (expr.is_size_lit() || expr_ty.is_usize_like())
{
err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
comma_span,
descr: "a vector",
});
return true;
}

// `array_expr` is from an array `["a", 10]` if
// 1. first element of array implements `Copy` trait
// 2. second element is an integer literal or is a const value of type `usize`
if self.type_is_copy_modulo_regions(self.param_env, first_ty)
&& (expr.is_size_lit() || expr_is_const_usize)
{
err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
comma_span,
descr: "an array",
});
return true;
}
}
false
}

/// If the expected type is an enum (Issue #55250) with any variants whose
/// sole field is of the found type, suggest such variants. (Issue #42764)
pub(crate) fn suggest_compatible_variants(
Expand Down
11 changes: 0 additions & 11 deletions compiler/rustc_middle/src/mir/interpret/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ use rustc_abi::{AddressSpace, Align, Endian, HasDataLayout, Size};
use rustc_ast::{LitKind, Mutability};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::Lock;
use rustc_errors::ErrorGuaranteed;
use rustc_hir::def::DefKind;
use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_macros::{HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable};
Expand Down Expand Up @@ -84,16 +83,6 @@ pub struct LitToConstInput<'tcx> {
pub neg: bool,
}

/// Error type for `tcx.lit_to_const`.
#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable)]
pub enum LitToConstError {
/// The literal's inferred type did not match the expected `ty` in the input.
/// This is used for graceful error handling (`span_delayed_bug`) in
/// type checking (`Const::from_anon_const`).
TypeError,
Reported(ErrorGuaranteed),
}

#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct AllocId(pub NonZero<u64>);

Expand Down
9 changes: 0 additions & 9 deletions compiler/rustc_middle/src/query/erase.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,14 +141,6 @@ impl EraseType for Result<rustc_abi::TyAndLayout<'_, Ty<'_>>, &ty::layout::Layou
>()];
}

impl EraseType for Result<ty::Const<'_>, mir::interpret::LitToConstError> {
type Result = [u8; size_of::<Result<ty::Const<'static>, mir::interpret::LitToConstError>>()];
}

impl EraseType for Result<mir::Const<'_>, mir::interpret::LitToConstError> {
type Result = [u8; size_of::<Result<mir::Const<'static>, mir::interpret::LitToConstError>>()];
}

impl EraseType for Result<mir::ConstAlloc<'_>, mir::interpret::ErrorHandled> {
type Result = [u8; size_of::<Result<mir::ConstAlloc<'static>, mir::interpret::ErrorHandled>>()];
}
Expand Down Expand Up @@ -296,7 +288,6 @@ trivial! {
rustc_middle::mir::interpret::AllocId,
rustc_middle::mir::interpret::CtfeProvenance,
rustc_middle::mir::interpret::ErrorHandled,
rustc_middle::mir::interpret::LitToConstError,
rustc_middle::thir::ExprId,
rustc_middle::traits::CodegenObligationError,
rustc_middle::traits::EvaluationResult,
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ use crate::middle::resolve_bound_vars::{ObjectLifetimeDefault, ResolveBoundVars,
use crate::middle::stability::{self, DeprecationEntry};
use crate::mir::interpret::{
EvalStaticInitializerRawResult, EvalToAllocationRawResult, EvalToConstValueResult,
EvalToValTreeResult, GlobalId, LitToConstError, LitToConstInput,
EvalToValTreeResult, GlobalId, LitToConstInput,
};
use crate::mir::mono::{CodegenUnit, CollectionMode, MonoItem};
use crate::query::erase::{Erase, erase, restore};
Expand Down Expand Up @@ -1268,7 +1268,7 @@ rustc_queries! {
// FIXME get rid of this with valtrees
query lit_to_const(
key: LitToConstInput<'tcx>
) -> Result<ty::Const<'tcx>, LitToConstError> {
) -> ty::Const<'tcx> {
desc { "converting literal to const" }
}

Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_middle/src/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1417,8 +1417,8 @@ impl Hash for FieldDef {
impl<'tcx> FieldDef {
/// Returns the type of this field. The resulting type is not normalized. The `arg` is
/// typically obtained via the second field of [`TyKind::Adt`].
pub fn ty(&self, tcx: TyCtxt<'tcx>, arg: GenericArgsRef<'tcx>) -> Ty<'tcx> {
tcx.type_of(self.did).instantiate(tcx, arg)
pub fn ty(&self, tcx: TyCtxt<'tcx>, args: GenericArgsRef<'tcx>) -> Ty<'tcx> {
tcx.type_of(self.did).instantiate(tcx, args)
}

/// Computes the `Ident` of this variant by looking up the `Span`
Expand Down
14 changes: 13 additions & 1 deletion compiler/rustc_middle/src/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use crate::infer::canonical::Canonical;
use crate::ty::InferTy::*;
use crate::ty::{
self, AdtDef, BoundRegionKind, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv,
Region, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor,
Region, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy,
};

// Re-export and re-parameterize some `I = TyCtxt<'tcx>` types here
Expand Down Expand Up @@ -1017,6 +1017,18 @@ impl<'tcx> Ty<'tcx> {
}
}

/// Check if type is an `usize`.
#[inline]
pub fn is_usize(self) -> bool {
matches!(self.kind(), Uint(UintTy::Usize))
}

/// Check if type is an `usize` or an integral type variable.
#[inline]
pub fn is_usize_like(self) -> bool {
matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
}

#[inline]
pub fn is_never(self) -> bool {
matches!(self.kind(), Never)
Expand Down
Loading
Loading