Skip to content

Commit a66278f

Browse files
authored
Rollup merge of rust-lang#128110 - veera-sivarajan:bugfix-80173, r=cjgillot
Suggest Replacing Comma with Semicolon in Incorrect Repeat Expressions Fixes rust-lang#80173 This PR detects typos in repeat expressions like `["_", 10]` and `vec![String::new(), 10]` and suggests replacing comma with semicolon. Also, improves code in other place by adding doc comments and making use of a helper function to check if a type implements `Clone`. References: 1. For `vec![T; N]`: https://doc.rust-lang.org/std/macro.vec.html 2. For `[T; N]`: https://doc.rust-lang.org/std/primitive.array.html
2 parents a580b5c + 98cc345 commit a66278f

File tree

9 files changed

+324
-11
lines changed

9 files changed

+324
-11
lines changed

Diff for: compiler/rustc_hir/src/hir.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_ast::token::CommentKind;
77
use rustc_ast::util::parser::{AssocOp, ExprPrecedence};
88
use rustc_ast::{
99
self as ast, AttrId, AttrStyle, DelimArgs, FloatTy, InlineAsmOptions, InlineAsmTemplatePiece,
10-
IntTy, Label, LitKind, MetaItemInner, MetaItemLit, TraitObjectSyntax, UintTy,
10+
IntTy, Label, LitIntType, LitKind, MetaItemInner, MetaItemLit, TraitObjectSyntax, UintTy,
1111
};
1212
pub use rustc_ast::{
1313
BinOp, BinOpKind, BindingMode, BorrowKind, BoundConstness, BoundPolarity, ByRef, CaptureBy,
@@ -2074,6 +2074,18 @@ impl Expr<'_> {
20742074
}
20752075
}
20762076

2077+
/// Check if expression is an integer literal that can be used
2078+
/// where `usize` is expected.
2079+
pub fn is_size_lit(&self) -> bool {
2080+
matches!(
2081+
self.kind,
2082+
ExprKind::Lit(Lit {
2083+
node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2084+
..
2085+
})
2086+
)
2087+
}
2088+
20772089
/// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
20782090
/// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
20792091
/// silent, only signaling the ownership system. By doing this, suggestions that check the

Diff for: compiler/rustc_hir_typeck/messages.ftl

+2
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ hir_typeck_remove_semi_for_coerce_ret = the `match` arms can conform to this ret
165165
hir_typeck_remove_semi_for_coerce_semi = the `match` is a statement because of this semicolon, consider removing it
166166
hir_typeck_remove_semi_for_coerce_suggestion = remove this semicolon
167167
168+
hir_typeck_replace_comma_with_semicolon = replace the comma with a semicolon to create {$descr}
169+
168170
hir_typeck_return_stmt_outside_of_fn_body =
169171
{$statement_kind} statement outside of function body
170172
.encl_body_label = the {$statement_kind} is part of this body...

Diff for: compiler/rustc_hir_typeck/src/demand.rs

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

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

Diff for: compiler/rustc_hir_typeck/src/errors.rs

+13
Original file line numberDiff line numberDiff line change
@@ -846,3 +846,16 @@ pub(crate) struct PassFnItemToVariadicFunction {
846846
pub sugg_span: Span,
847847
pub replace: String,
848848
}
849+
850+
#[derive(Subdiagnostic)]
851+
#[suggestion(
852+
hir_typeck_replace_comma_with_semicolon,
853+
applicability = "machine-applicable",
854+
style = "verbose",
855+
code = "; "
856+
)]
857+
pub(crate) struct ReplaceCommaWithSemicolon {
858+
#[primary_span]
859+
pub comma_span: Span,
860+
pub descr: &'static str,
861+
}

Diff for: compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

+82-8
Original file line numberDiff line numberDiff line change
@@ -1320,14 +1320,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
13201320
let span = expr.span.shrink_to_hi();
13211321
let subdiag = if self.type_is_copy_modulo_regions(self.param_env, ty) {
13221322
errors::OptionResultRefMismatch::Copied { span, def_path }
1323-
} else if let Some(clone_did) = self.tcx.lang_items().clone_trait()
1324-
&& rustc_trait_selection::traits::type_known_to_meet_bound_modulo_regions(
1325-
self,
1326-
self.param_env,
1327-
ty,
1328-
clone_did,
1329-
)
1330-
{
1323+
} else if self.type_is_clone_modulo_regions(self.param_env, ty) {
13311324
errors::OptionResultRefMismatch::Cloned { span, def_path }
13321325
} else {
13331326
return false;
@@ -2182,6 +2175,87 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
21822175
}
21832176
}
21842177

2178+
/// Suggest replacing comma with semicolon in incorrect repeat expressions
2179+
/// like `["_", 10]` or `vec![String::new(), 10]`.
2180+
pub(crate) fn suggest_semicolon_in_repeat_expr(
2181+
&self,
2182+
err: &mut Diag<'_>,
2183+
expr: &hir::Expr<'_>,
2184+
expr_ty: Ty<'tcx>,
2185+
) -> bool {
2186+
// Check if `expr` is contained in array of two elements
2187+
if let hir::Node::Expr(array_expr) = self.tcx.parent_hir_node(expr.hir_id)
2188+
&& let hir::ExprKind::Array(elements) = array_expr.kind
2189+
&& let [first, second] = &elements[..]
2190+
&& second.hir_id == expr.hir_id
2191+
{
2192+
// Span between the two elements of the array
2193+
let comma_span = first.span.between(second.span);
2194+
2195+
// Check if `expr` is a constant value of type `usize`.
2196+
// This can only detect const variable declarations and
2197+
// calls to const functions.
2198+
2199+
// Checking this here instead of rustc_hir::hir because
2200+
// this check needs access to `self.tcx` but rustc_hir
2201+
// has no access to `TyCtxt`.
2202+
let expr_is_const_usize = expr_ty.is_usize()
2203+
&& match expr.kind {
2204+
ExprKind::Path(QPath::Resolved(
2205+
None,
2206+
Path { res: Res::Def(DefKind::Const, _), .. },
2207+
)) => true,
2208+
ExprKind::Call(
2209+
Expr {
2210+
kind:
2211+
ExprKind::Path(QPath::Resolved(
2212+
None,
2213+
Path { res: Res::Def(DefKind::Fn, fn_def_id), .. },
2214+
)),
2215+
..
2216+
},
2217+
_,
2218+
) => self.tcx.is_const_fn(*fn_def_id),
2219+
_ => false,
2220+
};
2221+
2222+
// Type of the first element is guaranteed to be checked
2223+
// when execution reaches here because `mismatched types`
2224+
// error occurs only when type of second element of array
2225+
// is not the same as type of first element.
2226+
let first_ty = self.typeck_results.borrow().expr_ty(first);
2227+
2228+
// `array_expr` is from a macro `vec!["a", 10]` if
2229+
// 1. array expression's span is imported from a macro
2230+
// 2. first element of array implements `Clone` trait
2231+
// 3. second element is an integer literal or is an expression of `usize` like type
2232+
if self.tcx.sess.source_map().is_imported(array_expr.span)
2233+
&& self.type_is_clone_modulo_regions(self.param_env, first_ty)
2234+
&& (expr.is_size_lit() || expr_ty.is_usize_like())
2235+
{
2236+
err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2237+
comma_span,
2238+
descr: "a vector",
2239+
});
2240+
return true;
2241+
}
2242+
2243+
// `array_expr` is from an array `["a", 10]` if
2244+
// 1. first element of array implements `Copy` trait
2245+
// 2. second element is an integer literal or is a const value of type `usize`
2246+
if self.type_is_copy_modulo_regions(self.param_env, first_ty)
2247+
&& (expr.is_size_lit() || expr_is_const_usize)
2248+
{
2249+
err.subdiagnostic(errors::ReplaceCommaWithSemicolon {
2250+
comma_span,
2251+
descr: "an array",
2252+
});
2253+
return true;
2254+
}
2255+
}
2256+
false
2257+
}
2258+
21852259
/// If the expected type is an enum (Issue #55250) with any variants whose
21862260
/// sole field is of the found type, suggest such variants. (Issue #42764)
21872261
pub(crate) fn suggest_compatible_variants(

Diff for: compiler/rustc_middle/src/ty/sty.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use crate::infer::canonical::Canonical;
2727
use crate::ty::InferTy::*;
2828
use crate::ty::{
2929
self, AdtDef, BoundRegionKind, Discr, GenericArg, GenericArgs, GenericArgsRef, List, ParamEnv,
30-
Region, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor,
30+
Region, Ty, TyCtxt, TypeFlags, TypeSuperVisitable, TypeVisitable, TypeVisitor, UintTy,
3131
};
3232

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

1020+
/// Check if type is an `usize`.
1021+
#[inline]
1022+
pub fn is_usize(self) -> bool {
1023+
matches!(self.kind(), Uint(UintTy::Usize))
1024+
}
1025+
1026+
/// Check if type is an `usize` or an integral type variable.
1027+
#[inline]
1028+
pub fn is_usize_like(self) -> bool {
1029+
matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1030+
}
1031+
10201032
#[inline]
10211033
pub fn is_never(self) -> bool {
10221034
matches!(self.kind(), Never)

Diff for: compiler/rustc_trait_selection/src/infer.rs

+6
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,12 @@ impl<'tcx> InferCtxt<'tcx> {
4747
traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, copy_def_id)
4848
}
4949

50+
fn type_is_clone_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
51+
let ty = self.resolve_vars_if_possible(ty);
52+
let clone_def_id = self.tcx.require_lang_item(LangItem::Clone, None);
53+
traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, clone_def_id)
54+
}
55+
5056
fn type_is_sized_modulo_regions(&self, param_env: ty::ParamEnv<'tcx>, ty: Ty<'tcx>) -> bool {
5157
let lang_item = self.tcx.require_lang_item(LangItem::Sized, None);
5258
traits::type_known_to_meet_bound_modulo_regions(self, param_env, ty, lang_item)
+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#[derive(Copy, Clone)]
2+
struct Type;
3+
4+
struct NewType;
5+
6+
const fn get_size() -> usize {
7+
10
8+
}
9+
10+
fn get_dyn_size() -> usize {
11+
10
12+
}
13+
14+
fn main() {
15+
let a = ["a", 10];
16+
//~^ ERROR mismatched types
17+
//~| HELP replace the comma with a semicolon to create an array
18+
19+
const size_b: usize = 20;
20+
let b = [Type, size_b];
21+
//~^ ERROR mismatched types
22+
//~| HELP replace the comma with a semicolon to create an array
23+
24+
let size_c: usize = 13;
25+
let c = [Type, size_c];
26+
//~^ ERROR mismatched types
27+
28+
const size_d: bool = true;
29+
let d = [Type, size_d];
30+
//~^ ERROR mismatched types
31+
32+
let e = [String::new(), 10];
33+
//~^ ERROR mismatched types
34+
//~| HELP try using a conversion method
35+
36+
let f = ["f", get_size()];
37+
//~^ ERROR mismatched types
38+
//~| HELP replace the comma with a semicolon to create an array
39+
40+
let m = ["m", get_dyn_size()];
41+
//~^ ERROR mismatched types
42+
43+
// is_vec, is_clone, is_usize_like
44+
let g = vec![String::new(), 10];
45+
//~^ ERROR mismatched types
46+
//~| HELP replace the comma with a semicolon to create a vector
47+
48+
let dyn_size = 10;
49+
let h = vec![Type, dyn_size];
50+
//~^ ERROR mismatched types
51+
//~| HELP replace the comma with a semicolon to create a vector
52+
53+
let i = vec![Type, get_dyn_size()];
54+
//~^ ERROR mismatched types
55+
//~| HELP replace the comma with a semicolon to create a vector
56+
57+
let k = vec!['c', 10];
58+
//~^ ERROR mismatched types
59+
//~| HELP replace the comma with a semicolon to create a vector
60+
61+
let j = vec![Type, 10_u8];
62+
//~^ ERROR mismatched types
63+
64+
let l = vec![NewType, 10];
65+
//~^ ERROR mismatched types
66+
67+
let byte_size: u8 = 10;
68+
let h = vec![Type, byte_size];
69+
//~^ ERROR mismatched types
70+
}

0 commit comments

Comments
 (0)