Skip to content

Commit

Permalink
code suggestion for non-shorthand field patterns lint
Browse files Browse the repository at this point in the history
We also edit the lint description to clarify that this is different from
the struct field init shorthand.
  • Loading branch information
zackmdavis committed Oct 16, 2017
1 parent e596c1d commit f98939c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
14 changes: 9 additions & 5 deletions src/librustc_lint/builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for BoxPointers {
declare_lint! {
NON_SHORTHAND_FIELD_PATTERNS,
Warn,
"using `Struct { x: x }` instead of `Struct { x }`"
"using `Struct { x: x }` instead of `Struct { x }` in a pattern"
}

#[derive(Copy, Clone)]
Expand All @@ -174,11 +174,15 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonShorthandFieldPatterns {
}
if let PatKind::Binding(_, _, ident, None) = fieldpat.node.pat.node {
if ident.node == fieldpat.node.name {
cx.span_lint(NON_SHORTHAND_FIELD_PATTERNS,
let mut err = cx.struct_span_lint(NON_SHORTHAND_FIELD_PATTERNS,
fieldpat.span,
&format!("the `{}:` in this pattern is redundant and can \
be removed",
ident.node))
&format!("the `{}:` in this pattern is redundant",
ident.node));
let subspan = cx.tcx.sess.codemap().span_through_char(fieldpat.span, ':');
err.span_suggestion_short(subspan,
"remove this",
format!("{}", ident.node));
err.emit();
}
}
}
Expand Down
11 changes: 11 additions & 0 deletions src/libsyntax/codemap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,17 @@ impl CodeMap {
}
}

/// Given a `Span`, try to get a shorter span ending just after the first
/// occurrence of `char` `c`.
pub fn span_through_char(&self, sp: Span, c: char) -> Span {
if let Ok(snippet) = self.span_to_snippet(sp) {
if let Some(offset) = snippet.find(c) {
return sp.with_hi(BytePos(sp.lo().0 + (offset + c.len_utf8()) as u32));
}
}
sp
}

pub fn def_span(&self, sp: Span) -> Span {
self.span_until_char(sp, '{')
}
Expand Down

0 comments on commit f98939c

Please sign in to comment.