Skip to content

Commit 14c4da1

Browse files
Suggest Semicolon in Incorrect Repeat Expressions
1 parent 49e720d commit 14c4da1

File tree

7 files changed

+125
-11
lines changed

7 files changed

+125
-11
lines changed

compiler/rustc_hir/src/hir.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::intravisit::FnKind;
55
use crate::LangItem;
66
use rustc_ast as ast;
77
use rustc_ast::util::parser::ExprPrecedence;
8-
use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitKind, TraitObjectSyntax, UintTy};
8+
use rustc_ast::{Attribute, FloatTy, IntTy, Label, LitIntType, LitKind, TraitObjectSyntax, UintTy};
99
pub use rustc_ast::{BinOp, BinOpKind, BindingMode, BorrowKind, ByRef, CaptureBy};
1010
pub use rustc_ast::{ImplPolarity, IsAuto, Movability, Mutability, UnOp};
1111
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
@@ -1795,6 +1795,18 @@ impl Expr<'_> {
17951795
}
17961796
}
17971797

1798+
/// Check if expression is an integer literal that can be used
1799+
/// where `usize` is expected.
1800+
pub fn is_size_lit(&self) -> bool {
1801+
matches!(
1802+
self.kind,
1803+
ExprKind::Lit(Lit {
1804+
node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
1805+
..
1806+
})
1807+
)
1808+
}
1809+
17981810
/// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
17991811
/// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
18001812
/// silent, only signaling the ownership system. By doing this, suggestions that check the

compiler/rustc_hir_typeck/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,8 @@ hir_typeck_remove_semi_for_coerce_ret = the `match` arms can conform to this ret
155155
hir_typeck_remove_semi_for_coerce_semi = the `match` is a statement because of this semicolon, consider removing it
156156
hir_typeck_remove_semi_for_coerce_suggestion = remove this semicolon
157157
158+
hir_typeck_replace_comma_with_semicolon = replace comma with semicolon to create {$descr}
159+
158160
hir_typeck_return_stmt_outside_of_fn_body =
159161
{$statement_kind} statement outside of function body
160162
.encl_body_label = the {$statement_kind} is part of this body...

compiler/rustc_hir_typeck/src/demand.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
3131
if expr_ty == expected {
3232
return;
3333
}
34-
3534
self.annotate_alternative_method_deref(err, expr, error);
3635
self.explain_self_literal(err, expr, expected, expr_ty);
3736

@@ -40,6 +39,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
4039
|| self.suggest_missing_unwrap_expect(err, expr, expected, expr_ty)
4140
|| self.suggest_remove_last_method_call(err, expr, expected)
4241
|| self.suggest_associated_const(err, expr, expected)
42+
|| self.suggest_semicolon_in_repeat_expr(err, expr, expr_ty)
4343
|| self.suggest_deref_ref_or_into(err, expr, expected, expr_ty, expected_ty_expr)
4444
|| self.suggest_option_to_bool(err, expr, expr_ty, expected)
4545
|| self.suggest_compatible_variants(err, expr, expected, expr_ty)

compiler/rustc_hir_typeck/src/errors.rs

+13
Original file line numberDiff line numberDiff line change
@@ -724,3 +724,16 @@ pub(crate) struct PassToVariadicFunction<'tcx, 'a> {
724724
#[note(hir_typeck_teach_help)]
725725
pub(crate) teach: Option<()>,
726726
}
727+
728+
#[derive(Subdiagnostic)]
729+
#[suggestion(
730+
hir_typeck_replace_comma_with_semicolon,
731+
applicability = "machine-applicable",
732+
style = "verbose",
733+
code = "; "
734+
)]
735+
pub struct ReplaceCommaWithSemicolon {
736+
#[primary_span]
737+
pub comma_span: Span,
738+
pub descr: &'static str,
739+
}

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

+74-8
Original file line numberDiff line numberDiff line change
@@ -1298,14 +1298,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
12981298
let span = expr.span.shrink_to_hi();
12991299
let subdiag = if self.type_is_copy_modulo_regions(self.param_env, ty) {
13001300
errors::OptionResultRefMismatch::Copied { span, def_path }
1301-
} else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1302-
&& rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1303-
self,
1304-
self.param_env,
1305-
ty,
1306-
clone_did,
1307-
)
1308-
{
1301+
} else if self.type_is_clone_modulo_regions(self.param_env, ty) {
13091302
errors::OptionResultRefMismatch::Cloned { span, def_path }
13101303
} else {
13111304
return false;
@@ -2158,6 +2151,79 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21582151
}
21592152
}
21602153

2154+
/// Suggest replacing comma with semicolon in incorrect repeat expressions
2155+
/// like `["_", 10]` or `vec![String::new(), 10]`.
2156+
pub(crate) fn suggest_semicolon_in_repeat_expr(
2157+
&self,
2158+
err: &mut Diag<'_>,
2159+
expr: &hir::Expr<'_>,
2160+
expr_ty: Ty<'tcx>,
2161+
) -> bool {
2162+
// Check if `expr` is contained in array of two elements
2163+
if let hir::Node::Expr(array_expr) = self.tcx.parent_hir_node(expr.hir_id)
2164+
&& let hir::ExprKind::Array(elements) = array_expr.kind
2165+
&& let [first, second] = &elements[..]
2166+
&& second.hir_id == expr.hir_id
2167+
{
2168+
// Span between the two elements of the array
2169+
let comma_span = first.span.between(second.span);
2170+
2171+
// Check if `expr` is a constant value of type `usize`.
2172+
// This can only detect const variable declarations and
2173+
// calls to const functions.
2174+
2175+
// Checking this here instead of rustc_hir::hir because
2176+
// this check needs access to `self.tcx` but rustc_hir
2177+
// has no access to `TyCtxt`.
2178+
let expr_is_const_usize = expr_ty.is_usize()
2179+
&& match expr.kind {
2180+
ExprKind::Path(QPath::Resolved(
2181+
None,
2182+
Path { res: Res::Def(DefKind::Const, _), .. },
2183+
)) => true,
2184+
ExprKind::Call(
2185+
Expr {
2186+
kind:
2187+
ExprKind::Path(QPath::Resolved(
2188+
None,
2189+
Path { res: Res::Def(DefKind::Fn, fn_def_id), .. },
2190+
)),
2191+
..
2192+
},
2193+
_,
2194+
) => self.tcx.is_const_fn(*fn_def_id),
2195+
_ => false,
2196+
};
2197+
2198+
// `array_expr` is from a macro `vec!["a", 10]` if
2199+
// 1. array expression's span is imported from a macro
2200+
// 2. first element of array implements `Clone` trait
2201+
// 3. second element is an integer literal or is an expression of `usize` like type
2202+
if self.tcx.sess.source_map().is_imported(array_expr.span)
2203+
&& self.type_is_clone_modulo_regions(self.param_env, self.check_expr(first))
2204+
&& (second.is_size_lit() || expr_ty.is_usize_like())
2205+
{
2206+
err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2207+
comma_span,
2208+
descr: "a vector",
2209+
});
2210+
return true;
2211+
} else if self.type_is_copy_modulo_regions(self.param_env, self.check_expr(first))
2212+
&& (second.is_size_lit() || expr_is_const_usize)
2213+
{
2214+
// `array_expr` is from an array `["a", 10]` if
2215+
// 1. first element of array implements `Copy` trait
2216+
// 2. second element is an integer literal or is a const value of type `usize`
2217+
err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2218+
comma_span,
2219+
descr: "an array",
2220+
});
2221+
return true;
2222+
}
2223+
}
2224+
false
2225+
}
2226+
21612227
/// If the expected type is an enum (Issue #55250) with any variants whose
21622228
/// sole field is of the found type, suggest such variants. (Issue #42764)
21632229
pub(crate) fn suggest_compatible_variants(

compiler/rustc_middle/src/ty/sty.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use crate::ty::{
99
TypeVisitable, TypeVisitor,
1010
};
1111
use crate::ty::{GenericArg, GenericArgs, GenericArgsRef};
12-
use crate::ty::{List, ParamEnv};
12+
use crate::ty::{List, ParamEnv, UintTy};
1313
use hir::def::{CtorKind, DefKind};
1414
use rustc_data_structures::captures::Captures;
1515
use rustc_errors::{ErrorGuaranteed, MultiSpan};
@@ -990,6 +990,18 @@ impl<'tcx> Ty<'tcx> {
990990
}
991991
}
992992

993+
/// Check if type is an `usize`.
994+
#[inline]
995+
pub fn is_usize(self) -> bool {
996+
matches!(self.kind(), Uint(UintTy::Usize))
997+
}
998+
999+
/// Check if type is an `usize` or an integral type variable.
1000+
#[inline]
1001+
pub fn is_usize_like(self) -> bool {
1002+
matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1003+
}
1004+
9931005
#[inline]
9941006
pub fn is_never(self) -> bool {
9951007
matches!(self.kind(), Never)

compiler/rustc_trait_selection/src/infer.rs

+9
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ impl<'tcx> InferCtxt<'tcx> {
2828
})
2929
}
3030

31+
/// Check if `ty` implements the `Copy` trait.
3132
fn type_is_copy_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
3233
let ty = self.resolve_vars_if_possible(ty);
3334

@@ -44,6 +45,14 @@ impl<'tcx> InferCtxt<'tcx> {
4445
traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id)
4546
}
4647

48+
/// Check if `ty` implements the `Clone` trait.
49+
fn type_is_clone_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
50+
let ty = self.resolve_vars_if_possible(ty);
51+
let clone_def_id = self.tcx.require_lang_item(LangItem::Clone, None);
52+
traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, clone_def_id)
53+
}
54+
55+
/// Check if `ty` implements the `Sized` trait.
4756
fn type_is_sized_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
4857
let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
4958
traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, lang_item)

0 commit comments

Comments
 (0)