Skip to content

Commit f98939c

Browse files
committed
code suggestion for non-shorthand field patterns lint
We also edit the lint description to clarify that this is different from the struct field init shorthand.
1 parent e596c1d commit f98939c

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

src/librustc_lint/builtin.rs

+9-5
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
153153
declare_lint! {
154154
NON_SHORTHAND_FIELD_PATTERNS,
155155
Warn,
156-
"using `Struct { x: x }` instead of `Struct { x }`"
156+
"using `Struct { x: x }` instead of `Struct { x }` in a pattern"
157157
}
158158

159159
#[derive(Copy, Clone)]
@@ -174,11 +174,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
174174
}
175175
if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
176176
if ident.node == fieldpat.node.name {
177-
cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS,
177+
let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
178178
fieldpat.span,
179-
&format!("the `{}:` in this pattern is redundant and can \
180-
be removed",
181-
ident.node))
179+
&format!("the `{}:` in this pattern is redundant",
180+
ident.node));
181+
let subspan = cx.tcx.sess.codemap().span_through_char(fieldpat.span, ':');
182+
err.span_suggestion_short(subspan,
183+
"remove this",
184+
format!("{}", ident.node));
185+
err.emit();
182186
}
183187
}
184188
}

src/libsyntax/codemap.rs

+11
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,17 @@ impl CodeMap {
471471
}
472472
}
473473

474+
/// Given a `Span`, try to get a shorter span ending just after the first
475+
/// occurrence of `char` `c`.
476+
pub fn span_through_char(&self, sp: Span, c: char) -> Span {
477+
if let Ok(snippet) = self.span_to_snippet(sp) {
478+
if let Some(offset) = snippet.find(c) {
479+
return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
480+
}
481+
}
482+
sp
483+
}
484+
474485
pub fn def_span(&self, sp: Span) -> Span {
475486
self.span_until_char(sp, '{')
476487
}

0 commit comments

Comments
 (0)