Skip to content

Commit 98cc345

Browse files
Suggest Semicolon in Incorrect Repeat Expressions
1 parent 872aa75 commit 98cc345

File tree

9 files changed

+144
-25
lines changed

9 files changed

+144
-25
lines changed

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,
@@ -2064,6 +2064,18 @@ impl Expr<'_> {
20642064
}
20652065
}
20662066

2067+
/// Check if expression is an integer literal that can be used
2068+
/// where `usize` is expected.
2069+
pub fn is_size_lit(&self) -> bool {
2070+
matches!(
2071+
self.kind,
2072+
ExprKind::Lit(Lit {
2073+
node: LitKind::Int(_, LitIntType::Unsuffixed | LitIntType::Unsigned(UintTy::Usize)),
2074+
..
2075+
})
2076+
)
2077+
}
2078+
20672079
/// If `Self.kind` is `ExprKind::DropTemps(expr)`, drill down until we get a non-`DropTemps`
20682080
/// `Expr`. This is used in suggestions to ignore this `ExprKind` as it is semantically
20692081
/// 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
@@ -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...

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)

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

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

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

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

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
@@ -1008,6 +1008,18 @@ impl<'tcx> Ty<'tcx> {
10081008
}
10091009
}
10101010

1011+
/// Check if type is an `usize`.
1012+
#[inline]
1013+
pub fn is_usize(self) -> bool {
1014+
matches!(self.kind(), Uint(UintTy::Usize))
1015+
}
1016+
1017+
/// Check if type is an `usize` or an integral type variable.
1018+
#[inline]
1019+
pub fn is_usize_like(self) -> bool {
1020+
matches!(self.kind(), Uint(UintTy::Usize) | Infer(IntVar(_)))
1021+
}
1022+
10111023
#[inline]
10121024
pub fn is_never(self) -> bool {
10131025
matches!(self.kind(), Never)

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)

tests/ui/repeat-expr/typo-in-repeat-expr-issue-80173.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,12 @@ fn get_dyn_size() -> usize {
1414
fn main() {
1515
let a = ["a", 10];
1616
//~^ ERROR mismatched types
17-
//~| HELP replace comma with semicolon to create an array
17+
//~| HELP replace the comma with a semicolon to create an array
1818

1919
const size_b: usize = 20;
2020
let b = [Type, size_b];
2121
//~^ ERROR mismatched types
22-
//~| HELP replace comma with semicolon to create an array
22+
//~| HELP replace the comma with a semicolon to create an array
2323

2424
let size_c: usize = 13;
2525
let c = [Type, size_c];
@@ -35,28 +35,28 @@ fn main() {
3535

3636
let f = ["f", get_size()];
3737
//~^ ERROR mismatched types
38-
//~| HELP replace comma with semicolon to create an array
38+
//~| HELP replace the comma with a semicolon to create an array
3939

4040
let m = ["m", get_dyn_size()];
4141
//~^ ERROR mismatched types
4242

4343
// is_vec, is_clone, is_usize_like
4444
let g = vec![String::new(), 10];
4545
//~^ ERROR mismatched types
46-
//~| HELP replace comma with semicolon to create a vector
46+
//~| HELP replace the comma with a semicolon to create a vector
4747

4848
let dyn_size = 10;
4949
let h = vec![Type, dyn_size];
5050
//~^ ERROR mismatched types
51-
//~| HELP replace comma with semicolon to create a vector
51+
//~| HELP replace the comma with a semicolon to create a vector
5252

5353
let i = vec![Type, get_dyn_size()];
5454
//~^ ERROR mismatched types
55-
//~| HELP replace comma with semicolon to create a vector
55+
//~| HELP replace the comma with a semicolon to create a vector
5656

5757
let k = vec!['c', 10];
5858
//~^ ERROR mismatched types
59-
//~| HELP replace comma with semicolon to create a vector
59+
//~| HELP replace the comma with a semicolon to create a vector
6060

6161
let j = vec![Type, 10_u8];
6262
//~^ ERROR mismatched types

tests/ui/repeat-expr/typo-in-repeat-expr-issue-80173.stderr

+7-7
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ error[E0308]: mismatched types
44
LL | let a = ["a", 10];
55
| ^^ expected `&str`, found integer
66
|
7-
help: replace comma with semicolon to create an array
7+
help: replace the comma with a semicolon to create an array
88
|
99
LL | let a = ["a"; 10];
1010
| ~
@@ -15,7 +15,7 @@ error[E0308]: mismatched types
1515
LL | let b = [Type, size_b];
1616
| ^^^^^^ expected `Type`, found `usize`
1717
|
18-
help: replace comma with semicolon to create an array
18+
help: replace the comma with a semicolon to create an array
1919
|
2020
LL | let b = [Type; size_b];
2121
| ~
@@ -46,7 +46,7 @@ error[E0308]: mismatched types
4646
LL | let f = ["f", get_size()];
4747
| ^^^^^^^^^^ expected `&str`, found `usize`
4848
|
49-
help: replace comma with semicolon to create an array
49+
help: replace the comma with a semicolon to create an array
5050
|
5151
LL | let f = ["f"; get_size()];
5252
| ~
@@ -63,7 +63,7 @@ error[E0308]: mismatched types
6363
LL | let g = vec![String::new(), 10];
6464
| ^^ expected `String`, found integer
6565
|
66-
help: replace comma with semicolon to create a vector
66+
help: replace the comma with a semicolon to create a vector
6767
|
6868
LL | let g = vec![String::new(); 10];
6969
| ~
@@ -74,7 +74,7 @@ error[E0308]: mismatched types
7474
LL | let h = vec![Type, dyn_size];
7575
| ^^^^^^^^ expected `Type`, found integer
7676
|
77-
help: replace comma with semicolon to create a vector
77+
help: replace the comma with a semicolon to create a vector
7878
|
7979
LL | let h = vec![Type; dyn_size];
8080
| ~
@@ -85,7 +85,7 @@ error[E0308]: mismatched types
8585
LL | let i = vec![Type, get_dyn_size()];
8686
| ^^^^^^^^^^^^^^ expected `Type`, found `usize`
8787
|
88-
help: replace comma with semicolon to create a vector
88+
help: replace the comma with a semicolon to create a vector
8989
|
9090
LL | let i = vec![Type; get_dyn_size()];
9191
| ~
@@ -96,7 +96,7 @@ error[E0308]: mismatched types
9696
LL | let k = vec!['c', 10];
9797
| ^^ expected `char`, found `u8`
9898
|
99-
help: replace comma with semicolon to create a vector
99+
help: replace the comma with a semicolon to create a vector
100100
|
101101
LL | let k = vec!['c'; 10];
102102
| ~

0 commit comments

Comments
 (0)