Add help on field binding

This commit is contained in:
Guillaume Gomez 2016-01-02 05:52:13 +01:00
parent 32cf6e32f6
commit bd8a265000
1 changed files with 33 additions and 8 deletions

View File

@ -4,7 +4,7 @@ use rustc::lint::*;
use syntax::ast::*;
use utils::span_lint;
use utils::{span_lint, span_help_and_lint};
/// **What it does:** This lint `Warn`s on struct field patterns bound to wildcards.
///
@ -27,8 +27,12 @@ impl LintPass for MiscEarly {
impl EarlyLintPass for MiscEarly {
fn check_pat(&mut self, cx: &EarlyContext, pat: &Pat) {
if let PatStruct(_, ref pfields, _) = pat.node {
if let PatStruct(ref npat, ref pfields, _) = pat.node {
let mut wilds = 0;
let type_name = match npat.segments.last() {
Some(elem) => format!("{}", elem.identifier.name),
None => String::new(),
};
for field in pfields {
if field.node.pat.node == PatWild {
@ -36,17 +40,38 @@ impl EarlyLintPass for MiscEarly {
}
}
if !pfields.is_empty() && wilds == pfields.len() {
span_lint(cx, UNNEEDED_FIELD_PATTERN, pat.span,
"All the struct fields are matched to a wildcard pattern, \
consider using `..`.");
span_help_and_lint(cx, UNNEEDED_FIELD_PATTERN, pat.span,
"All the struct fields are matched to a wildcard pattern, \
consider using `..`.",
&format!("Try with `{} {{ .. }}` instead",
type_name));
return;
}
if wilds > 0 {
let mut normal = vec!();
for field in pfields {
if field.node.pat.node != PatWild {
if let Ok(n) = cx.sess().codemap().span_to_snippet(field.span) {
normal.push(n);
}
}
}
for field in pfields {
if field.node.pat.node == PatWild {
span_lint(cx, UNNEEDED_FIELD_PATTERN, field.span,
"You matched a field with a wildcard pattern. \
Consider using `..` instead");
wilds -= 1;
if wilds > 0 {
span_lint(cx, UNNEEDED_FIELD_PATTERN, field.span,
"You matched a field with a wildcard pattern. \
Consider using `..` instead");
} else {
span_help_and_lint(cx, UNNEEDED_FIELD_PATTERN, field.span,
"You matched a field with a wildcard pattern. \
Consider using `..` instead",
&format!("Try with `{} {{ {}, .. }}`",
type_name,
normal[..].join(", ")));
}
}
}
}