From 8552c61c5a8e91b30bd35e4711d39d470c83cbb1 Mon Sep 17 00:00:00 2001 From: Kevin Leimkuhler Date: Mon, 1 Oct 2018 22:32:26 -0700 Subject: [PATCH 01/21] Add initial impl of check_pat() for UnusedParens This uses a copied version of `check_unused_parens_expr` that is specific to `ast::Pat`. `check_unused_parens_` could possibly be made more generic to work with any `ast::*` that has `node` and `span` fields. This also only checks for the case of parens around the wildcard pattern. It covers the case highlighted in the issue, but could check for a lot more. --- src/librustc_lint/unused.rs | 72 ++++++++++++++++++++++++++++++++++--- 1 file changed, 68 insertions(+), 4 deletions(-) diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index ae178888b6a1c..b559b7b8cd8c0 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -264,7 +264,7 @@ declare_lint! { pub struct UnusedParens; impl UnusedParens { - fn check_unused_parens_core(&self, + fn check_unused_parens_expr(&self, cx: &EarlyContext, value: &ast::Expr, msg: &str, @@ -313,6 +313,56 @@ impl UnusedParens { } } } + + fn check_unused_parens_pat(&self, + cx: &EarlyContext, + value: &ast::Pat, + msg: &str, + struct_lit_needs_parens: bool) { + if let ast::PatKind::Paren(_) = value.node { + // Does there need to be a check similar to `parser::contains_exterior_struct_lit` + // here? + if !struct_lit_needs_parens { + let span_msg = format!("unnecessary parentheses around {}", msg); + let mut err = cx.struct_span_lint(UNUSED_PARENS, + value.span, + &span_msg); + // Remove exactly one pair of parentheses (rather than naïvely + // stripping all paren characters) + let mut ate_left_paren = false; + let mut ate_right_paren = false; + let parens_removed = pprust::pat_to_string(value) + .trim_matches(|c| { + match c { + '(' => { + if ate_left_paren { + false + } else { + ate_left_paren = true; + true + } + }, + ')' => { + if ate_right_paren { + false + } else { + ate_right_paren = true; + true + } + }, + _ => false, + } + }).to_owned(); + err.span_suggestion_short_with_applicability( + value.span, + "remove these parentheses", + parens_removed, + Applicability::MachineApplicable + ); + err.emit(); + } + } + } } impl LintPass for UnusedParens { @@ -354,18 +404,32 @@ impl EarlyLintPass for UnusedParens { } let msg = format!("{} argument", call_kind); for arg in args_to_check { - self.check_unused_parens_core(cx, arg, &msg, false); + self.check_unused_parens_expr(cx, arg, &msg, false); } return; } }; - self.check_unused_parens_core(cx, &value, msg, struct_lit_needs_parens); + self.check_unused_parens_expr(cx, &value, msg, struct_lit_needs_parens); + } + + fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat) { + use ast::PatKind::*; + let (value, msg) = match p.node { + Paren(ref pat) => { + match pat.node { + Wild => (p, "wildcard pattern"), + _ => return, + } + } + _ => return, + }; + self.check_unused_parens_pat(cx, &value, msg, false); } fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) { if let ast::StmtKind::Local(ref local) = s.node { if let Some(ref value) = local.init { - self.check_unused_parens_core(cx, &value, "assigned value", false); + self.check_unused_parens_expr(cx, &value, "assigned value", false); } } } From 5217527a5b2e09342e00cf8571e8af22f50546c3 Mon Sep 17 00:00:00 2001 From: Kevin Leimkuhler Date: Thu, 4 Oct 2018 09:36:55 -0700 Subject: [PATCH 02/21] Share outer paren trimming logic --- src/librustc_lint/unused.rs | 130 +++++++++++++----------------------- 1 file changed, 46 insertions(+), 84 deletions(-) diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index b559b7b8cd8c0..a176bd8302609 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -273,43 +273,8 @@ impl UnusedParens { let necessary = struct_lit_needs_parens && parser::contains_exterior_struct_lit(&inner); if !necessary { - let span_msg = format!("unnecessary parentheses around {}", msg); - let mut err = cx.struct_span_lint(UNUSED_PARENS, - value.span, - &span_msg); - // Remove exactly one pair of parentheses (rather than naïvely - // stripping all paren characters) - let mut ate_left_paren = false; - let mut ate_right_paren = false; - let parens_removed = pprust::expr_to_string(value) - .trim_matches(|c| { - match c { - '(' => { - if ate_left_paren { - false - } else { - ate_left_paren = true; - true - } - }, - ')' => { - if ate_right_paren { - false - } else { - ate_right_paren = true; - true - } - }, - _ => false, - } - }).to_owned(); - err.span_suggestion_short_with_applicability( - value.span, - "remove these parentheses", - parens_removed, - Applicability::MachineApplicable - ); - err.emit(); + let pattern = pprust::expr_to_string(value); + Self::remove_outer_parens(cx, value.span, &pattern, msg) } } } @@ -320,49 +285,48 @@ impl UnusedParens { msg: &str, struct_lit_needs_parens: bool) { if let ast::PatKind::Paren(_) = value.node { - // Does there need to be a check similar to `parser::contains_exterior_struct_lit` - // here? if !struct_lit_needs_parens { - let span_msg = format!("unnecessary parentheses around {}", msg); - let mut err = cx.struct_span_lint(UNUSED_PARENS, - value.span, - &span_msg); - // Remove exactly one pair of parentheses (rather than naïvely - // stripping all paren characters) - let mut ate_left_paren = false; - let mut ate_right_paren = false; - let parens_removed = pprust::pat_to_string(value) - .trim_matches(|c| { - match c { - '(' => { - if ate_left_paren { - false - } else { - ate_left_paren = true; - true - } - }, - ')' => { - if ate_right_paren { - false - } else { - ate_right_paren = true; - true - } - }, - _ => false, - } - }).to_owned(); - err.span_suggestion_short_with_applicability( - value.span, - "remove these parentheses", - parens_removed, - Applicability::MachineApplicable - ); - err.emit(); + let pattern = pprust::pat_to_string(value); + Self::remove_outer_parens(cx, value.span, &pattern, msg) } } } + + fn remove_outer_parens(cx: &EarlyContext, span: Span, pattern: &str, msg: &str) { + let span_msg = format!("unnecessary parentheses around {}", msg); + let mut err = cx.struct_span_lint(UNUSED_PARENS, span, &span_msg); + let mut ate_left_paren = false; + let mut ate_right_paren = false; + let parens_removed = pattern + .trim_matches(|c| { + match c { + '(' => { + if ate_left_paren { + false + } else { + ate_left_paren = true; + true + } + }, + ')' => { + if ate_right_paren { + false + } else { + ate_right_paren = true; + true + } + }, + _ => false, + } + }).to_owned(); + err.span_suggestion_short_with_applicability( + span, + "remove these parentheses", + parens_removed, + Applicability::MachineApplicable + ); + err.emit(); + } } impl LintPass for UnusedParens { @@ -414,16 +378,14 @@ impl EarlyLintPass for UnusedParens { fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat) { use ast::PatKind::*; - let (value, msg) = match p.node { - Paren(ref pat) => { - match pat.node { - Wild => (p, "wildcard pattern"), - _ => return, - } - } + let (value, msg, struct_lit_needs_parens) = match p.node { + Ident(.., Some(ref pat)) => (pat, "optional subpattern", false), + Ref(ref pat, _) => (pat, "reference pattern", false), + Slice(_, Some(ref pat), _) => (pat, "optional position pattern", false), + Paren(_) => (p, "pattern", false), _ => return, }; - self.check_unused_parens_pat(cx, &value, msg, false); + self.check_unused_parens_pat(cx, &value, msg, struct_lit_needs_parens); } fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) { From 46b07d670a168e832391bba35d58f823cd00b76d Mon Sep 17 00:00:00 2001 From: Kevin Leimkuhler Date: Fri, 5 Oct 2018 19:09:14 -0700 Subject: [PATCH 03/21] Simply unused_parens check and add tests --- src/librustc_lint/unused.rs | 27 +++++------- src/test/run-pass/binding/pat-tuple-7.rs | 2 +- .../ui/lint/issue-54538-unused-parens-lint.rs | 42 +++++++++++++++++++ .../issue-54538-unused-parens-lint.stderr | 42 +++++++++++++++++++ 4 files changed, 95 insertions(+), 18 deletions(-) create mode 100644 src/test/ui/lint/issue-54538-unused-parens-lint.rs create mode 100644 src/test/ui/lint/issue-54538-unused-parens-lint.stderr diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index a176bd8302609..0ef46e77280db 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -274,7 +274,7 @@ impl UnusedParens { parser::contains_exterior_struct_lit(&inner); if !necessary { let pattern = pprust::expr_to_string(value); - Self::remove_outer_parens(cx, value.span, &pattern, msg) + Self::remove_outer_parens(cx, value.span, &pattern, msg); } } } @@ -282,13 +282,10 @@ impl UnusedParens { fn check_unused_parens_pat(&self, cx: &EarlyContext, value: &ast::Pat, - msg: &str, - struct_lit_needs_parens: bool) { + msg: &str) { if let ast::PatKind::Paren(_) = value.node { - if !struct_lit_needs_parens { - let pattern = pprust::pat_to_string(value); - Self::remove_outer_parens(cx, value.span, &pattern, msg) - } + let pattern = pprust::pat_to_string(value); + Self::remove_outer_parens(cx, value.span, &pattern, msg); } } @@ -355,7 +352,9 @@ impl EarlyLintPass for UnusedParens { // first "argument" is self (which sometimes needs parens) MethodCall(_, ref args) => (&args[1..], "method"), // actual catch-all arm - _ => { return; } + _ => { + return; + } }; // Don't lint if this is a nested macro expansion: otherwise, the lint could // trigger in situations that macro authors shouldn't have to care about, e.g., @@ -377,15 +376,9 @@ impl EarlyLintPass for UnusedParens { } fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat) { - use ast::PatKind::*; - let (value, msg, struct_lit_needs_parens) = match p.node { - Ident(.., Some(ref pat)) => (pat, "optional subpattern", false), - Ref(ref pat, _) => (pat, "reference pattern", false), - Slice(_, Some(ref pat), _) => (pat, "optional position pattern", false), - Paren(_) => (p, "pattern", false), - _ => return, - }; - self.check_unused_parens_pat(cx, &value, msg, struct_lit_needs_parens); + if let ast::PatKind::Paren(_) = p.node { + self.check_unused_parens_pat(cx, &p, "pattern"); + } } fn check_stmt(&mut self, cx: &EarlyContext, s: &ast::Stmt) { diff --git a/src/test/run-pass/binding/pat-tuple-7.rs b/src/test/run-pass/binding/pat-tuple-7.rs index c32b52eac33d1..f02e3198984f4 100644 --- a/src/test/run-pass/binding/pat-tuple-7.rs +++ b/src/test/run-pass/binding/pat-tuple-7.rs @@ -12,6 +12,6 @@ fn main() { match 0 { - (pat) => assert_eq!(pat, 0) + pat => assert_eq!(pat, 0) } } diff --git a/src/test/ui/lint/issue-54538-unused-parens-lint.rs b/src/test/ui/lint/issue-54538-unused-parens-lint.rs new file mode 100644 index 0000000000000..5702a8941d466 --- /dev/null +++ b/src/test/ui/lint/issue-54538-unused-parens-lint.rs @@ -0,0 +1,42 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// compile-pass + +#![allow(unreachable_patterns)] +#![allow(unused_variables)] +#![warn(unused_parens)] + +struct A { + field: Option, +} + +fn main() { + let x = 3; + match x { + (_) => {} //~ WARNING: unnecessary parentheses around pattern + (y) => {} //~ WARNING: unnecessary parentheses around pattern + (ref r) => {} //~ WARNING: unnecessary parentheses around pattern + e @ 1...2 | (e @ (3...4)) => {} + //~^ WARNING: unnecessary parentheses around pattern (3 ... 4) + //~^ WARNING: unnecessary parentheses around pattern (e @ _) + } + + let field = "foo".to_string(); + let x: Option = Some(A { field: Some(field) }); + match x { + Some(A { + field: (ref a @ Some(_)), + //~^ WARNING: unnecessary parentheses around pattern + .. + }) => {} + _ => {} + } +} diff --git a/src/test/ui/lint/issue-54538-unused-parens-lint.stderr b/src/test/ui/lint/issue-54538-unused-parens-lint.stderr new file mode 100644 index 0000000000000..7d9eb697fd7ea --- /dev/null +++ b/src/test/ui/lint/issue-54538-unused-parens-lint.stderr @@ -0,0 +1,42 @@ +warning: unnecessary parentheses around pattern + --> $DIR/issue-54538-unused-parens-lint.rs:24:9 + | +LL | (_) => {} //~ WARNING: unnecessary parentheses around pattern + | ^^^ help: remove these parentheses + | +note: lint level defined here + --> $DIR/issue-54538-unused-parens-lint.rs:15:9 + | +LL | #![warn(unused_parens)] + | ^^^^^^^^^^^^^ + +warning: unnecessary parentheses around pattern + --> $DIR/issue-54538-unused-parens-lint.rs:25:9 + | +LL | (y) => {} //~ WARNING: unnecessary parentheses around pattern + | ^^^ help: remove these parentheses + +warning: unnecessary parentheses around pattern + --> $DIR/issue-54538-unused-parens-lint.rs:26:9 + | +LL | (ref r) => {} //~ WARNING: unnecessary parentheses around pattern + | ^^^^^^^ help: remove these parentheses + +warning: unnecessary parentheses around pattern + --> $DIR/issue-54538-unused-parens-lint.rs:27:21 + | +LL | e @ 1...2 | (e @ (3...4)) => {} + | ^^^^^^^^^^^^^ help: remove these parentheses + +warning: unnecessary parentheses around pattern + --> $DIR/issue-54538-unused-parens-lint.rs:27:26 + | +LL | e @ 1...2 | (e @ (3...4)) => {} + | ^^^^^^^ help: remove these parentheses + +warning: unnecessary parentheses around pattern + --> $DIR/issue-54538-unused-parens-lint.rs:36:20 + | +LL | field: (ref a @ Some(_)), + | ^^^^^^^^^^^^^^^^^ help: remove these parentheses + From 47014df79083f837323aa60021b893d2a33a9828 Mon Sep 17 00:00:00 2001 From: Kevin Leimkuhler Date: Sat, 6 Oct 2018 19:48:04 -0700 Subject: [PATCH 04/21] Fix Range warning and improve tests --- src/librustc_lint/unused.rs | 8 +++- .../ui/lint/issue-54538-unused-parens-lint.rs | 38 +++++++++---------- .../issue-54538-unused-parens-lint.stderr | 30 +++++++-------- 3 files changed, 38 insertions(+), 38 deletions(-) diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 0ef46e77280db..050e52d2e0cdd 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -376,8 +376,12 @@ impl EarlyLintPass for UnusedParens { } fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat) { - if let ast::PatKind::Paren(_) = p.node { - self.check_unused_parens_pat(cx, &p, "pattern"); + use ast::PatKind::{Paren, Range}; + if let Paren(ref pat) = p.node { + match pat.node { + Range(..) => {} + _ => self.check_unused_parens_pat(cx, &p, "pattern") + } } } diff --git a/src/test/ui/lint/issue-54538-unused-parens-lint.rs b/src/test/ui/lint/issue-54538-unused-parens-lint.rs index 5702a8941d466..97a2dd59a6209 100644 --- a/src/test/ui/lint/issue-54538-unused-parens-lint.rs +++ b/src/test/ui/lint/issue-54538-unused-parens-lint.rs @@ -14,29 +14,25 @@ #![allow(unused_variables)] #![warn(unused_parens)] -struct A { - field: Option, -} - fn main() { - let x = 3; - match x { - (_) => {} //~ WARNING: unnecessary parentheses around pattern - (y) => {} //~ WARNING: unnecessary parentheses around pattern - (ref r) => {} //~ WARNING: unnecessary parentheses around pattern - e @ 1...2 | (e @ (3...4)) => {} - //~^ WARNING: unnecessary parentheses around pattern (3 ... 4) - //~^ WARNING: unnecessary parentheses around pattern (e @ _) + match 1 { + (_) => {} //~ WARNING: unnecessary parentheses around pattern + (y) => {} //~ WARNING: unnecessary parentheses around pattern + (ref r) => {} //~ WARNING: unnecessary parentheses around pattern + (e @ 1..=2) => {} //~ WARNING: unnecessary parentheses around outer pattern + (1..=2) => {} // Non ambiguous range pattern should not warn + e @ (3..=4) => {} // Non ambiguous range pattern should not warn + } + + match &1 { + (e @ &(1...2)) => {} //~ WARNING: unnecessary parentheses around outer pattern + &(_) => {} //~ WARNING: unnecessary parentheses around pattern + e @ &(1...2) => {} // Ambiguous range pattern should not warn + &(1..=2) => {} // Ambiguous range pattern should not warn } - let field = "foo".to_string(); - let x: Option = Some(A { field: Some(field) }); - match x { - Some(A { - field: (ref a @ Some(_)), - //~^ WARNING: unnecessary parentheses around pattern - .. - }) => {} - _ => {} + match &1 { + e @ &(1...2) | e @ &(3..=4) => {} // Complex ambiguous pattern should not warn + &_ => {} } } diff --git a/src/test/ui/lint/issue-54538-unused-parens-lint.stderr b/src/test/ui/lint/issue-54538-unused-parens-lint.stderr index 7d9eb697fd7ea..b76b969fd2b1a 100644 --- a/src/test/ui/lint/issue-54538-unused-parens-lint.stderr +++ b/src/test/ui/lint/issue-54538-unused-parens-lint.stderr @@ -1,7 +1,7 @@ warning: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:24:9 + --> $DIR/issue-54538-unused-parens-lint.rs:19:9 | -LL | (_) => {} //~ WARNING: unnecessary parentheses around pattern +LL | (_) => {} //~ WARNING: unnecessary parentheses around pattern | ^^^ help: remove these parentheses | note: lint level defined here @@ -11,32 +11,32 @@ LL | #![warn(unused_parens)] | ^^^^^^^^^^^^^ warning: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:25:9 + --> $DIR/issue-54538-unused-parens-lint.rs:20:9 | -LL | (y) => {} //~ WARNING: unnecessary parentheses around pattern +LL | (y) => {} //~ WARNING: unnecessary parentheses around pattern | ^^^ help: remove these parentheses warning: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:26:9 + --> $DIR/issue-54538-unused-parens-lint.rs:21:9 | -LL | (ref r) => {} //~ WARNING: unnecessary parentheses around pattern +LL | (ref r) => {} //~ WARNING: unnecessary parentheses around pattern | ^^^^^^^ help: remove these parentheses warning: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:27:21 + --> $DIR/issue-54538-unused-parens-lint.rs:22:9 | -LL | e @ 1...2 | (e @ (3...4)) => {} - | ^^^^^^^^^^^^^ help: remove these parentheses +LL | (e @ 1..=2) => {} //~ WARNING: unnecessary parentheses around outer pattern + | ^^^^^^^^^^^ help: remove these parentheses warning: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:27:26 + --> $DIR/issue-54538-unused-parens-lint.rs:28:9 | -LL | e @ 1...2 | (e @ (3...4)) => {} - | ^^^^^^^ help: remove these parentheses +LL | (e @ &(1...2)) => {} //~ WARNING: unnecessary parentheses around outer pattern + | ^^^^^^^^^^^^^^ help: remove these parentheses warning: unnecessary parentheses around pattern - --> $DIR/issue-54538-unused-parens-lint.rs:36:20 + --> $DIR/issue-54538-unused-parens-lint.rs:29:10 | -LL | field: (ref a @ Some(_)), - | ^^^^^^^^^^^^^^^^^ help: remove these parentheses +LL | &(_) => {} //~ WARNING: unnecessary parentheses around pattern + | ^^^ help: remove these parentheses From 0e411c2597dcfe75dd76acefcecec916a950ac6e Mon Sep 17 00:00:00 2001 From: Kevin Leimkuhler Date: Tue, 9 Oct 2018 17:37:45 -0700 Subject: [PATCH 05/21] Add clarifying pattern lint comment and revert test --- src/librustc_lint/unused.rs | 4 ++++ src/test/run-pass/binding/pat-tuple-7.rs | 3 ++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/librustc_lint/unused.rs b/src/librustc_lint/unused.rs index 050e52d2e0cdd..297b60d57289f 100644 --- a/src/librustc_lint/unused.rs +++ b/src/librustc_lint/unused.rs @@ -377,6 +377,10 @@ impl EarlyLintPass for UnusedParens { fn check_pat(&mut self, cx: &EarlyContext, p: &ast::Pat) { use ast::PatKind::{Paren, Range}; + // The lint visitor will visit each subpattern of `p`. We do not want to lint any range + // pattern no matter where it occurs in the pattern. For something like `&(a..=b)`, there + // is a recursive `check_pat` on `a` and `b`, but we will assume that if there are + // unnecessry parens they serve a purpose of readability. if let Paren(ref pat) = p.node { match pat.node { Range(..) => {} diff --git a/src/test/run-pass/binding/pat-tuple-7.rs b/src/test/run-pass/binding/pat-tuple-7.rs index f02e3198984f4..06bd14d188e34 100644 --- a/src/test/run-pass/binding/pat-tuple-7.rs +++ b/src/test/run-pass/binding/pat-tuple-7.rs @@ -11,7 +11,8 @@ // run-pass fn main() { + #[allow(unused_parens)] match 0 { - pat => assert_eq!(pat, 0) + (pat) => assert_eq!(pat, 0) } } From 3855af573475f7dbdc143b477f73362b7f0723d2 Mon Sep 17 00:00:00 2001 From: Andy Russell Date: Thu, 11 Oct 2018 11:32:57 -0400 Subject: [PATCH 06/21] add test for #23189 Fixes #23189. --- src/test/ui/issues/issue-23189.rs | 15 +++++++++++++++ src/test/ui/issues/issue-23189.stderr | 9 +++++++++ 2 files changed, 24 insertions(+) create mode 100644 src/test/ui/issues/issue-23189.rs create mode 100644 src/test/ui/issues/issue-23189.stderr diff --git a/src/test/ui/issues/issue-23189.rs b/src/test/ui/issues/issue-23189.rs new file mode 100644 index 0000000000000..7a475d1a6abdb --- /dev/null +++ b/src/test/ui/issues/issue-23189.rs @@ -0,0 +1,15 @@ +// Copyright 2018 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +mod module {} + +fn main() { + let _ = module { x: 0 }; //~ERROR expected struct +} diff --git a/src/test/ui/issues/issue-23189.stderr b/src/test/ui/issues/issue-23189.stderr new file mode 100644 index 0000000000000..c7bbab4524dc8 --- /dev/null +++ b/src/test/ui/issues/issue-23189.stderr @@ -0,0 +1,9 @@ +error[E0574]: expected struct, variant or union type, found module `module` + --> $DIR/issue-23189.rs:14:13 + | +LL | let _ = module { x: 0 }; //~ERROR expected struct + | ^^^^^^ not a struct, variant or union type + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0574`. From 09f42dd9029f0913355a9c52d6a0c6642f0e6e52 Mon Sep 17 00:00:00 2001 From: Eric Huss Date: Fri, 12 Oct 2018 17:51:48 -0700 Subject: [PATCH 07/21] Add missing lifetime fragment specifier to error message. A very minor issue, `lifetime` was missing from the error list. I left `literal` in the list, even though it is unstable. It looks like it may stabilize soon anyways. --- src/libsyntax/ext/tt/macro_rules.rs | 11 ++++++----- src/test/ui/issues/issue-21356.stderr | 2 +- src/test/ui/macros/macro-invalid-fragment-spec.stderr | 2 +- .../ui/unused/unused-macro-with-bad-frag-spec.stderr | 2 +- 4 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/libsyntax/ext/tt/macro_rules.rs b/src/libsyntax/ext/tt/macro_rules.rs index 214bc9cffc483..87ade278c685a 100644 --- a/src/libsyntax/ext/tt/macro_rules.rs +++ b/src/libsyntax/ext/tt/macro_rules.rs @@ -34,6 +34,10 @@ use std::collections::hash_map::Entry; use rustc_data_structures::sync::Lrc; use errors::Applicability; +const VALID_FRAGMENT_NAMES_MSG: &str = "valid fragment specifiers are \ + `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, \ + `path`, `meta`, `tt`, `item` and `vis`"; + pub struct ParserAnyMacro<'a> { parser: Parser<'a>, @@ -708,8 +712,7 @@ fn check_matcher_core(sess: &ParseSess, if let Err(bad_frag) = has_legal_fragment_specifier(sess, features, attrs, token) { let msg = format!("invalid fragment specifier `{}`", bad_frag); sess.span_diagnostic.struct_span_err(token.span(), &msg) - .help("valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, \ - `pat`, `ty`, `literal`, `path`, `meta`, `tt`, `item` and `vis`") + .help(VALID_FRAGMENT_NAMES_MSG) .emit(); // (This eliminates false positives and duplicates // from error messages.) @@ -938,9 +941,7 @@ fn is_in_follow(tok: "ed::TokenTree, frag: &str) -> Result Ok(true), // keywords::Invalid _ => Err((format!("invalid fragment specifier `{}`", frag), - "valid fragment specifiers are `ident`, `block`, \ - `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt`, \ - `literal`, `item` and `vis`")) + VALID_FRAGMENT_NAMES_MSG)) } } } diff --git a/src/test/ui/issues/issue-21356.stderr b/src/test/ui/issues/issue-21356.stderr index 5787476c2f235..924767fb5e17a 100644 --- a/src/test/ui/issues/issue-21356.stderr +++ b/src/test/ui/issues/issue-21356.stderr @@ -4,7 +4,7 @@ error: invalid fragment specifier `t_ty` LL | macro_rules! test { ($wrong:t_ty ..) => () } | ^^^^^^^^^^^ | - = help: valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `literal`, `path`, `meta`, `tt`, `item` and `vis` + = help: valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, `path`, `meta`, `tt`, `item` and `vis` error: aborting due to previous error diff --git a/src/test/ui/macros/macro-invalid-fragment-spec.stderr b/src/test/ui/macros/macro-invalid-fragment-spec.stderr index 765621f51d4fd..e683d47cf5482 100644 --- a/src/test/ui/macros/macro-invalid-fragment-spec.stderr +++ b/src/test/ui/macros/macro-invalid-fragment-spec.stderr @@ -4,7 +4,7 @@ error: invalid fragment specifier `foo` LL | ($x:foo) => () | ^^^^^^ | - = help: valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `literal`, `path`, `meta`, `tt`, `item` and `vis` + = help: valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, `path`, `meta`, `tt`, `item` and `vis` error: aborting due to previous error diff --git a/src/test/ui/unused/unused-macro-with-bad-frag-spec.stderr b/src/test/ui/unused/unused-macro-with-bad-frag-spec.stderr index 8843587890549..20b1ae690ec82 100644 --- a/src/test/ui/unused/unused-macro-with-bad-frag-spec.stderr +++ b/src/test/ui/unused/unused-macro-with-bad-frag-spec.stderr @@ -4,7 +4,7 @@ error: invalid fragment specifier `t_ty` LL | ($wrong:t_ty) => () //~ ERROR invalid fragment specifier `t_ty` | ^^^^^^^^^^^ | - = help: valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `literal`, `path`, `meta`, `tt`, `item` and `vis` + = help: valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, `path`, `meta`, `tt`, `item` and `vis` error: aborting due to previous error From af6c871fa1e32edb9767226aa13b09c60e3aeda5 Mon Sep 17 00:00:00 2001 From: Tshepang Lekhonkhobe Date: Sat, 13 Oct 2018 19:28:18 +0200 Subject: [PATCH 08/21] doc: make core::fmt::Error example more simple --- src/libcore/fmt/mod.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/libcore/fmt/mod.rs b/src/libcore/fmt/mod.rs index bd253e69db319..75ec0d7d50be6 100644 --- a/src/libcore/fmt/mod.rs +++ b/src/libcore/fmt/mod.rs @@ -96,9 +96,8 @@ pub type Result = result::Result<(), Error>; /// use std::fmt::{self, write}; /// /// let mut output = String::new(); -/// match write(&mut output, format_args!("Hello {}!", "world")) { -/// Err(fmt::Error) => panic!("An error occurred"), -/// _ => (), +/// if let Err(fmt::Error) = write(&mut output, format_args!("Hello {}!", "world")) { +/// panic!("An error occurred"); /// } /// ``` #[stable(feature = "rust1", since = "1.0.0")] From 12b5c7b26dd5d9dd17a6f4241b5e8baf6d17a682 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Sat, 13 Oct 2018 20:51:25 +0200 Subject: [PATCH 09/21] Don't collect to vectors where unnecessary --- src/librustc/hir/lowering.rs | 5 +---- src/librustc_traits/lowering.rs | 7 ++----- src/librustc_typeck/check/demand.rs | 10 +++++----- 3 files changed, 8 insertions(+), 14 deletions(-) diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 4d51126621d7d..e99d65024967b 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -60,7 +60,6 @@ use util::nodemap::{DefIdMap, NodeMap}; use std::collections::BTreeMap; use std::fmt::Debug; -use std::iter; use std::mem; use smallvec::SmallVec; use syntax::attr; @@ -3888,9 +3887,7 @@ impl<'a> LoweringContext<'a> { .collect::>(); let is_unit = fields.is_empty(); - let struct_path = iter::once("ops") - .chain(iter::once(path)) - .collect::>(); + let struct_path = ["ops", path]; let struct_path = self.std_path(e.span, &struct_path, None, is_unit); let struct_path = hir::QPath::Resolved(None, P(struct_path)); diff --git a/src/librustc_traits/lowering.rs b/src/librustc_traits/lowering.rs index 181106d3f84bf..1e3f0a21cefb3 100644 --- a/src/librustc_traits/lowering.rs +++ b/src/librustc_traits/lowering.rs @@ -306,8 +306,7 @@ fn program_clauses_for_trait<'a, 'tcx>( let wf_conditions = iter::once(ty::Binder::dummy(trait_pred.lower())) .chain( where_clauses - .iter() - .cloned() + .into_iter() .map(|wc| wc.map_bound(|goal| goal.into_well_formed_goal())) ); @@ -350,15 +349,13 @@ fn program_clauses_for_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId // `WC` let where_clauses = tcx.predicates_of(def_id).predicates .into_iter() - .map(|(wc, _)| wc.lower()) - .collect::>(); + .map(|(wc, _)| wc.lower()); // `Implemented(A0: Trait) :- WC` let clause = ProgramClause { goal: trait_pred, hypotheses: tcx.mk_goals( where_clauses - .into_iter() .map(|wc| tcx.mk_goal(GoalKind::from_poly_domain_goal(wc, tcx))), ), }; diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index 85b6bcbd144fc..d82d36a1937bf 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -115,7 +115,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { // field is of the found type, suggest such variants. See Issue // #42764. if let ty::Adt(expected_adt, substs) = expected.sty { - let compatible_variants = expected_adt.variants + let mut compatible_variants = expected_adt.variants .iter() .filter(|variant| variant.fields.len() == 1) .filter_map(|variant| { @@ -127,12 +127,12 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } else { None } - }).collect::>(); + }).peekable(); - if !compatible_variants.is_empty() { + if compatible_variants.peek().is_some() { let expr_text = print::to_string(print::NO_ANN, |s| s.print_expr(expr)); - let suggestions = compatible_variants.iter() - .map(|v| format!("{}({})", v, expr_text)).collect::>(); + let suggestions = compatible_variants.map(|v| + format!("{}({})", v, expr_text)).collect::>(); err.span_suggestions_with_applicability( expr.span, "try using a variant of the expected type", From 9d3643dd72aad4be88ee6aceb1e152bf44a8efe5 Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Sun, 14 Oct 2018 11:10:41 +0200 Subject: [PATCH 10/21] Make EvalContext::step public again Fixes #55061 --- src/librustc_mir/interpret/step.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc_mir/interpret/step.rs b/src/librustc_mir/interpret/step.rs index d5e8715448025..2f05af7fc2908 100644 --- a/src/librustc_mir/interpret/step.rs +++ b/src/librustc_mir/interpret/step.rs @@ -52,7 +52,7 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> } /// Returns true as long as there are more things to do. - fn step(&mut self) -> EvalResult<'tcx, bool> { + pub fn step(&mut self) -> EvalResult<'tcx, bool> { if self.stack.is_empty() { return Ok(false); } From 8a228fd7b6521bff7e2913c30f4ca04e9863f470 Mon Sep 17 00:00:00 2001 From: bjorn3 Date: Sun, 14 Oct 2018 11:50:05 +0200 Subject: [PATCH 11/21] Add comment about step being used by priroda --- src/librustc_mir/interpret/step.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/librustc_mir/interpret/step.rs b/src/librustc_mir/interpret/step.rs index 2f05af7fc2908..d15867eacddc6 100644 --- a/src/librustc_mir/interpret/step.rs +++ b/src/librustc_mir/interpret/step.rs @@ -52,6 +52,8 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> } /// Returns true as long as there are more things to do. + /// + /// This is used by [priroda](https://github.com/oli-obk/priroda) pub fn step(&mut self) -> EvalResult<'tcx, bool> { if self.stack.is_empty() { return Ok(false); From 1b355a89763efa5a67931f5190cbd0331d1f9a5d Mon Sep 17 00:00:00 2001 From: Diana Date: Sun, 14 Oct 2018 08:14:21 -0400 Subject: [PATCH 12/21] Fix incorrect link in println! documentation The eprintln! link was incorrectly linking to eprint! instead --- src/libstd/macros.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/macros.rs b/src/libstd/macros.rs index 16a3aecfc186b..34bbbb53d5ff1 100644 --- a/src/libstd/macros.rs +++ b/src/libstd/macros.rs @@ -139,7 +139,7 @@ macro_rules! print { /// /// [`format!`]: ../std/macro.format.html /// [`std::fmt`]: ../std/fmt/index.html -/// [`eprintln!`]: ../std/macro.eprint.html +/// [`eprintln!`]: ../std/macro.eprintln.html /// # Panics /// /// Panics if writing to `io::stdout` fails. From e8ec4987a8b26ea0cca076796689d2b1c00812a5 Mon Sep 17 00:00:00 2001 From: Jan Niehusmann Date: Sun, 14 Oct 2018 08:06:36 +0000 Subject: [PATCH 13/21] clarify pointer add/sub function safety concerns Ralf Jung made the same changes to the offset functions' documentation in commit fb089156. As add/sub just call offset, the same limitation applies here, as well. Removed emphasis on review request by @joshtriplett --- src/libcore/ptr.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index b8d7fcffbcc09..19a4fb93c306d 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -1255,7 +1255,7 @@ impl *const T { /// Behavior: /// /// * Both the starting and resulting pointer must be either in bounds or one - /// byte past the end of an allocated object. + /// byte past the end of the same allocated object. /// /// * The computed offset, **in bytes**, cannot overflow an `isize`. /// @@ -1312,7 +1312,7 @@ impl *const T { /// Behavior: /// /// * Both the starting and resulting pointer must be either in bounds or one - /// byte past the end of an allocated object. + /// byte past the end of the same allocated object. /// /// * The computed offset cannot exceed `isize::MAX` **bytes**. /// @@ -1893,7 +1893,7 @@ impl *mut T { /// Behavior: /// /// * Both the starting and resulting pointer must be either in bounds or one - /// byte past the end of an allocated object. + /// byte past the end of the same allocated object. /// /// * The computed offset, **in bytes**, cannot overflow an `isize`. /// @@ -1950,7 +1950,7 @@ impl *mut T { /// Behavior: /// /// * Both the starting and resulting pointer must be either in bounds or one - /// byte past the end of an allocated object. + /// byte past the end of the same allocated object. /// /// * The computed offset cannot exceed `isize::MAX` **bytes**. /// From 6cc84acc60c21389107dac5f9dd70f08862519fd Mon Sep 17 00:00:00 2001 From: Jan Niehusmann Date: Sun, 14 Oct 2018 20:23:33 +0000 Subject: [PATCH 14/21] remove unnecessary emphasis in doc comment During review of the previous commit, @joshtriplett noticed that the emphasis on 'the same' is unnecessary. For consistency, remove it on the offset() functions, as well. --- src/libcore/ptr.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/ptr.rs b/src/libcore/ptr.rs index 19a4fb93c306d..1c761ba21b3ec 100644 --- a/src/libcore/ptr.rs +++ b/src/libcore/ptr.rs @@ -1037,7 +1037,7 @@ impl *const T { /// Behavior: /// /// * Both the starting and resulting pointer must be either in bounds or one - /// byte past the end of *the same* allocated object. + /// byte past the end of the same allocated object. /// /// * The computed offset, **in bytes**, cannot overflow an `isize`. /// @@ -1657,7 +1657,7 @@ impl *mut T { /// Behavior: /// /// * Both the starting and resulting pointer must be either in bounds or one - /// byte past the end of *the same* allocated object. + /// byte past the end of the same allocated object. /// /// * The computed offset, **in bytes**, cannot overflow an `isize`. /// From ac6b3f88c77444a4080f24e8620ece911a467231 Mon Sep 17 00:00:00 2001 From: Shotaro Yamada Date: Mon, 15 Oct 2018 09:29:17 +0900 Subject: [PATCH 15/21] Deduplicate tests * `ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4` and `ex3-both-anon-regions-both-are-structs-3` * `ui/lint/lint-group-style` and `lint-group-nonstandard-style` --- ...anon-regions-both-are-structs-4.nll.stderr | 13 ---- ...x3-both-anon-regions-both-are-structs-4.rs | 19 ------ ...oth-anon-regions-both-are-structs-4.stderr | 13 ---- src/test/ui/lint/lint-group-style.rs | 36 ---------- src/test/ui/lint/lint-group-style.stderr | 67 ------------------- 5 files changed, 148 deletions(-) delete mode 100644 src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.nll.stderr delete mode 100644 src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.rs delete mode 100644 src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.stderr delete mode 100644 src/test/ui/lint/lint-group-style.rs delete mode 100644 src/test/ui/lint/lint-group-style.stderr diff --git a/src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.nll.stderr b/src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.nll.stderr deleted file mode 100644 index 4f0efe24cf70a..0000000000000 --- a/src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.nll.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error: unsatisfied lifetime constraints - --> $DIR/ex3-both-anon-regions-both-are-structs-4.rs:16:5 - | -LL | fn foo(mut x: Ref) { - | ----- - | | - | has type `Ref<'_, '1>` - | has type `Ref<'2, '_>` -LL | x.a = x.b; //~ ERROR lifetime mismatch - | ^^^^^^^^^ assignment requires that `'1` must outlive `'2` - -error: aborting due to previous error - diff --git a/src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.rs b/src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.rs deleted file mode 100644 index 78e6dc2d3e75f..0000000000000 --- a/src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.rs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. -struct Ref<'a, 'b> { - a: &'a u32, - b: &'b u32, -} - -fn foo(mut x: Ref) { - x.a = x.b; //~ ERROR lifetime mismatch -} - -fn main() {} diff --git a/src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.stderr b/src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.stderr deleted file mode 100644 index ccc5e02ab704c..0000000000000 --- a/src/test/ui/lifetimes/lifetime-errors/ex3-both-anon-regions-both-are-structs-4.stderr +++ /dev/null @@ -1,13 +0,0 @@ -error[E0623]: lifetime mismatch - --> $DIR/ex3-both-anon-regions-both-are-structs-4.rs:16:11 - | -LL | fn foo(mut x: Ref) { - | --- - | | - | this type is declared with multiple lifetimes... -LL | x.a = x.b; //~ ERROR lifetime mismatch - | ^^^ ...but data with one lifetime flows into the other here - -error: aborting due to previous error - -For more information about this error, try `rustc --explain E0623`. diff --git a/src/test/ui/lint/lint-group-style.rs b/src/test/ui/lint/lint-group-style.rs deleted file mode 100644 index 55d6168e6e008..0000000000000 --- a/src/test/ui/lint/lint-group-style.rs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2014–2017 The Rust Project Developers. See the COPYRIGHT -// file at the top-level directory of this distribution and at -// http://rust-lang.org/COPYRIGHT. -// -// Licensed under the Apache License, Version 2.0 or the MIT license -// , at your -// option. This file may not be copied, modified, or distributed -// except according to those terms. - -#![deny(nonstandard_style)] -#![allow(dead_code)] - -fn CamelCase() {} //~ ERROR should have a snake - -#[allow(nonstandard_style)] -mod test { - fn CamelCase() {} - - #[forbid(nonstandard_style)] - mod bad { - fn CamelCase() {} //~ ERROR should have a snake - - static bad: isize = 1; //~ ERROR should have an upper - } - - mod warn { - #![warn(nonstandard_style)] - - fn CamelCase() {} //~ WARN should have a snake - - struct snake_case; //~ WARN should have a camel - } -} - -fn main() {} diff --git a/src/test/ui/lint/lint-group-style.stderr b/src/test/ui/lint/lint-group-style.stderr deleted file mode 100644 index 6b91ce5b93ca6..0000000000000 --- a/src/test/ui/lint/lint-group-style.stderr +++ /dev/null @@ -1,67 +0,0 @@ -error: function `CamelCase` should have a snake case name such as `camel_case` - --> $DIR/lint-group-style.rs:14:1 - | -LL | fn CamelCase() {} //~ ERROR should have a snake - | ^^^^^^^^^^^^^^^^^ - | -note: lint level defined here - --> $DIR/lint-group-style.rs:11:9 - | -LL | #![deny(nonstandard_style)] - | ^^^^^^^^^^^^^^^^^ - = note: #[deny(non_snake_case)] implied by #[deny(nonstandard_style)] - -error: function `CamelCase` should have a snake case name such as `camel_case` - --> $DIR/lint-group-style.rs:22:9 - | -LL | fn CamelCase() {} //~ ERROR should have a snake - | ^^^^^^^^^^^^^^^^^ - | -note: lint level defined here - --> $DIR/lint-group-style.rs:20:14 - | -LL | #[forbid(nonstandard_style)] - | ^^^^^^^^^^^^^^^^^ - = note: #[forbid(non_snake_case)] implied by #[forbid(nonstandard_style)] - -error: static variable `bad` should have an upper case name such as `BAD` - --> $DIR/lint-group-style.rs:24:9 - | -LL | static bad: isize = 1; //~ ERROR should have an upper - | ^^^^^^^^^^^^^^^^^^^^^^ - | -note: lint level defined here - --> $DIR/lint-group-style.rs:20:14 - | -LL | #[forbid(nonstandard_style)] - | ^^^^^^^^^^^^^^^^^ - = note: #[forbid(non_upper_case_globals)] implied by #[forbid(nonstandard_style)] - -warning: function `CamelCase` should have a snake case name such as `camel_case` - --> $DIR/lint-group-style.rs:30:9 - | -LL | fn CamelCase() {} //~ WARN should have a snake - | ^^^^^^^^^^^^^^^^^ - | -note: lint level defined here - --> $DIR/lint-group-style.rs:28:17 - | -LL | #![warn(nonstandard_style)] - | ^^^^^^^^^^^^^^^^^ - = note: #[warn(non_snake_case)] implied by #[warn(nonstandard_style)] - -warning: type `snake_case` should have a camel case name such as `SnakeCase` - --> $DIR/lint-group-style.rs:32:9 - | -LL | struct snake_case; //~ WARN should have a camel - | ^^^^^^^^^^^^^^^^^^ - | -note: lint level defined here - --> $DIR/lint-group-style.rs:28:17 - | -LL | #![warn(nonstandard_style)] - | ^^^^^^^^^^^^^^^^^ - = note: #[warn(non_camel_case_types)] implied by #[warn(nonstandard_style)] - -error: aborting due to 3 previous errors - From 942a79615bb479f377f811a66796c2de7c9c058f Mon Sep 17 00:00:00 2001 From: ljedrz Date: Wed, 10 Oct 2018 15:24:31 +0200 Subject: [PATCH 16/21] rustc/session: whitespace & formatting improvements --- src/librustc/session/config.rs | 158 ++++++++++++++--------------- src/librustc/session/filesearch.rs | 2 +- src/librustc/session/mod.rs | 4 +- 3 files changed, 79 insertions(+), 85 deletions(-) diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index d8c36f81da324..8b921a4b46c20 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -736,19 +736,19 @@ macro_rules! options { match (value, opt_type_desc) { (Some(..), None) => { early_error(error_format, &format!("{} option `{}` takes no \ - value", $outputname, key)) + value", $outputname, key)) } (None, Some(type_desc)) => { early_error(error_format, &format!("{0} option `{1}` requires \ - {2} ({3} {1}=)", - $outputname, key, - type_desc, $prefix)) + {2} ({3} {1}=)", + $outputname, key, + type_desc, $prefix)) } (Some(value), Some(type_desc)) => { early_error(error_format, &format!("incorrect value `{}` for {} \ - option `{}` - {} was expected", - value, $outputname, - key, type_desc)) + option `{}` - {} was expected", + value, $outputname, + key, type_desc)) } (None, None) => bug!() } @@ -758,14 +758,13 @@ macro_rules! options { } if !found { early_error(error_format, &format!("unknown {} option: `{}`", - $outputname, key)); + $outputname, key)); } } return op; } impl<'a> dep_tracking::DepTrackingHash for $struct_name { - fn hash(&self, hasher: &mut DefaultHasher, error_format: ErrorOutputType) { let mut sub_hashes = BTreeMap::new(); $({ @@ -782,7 +781,7 @@ macro_rules! options { pub type $setter_name = fn(&mut $struct_name, v: Option<&str>) -> bool; pub const $stat: &'static [(&'static str, $setter_name, - Option<&'static str>, &'static str)] = + Option<&'static str>, &'static str)] = &[ $( (stringify!($opt), $mod_set::$opt, $mod_desc::$parse, $desc) ),* ]; #[allow(non_upper_case_globals, dead_code)] @@ -1062,8 +1061,8 @@ macro_rules! options { ) } options! {CodegenOptions, CodegenSetter, basic_codegen_options, - build_codegen_options, "C", "codegen", - CG_OPTIONS, cg_type_desc, cgsetters, + build_codegen_options, "C", "codegen", + CG_OPTIONS, cg_type_desc, cgsetters, ar: Option = (None, parse_opt_string, [UNTRACKED], "this option is deprecated and does nothing"), linker: Option = (None, parse_opt_pathbuf, [UNTRACKED], @@ -1107,13 +1106,13 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options, no_redzone: Option = (None, parse_opt_bool, [TRACKED], "disable the use of the redzone"), relocation_model: Option = (None, parse_opt_string, [TRACKED], - "choose the relocation model to use (rustc --print relocation-models for details)"), + "choose the relocation model to use (rustc --print relocation-models for details)"), code_model: Option = (None, parse_opt_string, [TRACKED], - "choose the code model to use (rustc --print code-models for details)"), + "choose the code model to use (rustc --print code-models for details)"), metadata: Vec = (Vec::new(), parse_list, [TRACKED], - "metadata to mangle symbol names with"), + "metadata to mangle symbol names with"), extra_filename: String = (String::new(), parse_string, [UNTRACKED], - "extra data to put in each output filename"), + "extra data to put in each output filename"), codegen_units: Option = (None, parse_opt_uint, [UNTRACKED], "divide crate into N units to optimize in parallel"), remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED], @@ -1134,14 +1133,14 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options, panic: Option = (None, parse_panic_strategy, [TRACKED], "panic strategy to compile crate with"), incremental: Option = (None, parse_opt_string, [UNTRACKED], - "enable incremental compilation"), + "enable incremental compilation"), default_linker_libraries: Option = (None, parse_opt_bool, [UNTRACKED], - "allow the linker to link its default libraries"), + "allow the linker to link its default libraries"), } options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, - build_debugging_options, "Z", "debugging", - DB_OPTIONS, db_type_desc, dbsetters, + build_debugging_options, "Z", "debugging", + DB_OPTIONS, db_type_desc, dbsetters, codegen_backend: Option = (None, parse_opt_string, [TRACKED], "the backend to use"), verbose: bool = (false, parse_bool, [UNTRACKED], @@ -1211,26 +1210,26 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, flowgraph_print_all: bool = (false, parse_bool, [UNTRACKED], "include all dataflow analysis data in -Z unpretty flowgraph output"), print_region_graph: bool = (false, parse_bool, [UNTRACKED], - "prints region inference graph. \ - Use with RUST_REGION_GRAPH=help for more info"), + "prints region inference graph. \ + Use with RUST_REGION_GRAPH=help for more info"), parse_only: bool = (false, parse_bool, [UNTRACKED], - "parse only; do not compile, assemble, or link"), + "parse only; do not compile, assemble, or link"), no_codegen: bool = (false, parse_bool, [TRACKED], - "run all passes except codegen; no output"), + "run all passes except codegen; no output"), treat_err_as_bug: bool = (false, parse_bool, [TRACKED], - "treat all errors that occur as bugs"), + "treat all errors that occur as bugs"), report_delayed_bugs: bool = (false, parse_bool, [TRACKED], - "immediately print bugs registered with `delay_span_bug`"), + "immediately print bugs registered with `delay_span_bug`"), external_macro_backtrace: bool = (false, parse_bool, [UNTRACKED], - "show macro backtraces even for non-local macros"), + "show macro backtraces even for non-local macros"), teach: bool = (false, parse_bool, [TRACKED], - "show extended diagnostic help"), + "show extended diagnostic help"), continue_parse_after_error: bool = (false, parse_bool, [TRACKED], - "attempt to recover from parse errors (experimental)"), + "attempt to recover from parse errors (experimental)"), incremental: Option = (None, parse_opt_string, [UNTRACKED], - "enable incremental compilation (experimental)"), + "enable incremental compilation (experimental)"), incremental_queries: bool = (true, parse_bool, [UNTRACKED], - "enable incremental compilation support for queries (experimental)"), + "enable incremental compilation support for queries (experimental)"), incremental_info: bool = (false, parse_bool, [UNTRACKED], "print high-level information about incremental reuse (or the lack thereof)"), incremental_dump_hash: bool = (false, parse_bool, [UNTRACKED], @@ -1240,64 +1239,64 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, incremental_ignore_spans: bool = (false, parse_bool, [UNTRACKED], "ignore spans during ICH computation -- used for testing"), dump_dep_graph: bool = (false, parse_bool, [UNTRACKED], - "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"), + "dump the dependency graph to $RUST_DEP_GRAPH (default: /tmp/dep_graph.gv)"), query_dep_graph: bool = (false, parse_bool, [UNTRACKED], - "enable queries of the dependency graph for regression testing"), + "enable queries of the dependency graph for regression testing"), profile_queries: bool = (false, parse_bool, [UNTRACKED], - "trace and profile the queries of the incremental compilation framework"), + "trace and profile the queries of the incremental compilation framework"), profile_queries_and_keys: bool = (false, parse_bool, [UNTRACKED], - "trace and profile the queries and keys of the incremental compilation framework"), + "trace and profile the queries and keys of the incremental compilation framework"), no_analysis: bool = (false, parse_bool, [UNTRACKED], - "parse and expand the source, but run no analysis"), + "parse and expand the source, but run no analysis"), extra_plugins: Vec = (Vec::new(), parse_list, [TRACKED], "load extra plugins"), unstable_options: bool = (false, parse_bool, [UNTRACKED], - "adds unstable command line options to rustc interface"), + "adds unstable command line options to rustc interface"), force_overflow_checks: Option = (None, parse_opt_bool, [TRACKED], - "force overflow checks on or off"), + "force overflow checks on or off"), trace_macros: bool = (false, parse_bool, [UNTRACKED], - "for every macro invocation, print its name and arguments"), + "for every macro invocation, print its name and arguments"), debug_macros: bool = (false, parse_bool, [TRACKED], - "emit line numbers debug info inside macros"), + "emit line numbers debug info inside macros"), keep_hygiene_data: bool = (false, parse_bool, [UNTRACKED], - "don't clear the hygiene data after analysis"), + "don't clear the hygiene data after analysis"), keep_ast: bool = (false, parse_bool, [UNTRACKED], - "keep the AST after lowering it to HIR"), + "keep the AST after lowering it to HIR"), show_span: Option = (None, parse_opt_string, [TRACKED], - "show spans for compiler debugging (expr|pat|ty)"), + "show spans for compiler debugging (expr|pat|ty)"), print_type_sizes: bool = (false, parse_bool, [UNTRACKED], - "print layout information for each type encountered"), + "print layout information for each type encountered"), print_mono_items: Option = (None, parse_opt_string, [UNTRACKED], - "print the result of the monomorphization collection pass"), + "print the result of the monomorphization collection pass"), mir_opt_level: usize = (1, parse_uint, [TRACKED], - "set the MIR optimization level (0-3, default: 1)"), + "set the MIR optimization level (0-3, default: 1)"), mutable_noalias: Option = (None, parse_opt_bool, [TRACKED], - "emit noalias metadata for mutable references (default: yes on LLVM >= 6)"), + "emit noalias metadata for mutable references (default: yes on LLVM >= 6)"), arg_align_attributes: bool = (false, parse_bool, [TRACKED], - "emit align metadata for reference arguments"), + "emit align metadata for reference arguments"), dump_mir: Option = (None, parse_opt_string, [UNTRACKED], - "dump MIR state at various points in transforms"), + "dump MIR state at various points in transforms"), dump_mir_dir: String = (String::from("mir_dump"), parse_string, [UNTRACKED], - "the directory the MIR is dumped into"), + "the directory the MIR is dumped into"), dump_mir_graphviz: bool = (false, parse_bool, [UNTRACKED], - "in addition to `.mir` files, create graphviz `.dot` files"), + "in addition to `.mir` files, create graphviz `.dot` files"), dump_mir_exclude_pass_number: bool = (false, parse_bool, [UNTRACKED], - "if set, exclude the pass number when dumping MIR (used in tests)"), + "if set, exclude the pass number when dumping MIR (used in tests)"), mir_emit_validate: usize = (0, parse_uint, [TRACKED], - "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \ - contains unsafe block, only validate arguments; 2: always emit full validation)"), + "emit Validate MIR statements, interpreted e.g. by miri (0: do not emit; 1: if function \ + contains unsafe block, only validate arguments; 2: always emit full validation)"), perf_stats: bool = (false, parse_bool, [UNTRACKED], - "print some performance-related statistics"), + "print some performance-related statistics"), hir_stats: bool = (false, parse_bool, [UNTRACKED], - "print some statistics about AST and HIR"), + "print some statistics about AST and HIR"), mir_stats: bool = (false, parse_bool, [UNTRACKED], - "print some statistics about MIR"), + "print some statistics about MIR"), always_encode_mir: bool = (false, parse_bool, [TRACKED], - "encode MIR of all functions into the crate metadata"), + "encode MIR of all functions into the crate metadata"), osx_rpath_install_name: bool = (false, parse_bool, [TRACKED], - "pass `-install_name @rpath/...` to the macOS linker"), + "pass `-install_name @rpath/...` to the macOS linker"), sanitizer: Option = (None, parse_sanitizer, [TRACKED], - "Use a sanitizer"), + "Use a sanitizer"), linker_flavor: Option = (None, parse_linker_flavor, [UNTRACKED], "Linker flavor"), fuel: Option<(String, u64)> = (None, parse_optimization_fuel, [TRACKED], @@ -1313,13 +1312,11 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, profile: bool = (false, parse_bool, [TRACKED], "insert profiling code"), pgo_gen: Option = (None, parse_opt_string, [TRACKED], - "Generate PGO profile data, to a given file, or to the default \ - location if it's empty."), + "Generate PGO profile data, to a given file, or to the default location if it's empty."), pgo_use: String = (String::new(), parse_string, [TRACKED], "Use PGO profile data from the given profile file."), - disable_instrumentation_preinliner: bool = - (false, parse_bool, [TRACKED], "Disable the instrumentation pre-inliner, \ - useful for profiling / PGO."), + disable_instrumentation_preinliner: bool = (false, parse_bool, [TRACKED], + "Disable the instrumentation pre-inliner, useful for profiling / PGO."), relro_level: Option = (None, parse_relro_level, [TRACKED], "choose which RELRO level to use"), nll_subminimal_causes: bool = (false, parse_bool, [UNTRACKED], @@ -1341,7 +1338,7 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, inline_in_all_cgus: Option = (None, parse_opt_bool, [TRACKED], "control whether #[inline] functions are in all cgus"), tls_model: Option = (None, parse_opt_string, [TRACKED], - "choose the TLS model to use (rustc --print tls-models for details)"), + "choose the TLS model to use (rustc --print tls-models for details)"), saturating_float_casts: bool = (false, parse_bool, [TRACKED], "make float->int casts UB-free: numbers outside the integer type's range are clipped to \ the max/min integer respectively, and NaN is mapped to 0"), @@ -1362,31 +1359,31 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options, `hir` (the HIR), `hir,identified`, or `hir,typed` (HIR with types for each node)."), run_dsymutil: Option = (None, parse_opt_bool, [TRACKED], - "run `dsymutil` and delete intermediate object files"), + "run `dsymutil` and delete intermediate object files"), ui_testing: bool = (false, parse_bool, [UNTRACKED], - "format compiler diagnostics in a way that's better suitable for UI testing"), + "format compiler diagnostics in a way that's better suitable for UI testing"), embed_bitcode: bool = (false, parse_bool, [TRACKED], - "embed LLVM bitcode in object files"), + "embed LLVM bitcode in object files"), strip_debuginfo_if_disabled: Option = (None, parse_opt_bool, [TRACKED], "tell the linker to strip debuginfo when building without debuginfo enabled."), share_generics: Option = (None, parse_opt_bool, [TRACKED], - "make the current crate share its generic instantiations"), + "make the current crate share its generic instantiations"), chalk: bool = (false, parse_bool, [TRACKED], - "enable the experimental Chalk-based trait solving engine"), + "enable the experimental Chalk-based trait solving engine"), cross_lang_lto: CrossLangLto = (CrossLangLto::Disabled, parse_cross_lang_lto, [TRACKED], - "generate build artifacts that are compatible with linker-based LTO."), + "generate build artifacts that are compatible with linker-based LTO."), no_parallel_llvm: bool = (false, parse_bool, [UNTRACKED], - "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"), + "don't run LLVM in parallel (while keeping codegen-units and ThinLTO)"), no_leak_check: bool = (false, parse_bool, [UNTRACKED], "disables the 'leak check' for subtyping; unsound, but useful for tests"), crate_attr: Vec = (Vec::new(), parse_string_push, [TRACKED], "inject the given attribute in the crate"), self_profile: bool = (false, parse_bool, [UNTRACKED], - "run the self profiler"), + "run the self profiler"), profile_json: bool = (false, parse_bool, [UNTRACKED], - "output a json file with profiler results"), + "output a json file with profiler results"), emit_stack_sizes: bool = (false, parse_bool, [UNTRACKED], - "emits a section containing stack size metadata"), + "emits a section containing stack size metadata"), plt: Option = (None, parse_opt_bool, [TRACKED], "whether to use the PLT when calling into shared libraries; only has effect for PIC code on systems with ELF binaries @@ -1502,7 +1499,6 @@ pub fn build_target_config(opts: &Options, sp: &Handler) -> Config { #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum OptionStability { Stable, - Unstable, } @@ -1851,7 +1847,7 @@ pub fn build_session_options_and_crate_config( ErrorOutputType::default(), &format!( "argument for --edition must be one of: \ - {}. (instead was `{}`)", + {}. (instead was `{}`)", EDITION_NAME_LIST, arg ), @@ -1865,7 +1861,7 @@ pub fn build_session_options_and_crate_config( ErrorOutputType::default(), &format!( "Edition {} is unstable and only \ - available for nightly builds of rustc.", + available for nightly builds of rustc.", edition, ) ) @@ -2308,9 +2304,7 @@ pub fn parse_crate_types_from_list(list_list: Vec) -> Result CrateType::Cdylib, "bin" => CrateType::Executable, "proc-macro" => CrateType::ProcMacro, - _ => { - return Err(format!("unknown crate type: `{}`", part)); - } + _ => return Err(format!("unknown crate type: `{}`", part)) }; if !crate_types.contains(&new_part) { crate_types.push(new_part) diff --git a/src/librustc/session/filesearch.rs b/src/librustc/session/filesearch.rs index 0de5d3d03d5c3..e55b82c63c3e5 100644 --- a/src/librustc/session/filesearch.rs +++ b/src/librustc/session/filesearch.rs @@ -175,7 +175,7 @@ fn find_libdir(sysroot: &Path) -> Cow<'static, str> { // to lib64/lib32. This would be more foolproof by basing the sysroot off // of the directory where librustc is located, rather than where the rustc // binary is. - //If --libdir is set during configuration to the value other than + // If --libdir is set during configuration to the value other than // "lib" (i.e. non-default), this value is used (see issue #16552). match option_env!("CFG_LIBDIR_RELATIVE") { diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 10a506da4eab4..43c4bea9def36 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -703,8 +703,8 @@ impl Session { match self.opts.maybe_sysroot { Some(ref sysroot) => sysroot, None => self.default_sysroot - .as_ref() - .expect("missing sysroot and default_sysroot in Session"), + .as_ref() + .expect("missing sysroot and default_sysroot in Session"), } } pub fn target_filesearch(&self, kind: PathKind) -> filesearch::FileSearch<'_> { From 675f00bfa864f792ab42d1ab33e9e2d0cf62057d Mon Sep 17 00:00:00 2001 From: ljedrz Date: Wed, 10 Oct 2018 15:30:53 +0200 Subject: [PATCH 17/21] rustc/session: improve allocations --- src/librustc/session/config.rs | 7 ++++--- src/librustc/session/filesearch.rs | 2 +- src/librustc/session/search_paths.rs | 2 +- src/librustc_driver/driver.rs | 2 +- 4 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 8b921a4b46c20..d2020ac852d0c 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -490,10 +490,10 @@ pub enum Input { } impl Input { - pub fn filestem(&self) -> String { + pub fn filestem(&self) -> &str { match *self { - Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap().to_string(), - Input::Str { .. } => "rust_out".to_string(), + Input::File(ref ifile) => ifile.file_stem().unwrap().to_str().unwrap(), + Input::Str { .. } => "rust_out", } } @@ -1406,6 +1406,7 @@ pub fn default_configuration(sess: &Session) -> ast::CrateConfig { let atomic_cas = sess.target.target.options.atomic_cas; let mut ret = FxHashSet::default(); + ret.reserve(6); // the minimum number of insertions // Target bindings. ret.insert((Symbol::intern("target_os"), Some(Symbol::intern(os)))); if let Some(ref fam) = sess.target.target.options.target_family { diff --git a/src/librustc/session/filesearch.rs b/src/librustc/session/filesearch.rs index e55b82c63c3e5..fb8bf8be1c246 100644 --- a/src/librustc/session/filesearch.rs +++ b/src/librustc/session/filesearch.rs @@ -41,7 +41,7 @@ impl<'a> FileSearch<'a> { F: FnMut(&Path, PathKind) { let mut visited_dirs = FxHashSet::default(); - + visited_dirs.reserve(self.search_paths.paths.len() + 1); for (path, kind) in self.search_paths.iter(self.kind) { f(path, kind); visited_dirs.insert(path.to_path_buf()); diff --git a/src/librustc/session/search_paths.rs b/src/librustc/session/search_paths.rs index be1bfcc0894dd..768d4f1e5fb65 100644 --- a/src/librustc/session/search_paths.rs +++ b/src/librustc/session/search_paths.rs @@ -14,7 +14,7 @@ use session::{early_error, config}; #[derive(Clone, Debug)] pub struct SearchPaths { - paths: Vec<(PathKind, PathBuf)>, + crate paths: Vec<(PathKind, PathBuf)>, } pub struct Iter<'a> { diff --git a/src/librustc_driver/driver.rs b/src/librustc_driver/driver.rs index b4f95b915eb8d..223df7cbb1874 100644 --- a/src/librustc_driver/driver.rs +++ b/src/librustc_driver/driver.rs @@ -1657,7 +1657,7 @@ pub fn build_output_filenames( .crate_name .clone() .or_else(|| attr::find_crate_name(attrs).map(|n| n.to_string())) - .unwrap_or_else(|| input.filestem()); + .unwrap_or_else(|| input.filestem().to_owned()); OutputFilenames { out_directory: dirpath, From 0b2e9f762a4dfe707b8eb7f48fa8430544bac87e Mon Sep 17 00:00:00 2001 From: ljedrz Date: Wed, 10 Oct 2018 15:33:10 +0200 Subject: [PATCH 18/21] rustc/session: improve common patterns --- src/librustc/session/config.rs | 45 +++++++++++------------------ src/librustc/session/filesearch.rs | 2 +- src/librustc/session/mod.rs | 46 +++++++++++------------------- 3 files changed, 35 insertions(+), 58 deletions(-) diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index d2020ac852d0c..1498004e66caa 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -1453,7 +1453,7 @@ pub fn default_configuration(sess: &Session) -> ast::CrateConfig { if sess.opts.crate_types.contains(&CrateType::ProcMacro) { ret.insert((Symbol::intern("proc_macro"), None)); } - return ret; + ret } pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> ast::CrateConfig { @@ -1469,15 +1469,12 @@ pub fn build_configuration(sess: &Session, mut user_cfg: ast::CrateConfig) -> as } pub fn build_target_config(opts: &Options, sp: &Handler) -> Config { - let target = match Target::search(&opts.target_triple) { - Ok(t) => t, - Err(e) => { - sp.struct_fatal(&format!("Error loading target specification: {}", e)) - .help("Use `--print target-list` for a list of built-in targets") - .emit(); - FatalError.raise(); - } - }; + let target = Target::search(&opts.target_triple).unwrap_or_else(|e| { + sp.struct_fatal(&format!("Error loading target specification: {}", e)) + .help("Use `--print target-list` for a list of built-in targets") + .emit(); + FatalError.raise(); + }); let (isize_ty, usize_ty) = match &target.target_pointer_width[..] { "16" => (ast::IntTy::I16, ast::UintTy::U16), @@ -1842,9 +1839,8 @@ pub fn build_session_options_and_crate_config( }; let edition = match matches.opt_str("edition") { - Some(arg) => match Edition::from_str(&arg){ - Ok(edition) => edition, - Err(_) => early_error( + Some(arg) => Edition::from_str(&arg).unwrap_or_else(|_| + early_error( ErrorOutputType::default(), &format!( "argument for --edition must be one of: \ @@ -1853,7 +1849,7 @@ pub fn build_session_options_and_crate_config( arg ), ), - } + ), None => DEFAULT_EDITION, }; @@ -1922,9 +1918,8 @@ pub fn build_session_options_and_crate_config( for output_type in list.split(',') { let mut parts = output_type.splitn(2, '='); let shorthand = parts.next().unwrap(); - let output_type = match OutputType::from_shorthand(shorthand) { - Some(output_type) => output_type, - None => early_error( + let output_type = OutputType::from_shorthand(shorthand).unwrap_or_else(|| + early_error( error_format, &format!( "unknown emission type: `{}` - expected one of: {}", @@ -1932,7 +1927,7 @@ pub fn build_session_options_and_crate_config( OutputType::shorthands_display(), ), ), - }; + ); let path = parts.next().map(PathBuf::from); output_types.insert(output_type, path); } @@ -2060,12 +2055,8 @@ pub fn build_session_options_and_crate_config( let target_triple = if let Some(target) = matches.opt_str("target") { if target.ends_with(".json") { let path = Path::new(&target); - match TargetTriple::from_path(&path) { - Ok(triple) => triple, - Err(_) => { - early_error(error_format, &format!("target file {:?} does not exist", path)) - } - } + TargetTriple::from_path(&path).unwrap_or_else(|_| + early_error(error_format, &format!("target file {:?} does not exist", path))) } else { TargetTriple::TargetTriple(target) } @@ -2220,10 +2211,8 @@ pub fn build_session_options_and_crate_config( let mut externs: BTreeMap<_, BTreeSet<_>> = BTreeMap::new(); for arg in &matches.opt_strs("extern") { let mut parts = arg.splitn(2, '='); - let name = match parts.next() { - Some(s) => s, - None => early_error(error_format, "--extern value must not be empty"), - }; + let name = parts.next().unwrap_or_else(|| + early_error(error_format, "--extern value must not be empty")); let location = parts.next().map(|s| s.to_string()); if location.is_none() && !is_unstable_enabled { early_error( diff --git a/src/librustc/session/filesearch.rs b/src/librustc/session/filesearch.rs index fb8bf8be1c246..f7a2a2d1bf14b 100644 --- a/src/librustc/session/filesearch.rs +++ b/src/librustc/session/filesearch.rs @@ -160,7 +160,7 @@ pub fn get_or_default_sysroot() -> PathBuf { match env::current_exe() { Ok(exe) => { match canonicalize(Some(exe)) { - Some(mut p) => { p.pop(); p.pop(); return p; }, + Some(mut p) => { p.pop(); p.pop(); p }, None => bug!("can't determine value for sysroot") } } diff --git a/src/librustc/session/mod.rs b/src/librustc/session/mod.rs index 43c4bea9def36..e983ddc3108d7 100644 --- a/src/librustc/session/mod.rs +++ b/src/librustc/session/mod.rs @@ -727,14 +727,8 @@ impl Session { pub fn set_incr_session_load_dep_graph(&self, load: bool) { let mut incr_comp_session = self.incr_comp_session.borrow_mut(); - match *incr_comp_session { - IncrCompSession::Active { - ref mut load_dep_graph, - .. - } => { - *load_dep_graph = load; - } - _ => {} + if let IncrCompSession::Active { ref mut load_dep_graph, .. } = *incr_comp_session { + *load_dep_graph = load; } } @@ -872,9 +866,9 @@ impl Session { /// This expends fuel if applicable, and records fuel if applicable. pub fn consider_optimizing String>(&self, crate_name: &str, msg: T) -> bool { let mut ret = true; - match self.optimization_fuel_crate { - Some(ref c) if c == crate_name => { - assert!(self.query_threads() == 1); + if let Some(ref c) = self.optimization_fuel_crate { + if c == crate_name { + assert_eq!(self.query_threads(), 1); let fuel = self.optimization_fuel_limit.get(); ret = fuel != 0; if fuel == 0 && !self.out_of_fuel.get() { @@ -884,14 +878,12 @@ impl Session { self.optimization_fuel_limit.set(fuel - 1); } } - _ => {} } - match self.print_fuel_crate { - Some(ref c) if c == crate_name => { - assert!(self.query_threads() == 1); + if let Some(ref c) = self.print_fuel_crate { + if c == crate_name { + assert_eq!(self.query_threads(), 1); self.print_fuel.set(self.print_fuel.get() + 1); } - _ => {} } ret } @@ -1108,14 +1100,11 @@ pub fn build_session_( source_map: Lrc, ) -> Session { let host_triple = TargetTriple::from_triple(config::host_triple()); - let host = match Target::search(&host_triple) { - Ok(t) => t, - Err(e) => { - span_diagnostic - .fatal(&format!("Error loading host specification: {}", e)) - .raise(); - } - }; + let host = Target::search(&host_triple).unwrap_or_else(|e| + span_diagnostic + .fatal(&format!("Error loading host specification: {}", e)) + .raise() + ); let target_cfg = config::build_target_config(&sopts, &span_diagnostic); let p_s = parse::ParseSess::with_span_handler(span_diagnostic, source_map); @@ -1135,12 +1124,11 @@ pub fn build_session_( let print_fuel_crate = sopts.debugging_opts.print_fuel.clone(); let print_fuel = LockCell::new(0); - let working_dir = match env::current_dir() { - Ok(dir) => dir, - Err(e) => p_s.span_diagnostic + let working_dir = env::current_dir().unwrap_or_else(|e| + p_s.span_diagnostic .fatal(&format!("Current directory is invalid: {}", e)) - .raise(), - }; + .raise() + ); let working_dir = file_path_mapping.map_prefix(working_dir); let cgu_reuse_tracker = if sopts.debugging_opts.query_dep_graph { From e5eb5385630a22b8d0e6d08fe88ce171f96c79d3 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Wed, 10 Oct 2018 15:34:07 +0200 Subject: [PATCH 19/21] rustc/session: use to_owned when no string conversion is needed --- src/librustc/session/config.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/librustc/session/config.rs b/src/librustc/session/config.rs index 1498004e66caa..569e7a24d2353 100644 --- a/src/librustc/session/config.rs +++ b/src/librustc/session/config.rs @@ -2157,7 +2157,7 @@ pub fn build_session_options_and_crate_config( let mut name_parts = name.splitn(2, ':'); let name = name_parts.next().unwrap(); let new_name = name_parts.next(); - (name.to_string(), new_name.map(|n| n.to_string()), kind) + (name.to_owned(), new_name.map(|n| n.to_owned()), kind) }) .collect(); @@ -2223,7 +2223,7 @@ pub fn build_session_options_and_crate_config( }; externs - .entry(name.to_string()) + .entry(name.to_owned()) .or_default() .insert(location); } From 42ae9dc508728bc5c3b88a947ddfbef36e6356c4 Mon Sep 17 00:00:00 2001 From: ljedrz Date: Wed, 10 Oct 2018 15:35:56 +0200 Subject: [PATCH 20/21] rustc/session: move consts up to improve readability --- src/librustc/session/filesearch.rs | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/librustc/session/filesearch.rs b/src/librustc/session/filesearch.rs index f7a2a2d1bf14b..f410c270bcef9 100644 --- a/src/librustc/session/filesearch.rs +++ b/src/librustc/session/filesearch.rs @@ -178,15 +178,6 @@ fn find_libdir(sysroot: &Path) -> Cow<'static, str> { // If --libdir is set during configuration to the value other than // "lib" (i.e. non-default), this value is used (see issue #16552). - match option_env!("CFG_LIBDIR_RELATIVE") { - Some(libdir) if libdir != "lib" => return libdir.into(), - _ => if sysroot.join(PRIMARY_LIB_DIR).join(RUST_LIB_DIR).exists() { - return PRIMARY_LIB_DIR.into(); - } else { - return SECONDARY_LIB_DIR.into(); - } - } - #[cfg(target_pointer_width = "64")] const PRIMARY_LIB_DIR: &'static str = "lib64"; @@ -194,6 +185,15 @@ fn find_libdir(sysroot: &Path) -> Cow<'static, str> { const PRIMARY_LIB_DIR: &'static str = "lib32"; const SECONDARY_LIB_DIR: &'static str = "lib"; + + match option_env!("CFG_LIBDIR_RELATIVE") { + Some(libdir) if libdir != "lib" => libdir.into(), + _ => if sysroot.join(PRIMARY_LIB_DIR).join(RUST_LIB_DIR).exists() { + PRIMARY_LIB_DIR.into() + } else { + SECONDARY_LIB_DIR.into() + } + } } // The name of rustc's own place to organize libraries. From e03d24e153ca7cfe6921f39e9aea1167e01127bb Mon Sep 17 00:00:00 2001 From: Do Duy Date: Mon, 15 Oct 2018 15:54:29 +0700 Subject: [PATCH 21/21] Update rustc documentation link --- CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 49961d02ddab7..fe6bea9d8dc3f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -646,7 +646,7 @@ are: * Don't be afraid to ask! The Rust community is friendly and helpful. [rustc guide]: https://rust-lang-nursery.github.io/rustc-guide/about-this-guide.html -[gdfrustc]: http://manishearth.github.io/rust-internals-docs/rustc/ +[gdfrustc]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc/ [gsearchdocs]: https://www.google.com/search?q=site:doc.rust-lang.org+your+query+here [rif]: http://internals.rust-lang.org [rr]: https://doc.rust-lang.org/book/README.html