From 6f6fe38b19339265397fc199c61df37772bef54c Mon Sep 17 00:00:00 2001 From: Eduard-Mihai Burtescu Date: Fri, 20 Mar 2020 08:00:06 +0200 Subject: [PATCH 01/34] parse/lexer: support `StringReader::retokenize` called on external files. --- src/librustc_parse/lexer/mod.rs | 16 ++++++++++++---- src/librustc_span/lib.rs | 6 +++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/src/librustc_parse/lexer/mod.rs b/src/librustc_parse/lexer/mod.rs index f7fb704fcbc2c..6c0b2c40c7622 100644 --- a/src/librustc_parse/lexer/mod.rs +++ b/src/librustc_parse/lexer/mod.rs @@ -46,12 +46,20 @@ impl<'a> StringReader<'a> { source_file: Lrc, override_span: Option, ) -> Self { - if source_file.src.is_none() { + // Make sure external source is loaded first, before accessing it. + // While this can't show up during normal parsing, `retokenize` may + // be called with a source file from an external crate. + sess.source_map().ensure_source_file_source_present(source_file.clone()); + + // FIXME(eddyb) use `Lrc` or similar to avoid cloning the `String`. + let src = if let Some(src) = &source_file.src { + src.clone() + } else if let Some(src) = source_file.external_src.borrow().get_source() { + src.clone() + } else { sess.span_diagnostic .bug(&format!("cannot lex `source_file` without source: {}", source_file.name)); - } - - let src = (*source_file.src.as_ref().unwrap()).clone(); + }; StringReader { sess, diff --git a/src/librustc_span/lib.rs b/src/librustc_span/lib.rs index dbc180114f1c1..28864737072b2 100644 --- a/src/librustc_span/lib.rs +++ b/src/librustc_span/lib.rs @@ -856,7 +856,7 @@ pub enum ExternalSource { #[derive(PartialEq, Eq, Clone, Debug)] pub enum ExternalSourceKind { /// The external source has been loaded already. - Present(String), + Present(Lrc), /// No attempt has been made to load the external source. AbsentOk, /// A failed attempt has been made to load the external source. @@ -872,7 +872,7 @@ impl ExternalSource { } } - pub fn get_source(&self) -> Option<&str> { + pub fn get_source(&self) -> Option<&Lrc> { match self { ExternalSource::Foreign { kind: ExternalSourceKind::Present(ref src), .. } => Some(src), _ => None, @@ -1138,7 +1138,7 @@ impl SourceFile { hasher.write(src.as_bytes()); if hasher.finish::() == self.src_hash { - *src_kind = ExternalSourceKind::Present(src); + *src_kind = ExternalSourceKind::Present(Lrc::new(src)); return true; } } else { From 4d30b92e3e57cf606a25c807a9e4ab2b7a4d1064 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Sat, 21 Mar 2020 08:32:55 +0100 Subject: [PATCH 02/34] recover on `for<'a> |...| body` closures. --- src/librustc_parse/parser/expr.rs | 33 +++++++++++++++++-- src/librustc_parse/parser/generics.rs | 19 +++++------ src/librustc_parse/parser/item.rs | 2 +- .../ui/parser/recover-quantified-closure.rs | 10 ++++++ .../parser/recover-quantified-closure.stderr | 16 +++++++++ 5 files changed, 66 insertions(+), 14 deletions(-) create mode 100644 src/test/ui/parser/recover-quantified-closure.rs create mode 100644 src/test/ui/parser/recover-quantified-closure.stderr diff --git a/src/librustc_parse/parser/expr.rs b/src/librustc_parse/parser/expr.rs index c65e99842c5dd..957bdd082bb62 100644 --- a/src/librustc_parse/parser/expr.rs +++ b/src/librustc_parse/parser/expr.rs @@ -925,8 +925,17 @@ impl<'a> Parser<'a> { self.parse_closure_expr(attrs) } else if self.eat_keyword(kw::If) { self.parse_if_expr(attrs) - } else if self.eat_keyword(kw::For) { - self.parse_for_expr(None, self.prev_token.span, attrs) + } else if self.check_keyword(kw::For) { + if self.choose_generics_over_qpath(1) { + // NOTE(Centril, eddyb): DO NOT REMOVE! Beyond providing parser recovery, + // this is an insurance policy in case we allow qpaths in (tuple-)struct patterns. + // When `for ::Proj in $expr $block` is wanted, + // you can disambiguate in favor of a pattern with `(...)`. + self.recover_quantified_closure_expr(attrs) + } else { + assert!(self.eat_keyword(kw::For)); + self.parse_for_expr(None, self.prev_token.span, attrs) + } } else if self.eat_keyword(kw::While) { self.parse_while_expr(None, self.prev_token.span, attrs) } else if let Some(label) = self.eat_label() { @@ -1416,6 +1425,26 @@ impl<'a> Parser<'a> { Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs)) } + /// Recover on an explicitly quantified closure expression, e.g., `for<'a> |x: &'a u8| *x + 1`. + fn recover_quantified_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { + let lo = self.token.span; + let _ = self.parse_late_bound_lifetime_defs()?; + let span_for = lo.to(self.prev_token.span); + let closure = self.parse_closure_expr(attrs)?; + + self.struct_span_err(span_for, "cannot introduce explicit parameters for a closure") + .span_label(closure.span, "the parameters are attached to this closure") + .span_suggestion( + span_for, + "remove the parameters", + String::new(), + Applicability::MachineApplicable, + ) + .emit(); + + Ok(self.mk_expr_err(lo.to(closure.span))) + } + /// Parses a closure expression (e.g., `move |args| expr`). fn parse_closure_expr(&mut self, attrs: AttrVec) -> PResult<'a, P> { let lo = self.token.span; diff --git a/src/librustc_parse/parser/generics.rs b/src/librustc_parse/parser/generics.rs index 59fd5f7c4be1f..3442c5081c18f 100644 --- a/src/librustc_parse/parser/generics.rs +++ b/src/librustc_parse/parser/generics.rs @@ -181,7 +181,7 @@ impl<'a> Parser<'a> { // We are considering adding generics to the `where` keyword as an alternative higher-rank // parameter syntax (as in `where<'a>` or `where`. To avoid that being a breaking // change we parse those generics now, but report an error. - if self.choose_generics_over_qpath() { + if self.choose_generics_over_qpath(0) { let generics = self.parse_generics()?; self.struct_span_err( generics.span, @@ -257,7 +257,7 @@ impl<'a> Parser<'a> { } } - pub(super) fn choose_generics_over_qpath(&self) -> bool { + pub(super) fn choose_generics_over_qpath(&self, start: usize) -> bool { // There's an ambiguity between generic parameters and qualified paths in impls. // If we see `<` it may start both, so we have to inspect some following tokens. // The following combinations can only start generics, @@ -274,15 +274,12 @@ impl<'a> Parser<'a> { // we disambiguate it in favor of generics (`impl ::absolute::Path { ... }`) // because this is what almost always expected in practice, qualified paths in impls // (`impl ::AssocTy { ... }`) aren't even allowed by type checker at the moment. - self.token == token::Lt - && (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) - || self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) - && self.look_ahead(2, |t| { - t == &token::Gt - || t == &token::Comma - || t == &token::Colon - || t == &token::Eq + self.look_ahead(start, |t| t == &token::Lt) + && (self.look_ahead(start + 1, |t| t == &token::Pound || t == &token::Gt) + || self.look_ahead(start + 1, |t| t.is_lifetime() || t.is_ident()) + && self.look_ahead(start + 2, |t| { + matches!(t.kind, token::Gt | token::Comma | token::Colon | token::Eq) }) - || self.is_keyword_ahead(1, &[kw::Const])) + || self.is_keyword_ahead(start + 1, &[kw::Const])) } } diff --git a/src/librustc_parse/parser/item.rs b/src/librustc_parse/parser/item.rs index 9d70f606f3ef4..42c4bac3b8db4 100644 --- a/src/librustc_parse/parser/item.rs +++ b/src/librustc_parse/parser/item.rs @@ -458,7 +458,7 @@ impl<'a> Parser<'a> { self.expect_keyword(kw::Impl)?; // First, parse generic parameters if necessary. - let mut generics = if self.choose_generics_over_qpath() { + let mut generics = if self.choose_generics_over_qpath(0) { self.parse_generics()? } else { let mut generics = Generics::default(); diff --git a/src/test/ui/parser/recover-quantified-closure.rs b/src/test/ui/parser/recover-quantified-closure.rs new file mode 100644 index 0000000000000..381324738f62b --- /dev/null +++ b/src/test/ui/parser/recover-quantified-closure.rs @@ -0,0 +1,10 @@ +fn main() { + for<'a> |x: &'a u8| *x + 1; + //~^ ERROR cannot introduce explicit parameters for a closure +} + +enum Foo { Bar } +fn foo(x: impl Iterator) { + for ::Bar in x {} + //~^ ERROR expected one of `move`, `static`, `|` +} diff --git a/src/test/ui/parser/recover-quantified-closure.stderr b/src/test/ui/parser/recover-quantified-closure.stderr new file mode 100644 index 0000000000000..0f01132651648 --- /dev/null +++ b/src/test/ui/parser/recover-quantified-closure.stderr @@ -0,0 +1,16 @@ +error: cannot introduce explicit parameters for a closure + --> $DIR/recover-quantified-closure.rs:2:5 + | +LL | for<'a> |x: &'a u8| *x + 1; + | ^^^^^^^ ------------------ the parameters are attached to this closure + | | + | help: remove the parameters + +error: expected one of `move`, `static`, `|`, or `||`, found `::` + --> $DIR/recover-quantified-closure.rs:8:14 + | +LL | for ::Bar in x {} + | ^^ expected one of `move`, `static`, `|`, or `||` + +error: aborting due to 2 previous errors + From a9c2378b7dc365189178130d3d3b701aec3809aa Mon Sep 17 00:00:00 2001 From: Bastian Kauschke Date: Sat, 21 Mar 2020 13:22:26 +0100 Subject: [PATCH 03/34] fix type of const params in associated types. --- src/librustc_typeck/collect/type_of.rs | 20 +++++++++++++++---- .../ui/const-generics/issues/issue-66906.rs | 12 +++++++++++ .../const-generics/issues/issue-66906.stderr | 8 ++++++++ .../ui/const-generics/issues/issue-70167.rs | 10 ++++++++++ .../const-generics/issues/issue-70167.stderr | 8 ++++++++ 5 files changed, 54 insertions(+), 4 deletions(-) create mode 100644 src/test/ui/const-generics/issues/issue-66906.rs create mode 100644 src/test/ui/const-generics/issues/issue-66906.stderr create mode 100644 src/test/ui/const-generics/issues/issue-70167.rs create mode 100644 src/test/ui/const-generics/issues/issue-70167.stderr diff --git a/src/librustc_typeck/collect/type_of.rs b/src/librustc_typeck/collect/type_of.rs index 41c205bc11b35..45587e5e90fec 100644 --- a/src/librustc_typeck/collect/type_of.rs +++ b/src/librustc_typeck/collect/type_of.rs @@ -256,15 +256,18 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { // figure out which generic parameter it corresponds to and return // the relevant type. let generics = match path.res { - Res::Def(DefKind::Ctor(..), def_id) => { + Res::Def(DefKind::Ctor(..), def_id) + | Res::Def(DefKind::AssocTy, def_id) => { tcx.generics_of(tcx.parent(def_id).unwrap()) } Res::Def(_, def_id) => tcx.generics_of(def_id), - Res::Err => return tcx.types.err, res => { tcx.sess.delay_span_bug( DUMMY_SP, - &format!("unexpected const parent path def {:?}", res,), + &format!( + "unexpected const parent path def, parent: {:?}, def: {:?}", + parent_node, res + ), ); return tcx.types.err; } @@ -284,7 +287,16 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { .map(|param| tcx.type_of(param.def_id)) // This is no generic parameter associated with the arg. This is // probably from an extra arg where one is not needed. - .unwrap_or(tcx.types.err) + .unwrap_or_else(|| { + tcx.sess.delay_span_bug( + DUMMY_SP, + &format!( + "missing generic parameter for `AnonConst`, parent {:?}", + parent_node + ), + ); + tcx.types.err + }) } else { tcx.sess.delay_span_bug( DUMMY_SP, diff --git a/src/test/ui/const-generics/issues/issue-66906.rs b/src/test/ui/const-generics/issues/issue-66906.rs new file mode 100644 index 0000000000000..461fe837dac44 --- /dev/null +++ b/src/test/ui/const-generics/issues/issue-66906.rs @@ -0,0 +1,12 @@ +// check-pass + +#![feature(const_generics)] +//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash + +pub struct Tuple; + +pub trait Trait { + type Input: From<>::Input>; +} + +fn main() {} diff --git a/src/test/ui/const-generics/issues/issue-66906.stderr b/src/test/ui/const-generics/issues/issue-66906.stderr new file mode 100644 index 0000000000000..f8710b67b687e --- /dev/null +++ b/src/test/ui/const-generics/issues/issue-66906.stderr @@ -0,0 +1,8 @@ +warning: the feature `const_generics` is incomplete and may cause the compiler to crash + --> $DIR/issue-66906.rs:3:12 + | +LL | #![feature(const_generics)] + | ^^^^^^^^^^^^^^ + | + = note: `#[warn(incomplete_features)]` on by default + diff --git a/src/test/ui/const-generics/issues/issue-70167.rs b/src/test/ui/const-generics/issues/issue-70167.rs new file mode 100644 index 0000000000000..58fac8e05114a --- /dev/null +++ b/src/test/ui/const-generics/issues/issue-70167.rs @@ -0,0 +1,10 @@ +// check-pass + +#![feature(const_generics)] +//~^ WARN the feature `const_generics` is incomplete and may cause the compiler to crash + +pub trait Trait: From<>::Item> { + type Item; +} + +fn main() {} diff --git a/src/test/ui/const-generics/issues/issue-70167.stderr b/src/test/ui/const-generics/issues/issue-70167.stderr new file mode 100644 index 0000000000000..4ba3c204097dc --- /dev/null +++ b/src/test/ui/const-generics/issues/issue-70167.stderr @@ -0,0 +1,8 @@ +warning: the feature `const_generics` is incomplete and may cause the compiler to crash + --> $DIR/issue-70167.rs:3:12 + | +LL | #![feature(const_generics)] + | ^^^^^^^^^^^^^^ + | + = note: `#[warn(incomplete_features)]` on by default + From e991df82faf3b2807e2baab166ec0d589b38b31f Mon Sep 17 00:00:00 2001 From: LeSeulArtichaut Date: Sat, 21 Mar 2020 14:28:07 +0100 Subject: [PATCH 04/34] Only display definition on typo --- src/librustc_resolve/diagnostics.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 6f567ab65a70c..09983489c25d7 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -797,7 +797,7 @@ impl<'a> Resolver<'a> { }); if let Some(span) = def_span { err.span_label( - span, + self.session.source_map().def_span(span), &format!( "similarly named {} `{}` defined here", suggestion.res.descr(), From cb7a2c16aa086f89b0cc5ceb29dd46988ff21fc3 Mon Sep 17 00:00:00 2001 From: LeSeulArtichaut Date: Sat, 21 Mar 2020 15:03:58 +0100 Subject: [PATCH 05/34] Bless tests --- src/test/ui/error-codes/E0423.stderr | 21 ++--- src/test/ui/glob-resolve1.stderr | 6 +- src/test/ui/issues/issue-31845.stderr | 9 +- src/test/ui/issues/issue-46332.stderr | 2 +- src/test/ui/macros/macro_undefined.stderr | 10 +-- .../ui/privacy/legacy-ctor-visibility.stderr | 10 +-- src/test/ui/proc-macro/resolve-error.stderr | 20 ++--- src/test/ui/resolve/issue-5035.stderr | 2 +- src/test/ui/resolve/levenshtein.stderr | 4 +- src/test/ui/resolve/privacy-enum-ctor.stderr | 84 ++++++------------- .../ui/traits/trait-impl-for-module.stderr | 11 ++- .../ui/ufcs/ufcs-partially-resolved.stderr | 4 +- 12 files changed, 68 insertions(+), 115 deletions(-) diff --git a/src/test/ui/error-codes/E0423.stderr b/src/test/ui/error-codes/E0423.stderr index 09792845d162c..a985e963e5726 100644 --- a/src/test/ui/error-codes/E0423.stderr +++ b/src/test/ui/error-codes/E0423.stderr @@ -29,20 +29,17 @@ LL | for _ in (std::ops::Range { start: 0, end: 10 }) {} error[E0423]: expected function, tuple struct or tuple variant, found struct `Foo` --> $DIR/E0423.rs:4:13 | -LL | struct Foo { a: bool }; - | ---------------------- `Foo` defined here +LL | struct Foo { a: bool }; + | ---------------------- `Foo` defined here LL | -LL | let f = Foo(); - | ^^^ - | | - | did you mean `Foo { /* fields */ }`? - | help: a function with a similar name exists (notice the capitalization): `foo` +LL | let f = Foo(); + | ^^^ + | | + | did you mean `Foo { /* fields */ }`? + | help: a function with a similar name exists (notice the capitalization): `foo` ... -LL | / fn foo() { -LL | | for _ in std::ops::Range { start: 0, end: 10 } {} -LL | | -LL | | } - | |_- similarly named function `foo` defined here +LL | fn foo() { + | -------- similarly named function `foo` defined here error[E0423]: expected value, found struct `T` --> $DIR/E0423.rs:14:8 diff --git a/src/test/ui/glob-resolve1.stderr b/src/test/ui/glob-resolve1.stderr index 3db24431586da..efbd53fd223a4 100644 --- a/src/test/ui/glob-resolve1.stderr +++ b/src/test/ui/glob-resolve1.stderr @@ -47,7 +47,7 @@ error[E0412]: cannot find type `A` in this scope --> $DIR/glob-resolve1.rs:28:11 | LL | pub enum B { B1 } - | ----------------- similarly named enum `B` defined here + | ---------- similarly named enum `B` defined here ... LL | foo::(); | ^ @@ -65,7 +65,7 @@ error[E0412]: cannot find type `C` in this scope --> $DIR/glob-resolve1.rs:29:11 | LL | pub enum B { B1 } - | ----------------- similarly named enum `B` defined here + | ---------- similarly named enum `B` defined here ... LL | foo::(); | ^ @@ -83,7 +83,7 @@ error[E0412]: cannot find type `D` in this scope --> $DIR/glob-resolve1.rs:30:11 | LL | pub enum B { B1 } - | ----------------- similarly named enum `B` defined here + | ---------- similarly named enum `B` defined here ... LL | foo::(); | ^ diff --git a/src/test/ui/issues/issue-31845.stderr b/src/test/ui/issues/issue-31845.stderr index 75d8859961a04..fe51fa0699fb4 100644 --- a/src/test/ui/issues/issue-31845.stderr +++ b/src/test/ui/issues/issue-31845.stderr @@ -1,11 +1,10 @@ error[E0425]: cannot find function `g` in this scope --> $DIR/issue-31845.rs:7:12 | -LL | / fn h() { -LL | | g(); - | | ^ help: a function with a similar name exists: `h` -LL | | } - | |_________- similarly named function `h` defined here +LL | fn h() { + | ------ similarly named function `h` defined here +LL | g(); + | ^ help: a function with a similar name exists: `h` error: aborting due to previous error diff --git a/src/test/ui/issues/issue-46332.stderr b/src/test/ui/issues/issue-46332.stderr index 5d8a859a7379c..890ef8014b489 100644 --- a/src/test/ui/issues/issue-46332.stderr +++ b/src/test/ui/issues/issue-46332.stderr @@ -2,7 +2,7 @@ error[E0422]: cannot find struct, variant or union type `TyUInt` in this scope --> $DIR/issue-46332.rs:9:5 | LL | struct TyUint {} - | ---------------- similarly named struct `TyUint` defined here + | ------------- similarly named struct `TyUint` defined here ... LL | TyUInt {}; | ^^^^^^ help: a struct with a similar name exists (notice the capitalization): `TyUint` diff --git a/src/test/ui/macros/macro_undefined.stderr b/src/test/ui/macros/macro_undefined.stderr index b2caba893e072..4ab16bd10173d 100644 --- a/src/test/ui/macros/macro_undefined.stderr +++ b/src/test/ui/macros/macro_undefined.stderr @@ -1,13 +1,11 @@ error: cannot find macro `k` in this scope --> $DIR/macro_undefined.rs:11:5 | -LL | / macro_rules! kl { -LL | | () => () -LL | | } - | |_____- similarly named macro `kl` defined here +LL | macro_rules! kl { + | --------------- similarly named macro `kl` defined here ... -LL | k!(); - | ^ help: a macro with a similar name exists: `kl` +LL | k!(); + | ^ help: a macro with a similar name exists: `kl` error: aborting due to previous error diff --git a/src/test/ui/privacy/legacy-ctor-visibility.stderr b/src/test/ui/privacy/legacy-ctor-visibility.stderr index 74a1f1ceeffb4..4f0d72de6f1a4 100644 --- a/src/test/ui/privacy/legacy-ctor-visibility.stderr +++ b/src/test/ui/privacy/legacy-ctor-visibility.stderr @@ -1,12 +1,10 @@ error[E0423]: expected function, tuple struct or tuple variant, found struct `S` --> $DIR/legacy-ctor-visibility.rs:9:13 | -LL | / fn f() { -LL | | S(10); - | | ^ help: a function with a similar name exists: `f` -LL | | -LL | | } - | |_________- similarly named function `f` defined here +LL | fn f() { + | ------ similarly named function `f` defined here +LL | S(10); + | ^ help: a function with a similar name exists: `f` error: aborting due to previous error diff --git a/src/test/ui/proc-macro/resolve-error.stderr b/src/test/ui/proc-macro/resolve-error.stderr index 73a6ab1cfb910..15a1d6d9479fe 100644 --- a/src/test/ui/proc-macro/resolve-error.stderr +++ b/src/test/ui/proc-macro/resolve-error.stderr @@ -18,24 +18,20 @@ LL | Dlona!(); error: cannot find macro `attr_proc_macra` in this scope --> $DIR/resolve-error.rs:58:5 | -LL | / macro_rules! attr_proc_mac { -LL | | () => {} -LL | | } - | |_- similarly named macro `attr_proc_mac` defined here +LL | macro_rules! attr_proc_mac { + | -------------------------- similarly named macro `attr_proc_mac` defined here ... -LL | attr_proc_macra!(); - | ^^^^^^^^^^^^^^^ help: a macro with a similar name exists: `attr_proc_mac` +LL | attr_proc_macra!(); + | ^^^^^^^^^^^^^^^ help: a macro with a similar name exists: `attr_proc_mac` error: cannot find macro `FooWithLongNama` in this scope --> $DIR/resolve-error.rs:55:5 | -LL | / macro_rules! FooWithLongNam { -LL | | () => {} -LL | | } - | |_- similarly named macro `FooWithLongNam` defined here +LL | macro_rules! FooWithLongNam { + | --------------------------- similarly named macro `FooWithLongNam` defined here ... -LL | FooWithLongNama!(); - | ^^^^^^^^^^^^^^^ help: a macro with a similar name exists: `FooWithLongNam` +LL | FooWithLongNama!(); + | ^^^^^^^^^^^^^^^ help: a macro with a similar name exists: `FooWithLongNam` error: cannot find derive macro `attr_proc_macra` in this scope --> $DIR/resolve-error.rs:49:10 diff --git a/src/test/ui/resolve/issue-5035.stderr b/src/test/ui/resolve/issue-5035.stderr index 1674c166ddacb..622f0dfcda4cb 100644 --- a/src/test/ui/resolve/issue-5035.stderr +++ b/src/test/ui/resolve/issue-5035.stderr @@ -8,7 +8,7 @@ error[E0404]: expected trait, found type alias `K` --> $DIR/issue-5035.rs:3:6 | LL | trait I {} - | ---------- similarly named trait `I` defined here + | ------- similarly named trait `I` defined here LL | type K = dyn I; LL | impl K for isize {} | ^ diff --git a/src/test/ui/resolve/levenshtein.stderr b/src/test/ui/resolve/levenshtein.stderr index a622d6cb34948..ecdec3c24a1d8 100644 --- a/src/test/ui/resolve/levenshtein.stderr +++ b/src/test/ui/resolve/levenshtein.stderr @@ -8,7 +8,7 @@ error[E0412]: cannot find type `Baz` in this scope --> $DIR/levenshtein.rs:14:10 | LL | enum Bar { } - | ------------ similarly named enum `Bar` defined here + | -------- similarly named enum `Bar` defined here LL | LL | type A = Baz; // Misspelled type name. | ^^^ help: an enum with a similar name exists: `Bar` @@ -43,7 +43,7 @@ error[E0425]: cannot find function `foobar` in this scope --> $DIR/levenshtein.rs:30:5 | LL | fn foo_bar() {} - | --------------- similarly named function `foo_bar` defined here + | ------------ similarly named function `foo_bar` defined here ... LL | foobar(); // Misspelled function name. | ^^^^^^ help: a function with a similar name exists: `foo_bar` diff --git a/src/test/ui/resolve/privacy-enum-ctor.stderr b/src/test/ui/resolve/privacy-enum-ctor.stderr index 08a1d790197a6..1187a661bbed1 100644 --- a/src/test/ui/resolve/privacy-enum-ctor.stderr +++ b/src/test/ui/resolve/privacy-enum-ctor.stderr @@ -16,15 +16,11 @@ LL | m::Z::Unit; error[E0423]: expected value, found enum `Z` --> $DIR/privacy-enum-ctor.rs:25:9 | -LL | / fn f() { -LL | | n::Z; -LL | | -LL | | Z; - | | ^ -... | -LL | | // This is ok, it is equivalent to not having braces -LL | | } - | |_____- similarly named function `f` defined here +LL | fn f() { + | ------ similarly named function `f` defined here +... +LL | Z; + | ^ | help: a function with a similar name exists | @@ -53,17 +49,11 @@ LL | let _: Z = Z::Struct; error[E0423]: expected value, found enum `m::E` --> $DIR/privacy-enum-ctor.rs:41:16 | -LL | / fn f() { -LL | | n::Z; -LL | | -LL | | Z; -... | -LL | | // This is ok, it is equivalent to not having braces -LL | | } - | |_____- similarly named function `f` defined here +LL | fn f() { + | ------ similarly named function `f` defined here ... -LL | let _: E = m::E; - | ^^^^ +LL | let _: E = m::E; + | ^^^^ | help: a function with a similar name exists | @@ -130,17 +120,11 @@ LL | let _: E = E::Struct; error[E0412]: cannot find type `Z` in this scope --> $DIR/privacy-enum-ctor.rs:57:12 | -LL | / pub enum E { -LL | | Fn(u8), -LL | | Struct { -LL | | s: u8, -LL | | }, -LL | | Unit, -LL | | } - | |_____- similarly named enum `E` defined here +LL | pub enum E { + | ---------- similarly named enum `E` defined here ... -LL | let _: Z = m::n::Z; - | ^ +LL | let _: Z = m::n::Z; + | ^ | help: an enum with a similar name exists | @@ -169,17 +153,11 @@ LL | let _: Z = m::Z::Unit; error[E0412]: cannot find type `Z` in this scope --> $DIR/privacy-enum-ctor.rs:61:12 | -LL | / pub enum E { -LL | | Fn(u8), -LL | | Struct { -LL | | s: u8, -LL | | }, -LL | | Unit, -LL | | } - | |_____- similarly named enum `E` defined here +LL | pub enum E { + | ---------- similarly named enum `E` defined here ... -LL | let _: Z = m::n::Z::Fn; - | ^ +LL | let _: Z = m::n::Z::Fn; + | ^ | help: an enum with a similar name exists | @@ -193,17 +171,11 @@ LL | use m::n::Z; error[E0412]: cannot find type `Z` in this scope --> $DIR/privacy-enum-ctor.rs:64:12 | -LL | / pub enum E { -LL | | Fn(u8), -LL | | Struct { -LL | | s: u8, -LL | | }, -LL | | Unit, -LL | | } - | |_____- similarly named enum `E` defined here +LL | pub enum E { + | ---------- similarly named enum `E` defined here ... -LL | let _: Z = m::n::Z::Struct; - | ^ +LL | let _: Z = m::n::Z::Struct; + | ^ | help: an enum with a similar name exists | @@ -228,17 +200,11 @@ LL | let _: Z = m::n::Z::Struct; error[E0412]: cannot find type `Z` in this scope --> $DIR/privacy-enum-ctor.rs:68:12 | -LL | / pub enum E { -LL | | Fn(u8), -LL | | Struct { -LL | | s: u8, -LL | | }, -LL | | Unit, -LL | | } - | |_____- similarly named enum `E` defined here +LL | pub enum E { + | ---------- similarly named enum `E` defined here ... -LL | let _: Z = m::n::Z::Unit {}; - | ^ +LL | let _: Z = m::n::Z::Unit {}; + | ^ | help: an enum with a similar name exists | diff --git a/src/test/ui/traits/trait-impl-for-module.stderr b/src/test/ui/traits/trait-impl-for-module.stderr index 4b3c930dccd45..cd2713a5bd50c 100644 --- a/src/test/ui/traits/trait-impl-for-module.stderr +++ b/src/test/ui/traits/trait-impl-for-module.stderr @@ -1,12 +1,11 @@ error[E0573]: expected type, found module `a` --> $DIR/trait-impl-for-module.rs:7:12 | -LL | / trait A { -LL | | } - | |_- similarly named trait `A` defined here -LL | -LL | impl A for a { - | ^ help: a trait with a similar name exists: `A` +LL | trait A { + | ------- similarly named trait `A` defined here +... +LL | impl A for a { + | ^ help: a trait with a similar name exists: `A` error: aborting due to previous error diff --git a/src/test/ui/ufcs/ufcs-partially-resolved.stderr b/src/test/ui/ufcs/ufcs-partially-resolved.stderr index 7177ca4908545..3950dc9877cd8 100644 --- a/src/test/ui/ufcs/ufcs-partially-resolved.stderr +++ b/src/test/ui/ufcs/ufcs-partially-resolved.stderr @@ -35,7 +35,7 @@ error[E0576]: cannot find method or associated constant `N` in trait `Tr` --> $DIR/ufcs-partially-resolved.rs:22:17 | LL | fn Y() {} - | --------- similarly named associated function `Y` defined here + | ------ similarly named associated function `Y` defined here ... LL | ::N; | ^ help: an associated function with a similar name exists: `Y` @@ -181,7 +181,7 @@ error[E0575]: expected method or associated constant, found associated type `Dr: --> $DIR/ufcs-partially-resolved.rs:53:5 | LL | fn Z() {} - | --------- similarly named associated function `Z` defined here + | ------ similarly named associated function `Z` defined here ... LL | ::X; | ^^^^^^^^^^^^- From 54e103b2f9d0141ce751df3e99b3a7bc4337181b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 21 Mar 2020 12:50:22 +0100 Subject: [PATCH 06/34] don't convert results to options just for matching (clippy::if_let_some_result) --- src/librustc_target/spec/apple_base.rs | 2 +- src/librustc_target/spec/apple_sdk_base.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/librustc_target/spec/apple_base.rs b/src/librustc_target/spec/apple_base.rs index d116ddf952aaa..4ad65569e6a8a 100644 --- a/src/librustc_target/spec/apple_base.rs +++ b/src/librustc_target/spec/apple_base.rs @@ -57,7 +57,7 @@ pub fn macos_link_env_remove() -> Vec { let mut env_remove = Vec::with_capacity(2); // Remove the `SDKROOT` environment variable if it's clearly set for the wrong platform, which // may occur when we're linking a custom build script while targeting iOS for example. - if let Some(sdkroot) = env::var("SDKROOT").ok() { + if let Ok(sdkroot) = env::var("SDKROOT") { if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("iPhoneSimulator.platform") { env_remove.push("SDKROOT".to_string()) } diff --git a/src/librustc_target/spec/apple_sdk_base.rs b/src/librustc_target/spec/apple_sdk_base.rs index 513754352fbfb..03e0c55282e4d 100644 --- a/src/librustc_target/spec/apple_sdk_base.rs +++ b/src/librustc_target/spec/apple_sdk_base.rs @@ -43,7 +43,7 @@ pub fn get_sdk_root(sdk_name: &str) -> Result { // to allow the SDK path to be set. (For clang, xcrun sets // SDKROOT; for rustc, the user or build system can set it, or we // can fall back to checking for xcrun on PATH.) - if let Some(sdkroot) = env::var("SDKROOT").ok() { + if let Ok(sdkroot) = env::var("SDKROOT") { let p = Path::new(&sdkroot); match sdk_name { // Ignore `SDKROOT` if it's clearly set for the wrong platform. From 1dcbdbdf4ff808906d68c59e1e4be30c2a658797 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 21 Mar 2020 13:14:44 +0100 Subject: [PATCH 07/34] use let instead of match for matches with single bindings (clippy::match_single_binding) --- .../deriving/generic/mod.rs | 5 ++-- src/librustc_typeck/check/method/mod.rs | 23 +++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/librustc_builtin_macros/deriving/generic/mod.rs b/src/librustc_builtin_macros/deriving/generic/mod.rs index ee32e914acba4..9338f9afbbb31 100644 --- a/src/librustc_builtin_macros/deriving/generic/mod.rs +++ b/src/librustc_builtin_macros/deriving/generic/mod.rs @@ -1056,8 +1056,9 @@ impl<'a> MethodDef<'a> { self_: field, other: other_fields .iter_mut() - .map(|l| match l.next().unwrap() { - (.., ex, _) => ex, + .map(|l| { + let (.., ex, _) = l.next().unwrap(); + ex }) .collect(), attrs, diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index 3cf7b65e30f2f..7068e3c521c81 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -368,11 +368,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let fn_sig = tcx.fn_sig(def_id); let fn_sig = self.replace_bound_vars_with_fresh_vars(span, infer::FnCall, &fn_sig).0; let fn_sig = fn_sig.subst(self.tcx, substs); - let fn_sig = match self.normalize_associated_types_in_as_infer_ok(span, &fn_sig) { - InferOk { value, obligations: o } => { - obligations.extend(o); - value - } + + let InferOk { value, obligations: o } = + self.normalize_associated_types_in_as_infer_ok(span, &fn_sig); + let fn_sig = { + obligations.extend(o); + value }; // Register obligations for the parameters. This will include the @@ -384,12 +385,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Note that as the method comes from a trait, it should not have // any late-bound regions appearing in its bounds. let bounds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs); - let bounds = match self.normalize_associated_types_in_as_infer_ok(span, &bounds) { - InferOk { value, obligations: o } => { - obligations.extend(o); - value - } + + let InferOk { value, obligations: o } = + self.normalize_associated_types_in_as_infer_ok(span, &bounds); + let bounds = { + obligations.extend(o); + value }; + assert!(!bounds.has_escaping_bound_vars()); let cause = traits::ObligationCause::misc(span, self.body_id); From 5566a1cee4df47b68c7902c6db3f207a2b4a479d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 21 Mar 2020 13:37:29 +0100 Subject: [PATCH 08/34] remove redundant returns (clippy::needless_return) --- src/librustc_span/source_map.rs | 8 ++++---- src/librustdoc/theme.rs | 4 +--- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/librustc_span/source_map.rs b/src/librustc_span/source_map.rs index 39eb318a785e7..8f806909f0047 100644 --- a/src/librustc_span/source_map.rs +++ b/src/librustc_span/source_map.rs @@ -370,11 +370,11 @@ impl SourceMap { pub fn doctest_offset_line(&self, file: &FileName, orig: usize) -> usize { match file { FileName::DocTest(_, offset) => { - return if *offset >= 0 { - orig + *offset as usize - } else { + if *offset < 0 { orig - (-(*offset)) as usize - }; + } else { + orig + *offset as usize + } } _ => orig, } diff --git a/src/librustdoc/theme.rs b/src/librustdoc/theme.rs index a8a571e7c5491..9dd1d3706ffbd 100644 --- a/src/librustdoc/theme.rs +++ b/src/librustdoc/theme.rs @@ -234,9 +234,7 @@ pub fn load_css_paths(v: &[u8]) -> CssPath { } pub fn get_differences(against: &CssPath, other: &CssPath, v: &mut Vec) { - if against.name != other.name { - return; - } else { + if against.name == other.name { for child in &against.children { let mut found = false; let mut found_working = false; From 3b4c2f67add84b905f3ad8066846b34e36ee5ea3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 21 Mar 2020 13:53:34 +0100 Subject: [PATCH 09/34] don't redundantly repeat field names (clippy::redundant_field_names) --- src/librustc_infer/traits/project.rs | 2 +- src/librustc_infer/traits/util.rs | 2 +- src/librustc_trait_selection/traits/select.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/librustc_infer/traits/project.rs b/src/librustc_infer/traits/project.rs index 183e4be189022..06870ccc7dd5e 100644 --- a/src/librustc_infer/traits/project.rs +++ b/src/librustc_infer/traits/project.rs @@ -23,7 +23,7 @@ pub type NormalizedTy<'tcx> = Normalized<'tcx, Ty<'tcx>>; impl<'tcx, T> Normalized<'tcx, T> { pub fn with(self, value: U) -> Normalized<'tcx, U> { - Normalized { value: value, obligations: self.obligations } + Normalized { value, obligations: self.obligations } } } diff --git a/src/librustc_infer/traits/util.rs b/src/librustc_infer/traits/util.rs index a7c0267111522..90f3cb1d24ccc 100644 --- a/src/librustc_infer/traits/util.rs +++ b/src/librustc_infer/traits/util.rs @@ -47,7 +47,7 @@ struct PredicateSet<'tcx> { impl PredicateSet<'tcx> { fn new(tcx: TyCtxt<'tcx>) -> Self { - Self { tcx: tcx, set: Default::default() } + Self { tcx, set: Default::default() } } fn insert(&mut self, pred: &ty::Predicate<'tcx>) -> bool { diff --git a/src/librustc_trait_selection/traits/select.rs b/src/librustc_trait_selection/traits/select.rs index 660d4d14bc728..ca169d550e782 100644 --- a/src/librustc_trait_selection/traits/select.rs +++ b/src/librustc_trait_selection/traits/select.rs @@ -2792,7 +2792,7 @@ impl<'cx, 'tcx> SelectionContext<'cx, 'tcx> { trait_def_id, trait_obligations ); - VtableTraitAliasData { alias_def_id, substs: substs, nested: trait_obligations } + VtableTraitAliasData { alias_def_id, substs, nested: trait_obligations } }) } From c8140a88f67cf1fea104b1aaa615af7816984615 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20B=C3=A4chler?= Date: Sat, 21 Mar 2020 19:48:23 +0100 Subject: [PATCH 10/34] Return NonZeroU64 from ThreadId::as_u64. As discussed in #67939, this allows turning Option into Option which can then be stored inside an AtomicU64. --- src/librustc_data_structures/profiling.rs | 4 ++-- src/libstd/thread/mod.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/librustc_data_structures/profiling.rs b/src/librustc_data_structures/profiling.rs index a70314c35c07c..a7cdc48d60342 100644 --- a/src/librustc_data_structures/profiling.rs +++ b/src/librustc_data_structures/profiling.rs @@ -345,7 +345,7 @@ impl SelfProfilerRef { ) { drop(self.exec(event_filter, |profiler| { let event_id = StringId::new_virtual(query_invocation_id.0); - let thread_id = std::thread::current().id().as_u64() as u32; + let thread_id = std::thread::current().id().as_u64().get() as u32; profiler.profiler.record_instant_event( event_kind(profiler), @@ -522,7 +522,7 @@ impl<'a> TimingGuard<'a> { event_kind: StringId, event_id: EventId, ) -> TimingGuard<'a> { - let thread_id = std::thread::current().id().as_u64() as u32; + let thread_id = std::thread::current().id().as_u64().get() as u32; let raw_profiler = &profiler.profiler; let timing_guard = raw_profiler.start_recording_interval_event(event_kind, event_id, thread_id); diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs index 0dc43c7e6510a..282e268efd206 100644 --- a/src/libstd/thread/mod.rs +++ b/src/libstd/thread/mod.rs @@ -1082,8 +1082,8 @@ impl ThreadId { /// it is not guaranteed which values new threads will return, and this may /// change across Rust versions. #[unstable(feature = "thread_id_value", issue = "67939")] - pub fn as_u64(&self) -> u64 { - self.0.get() + pub fn as_u64(&self) -> NonZeroU64 { + self.0 } } From a6692b793542291c5bf935d50d9a44982d792719 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 21 Mar 2020 14:24:57 +0100 Subject: [PATCH 11/34] clarify when we pass () to functions (clippy::unit_arg) --- src/librustc_mir/interpret/eval_context.rs | 3 ++- .../interpret/intrinsics/type_name.rs | 3 ++- src/librustc_mir/interpret/terminator.rs | 2 +- src/librustc_traits/type_op.rs | 16 +++++++++------- 4 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index 68a893dc4be5d..ac593d0845a7d 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -581,7 +581,8 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { /// If `target` is `None`, that indicates the function cannot return, so we raise UB. pub fn return_to_block(&mut self, target: Option) -> InterpResult<'tcx> { if let Some(target) = target { - Ok(self.go_to_block(target)) + self.go_to_block(target); + Ok(()) } else { throw_ub!(Unreachable) } diff --git a/src/librustc_mir/interpret/intrinsics/type_name.rs b/src/librustc_mir/interpret/intrinsics/type_name.rs index 677dc69773516..162387308040d 100644 --- a/src/librustc_mir/interpret/intrinsics/type_name.rs +++ b/src/librustc_mir/interpret/intrinsics/type_name.rs @@ -192,7 +192,8 @@ impl PrettyPrinter<'tcx> for AbsolutePathPrinter<'tcx> { impl Write for AbsolutePathPrinter<'_> { fn write_str(&mut self, s: &str) -> std::fmt::Result { - Ok(self.path.push_str(s)) + self.path.push_str(s); + Ok(()) } } diff --git a/src/librustc_mir/interpret/terminator.rs b/src/librustc_mir/interpret/terminator.rs index a9e45a032a6be..6b0bbe4f6e0bb 100644 --- a/src/librustc_mir/interpret/terminator.rs +++ b/src/librustc_mir/interpret/terminator.rs @@ -370,7 +370,7 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> { self.stack.pop(); Err(err) } - Ok(v) => Ok(v), + Ok(()) => Ok(()), } } // cannot use the shim here, because that will only result in infinite recursion diff --git a/src/librustc_traits/type_op.rs b/src/librustc_traits/type_op.rs index e174c040e0da1..7ed828c91679c 100644 --- a/src/librustc_traits/type_op.rs +++ b/src/librustc_traits/type_op.rs @@ -80,11 +80,11 @@ impl AscribeUserTypeCx<'me, 'tcx> { where T: ToTrace<'tcx>, { - Ok(self - .infcx + self.infcx .at(&ObligationCause::dummy(), self.param_env) .relate(a, variance, b)? - .into_value_registering_obligations(self.infcx, self.fulfill_cx)) + .into_value_registering_obligations(self.infcx, self.fulfill_cx); + Ok(()) } fn prove_predicate(&mut self, predicate: Predicate<'tcx>) { @@ -165,10 +165,11 @@ fn type_op_eq<'tcx>( ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> { tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| { let (param_env, Eq { a, b }) = key.into_parts(); - Ok(infcx + infcx .at(&ObligationCause::dummy(), param_env) .eq(a, b)? - .into_value_registering_obligations(infcx, fulfill_cx)) + .into_value_registering_obligations(infcx, fulfill_cx); + Ok(()) }) } @@ -221,10 +222,11 @@ fn type_op_subtype<'tcx>( ) -> Result<&'tcx Canonical<'tcx, QueryResponse<'tcx, ()>>, NoSolution> { tcx.infer_ctxt().enter_canonical_trait_query(&canonicalized, |infcx, fulfill_cx, key| { let (param_env, Subtype { sub, sup }) = key.into_parts(); - Ok(infcx + infcx .at(&ObligationCause::dummy(), param_env) .sup(sup, sub)? - .into_value_registering_obligations(infcx, fulfill_cx)) + .into_value_registering_obligations(infcx, fulfill_cx); + Ok(()) }) } From 47e9775a9a529302d963937b558dd6691854e1cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 21 Mar 2020 14:44:17 +0100 Subject: [PATCH 12/34] make some let-if-bindings more idiomatic (clippy::useless_let_if_seq) --- src/librustc/ty/layout.rs | 54 +++++++++---------- .../borrow_check/diagnostics/move_errors.rs | 12 ++--- src/librustc_mir_build/build/mod.rs | 9 ++-- src/librustc_resolve/build_reduced_graph.rs | 12 +++-- 4 files changed, 41 insertions(+), 46 deletions(-) diff --git a/src/librustc/ty/layout.rs b/src/librustc/ty/layout.rs index 6d28796b34847..d66fcd3a20db9 100644 --- a/src/librustc/ty/layout.rs +++ b/src/librustc/ty/layout.rs @@ -381,12 +381,8 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { // Field 5 would be the first element, so memory_index is i: // Note: if we didn't optimize, it's already right. - let memory_index; - if optimize { - memory_index = invert_mapping(&inverse_memory_index); - } else { - memory_index = inverse_memory_index; - } + let memory_index = + if optimize { invert_mapping(&inverse_memory_index) } else { inverse_memory_index }; let size = min_size.align_to(align.abi); let mut abi = Abi::Aggregate { sized }; @@ -944,33 +940,33 @@ impl<'tcx> LayoutCx<'tcx, TyCtxt<'tcx>> { let offset = st[i].fields.offset(field_index) + niche.offset; let size = st[i].size; - let mut abi = match st[i].abi { - Abi::Scalar(_) => Abi::Scalar(niche_scalar.clone()), - Abi::ScalarPair(ref first, ref second) => { - // We need to use scalar_unit to reset the - // valid range to the maximal one for that - // primitive, because only the niche is - // guaranteed to be initialised, not the - // other primitive. - if offset.bytes() == 0 { - Abi::ScalarPair( - niche_scalar.clone(), - scalar_unit(second.value), - ) - } else { - Abi::ScalarPair( - scalar_unit(first.value), - niche_scalar.clone(), - ) + let abi = if st.iter().all(|v| v.abi.is_uninhabited()) { + Abi::Uninhabited + } else { + match st[i].abi { + Abi::Scalar(_) => Abi::Scalar(niche_scalar.clone()), + Abi::ScalarPair(ref first, ref second) => { + // We need to use scalar_unit to reset the + // valid range to the maximal one for that + // primitive, because only the niche is + // guaranteed to be initialised, not the + // other primitive. + if offset.bytes() == 0 { + Abi::ScalarPair( + niche_scalar.clone(), + scalar_unit(second.value), + ) + } else { + Abi::ScalarPair( + scalar_unit(first.value), + niche_scalar.clone(), + ) + } } + _ => Abi::Aggregate { sized: true }, } - _ => Abi::Aggregate { sized: true }, }; - if st.iter().all(|v| v.abi.is_uninhabited()) { - abi = Abi::Uninhabited; - } - let largest_niche = Niche::from_scalar(dl, offset, niche_scalar.clone()); diff --git a/src/librustc_mir/borrow_check/diagnostics/move_errors.rs b/src/librustc_mir/borrow_check/diagnostics/move_errors.rs index 9451fee499d36..7b65a5a10986a 100644 --- a/src/librustc_mir/borrow_check/diagnostics/move_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/move_errors.rs @@ -490,17 +490,13 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { { if pat_snippet.starts_with('&') { let pat_snippet = pat_snippet[1..].trim_start(); - let suggestion; - let to_remove; - if pat_snippet.starts_with("mut") + let (suggestion, to_remove) = if pat_snippet.starts_with("mut") && pat_snippet["mut".len()..].starts_with(rustc_lexer::is_whitespace) { - suggestion = pat_snippet["mut".len()..].trim_start(); - to_remove = "&mut"; + (pat_snippet["mut".len()..].trim_start(), "&mut") } else { - suggestion = pat_snippet; - to_remove = "&"; - } + (pat_snippet, "&") + }; suggestions.push((pat_span, to_remove, suggestion.to_owned())); } } diff --git a/src/librustc_mir_build/build/mod.rs b/src/librustc_mir_build/build/mod.rs index c21834bfde84b..d66650329313b 100644 --- a/src/librustc_mir_build/build/mod.rs +++ b/src/librustc_mir_build/build/mod.rs @@ -637,11 +637,12 @@ where ); assert_eq!(block, builder.return_block()); - let mut spread_arg = None; - if abi == Abi::RustCall { + let spread_arg = if abi == Abi::RustCall { // RustCall pseudo-ABI untuples the last argument. - spread_arg = Some(Local::new(arguments.len())); - } + Some(Local::new(arguments.len())) + } else { + None + }; debug!("fn_id {:?} has attrs {:?}", fn_def_id, tcx.get_attrs(fn_def_id)); let mut body = builder.finish(); diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index ce3b1233a7473..77d6e4560ab93 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -750,14 +750,16 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { // If this is a tuple or unit struct, define a name // in the value namespace as well. if let Some(ctor_node_id) = vdata.ctor_id() { - let mut ctor_vis = vis; // If the structure is marked as non_exhaustive then lower the visibility // to within the crate. - if vis == ty::Visibility::Public + let mut ctor_vis = if vis == ty::Visibility::Public && attr::contains_name(&item.attrs, sym::non_exhaustive) { - ctor_vis = ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)); - } + ty::Visibility::Restricted(DefId::local(CRATE_DEF_INDEX)) + } else { + vis + }; + for field in vdata.fields() { // NOTE: The field may be an expansion placeholder, but expansion sets // correct visibilities for unnamed field placeholders specifically, so the @@ -1166,7 +1168,7 @@ macro_rules! method { visit::$walk(self, node); } } - } + }; } impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> { From e45fdcfa9a611e4b29b727fb1c70ea60423f1c24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 21 Mar 2020 15:06:04 +0100 Subject: [PATCH 13/34] remove unused unit values (clippy::unused_unit) --- src/librustc/ty/query/plumbing.rs | 2 +- src/librustc_mir/const_eval/machine.rs | 4 +-- src/librustc_mir/transform/const_prop.rs | 4 +-- src/librustc_mir_build/build/expr/as_temp.rs | 5 +--- src/librustc_target/spec/apple_sdk_base.rs | 26 +++++--------------- src/librustc_typeck/coherence/builtin.rs | 5 +--- 6 files changed, 11 insertions(+), 35 deletions(-) diff --git a/src/librustc/ty/query/plumbing.rs b/src/librustc/ty/query/plumbing.rs index acf67f52dceaa..3d59fc782113b 100644 --- a/src/librustc/ty/query/plumbing.rs +++ b/src/librustc/ty/query/plumbing.rs @@ -692,7 +692,7 @@ impl<'tcx> TyCtxt<'tcx> { /// side-effects -- e.g., in order to report errors for erroneous programs. /// /// Note: The optimization is only available during incr. comp. - pub(super) fn ensure_query + 'tcx>(self, key: Q::Key) -> () { + pub(super) fn ensure_query + 'tcx>(self, key: Q::Key) { if Q::EVAL_ALWAYS { let _ = self.get_query::(DUMMY_SP, key); return; diff --git a/src/librustc_mir/const_eval/machine.rs b/src/librustc_mir/const_eval/machine.rs index d81aae6523a45..87d0424ece944 100644 --- a/src/librustc_mir/const_eval/machine.rs +++ b/src/librustc_mir/const_eval/machine.rs @@ -335,9 +335,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for CompileTimeInterpreter<'mir, } #[inline(always)] - fn tag_static_base_pointer(_memory_extra: &MemoryExtra, _id: AllocId) -> Self::PointerTag { - () - } + fn tag_static_base_pointer(_memory_extra: &MemoryExtra, _id: AllocId) -> Self::PointerTag {} fn box_alloc( _ecx: &mut InterpCx<'mir, 'tcx, Self>, diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 8d7cafc34b356..ba29b187b226e 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -232,9 +232,7 @@ impl<'mir, 'tcx> interpret::Machine<'mir, 'tcx> for ConstPropMachine { } #[inline(always)] - fn tag_static_base_pointer(_memory_extra: &(), _id: AllocId) -> Self::PointerTag { - () - } + fn tag_static_base_pointer(_memory_extra: &(), _id: AllocId) -> Self::PointerTag {} fn box_alloc( _ecx: &mut InterpCx<'mir, 'tcx, Self>, diff --git a/src/librustc_mir_build/build/expr/as_temp.rs b/src/librustc_mir_build/build/expr/as_temp.rs index 34dd10cbc0fc8..82183e6c96e9f 100644 --- a/src/librustc_mir_build/build/expr/as_temp.rs +++ b/src/librustc_mir_build/build/expr/as_temp.rs @@ -73,10 +73,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { // they are never assigned. ExprKind::Break { .. } | ExprKind::Continue { .. } | ExprKind::Return { .. } => (), ExprKind::Block { body: hir::Block { expr: None, targeted_by_break: false, .. } } - if expr_ty.is_never() => - { - () - } + if expr_ty.is_never() => {} _ => { this.cfg .push(block, Statement { source_info, kind: StatementKind::StorageLive(temp) }); diff --git a/src/librustc_target/spec/apple_sdk_base.rs b/src/librustc_target/spec/apple_sdk_base.rs index 03e0c55282e4d..c7cff17b1544c 100644 --- a/src/librustc_target/spec/apple_sdk_base.rs +++ b/src/librustc_target/spec/apple_sdk_base.rs @@ -49,34 +49,20 @@ pub fn get_sdk_root(sdk_name: &str) -> Result { // Ignore `SDKROOT` if it's clearly set for the wrong platform. "appletvos" if sdkroot.contains("TVSimulator.platform") - || sdkroot.contains("MacOSX.platform") => - { - () - } + || sdkroot.contains("MacOSX.platform") => {} "appletvsimulator" - if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => - { - () - } + if sdkroot.contains("TVOS.platform") || sdkroot.contains("MacOSX.platform") => {} "iphoneos" if sdkroot.contains("iPhoneSimulator.platform") - || sdkroot.contains("MacOSX.platform") => - { - () - } + || sdkroot.contains("MacOSX.platform") => {} "iphonesimulator" - if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => - { - () + if sdkroot.contains("iPhoneOS.platform") || sdkroot.contains("MacOSX.platform") => { } "macosx10.15" if sdkroot.contains("iPhoneOS.platform") - || sdkroot.contains("iPhoneSimulator.platform") => - { - () - } + || sdkroot.contains("iPhoneSimulator.platform") => {} // Ignore `SDKROOT` if it's not a valid path. - _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => (), + _ if !p.is_absolute() || p == Path::new("/") || !p.exists() => {} _ => return Ok(sdkroot), } } diff --git a/src/librustc_typeck/coherence/builtin.rs b/src/librustc_typeck/coherence/builtin.rs index e24d9bebf657f..d0a87e240da89 100644 --- a/src/librustc_typeck/coherence/builtin.rs +++ b/src/librustc_typeck/coherence/builtin.rs @@ -178,10 +178,7 @@ fn visit_implementation_of_dispatch_from_dyn(tcx: TyCtxt<'_>, impl_did: DefId) { use ty::TyKind::*; match (&source.kind, &target.kind) { (&Ref(r_a, _, mutbl_a), Ref(r_b, _, mutbl_b)) - if infcx.at(&cause, param_env).eq(r_a, r_b).is_ok() && mutbl_a == *mutbl_b => - { - () - } + if infcx.at(&cause, param_env).eq(r_a, r_b).is_ok() && mutbl_a == *mutbl_b => {} (&RawPtr(tm_a), &RawPtr(tm_b)) if tm_a.mutbl == tm_b.mutbl => (), (&Adt(def_a, substs_a), &Adt(def_b, substs_b)) if def_a.is_struct() && def_b.is_struct() => From c2fd4657a6ad7ab211e15045b8c518b44e92e98f Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 08:29:34 +0100 Subject: [PATCH 14/34] rustc_expand::base: nix panictry! uses --- src/librustc_expand/base.rs | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index 0fc477bbd0b4c..e47e0a757866c 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -1168,6 +1168,18 @@ pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) } } +/// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`. +fn parse_expr(p: &mut parser::Parser<'_>) -> Option> { + match p.parse_expr() { + Ok(e) => return Some(e), + Err(mut err) => err.emit(), + } + while p.token != token::Eof { + p.bump(); + } + None +} + /// Interpreting `tts` as a comma-separated sequence of expressions, /// expect exactly one string literal, or emit an error and return `None`. pub fn get_single_str_from_tts( @@ -1181,7 +1193,7 @@ pub fn get_single_str_from_tts( cx.span_err(sp, &format!("{} takes 1 argument", name)); return None; } - let ret = panictry!(p.parse_expr()); + let ret = parse_expr(&mut p)?; let _ = p.eat(&token::Comma); if p.token != token::Eof { @@ -1190,8 +1202,8 @@ pub fn get_single_str_from_tts( expr_to_string(cx, ret, "argument must be a string literal").map(|(s, _)| s.to_string()) } -/// Extracts comma-separated expressions from `tts`. If there is a -/// parsing error, emit a non-fatal error and return `None`. +/// Extracts comma-separated expressions from `tts`. +/// On error, emit it, and return `None`. pub fn get_exprs_from_tts( cx: &mut ExtCtxt<'_>, sp: Span, @@ -1200,7 +1212,7 @@ pub fn get_exprs_from_tts( let mut p = cx.new_parser_from_tts(tts); let mut es = Vec::new(); while p.token != token::Eof { - let expr = panictry!(p.parse_expr()); + let expr = parse_expr(&mut p)?; // Perform eager expansion on the expression. // We want to be able to handle e.g., `concat!("foo", "bar")`. From 2a9cd1d1c1fc5e7d70da831cd817e115a31f74dc Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 08:55:28 +0100 Subject: [PATCH 15/34] nix panictry! in ParserAnyMacro::make --- src/librustc_expand/expand.rs | 2 +- src/librustc_expand/mbe/macro_rules.rs | 77 +++++++++++-------- .../edition-keywords-2018-2015-parsing.rs | 8 +- .../edition-keywords-2018-2015-parsing.stderr | 22 ++++-- .../edition-keywords-2018-2018-parsing.rs | 8 +- .../edition-keywords-2018-2018-parsing.stderr | 22 ++++-- src/test/ui/macros/macro-context.rs | 2 + src/test/ui/macros/macro-context.stderr | 26 ++++++- src/test/ui/type/ascription/issue-47666.rs | 2 + .../ui/type/ascription/issue-47666.stderr | 32 +++++++- 10 files changed, 153 insertions(+), 48 deletions(-) diff --git a/src/librustc_expand/expand.rs b/src/librustc_expand/expand.rs index 4f568e5456c72..58217d98986bf 100644 --- a/src/librustc_expand/expand.rs +++ b/src/librustc_expand/expand.rs @@ -204,7 +204,7 @@ ast_fragments! { } impl AstFragmentKind { - fn dummy(self, span: Span) -> AstFragment { + crate fn dummy(self, span: Span) -> AstFragment { self.make_from(DummyResult::any(span)).expect("couldn't create a dummy AST fragment") } diff --git a/src/librustc_expand/mbe/macro_rules.rs b/src/librustc_expand/mbe/macro_rules.rs index 3de2169f1142e..0a346d483000e 100644 --- a/src/librustc_expand/mbe/macro_rules.rs +++ b/src/librustc_expand/mbe/macro_rules.rs @@ -83,41 +83,56 @@ fn suggest_slice_pat(e: &mut DiagnosticBuilder<'_>, site_span: Span, parser: &Pa ); } +fn emit_frag_parse_err( + mut e: DiagnosticBuilder<'_>, + parser: &Parser<'_>, + site_span: Span, + macro_ident: ast::Ident, + arm_span: Span, + kind: AstFragmentKind, +) { + if parser.token == token::Eof && e.message().ends_with(", found ``") { + if !e.span.is_dummy() { + // early end of macro arm (#52866) + e.replace_span_with(parser.sess.source_map().next_point(parser.token.span)); + } + let msg = &e.message[0]; + e.message[0] = ( + format!( + "macro expansion ends with an incomplete expression: {}", + msg.0.replace(", found ``", ""), + ), + msg.1, + ); + } + if e.span.is_dummy() { + // Get around lack of span in error (#30128) + e.replace_span_with(site_span); + if !parser.sess.source_map().is_imported(arm_span) { + e.span_label(arm_span, "in this macro arm"); + } + } else if parser.sess.source_map().is_imported(parser.token.span) { + e.span_label(site_span, "in this macro invocation"); + } + match kind { + AstFragmentKind::Pat if macro_ident.name == sym::vec => { + suggest_slice_pat(&mut e, site_span, parser); + } + _ => annotate_err_with_kind(&mut e, kind, site_span), + }; + e.emit(); +} + impl<'a> ParserAnyMacro<'a> { crate fn make(mut self: Box>, kind: AstFragmentKind) -> AstFragment { let ParserAnyMacro { site_span, macro_ident, ref mut parser, arm_span } = *self; - let fragment = panictry!(parse_ast_fragment(parser, kind).map_err(|mut e| { - if parser.token == token::Eof && e.message().ends_with(", found ``") { - if !e.span.is_dummy() { - // early end of macro arm (#52866) - e.replace_span_with(parser.sess.source_map().next_point(parser.token.span)); - } - let msg = &e.message[0]; - e.message[0] = ( - format!( - "macro expansion ends with an incomplete expression: {}", - msg.0.replace(", found ``", ""), - ), - msg.1, - ); + let fragment = match parse_ast_fragment(parser, kind) { + Ok(f) => f, + Err(err) => { + emit_frag_parse_err(err, parser, site_span, macro_ident, arm_span, kind); + return kind.dummy(site_span); } - if e.span.is_dummy() { - // Get around lack of span in error (#30128) - e.replace_span_with(site_span); - if !parser.sess.source_map().is_imported(arm_span) { - e.span_label(arm_span, "in this macro arm"); - } - } else if parser.sess.source_map().is_imported(parser.token.span) { - e.span_label(site_span, "in this macro invocation"); - } - match kind { - AstFragmentKind::Pat if macro_ident.name == sym::vec => { - suggest_slice_pat(&mut e, site_span, parser); - } - _ => annotate_err_with_kind(&mut e, kind, site_span), - }; - e - })); + }; // We allow semicolons at the end of expressions -- e.g., the semicolon in // `macro_rules! m { () => { panic!(); } }` isn't parsed by `.parse_expr()`, diff --git a/src/test/ui/editions/edition-keywords-2018-2015-parsing.rs b/src/test/ui/editions/edition-keywords-2018-2015-parsing.rs index dbc0465b08e77..a7a10d0f677af 100644 --- a/src/test/ui/editions/edition-keywords-2018-2015-parsing.rs +++ b/src/test/ui/editions/edition-keywords-2018-2015-parsing.rs @@ -1,9 +1,15 @@ // edition:2018 // aux-build:edition-kw-macro-2015.rs +fn main() {} + #[macro_use] extern crate edition_kw_macro_2015; +mod module { + pub fn r#async() {} +} + pub fn check_async() { let mut async = 1; //~ ERROR expected identifier, found keyword `async` let mut r#async = 1; // OK @@ -13,7 +19,7 @@ pub fn check_async() { r#async = consumes_async_raw!(async); //~ ERROR no rules expected the token `async` r#async = consumes_async_raw!(r#async); // OK - if passes_ident!(async) == 1 {} + if passes_ident!(async) == 1 {} //~ ERROR async closures are unstable if passes_ident!(r#async) == 1 {} // OK module::async(); //~ ERROR expected identifier, found keyword `async` module::r#async(); // OK diff --git a/src/test/ui/editions/edition-keywords-2018-2015-parsing.stderr b/src/test/ui/editions/edition-keywords-2018-2015-parsing.stderr index e12d1a48463d7..3c3b934b531c8 100644 --- a/src/test/ui/editions/edition-keywords-2018-2015-parsing.stderr +++ b/src/test/ui/editions/edition-keywords-2018-2015-parsing.stderr @@ -1,5 +1,5 @@ error: expected identifier, found keyword `async` - --> $DIR/edition-keywords-2018-2015-parsing.rs:8:13 + --> $DIR/edition-keywords-2018-2015-parsing.rs:14:13 | LL | let mut async = 1; | ^^^^^ expected identifier, found keyword @@ -10,7 +10,7 @@ LL | let mut r#async = 1; | ^^^^^^^ error: expected identifier, found keyword `async` - --> $DIR/edition-keywords-2018-2015-parsing.rs:18:13 + --> $DIR/edition-keywords-2018-2015-parsing.rs:24:13 | LL | module::async(); | ^^^^^ expected identifier, found keyword @@ -21,13 +21,13 @@ LL | module::r#async(); | ^^^^^^^ error: no rules expected the token `r#async` - --> $DIR/edition-keywords-2018-2015-parsing.rs:12:31 + --> $DIR/edition-keywords-2018-2015-parsing.rs:18:31 | LL | r#async = consumes_async!(r#async); | ^^^^^^^ no rules expected this token in macro call error: no rules expected the token `async` - --> $DIR/edition-keywords-2018-2015-parsing.rs:13:35 + --> $DIR/edition-keywords-2018-2015-parsing.rs:19:35 | LL | r#async = consumes_async_raw!(async); | ^^^^^ no rules expected this token in macro call @@ -38,10 +38,20 @@ error: macro expansion ends with an incomplete expression: expected one of `move LL | ($i: ident) => ($i) | ^ expected one of `move`, `|`, or `||` | - ::: $DIR/edition-keywords-2018-2015-parsing.rs:16:8 + ::: $DIR/edition-keywords-2018-2015-parsing.rs:22:8 | LL | if passes_ident!(async) == 1 {} | -------------------- in this macro invocation -error: aborting due to 5 previous errors +error[E0658]: async closures are unstable + --> $DIR/edition-keywords-2018-2015-parsing.rs:22:22 + | +LL | if passes_ident!(async) == 1 {} + | ^^^^^ + | + = note: see issue #62290 for more information + = help: add `#![feature(async_closure)]` to the crate attributes to enable + +error: aborting due to 6 previous errors +For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/ui/editions/edition-keywords-2018-2018-parsing.rs b/src/test/ui/editions/edition-keywords-2018-2018-parsing.rs index 5aca0839f0f15..b12ad76a74798 100644 --- a/src/test/ui/editions/edition-keywords-2018-2018-parsing.rs +++ b/src/test/ui/editions/edition-keywords-2018-2018-parsing.rs @@ -1,9 +1,15 @@ // edition:2018 // aux-build:edition-kw-macro-2018.rs +fn main() {} + #[macro_use] extern crate edition_kw_macro_2018; +mod module { + pub fn r#async() {} +} + pub fn check_async() { let mut async = 1; //~ ERROR expected identifier, found keyword `async` let mut r#async = 1; // OK @@ -13,7 +19,7 @@ pub fn check_async() { r#async = consumes_async_raw!(async); //~ ERROR no rules expected the token `async` r#async = consumes_async_raw!(r#async); // OK - if passes_ident!(async) == 1 {} + if passes_ident!(async) == 1 {} //~ ERROR async closures are unstable if passes_ident!(r#async) == 1 {} // OK module::async(); //~ ERROR expected identifier, found keyword `async` module::r#async(); // OK diff --git a/src/test/ui/editions/edition-keywords-2018-2018-parsing.stderr b/src/test/ui/editions/edition-keywords-2018-2018-parsing.stderr index 110165fc077ca..a2b129d17e0be 100644 --- a/src/test/ui/editions/edition-keywords-2018-2018-parsing.stderr +++ b/src/test/ui/editions/edition-keywords-2018-2018-parsing.stderr @@ -1,5 +1,5 @@ error: expected identifier, found keyword `async` - --> $DIR/edition-keywords-2018-2018-parsing.rs:8:13 + --> $DIR/edition-keywords-2018-2018-parsing.rs:14:13 | LL | let mut async = 1; | ^^^^^ expected identifier, found keyword @@ -10,7 +10,7 @@ LL | let mut r#async = 1; | ^^^^^^^ error: expected identifier, found keyword `async` - --> $DIR/edition-keywords-2018-2018-parsing.rs:18:13 + --> $DIR/edition-keywords-2018-2018-parsing.rs:24:13 | LL | module::async(); | ^^^^^ expected identifier, found keyword @@ -21,13 +21,13 @@ LL | module::r#async(); | ^^^^^^^ error: no rules expected the token `r#async` - --> $DIR/edition-keywords-2018-2018-parsing.rs:12:31 + --> $DIR/edition-keywords-2018-2018-parsing.rs:18:31 | LL | r#async = consumes_async!(r#async); | ^^^^^^^ no rules expected this token in macro call error: no rules expected the token `async` - --> $DIR/edition-keywords-2018-2018-parsing.rs:13:35 + --> $DIR/edition-keywords-2018-2018-parsing.rs:19:35 | LL | r#async = consumes_async_raw!(async); | ^^^^^ no rules expected this token in macro call @@ -38,10 +38,20 @@ error: macro expansion ends with an incomplete expression: expected one of `move LL | ($i: ident) => ($i) | ^ expected one of `move`, `|`, or `||` | - ::: $DIR/edition-keywords-2018-2018-parsing.rs:16:8 + ::: $DIR/edition-keywords-2018-2018-parsing.rs:22:8 | LL | if passes_ident!(async) == 1 {} | -------------------- in this macro invocation -error: aborting due to 5 previous errors +error[E0658]: async closures are unstable + --> $DIR/edition-keywords-2018-2018-parsing.rs:22:22 + | +LL | if passes_ident!(async) == 1 {} + | ^^^^^ + | + = note: see issue #62290 for more information + = help: add `#![feature(async_closure)]` to the crate attributes to enable + +error: aborting due to 6 previous errors +For more information about this error, try `rustc --explain E0658`. diff --git a/src/test/ui/macros/macro-context.rs b/src/test/ui/macros/macro-context.rs index 9130c3d921c52..13e179578ad01 100644 --- a/src/test/ui/macros/macro-context.rs +++ b/src/test/ui/macros/macro-context.rs @@ -4,6 +4,8 @@ macro_rules! m { //~| ERROR macro expansion ignores token `typeof` //~| ERROR macro expansion ignores token `;` //~| ERROR macro expansion ignores token `;` + //~| ERROR cannot find type `i` in this scope + //~| ERROR cannot find value `i` in this scope } fn main() { diff --git a/src/test/ui/macros/macro-context.stderr b/src/test/ui/macros/macro-context.stderr index 2e712110689f8..17c7389812475 100644 --- a/src/test/ui/macros/macro-context.stderr +++ b/src/test/ui/macros/macro-context.stderr @@ -42,5 +42,29 @@ LL | m!(); | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 4 previous errors +error[E0412]: cannot find type `i` in this scope + --> $DIR/macro-context.rs:3:13 + | +LL | () => ( i ; typeof ); + | ^ help: a builtin type with a similar name exists: `i8` +... +LL | let a: m!(); + | ---- in this macro invocation + | + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0425]: cannot find value `i` in this scope + --> $DIR/macro-context.rs:3:13 + | +LL | () => ( i ; typeof ); + | ^ help: a local variable with a similar name exists: `a` +... +LL | let i = m!(); + | ---- in this macro invocation + | + = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) + +error: aborting due to 6 previous errors +Some errors have detailed explanations: E0412, E0425. +For more information about an error, try `rustc --explain E0412`. diff --git a/src/test/ui/type/ascription/issue-47666.rs b/src/test/ui/type/ascription/issue-47666.rs index ceb1dd89daea9..8035de4a48a92 100644 --- a/src/test/ui/type/ascription/issue-47666.rs +++ b/src/test/ui/type/ascription/issue-47666.rs @@ -1,5 +1,7 @@ fn main() { let _ = Option:Some(vec![0, 1]); //~ ERROR expected type, found + //~^ ERROR expected value, found enum `Option` + //~| ERROR expected type, found variant `Some` } // This case isn't currently being handled gracefully due to the macro invocation. diff --git a/src/test/ui/type/ascription/issue-47666.stderr b/src/test/ui/type/ascription/issue-47666.stderr index f4c9240ab5372..3cd3be70aa75b 100644 --- a/src/test/ui/type/ascription/issue-47666.stderr +++ b/src/test/ui/type/ascription/issue-47666.stderr @@ -13,5 +13,35 @@ LL | let _ = Option:Some(vec![0, 1]); = note: see issue #23416 for more information = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to previous error +error[E0423]: expected value, found enum `Option` + --> $DIR/issue-47666.rs:2:13 + | +LL | let _ = Option:Some(vec![0, 1]); + | ^^^^^^ + | +help: try using one of the enum's variants + | +LL | let _ = std::option::Option::None:Some(vec![0, 1]); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | let _ = std::option::Option::Some:Some(vec![0, 1]); + | ^^^^^^^^^^^^^^^^^^^^^^^^^ + +error[E0573]: expected type, found variant `Some` + --> $DIR/issue-47666.rs:2:20 + | +LL | let _ = Option:Some(vec![0, 1]); + | ^^^^^^^^^^^^^^^^ not a type + | +help: try using the variant's enum + | +LL | let _ = Option:std::option::Option; + | ^^^^^^^^^^^^^^^^^^^ +help: maybe you meant to write a path separator here + | +LL | let _ = Option::Some(vec![0, 1]); + | ^^ + +error: aborting due to 3 previous errors +Some errors have detailed explanations: E0423, E0573. +For more information about an error, try `rustc --explain E0423`. From e6743b045acf2d7bc26876c3a5d6c1f866eeabcc Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 08:59:56 +0100 Subject: [PATCH 16/34] nix remaining rustc_expand::panictry! uses. --- src/librustc_builtin_macros/cmdline_attrs.rs | 9 ++++++-- src/librustc_builtin_macros/source_util.rs | 24 +++++++++----------- src/librustc_expand/base.rs | 2 +- src/librustc_expand/lib.rs | 19 ---------------- 4 files changed, 19 insertions(+), 35 deletions(-) diff --git a/src/librustc_builtin_macros/cmdline_attrs.rs b/src/librustc_builtin_macros/cmdline_attrs.rs index 7ddbf08306b72..093815dbbcd4f 100644 --- a/src/librustc_builtin_macros/cmdline_attrs.rs +++ b/src/librustc_builtin_macros/cmdline_attrs.rs @@ -3,7 +3,6 @@ use rustc_ast::ast::{self, AttrItem, AttrStyle}; use rustc_ast::attr::mk_attr; use rustc_ast::token; -use rustc_expand::panictry; use rustc_session::parse::ParseSess; use rustc_span::FileName; @@ -16,7 +15,13 @@ pub fn inject(mut krate: ast::Crate, parse_sess: &ParseSess, attrs: &[String]) - ); let start_span = parser.token.span; - let AttrItem { path, args } = panictry!(parser.parse_attr_item()); + let AttrItem { path, args } = match parser.parse_attr_item() { + Ok(ai) => ai, + Err(mut err) => { + err.emit(); + continue; + } + }; let end_span = parser.token.span; if parser.token != token::Eof { parse_sess.span_diagnostic.span_err(start_span.to(end_span), "invalid crate attribute"); diff --git a/src/librustc_builtin_macros/source_util.rs b/src/librustc_builtin_macros/source_util.rs index 718498f04b94e..3968a527b2dc0 100644 --- a/src/librustc_builtin_macros/source_util.rs +++ b/src/librustc_builtin_macros/source_util.rs @@ -5,7 +5,6 @@ use rustc_ast::tokenstream::TokenStream; use rustc_ast_pretty::pprust; use rustc_expand::base::{self, *}; use rustc_expand::module::DirectoryOwnership; -use rustc_expand::panictry; use rustc_parse::{self, new_sub_parser_from_file, parser::Parser}; use rustc_session::lint::builtin::INCOMPLETE_INCLUDE; use rustc_span::symbol::Symbol; @@ -126,7 +125,7 @@ pub fn expand_include<'cx>( } impl<'a> base::MacResult for ExpandResult<'a> { fn make_expr(mut self: Box>) -> Option> { - let r = panictry!(self.p.parse_expr()); + let r = base::parse_expr(&mut self.p)?; if self.p.token != token::Eof { self.p.sess.buffer_lint( &INCOMPLETE_INCLUDE, @@ -141,18 +140,17 @@ pub fn expand_include<'cx>( fn make_items(mut self: Box>) -> Option; 1]>> { let mut ret = SmallVec::new(); while self.p.token != token::Eof { - match panictry!(self.p.parse_item()) { - Some(item) => ret.push(item), - None => { + match self.p.parse_item() { + Err(mut err) => { + err.emit(); + break; + } + Ok(Some(item)) => ret.push(item), + Ok(None) => { let token = pprust::token_to_string(&self.p.token); - self.p - .sess - .span_diagnostic - .span_fatal( - self.p.token.span, - &format!("expected item, found `{}`", token), - ) - .raise(); + let msg = format!("expected item, found `{}`", token); + self.p.struct_span_err(self.p.token.span, &msg).emit(); + break; } } } diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index e47e0a757866c..b615b34634fb2 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -1169,7 +1169,7 @@ pub fn check_zero_tts(cx: &ExtCtxt<'_>, sp: Span, tts: TokenStream, name: &str) } /// Parse an expression. On error, emit it, advancing to `Eof`, and return `None`. -fn parse_expr(p: &mut parser::Parser<'_>) -> Option> { +pub fn parse_expr(p: &mut parser::Parser<'_>) -> Option> { match p.parse_expr() { Ok(e) => return Some(e), Err(mut err) => err.emit(), diff --git a/src/librustc_expand/lib.rs b/src/librustc_expand/lib.rs index 0320a275e5d20..876a26de3fb7e 100644 --- a/src/librustc_expand/lib.rs +++ b/src/librustc_expand/lib.rs @@ -9,25 +9,6 @@ extern crate proc_macro as pm; -// A variant of 'try!' that panics on an Err. This is used as a crutch on the -// way towards a non-panic!-prone parser. It should be used for fatal parsing -// errors; eventually we plan to convert all code using panictry to just use -// normal try. -#[macro_export] -macro_rules! panictry { - ($e:expr) => {{ - use rustc_errors::FatalError; - use std::result::Result::{Err, Ok}; - match $e { - Ok(e) => e, - Err(mut e) => { - e.emit(); - FatalError.raise() - } - } - }}; -} - mod placeholders; mod proc_macro_server; From 5f3d63e03376904b232e6517b434209207882ceb Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 09:37:59 +0100 Subject: [PATCH 17/34] generic_extension: defatalize Error case --- src/librustc_expand/mbe/macro_rules.rs | 6 +++++- src/test/ui/macros/macro-match-nonterminal.rs | 9 ++++++++- .../ui/macros/macro-match-nonterminal.stderr | 18 ++++++++++++++---- src/test/ui/parser/macro/issue-33569.rs | 2 ++ src/test/ui/parser/macro/issue-33569.stderr | 6 +++--- 5 files changed, 32 insertions(+), 9 deletions(-) diff --git a/src/librustc_expand/mbe/macro_rules.rs b/src/librustc_expand/mbe/macro_rules.rs index 0a346d483000e..e2267ccbefdd1 100644 --- a/src/librustc_expand/mbe/macro_rules.rs +++ b/src/librustc_expand/mbe/macro_rules.rs @@ -295,7 +295,11 @@ fn generic_extension<'cx>( Some((ref best_token, _)) if best_token.span.lo() >= token.span.lo() => {} _ => best_failure = Some((token, msg)), }, - Error(err_sp, ref msg) => cx.span_fatal(err_sp.substitute_dummy(sp), &msg[..]), + Error(err_sp, ref msg) => { + let span = err_sp.substitute_dummy(sp); + cx.struct_span_err(span, &msg).emit(); + return DummyResult::any(span); + } } // The matcher was not `Success(..)`ful. diff --git a/src/test/ui/macros/macro-match-nonterminal.rs b/src/test/ui/macros/macro-match-nonterminal.rs index 6d4b32c9bc9a0..b23e5c71c03f0 100644 --- a/src/test/ui/macros/macro-match-nonterminal.rs +++ b/src/test/ui/macros/macro-match-nonterminal.rs @@ -1,4 +1,11 @@ -macro_rules! test { ($a, $b) => (()); } //~ ERROR missing fragment +macro_rules! test { + ($a, $b) => { + //~^ ERROR missing fragment + //~| ERROR missing fragment + //~| WARN this was previously accepted + () + }; +} fn main() { test!() diff --git a/src/test/ui/macros/macro-match-nonterminal.stderr b/src/test/ui/macros/macro-match-nonterminal.stderr index 1de8c5bd4b472..674ce3434aac6 100644 --- a/src/test/ui/macros/macro-match-nonterminal.stderr +++ b/src/test/ui/macros/macro-match-nonterminal.stderr @@ -1,8 +1,18 @@ error: missing fragment specifier - --> $DIR/macro-match-nonterminal.rs:1:24 + --> $DIR/macro-match-nonterminal.rs:2:8 | -LL | macro_rules! test { ($a, $b) => (()); } - | ^ +LL | ($a, $b) => { + | ^ -error: aborting due to previous error +error: missing fragment specifier + --> $DIR/macro-match-nonterminal.rs:2:10 + | +LL | ($a, $b) => { + | ^^ + | + = note: `#[deny(missing_fragment_specifier)]` on by default + = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release! + = note: for more information, see issue #40107 + +error: aborting due to 2 previous errors diff --git a/src/test/ui/parser/macro/issue-33569.rs b/src/test/ui/parser/macro/issue-33569.rs index 9ed53519ceb31..e32825ad3e064 100644 --- a/src/test/ui/parser/macro/issue-33569.rs +++ b/src/test/ui/parser/macro/issue-33569.rs @@ -1,3 +1,5 @@ +fn main() {} + macro_rules! foo { { $+ } => { //~ ERROR expected identifier, found `+` //~^ ERROR missing fragment specifier diff --git a/src/test/ui/parser/macro/issue-33569.stderr b/src/test/ui/parser/macro/issue-33569.stderr index b4d38d3ce4806..a08d26095f564 100644 --- a/src/test/ui/parser/macro/issue-33569.stderr +++ b/src/test/ui/parser/macro/issue-33569.stderr @@ -1,17 +1,17 @@ error: expected identifier, found `+` - --> $DIR/issue-33569.rs:2:8 + --> $DIR/issue-33569.rs:4:8 | LL | { $+ } => { | ^ error: expected one of: `*`, `+`, or `?` - --> $DIR/issue-33569.rs:4:13 + --> $DIR/issue-33569.rs:6:13 | LL | $(x)(y) | ^^^ error: missing fragment specifier - --> $DIR/issue-33569.rs:2:8 + --> $DIR/issue-33569.rs:4:8 | LL | { $+ } => { | ^ From 20a5c4ada9f116a2a467bf2a7469c95fa5ce678c Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 10:09:18 +0100 Subject: [PATCH 18/34] defatalize BangProcMacro::expand --- src/librustc_expand/base.rs | 18 +++++++++++---- src/librustc_expand/expand.rs | 5 +++- src/librustc_expand/proc_macro.rs | 23 ++++++++----------- .../ui/proc-macro/invalid-punct-ident-1.rs | 2 ++ .../ui/proc-macro/invalid-punct-ident-2.rs | 2 ++ .../ui/proc-macro/invalid-punct-ident-3.rs | 2 ++ .../ui/proc-macro/invalid-punct-ident-4.rs | 9 +++++--- .../proc-macro/invalid-punct-ident-4.stderr | 16 ++++++++++--- 8 files changed, 52 insertions(+), 25 deletions(-) diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index b615b34634fb2..20e1895270a7b 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -10,7 +10,7 @@ use rustc_ast::visit::{AssocCtxt, Visitor}; use rustc_attr::{self as attr, Deprecation, HasAttrs, Stability}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::{self, Lrc}; -use rustc_errors::{DiagnosticBuilder, DiagnosticId}; +use rustc_errors::{DiagnosticBuilder, DiagnosticId, ErrorReported}; use rustc_parse::{self, parser, MACRO_ARGUMENTS}; use rustc_session::parse::ParseSess; use rustc_span::edition::Edition; @@ -296,16 +296,26 @@ where } pub trait ProcMacro { - fn expand<'cx>(&self, ecx: &'cx mut ExtCtxt<'_>, span: Span, ts: TokenStream) -> TokenStream; + fn expand<'cx>( + &self, + ecx: &'cx mut ExtCtxt<'_>, + span: Span, + ts: TokenStream, + ) -> Result; } impl ProcMacro for F where F: Fn(TokenStream) -> TokenStream, { - fn expand<'cx>(&self, _ecx: &'cx mut ExtCtxt<'_>, _span: Span, ts: TokenStream) -> TokenStream { + fn expand<'cx>( + &self, + _ecx: &'cx mut ExtCtxt<'_>, + _span: Span, + ts: TokenStream, + ) -> Result { // FIXME setup implicit context in TLS before calling self. - (*self)(ts) + Ok((*self)(ts)) } } diff --git a/src/librustc_expand/expand.rs b/src/librustc_expand/expand.rs index 58217d98986bf..57314824d5a84 100644 --- a/src/librustc_expand/expand.rs +++ b/src/librustc_expand/expand.rs @@ -682,7 +682,10 @@ impl<'a, 'b> MacroExpander<'a, 'b> { InvocationKind::Bang { mac, .. } => match ext { SyntaxExtensionKind::Bang(expander) => { self.gate_proc_macro_expansion_kind(span, fragment_kind); - let tok_result = expander.expand(self.cx, span, mac.args.inner_tokens()); + let tok_result = match expander.expand(self.cx, span, mac.args.inner_tokens()) { + Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)), + Ok(ts) => ts, + }; self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span) } SyntaxExtensionKind::LegacyBang(expander) => { diff --git a/src/librustc_expand/proc_macro.rs b/src/librustc_expand/proc_macro.rs index cb9afa4cd4f02..404f29f1fcf03 100644 --- a/src/librustc_expand/proc_macro.rs +++ b/src/librustc_expand/proc_macro.rs @@ -5,7 +5,7 @@ use rustc_ast::ast::{self, ItemKind, MetaItemKind, NestedMetaItem}; use rustc_ast::token; use rustc_ast::tokenstream::{self, TokenStream}; use rustc_data_structures::sync::Lrc; -use rustc_errors::{Applicability, FatalError}; +use rustc_errors::{Applicability, ErrorReported, FatalError}; use rustc_span::symbol::sym; use rustc_span::{Span, DUMMY_SP}; @@ -21,21 +21,16 @@ impl base::ProcMacro for BangProcMacro { ecx: &'cx mut ExtCtxt<'_>, span: Span, input: TokenStream, - ) -> TokenStream { + ) -> Result { let server = proc_macro_server::Rustc::new(ecx); - match self.client.run(&EXEC_STRATEGY, server, input) { - Ok(stream) => stream, - Err(e) => { - let msg = "proc macro panicked"; - let mut err = ecx.struct_span_fatal(span, msg); - if let Some(s) = e.as_str() { - err.help(&format!("message: {}", s)); - } - - err.emit(); - FatalError.raise(); + self.client.run(&EXEC_STRATEGY, server, input).map_err(|e| { + let mut err = ecx.struct_span_err(span, "proc macro panicked"); + if let Some(s) = e.as_str() { + err.help(&format!("message: {}", s)); } - } + err.emit(); + ErrorReported + }) } } diff --git a/src/test/ui/proc-macro/invalid-punct-ident-1.rs b/src/test/ui/proc-macro/invalid-punct-ident-1.rs index 9de57da5af434..3f78dea917b19 100644 --- a/src/test/ui/proc-macro/invalid-punct-ident-1.rs +++ b/src/test/ui/proc-macro/invalid-punct-ident-1.rs @@ -14,3 +14,5 @@ extern crate invalid_punct_ident; invalid_punct!(); //~ ERROR proc macro panicked + +fn main() {} diff --git a/src/test/ui/proc-macro/invalid-punct-ident-2.rs b/src/test/ui/proc-macro/invalid-punct-ident-2.rs index 79f72324b1d89..4e89e80ae7c41 100644 --- a/src/test/ui/proc-macro/invalid-punct-ident-2.rs +++ b/src/test/ui/proc-macro/invalid-punct-ident-2.rs @@ -14,3 +14,5 @@ extern crate invalid_punct_ident; invalid_ident!(); //~ ERROR proc macro panicked + +fn main() {} diff --git a/src/test/ui/proc-macro/invalid-punct-ident-3.rs b/src/test/ui/proc-macro/invalid-punct-ident-3.rs index d01e9b699cac5..8d8ce8f932e71 100644 --- a/src/test/ui/proc-macro/invalid-punct-ident-3.rs +++ b/src/test/ui/proc-macro/invalid-punct-ident-3.rs @@ -14,3 +14,5 @@ extern crate invalid_punct_ident; invalid_raw_ident!(); //~ ERROR proc macro panicked + +fn main() {} diff --git a/src/test/ui/proc-macro/invalid-punct-ident-4.rs b/src/test/ui/proc-macro/invalid-punct-ident-4.rs index e50f24deae343..ab0250f53f699 100644 --- a/src/test/ui/proc-macro/invalid-punct-ident-4.rs +++ b/src/test/ui/proc-macro/invalid-punct-ident-4.rs @@ -1,7 +1,10 @@ // aux-build:invalid-punct-ident.rs -#[macro_use] +// We use `main` not found below as a witness for error recovery in proc macro expansion. + +#[macro_use] //~ ERROR `main` function not found extern crate invalid_punct_ident; -lexer_failure!(); //~ ERROR proc macro panicked - //~| ERROR unexpected closing delimiter: `)` +lexer_failure!(); +//~^ ERROR proc macro panicked +//~| ERROR unexpected closing delimiter: `)` diff --git a/src/test/ui/proc-macro/invalid-punct-ident-4.stderr b/src/test/ui/proc-macro/invalid-punct-ident-4.stderr index fe3e55b31be5d..296e2fb094280 100644 --- a/src/test/ui/proc-macro/invalid-punct-ident-4.stderr +++ b/src/test/ui/proc-macro/invalid-punct-ident-4.stderr @@ -1,5 +1,5 @@ error: unexpected closing delimiter: `)` - --> $DIR/invalid-punct-ident-4.rs:6:1 + --> $DIR/invalid-punct-ident-4.rs:8:1 | LL | lexer_failure!(); | ^^^^^^^^^^^^^^^^^ unexpected closing delimiter @@ -7,10 +7,20 @@ LL | lexer_failure!(); = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: proc macro panicked - --> $DIR/invalid-punct-ident-4.rs:6:1 + --> $DIR/invalid-punct-ident-4.rs:8:1 | LL | lexer_failure!(); | ^^^^^^^^^^^^^^^^^ -error: aborting due to 2 previous errors +error[E0601]: `main` function not found in crate `invalid_punct_ident_4` + --> $DIR/invalid-punct-ident-4.rs:5:1 + | +LL | / #[macro_use] +LL | | extern crate invalid_punct_ident; +LL | | +LL | | lexer_failure!(); + | |_________________^ consider adding a `main` function to `$DIR/invalid-punct-ident-4.rs` + +error: aborting due to 3 previous errors +For more information about this error, try `rustc --explain E0601`. From 1b2ef28e1bf6a9dcade7b3a4209a8f6084963e7e Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 10:56:00 +0100 Subject: [PATCH 19/34] defatalize AttrProcMacro::expand --- src/librustc_expand/base.rs | 6 +++--- src/librustc_expand/expand.rs | 7 +++++-- src/librustc_expand/proc_macro.rs | 21 ++++++++------------- 3 files changed, 16 insertions(+), 18 deletions(-) diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index 20e1895270a7b..4947730a4aa7b 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -326,7 +326,7 @@ pub trait AttrProcMacro { span: Span, annotation: TokenStream, annotated: TokenStream, - ) -> TokenStream; + ) -> Result; } impl AttrProcMacro for F @@ -339,9 +339,9 @@ where _span: Span, annotation: TokenStream, annotated: TokenStream, - ) -> TokenStream { + ) -> Result { // FIXME setup implicit context in TLS before calling self. - (*self)(annotation, annotated) + Ok((*self)(annotation, annotated)) } } diff --git a/src/librustc_expand/expand.rs b/src/librustc_expand/expand.rs index 57314824d5a84..cbb695a815ac5 100644 --- a/src/librustc_expand/expand.rs +++ b/src/librustc_expand/expand.rs @@ -712,8 +712,11 @@ impl<'a, 'b> MacroExpander<'a, 'b> { if let MacArgs::Eq(..) = attr_item.args { self.cx.span_err(span, "key-value macro attributes are not supported"); } - let tok_result = - expander.expand(self.cx, span, attr_item.args.inner_tokens(), tokens); + let inner_tokens = attr_item.args.inner_tokens(); + let tok_result = match expander.expand(self.cx, span, inner_tokens, tokens) { + Err(_) => return ExpandResult::Ready(fragment_kind.dummy(span)), + Ok(ts) => ts, + }; self.parse_ast_fragment(tok_result, fragment_kind, &attr_item.path, span) } SyntaxExtensionKind::LegacyAttr(expander) => { diff --git a/src/librustc_expand/proc_macro.rs b/src/librustc_expand/proc_macro.rs index 404f29f1fcf03..40b5e63756be7 100644 --- a/src/librustc_expand/proc_macro.rs +++ b/src/librustc_expand/proc_macro.rs @@ -45,21 +45,16 @@ impl base::AttrProcMacro for AttrProcMacro { span: Span, annotation: TokenStream, annotated: TokenStream, - ) -> TokenStream { + ) -> Result { let server = proc_macro_server::Rustc::new(ecx); - match self.client.run(&EXEC_STRATEGY, server, annotation, annotated) { - Ok(stream) => stream, - Err(e) => { - let msg = "custom attribute panicked"; - let mut err = ecx.struct_span_fatal(span, msg); - if let Some(s) = e.as_str() { - err.help(&format!("message: {}", s)); - } - - err.emit(); - FatalError.raise(); + self.client.run(&EXEC_STRATEGY, server, annotation, annotated).map_err(|e| { + let mut err = ecx.struct_span_err(span, "custom attribute panicked"); + if let Some(s) = e.as_str() { + err.help(&format!("message: {}", s)); } - } + err.emit(); + ErrorReported + }) } } From daa30565041dcdbbe99aa29cb11ae79778e9bb6b Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 11:30:53 +0100 Subject: [PATCH 20/34] defatalize ProcMacroDerive::expand Also remove ExtCtxt::struct_span_fatal. --- src/librustc_expand/base.rs | 3 --- src/librustc_expand/proc_macro.rs | 25 +++++++--------------- src/test/ui/proc-macro/derive-bad.rs | 8 +++---- src/test/ui/proc-macro/derive-bad.stderr | 26 +++++++++++++++++------ src/test/ui/proc-macro/issue-36935.rs | 1 + src/test/ui/proc-macro/issue-36935.stderr | 14 +++++++++++- 6 files changed, 44 insertions(+), 33 deletions(-) diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index 4947730a4aa7b..c107a7f2409b8 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -1020,9 +1020,6 @@ impl<'a> ExtCtxt<'a> { pub fn struct_span_err>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> { self.parse_sess.span_diagnostic.struct_span_err(sp, msg) } - pub fn struct_span_fatal>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> { - self.parse_sess.span_diagnostic.struct_span_fatal(sp, msg) - } /// Emit `msg` attached to `sp`, and stop compilation immediately. /// diff --git a/src/librustc_expand/proc_macro.rs b/src/librustc_expand/proc_macro.rs index 40b5e63756be7..df7bf9438c3d0 100644 --- a/src/librustc_expand/proc_macro.rs +++ b/src/librustc_expand/proc_macro.rs @@ -5,7 +5,7 @@ use rustc_ast::ast::{self, ItemKind, MetaItemKind, NestedMetaItem}; use rustc_ast::token; use rustc_ast::tokenstream::{self, TokenStream}; use rustc_data_structures::sync::Lrc; -use rustc_errors::{Applicability, ErrorReported, FatalError}; +use rustc_errors::{Applicability, ErrorReported}; use rustc_span::symbol::sym; use rustc_span::{Span, DUMMY_SP}; @@ -86,8 +86,7 @@ impl MultiItemModifier for ProcMacroDerive { | Annotatable::Expr(_) => { ecx.span_err( span, - "proc-macro derives may only be \ - applied to a struct, enum, or union", + "proc-macro derives may only be applied to a struct, enum, or union", ); return ExpandResult::Ready(Vec::new()); } @@ -97,8 +96,7 @@ impl MultiItemModifier for ProcMacroDerive { _ => { ecx.span_err( span, - "proc-macro derives may only be \ - applied to a struct, enum, or union", + "proc-macro derives may only be applied to a struct, enum, or union", ); return ExpandResult::Ready(Vec::new()); } @@ -111,20 +109,16 @@ impl MultiItemModifier for ProcMacroDerive { let stream = match self.client.run(&EXEC_STRATEGY, server, input) { Ok(stream) => stream, Err(e) => { - let msg = "proc-macro derive panicked"; - let mut err = ecx.struct_span_fatal(span, msg); + let mut err = ecx.struct_span_err(span, "proc-macro derive panicked"); if let Some(s) = e.as_str() { err.help(&format!("message: {}", s)); } - err.emit(); - FatalError.raise(); + return ExpandResult::Ready(vec![]); } }; let error_count_before = ecx.parse_sess.span_diagnostic.err_count(); - let msg = "proc-macro derive produced unparseable tokens"; - let mut parser = rustc_parse::stream_to_parser(ecx.parse_sess, stream, Some("proc-macro derive")); let mut items = vec![]; @@ -134,18 +128,15 @@ impl MultiItemModifier for ProcMacroDerive { Ok(None) => break, Ok(Some(item)) => items.push(Annotatable::Item(item)), Err(mut err) => { - // FIXME: handle this better - err.cancel(); - ecx.struct_span_fatal(span, msg).emit(); - FatalError.raise(); + err.emit(); + break; } } } // fail if there have been errors emitted if ecx.parse_sess.span_diagnostic.err_count() > error_count_before { - ecx.struct_span_fatal(span, msg).emit(); - FatalError.raise(); + ecx.struct_span_err(span, "proc-macro derive produced unparseable tokens").emit(); } ExpandResult::Ready(items) diff --git a/src/test/ui/proc-macro/derive-bad.rs b/src/test/ui/proc-macro/derive-bad.rs index 62c0741b6697a..cb5188b5fb43f 100644 --- a/src/test/ui/proc-macro/derive-bad.rs +++ b/src/test/ui/proc-macro/derive-bad.rs @@ -3,11 +3,9 @@ #[macro_use] extern crate derive_bad; -#[derive( - A -)] -//~^^ ERROR proc-macro derive produced unparseable tokens +#[derive(A)] +//~^ ERROR proc-macro derive produced unparseable tokens //~| ERROR expected `:`, found `}` -struct A; +struct A; //~ ERROR the name `A` is defined multiple times fn main() {} diff --git a/src/test/ui/proc-macro/derive-bad.stderr b/src/test/ui/proc-macro/derive-bad.stderr index 8667396c98989..bc5ed9815238a 100644 --- a/src/test/ui/proc-macro/derive-bad.stderr +++ b/src/test/ui/proc-macro/derive-bad.stderr @@ -1,16 +1,28 @@ error: expected `:`, found `}` - --> $DIR/derive-bad.rs:7:5 + --> $DIR/derive-bad.rs:6:10 | -LL | A - | ^ expected `:` +LL | #[derive(A)] + | ^ expected `:` | = note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info) error: proc-macro derive produced unparseable tokens - --> $DIR/derive-bad.rs:7:5 + --> $DIR/derive-bad.rs:6:10 | -LL | A - | ^ +LL | #[derive(A)] + | ^ -error: aborting due to 2 previous errors +error[E0428]: the name `A` is defined multiple times + --> $DIR/derive-bad.rs:9:1 + | +LL | #[derive(A)] + | - previous definition of the type `A` here +... +LL | struct A; + | ^^^^^^^^^ `A` redefined here + | + = note: `A` must be defined only once in the type namespace of this module + +error: aborting due to 3 previous errors +For more information about this error, try `rustc --explain E0428`. diff --git a/src/test/ui/proc-macro/issue-36935.rs b/src/test/ui/proc-macro/issue-36935.rs index f809592d5f449..5c43a564c00c2 100644 --- a/src/test/ui/proc-macro/issue-36935.rs +++ b/src/test/ui/proc-macro/issue-36935.rs @@ -5,6 +5,7 @@ extern crate test_macros; #[derive(Identity, Panic)] //~ ERROR proc-macro derive panicked struct Baz { + //~^ ERROR the name `Baz` is defined multiple times a: i32, b: i32, } diff --git a/src/test/ui/proc-macro/issue-36935.stderr b/src/test/ui/proc-macro/issue-36935.stderr index da4366eb668d6..2b2e28fdb2fda 100644 --- a/src/test/ui/proc-macro/issue-36935.stderr +++ b/src/test/ui/proc-macro/issue-36935.stderr @@ -6,5 +6,17 @@ LL | #[derive(Identity, Panic)] | = help: message: panic-derive -error: aborting due to previous error +error[E0428]: the name `Baz` is defined multiple times + --> $DIR/issue-36935.rs:7:1 + | +LL | struct Baz { + | ^^^^^^^^^^ + | | + | `Baz` redefined here + | previous definition of the type `Baz` here + | + = note: `Baz` must be defined only once in the type namespace of this module + +error: aborting due to 2 previous errors +For more information about this error, try `rustc --explain E0428`. From ba4cf18088a03d03fe17609e311cb570f00a4c10 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 11:35:21 +0100 Subject: [PATCH 21/34] remove ExtCxt::struct_span_warn --- src/librustc_expand/base.rs | 3 --- src/librustc_expand/expand.rs | 2 ++ 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index c107a7f2409b8..0ecbd84cb6a0e 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -1014,9 +1014,6 @@ impl<'a> ExtCtxt<'a> { self.current_expansion.id.expansion_cause() } - pub fn struct_span_warn>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> { - self.parse_sess.span_diagnostic.struct_span_warn(sp, msg) - } pub fn struct_span_err>(&self, sp: S, msg: &str) -> DiagnosticBuilder<'a> { self.parse_sess.span_diagnostic.struct_span_err(sp, msg) } diff --git a/src/librustc_expand/expand.rs b/src/librustc_expand/expand.rs index cbb695a815ac5..51208906c2f2d 100644 --- a/src/librustc_expand/expand.rs +++ b/src/librustc_expand/expand.rs @@ -1145,6 +1145,8 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // macros are expanded before any lint passes so this warning has to be hardcoded if attr.has_name(sym::derive) { self.cx + .parse_sess() + .span_diagnostic .struct_span_warn(attr.span, "`#[derive]` does nothing on macro invocations") .note("this may become a hard error in a future release") .emit(); From 60d7608921955c31aea6cbbf329270ea3f4dd145 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 12:12:57 +0100 Subject: [PATCH 22/34] mbe::transcribe: defatalize errors. --- src/librustc_expand/base.rs | 16 ------------ src/librustc_expand/mbe/macro_rules.rs | 8 +++++- src/librustc_expand/mbe/transcribe.rs | 27 +++++++++++--------- src/test/ui/macros/issue-61033-1.rs | 3 ++- src/test/ui/macros/issue-61033-1.stderr | 11 +++++++- src/test/ui/macros/issue-61033-2.rs | 8 +++++- src/test/ui/macros/issue-61033-2.stderr | 15 ++++++++++- src/test/ui/parser/macro/macro-repeat.rs | 9 ++++--- src/test/ui/parser/macro/macro-repeat.stderr | 8 +++++- 9 files changed, 68 insertions(+), 37 deletions(-) diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index 0ecbd84cb6a0e..518a214b4a510 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -1018,22 +1018,6 @@ impl<'a> ExtCtxt<'a> { self.parse_sess.span_diagnostic.struct_span_err(sp, msg) } - /// Emit `msg` attached to `sp`, and stop compilation immediately. - /// - /// `span_err` should be strongly preferred where-ever possible: - /// this should *only* be used when: - /// - /// - continuing has a high risk of flow-on errors (e.g., errors in - /// declaring a macro would cause all uses of that macro to - /// complain about "undefined macro"), or - /// - there is literally nothing else that can be done (however, - /// in most cases one can construct a dummy expression/item to - /// substitute; we never hit resolve/type-checking so the dummy - /// value doesn't have to match anything) - pub fn span_fatal>(&self, sp: S, msg: &str) -> ! { - self.parse_sess.span_diagnostic.span_fatal(sp, msg).raise(); - } - /// Emit `msg` attached to `sp`, without immediately stopping /// compilation. /// diff --git a/src/librustc_expand/mbe/macro_rules.rs b/src/librustc_expand/mbe/macro_rules.rs index e2267ccbefdd1..a15d9cb982b67 100644 --- a/src/librustc_expand/mbe/macro_rules.rs +++ b/src/librustc_expand/mbe/macro_rules.rs @@ -255,7 +255,13 @@ fn generic_extension<'cx>( let rhs_spans = rhs.iter().map(|t| t.span()).collect::>(); // rhs has holes ( `$id` and `$(...)` that need filled) - let mut tts = transcribe(cx, &named_matches, rhs, transparency); + let mut tts = match transcribe(cx, &named_matches, rhs, transparency) { + Ok(tts) => tts, + Err(mut err) => { + err.emit(); + return DummyResult::any(arm_span); + } + }; // Replace all the tokens for the corresponding positions in the macro, to maintain // proper positions in error reporting, while maintaining the macro_backtrace. diff --git a/src/librustc_expand/mbe/transcribe.rs b/src/librustc_expand/mbe/transcribe.rs index 1b1093c9529f4..e2d3d5c4d644e 100644 --- a/src/librustc_expand/mbe/transcribe.rs +++ b/src/librustc_expand/mbe/transcribe.rs @@ -8,7 +8,7 @@ use rustc_ast::token::{self, NtTT, Token}; use rustc_ast::tokenstream::{DelimSpan, TokenStream, TokenTree, TreeAndJoint}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; -use rustc_errors::pluralize; +use rustc_errors::{pluralize, PResult}; use rustc_span::hygiene::{ExpnId, Transparency}; use rustc_span::symbol::MacroRulesNormalizedIdent; use rustc_span::Span; @@ -80,15 +80,15 @@ impl Iterator for Frame { /// `transcribe` would return a `TokenStream` containing `println!("{}", stringify!(bar));`. /// /// Along the way, we do some additional error checking. -pub(super) fn transcribe( - cx: &ExtCtxt<'_>, +pub(super) fn transcribe<'a>( + cx: &ExtCtxt<'a>, interp: &FxHashMap, src: Vec, transparency: Transparency, -) -> TokenStream { +) -> PResult<'a, TokenStream> { // Nothing for us to transcribe... if src.is_empty() { - return TokenStream::default(); + return Ok(TokenStream::default()); } // We descend into the RHS (`src`), expanding things as we go. This stack contains the things @@ -152,7 +152,7 @@ pub(super) fn transcribe( Frame::Delimited { forest, span, .. } => { if result_stack.is_empty() { // No results left to compute! We are back at the top-level. - return TokenStream::new(result); + return Ok(TokenStream::new(result)); } // Step back into the parent Delimited. @@ -173,11 +173,11 @@ pub(super) fn transcribe( seq @ mbe::TokenTree::Sequence(..) => { match lockstep_iter_size(&seq, interp, &repeats) { LockstepIterSize::Unconstrained => { - cx.span_fatal( + return Err(cx.struct_span_err( seq.span(), /* blame macro writer */ "attempted to repeat an expression containing no syntax variables \ matched as repeating at this depth", - ); + )); } LockstepIterSize::Contradiction(ref msg) => { @@ -185,7 +185,7 @@ pub(super) fn transcribe( // happens when two meta-variables are used in the same repetition in a // sequence, but they come from different sequence matchers and repeat // different amounts. - cx.span_fatal(seq.span(), &msg[..]); + return Err(cx.struct_span_err(seq.span(), &msg[..])); } LockstepIterSize::Constraint(len, _) => { @@ -203,7 +203,10 @@ pub(super) fn transcribe( // FIXME: this really ought to be caught at macro definition // time... It happens when the Kleene operator in the matcher and // the body for the same meta-variable do not match. - cx.span_fatal(sp.entire(), "this must repeat at least once"); + return Err(cx.struct_span_err( + sp.entire(), + "this must repeat at least once", + )); } } else { // 0 is the initial counter (we have done 0 repretitions so far). `len` @@ -242,10 +245,10 @@ pub(super) fn transcribe( } } else { // We were unable to descend far enough. This is an error. - cx.span_fatal( + return Err(cx.struct_span_err( sp, /* blame the macro writer */ &format!("variable '{}' is still repeating at this depth", ident), - ); + )); } } else { // If we aren't able to match the meta-var, we push it back into the result but diff --git a/src/test/ui/macros/issue-61033-1.rs b/src/test/ui/macros/issue-61033-1.rs index 8f85dec017f2a..18df3f6ee94c1 100644 --- a/src/test/ui/macros/issue-61033-1.rs +++ b/src/test/ui/macros/issue-61033-1.rs @@ -1,9 +1,10 @@ // Regression test for issue #61033. macro_rules! test1 { - ($x:ident, $($tt:tt)*) => { $($tt)+ } //~ERROR this must repeat at least once + ($x:ident, $($tt:tt)*) => { $($tt)+ } //~ ERROR this must repeat at least once } fn main() { test1!(x,); + let _recovery_witness: () = 0; //~ ERROR mismatched types } diff --git a/src/test/ui/macros/issue-61033-1.stderr b/src/test/ui/macros/issue-61033-1.stderr index f3c68f4928dbb..18205c3436b0b 100644 --- a/src/test/ui/macros/issue-61033-1.stderr +++ b/src/test/ui/macros/issue-61033-1.stderr @@ -4,5 +4,14 @@ error: this must repeat at least once LL | ($x:ident, $($tt:tt)*) => { $($tt)+ } | ^^^^^ -error: aborting due to previous error +error[E0308]: mismatched types + --> $DIR/issue-61033-1.rs:9:33 + | +LL | let _recovery_witness: () = 0; + | -- ^ expected `()`, found integer + | | + | expected due to this + +error: aborting due to 2 previous errors +For more information about this error, try `rustc --explain E0308`. diff --git a/src/test/ui/macros/issue-61033-2.rs b/src/test/ui/macros/issue-61033-2.rs index 0799be10b96c7..1760ba1584d0b 100644 --- a/src/test/ui/macros/issue-61033-2.rs +++ b/src/test/ui/macros/issue-61033-2.rs @@ -5,7 +5,9 @@ macro_rules! test2 { $(* $id1:ident)* $(+ $id2:ident)* ) => { - $( //~ERROR meta-variable `id1` repeats 2 times + $( + //~^ ERROR meta-variable `id1` repeats 2 times + //~| ERROR meta-variable `id1` repeats 2 times $id1 + $id2 // $id1 and $id2 may repeat different numbers of times )* } @@ -16,4 +18,8 @@ fn main() { * a * b + a + b + c } + test2! { + * a * b + + a + b + c + d + } } diff --git a/src/test/ui/macros/issue-61033-2.stderr b/src/test/ui/macros/issue-61033-2.stderr index bf502919cf794..cdfe7934a0cac 100644 --- a/src/test/ui/macros/issue-61033-2.stderr +++ b/src/test/ui/macros/issue-61033-2.stderr @@ -3,9 +3,22 @@ error: meta-variable `id1` repeats 2 times, but `id2` repeats 3 times | LL | $( | __________^ +LL | | +LL | | LL | | $id1 + $id2 // $id1 and $id2 may repeat different numbers of times LL | | )* | |_________^ -error: aborting due to previous error +error: meta-variable `id1` repeats 2 times, but `id2` repeats 4 times + --> $DIR/issue-61033-2.rs:8:10 + | +LL | $( + | __________^ +LL | | +LL | | +LL | | $id1 + $id2 // $id1 and $id2 may repeat different numbers of times +LL | | )* + | |_________^ + +error: aborting due to 2 previous errors diff --git a/src/test/ui/parser/macro/macro-repeat.rs b/src/test/ui/parser/macro/macro-repeat.rs index 580a1daacbf31..3ffbea217e79e 100644 --- a/src/test/ui/parser/macro/macro-repeat.rs +++ b/src/test/ui/parser/macro/macro-repeat.rs @@ -1,9 +1,12 @@ macro_rules! mac { - ( $($v:tt)* ) => ( - $v //~ ERROR still repeating at this depth - ) + ( $($v:tt)* ) => { + $v + //~^ ERROR still repeating at this depth + //~| ERROR still repeating at this depth + }; } fn main() { mac!(0); + mac!(1); } diff --git a/src/test/ui/parser/macro/macro-repeat.stderr b/src/test/ui/parser/macro/macro-repeat.stderr index c86684de74432..63554b197b91c 100644 --- a/src/test/ui/parser/macro/macro-repeat.stderr +++ b/src/test/ui/parser/macro/macro-repeat.stderr @@ -4,5 +4,11 @@ error: variable 'v' is still repeating at this depth LL | $v | ^^ -error: aborting due to previous error +error: variable 'v' is still repeating at this depth + --> $DIR/macro-repeat.rs:3:9 + | +LL | $v + | ^^ + +error: aborting due to 2 previous errors From 5fb479fc39a7453799911333315355e860ea1172 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 12:54:57 +0100 Subject: [PATCH 23/34] defatalize `compile_declarative_macro` --- src/librustc_expand/mbe/macro_rules.rs | 48 ++++++++++++------- ...ocal-ambiguity-multiple-parsing-options.rs | 8 ++++ ...-ambiguity-multiple-parsing-options.stderr | 14 ++++++ 3 files changed, 54 insertions(+), 16 deletions(-) create mode 100644 src/test/ui/macros/local-ambiguity-multiple-parsing-options.rs create mode 100644 src/test/ui/macros/local-ambiguity-multiple-parsing-options.stderr diff --git a/src/librustc_expand/mbe/macro_rules.rs b/src/librustc_expand/mbe/macro_rules.rs index a15d9cb982b67..4cf429fe7f3f9 100644 --- a/src/librustc_expand/mbe/macro_rules.rs +++ b/src/librustc_expand/mbe/macro_rules.rs @@ -15,7 +15,7 @@ use rustc_ast_pretty::pprust; use rustc_attr::{self as attr, TransparencyError}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::Lrc; -use rustc_errors::{Applicability, DiagnosticBuilder, FatalError}; +use rustc_errors::{Applicability, DiagnosticBuilder}; use rustc_feature::Features; use rustc_parse::parser::Parser; use rustc_session::parse::ParseSess; @@ -180,6 +180,19 @@ impl TTMacroExpander for MacroRulesMacroExpander { } } +struct MacroRulesDummyExpander; + +impl TTMacroExpander for MacroRulesDummyExpander { + fn expand<'cx>( + &self, + _: &'cx mut ExtCtxt<'_>, + sp: Span, + _: TokenStream, + ) -> Box { + DummyResult::any(sp) + } +} + fn trace_macros_note(cx_expansions: &mut FxHashMap>, sp: Span, message: String) { let sp = sp.macro_backtrace().last().map(|trace| trace.call_site).unwrap_or(sp); cx_expansions.entry(sp).or_default().push(message); @@ -364,6 +377,18 @@ pub fn compile_declarative_macro( def: &ast::Item, edition: Edition, ) -> SyntaxExtension { + let mk_syn_ext = |expander| { + SyntaxExtension::new( + sess, + SyntaxExtensionKind::LegacyBang(expander), + def.span, + Vec::new(), + edition, + def.ident.name, + &def.attrs, + ) + }; + let diag = &sess.span_diagnostic; let lhs_nm = ast::Ident::new(sym::lhs, def.span); let rhs_nm = ast::Ident::new(sym::rhs, def.span); @@ -418,13 +443,12 @@ pub fn compile_declarative_macro( Failure(token, msg) => { let s = parse_failure_msg(&token); let sp = token.span.substitute_dummy(def.span); - let mut err = sess.span_diagnostic.struct_span_fatal(sp, &s); - err.span_label(sp, msg); - err.emit(); - FatalError.raise(); + sess.span_diagnostic.struct_span_err(sp, &s).span_label(sp, msg).emit(); + return mk_syn_ext(Box::new(MacroRulesDummyExpander)); } - Error(sp, s) => { - sess.span_diagnostic.span_fatal(sp.substitute_dummy(def.span), &s).raise(); + Error(sp, msg) => { + sess.span_diagnostic.struct_span_err(sp.substitute_dummy(def.span), &msg).emit(); + return mk_syn_ext(Box::new(MacroRulesDummyExpander)); } }; @@ -496,15 +520,7 @@ pub fn compile_declarative_macro( valid, }); - SyntaxExtension::new( - sess, - SyntaxExtensionKind::LegacyBang(expander), - def.span, - Vec::new(), - edition, - def.ident.name, - &def.attrs, - ) + mk_syn_ext(expander) } fn check_lhs_nt_follows( diff --git a/src/test/ui/macros/local-ambiguity-multiple-parsing-options.rs b/src/test/ui/macros/local-ambiguity-multiple-parsing-options.rs new file mode 100644 index 0000000000000..3967481098cff --- /dev/null +++ b/src/test/ui/macros/local-ambiguity-multiple-parsing-options.rs @@ -0,0 +1,8 @@ +fn main() {} + +macro_rules! ambiguity { + ($($i:ident)* $j:ident) => {}; +} + +ambiguity!(error); //~ ERROR local ambiguity +ambiguity!(error); //~ ERROR local ambiguity diff --git a/src/test/ui/macros/local-ambiguity-multiple-parsing-options.stderr b/src/test/ui/macros/local-ambiguity-multiple-parsing-options.stderr new file mode 100644 index 0000000000000..0ae56c422213c --- /dev/null +++ b/src/test/ui/macros/local-ambiguity-multiple-parsing-options.stderr @@ -0,0 +1,14 @@ +error: local ambiguity: multiple parsing options: built-in NTs ident ('i') or ident ('j'). + --> $DIR/local-ambiguity-multiple-parsing-options.rs:7:12 + | +LL | ambiguity!(error); + | ^^^^^ + +error: local ambiguity: multiple parsing options: built-in NTs ident ('i') or ident ('j'). + --> $DIR/local-ambiguity-multiple-parsing-options.rs:8:12 + | +LL | ambiguity!(error); + | ^^^^^ + +error: aborting due to 2 previous errors + From 3ff93767de9f3a2626e7197b1a61f6e6043c5f30 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 13:06:01 +0100 Subject: [PATCH 24/34] expand: nix unused method --- src/librustc_expand/base.rs | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/librustc_expand/base.rs b/src/librustc_expand/base.rs index 518a214b4a510..59c1a5468f100 100644 --- a/src/librustc_expand/base.rs +++ b/src/librustc_expand/base.rs @@ -10,7 +10,7 @@ use rustc_ast::visit::{AssocCtxt, Visitor}; use rustc_attr::{self as attr, Deprecation, HasAttrs, Stability}; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::sync::{self, Lrc}; -use rustc_errors::{DiagnosticBuilder, DiagnosticId, ErrorReported}; +use rustc_errors::{DiagnosticBuilder, ErrorReported}; use rustc_parse::{self, parser, MACRO_ARGUMENTS}; use rustc_session::parse::ParseSess; use rustc_span::edition::Edition; @@ -1026,9 +1026,6 @@ impl<'a> ExtCtxt<'a> { pub fn span_err>(&self, sp: S, msg: &str) { self.parse_sess.span_diagnostic.span_err(sp, msg); } - pub fn span_err_with_code>(&self, sp: S, msg: &str, code: DiagnosticId) { - self.parse_sess.span_diagnostic.span_err_with_code(sp, msg, code); - } pub fn span_warn>(&self, sp: S, msg: &str) { self.parse_sess.span_diagnostic.span_warn(sp, msg); } From 615a5f0eaae89ea73224ea4e633570c81632ef26 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 13:19:06 +0100 Subject: [PATCH 25/34] defatalize get_test_runner --- src/librustc_builtin_macros/test_harness.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/librustc_builtin_macros/test_harness.rs b/src/librustc_builtin_macros/test_harness.rs index b87767f4a4127..160a5204eaf70 100644 --- a/src/librustc_builtin_macros/test_harness.rs +++ b/src/librustc_builtin_macros/test_harness.rs @@ -345,14 +345,14 @@ fn is_test_case(i: &ast::Item) -> bool { fn get_test_runner(sd: &rustc_errors::Handler, krate: &ast::Crate) -> Option { let test_attr = attr::find_by_name(&krate.attrs, sym::test_runner)?; - test_attr.meta_item_list().map(|meta_list| { - if meta_list.len() != 1 { - sd.span_fatal(test_attr.span, "`#![test_runner(..)]` accepts exactly 1 argument") - .raise() - } - match meta_list[0].meta_item() { - Some(meta_item) if meta_item.is_word() => meta_item.path.clone(), - _ => sd.span_fatal(test_attr.span, "`test_runner` argument must be a path").raise(), - } - }) + let meta_list = test_attr.meta_item_list()?; + let span = test_attr.span; + match &*meta_list { + [single] => match single.meta_item() { + Some(meta_item) if meta_item.is_word() => return Some(meta_item.path.clone()), + _ => sd.struct_span_err(span, "`test_runner` argument must be a path").emit(), + }, + _ => sd.struct_span_err(span, "`#![test_runner(..)]` accepts exactly 1 argument").emit(), + } + None } From f41ae8ed6d1a7db9bc831ab9521bf239bb37abe2 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 13:27:56 +0100 Subject: [PATCH 26/34] defatalize expand_test_or_bench --- src/librustc_builtin_macros/test.rs | 16 ++++++++-------- .../test-attr-non-associated-functions.rs | 8 +++++++- .../test-attr-non-associated-functions.stderr | 12 +++++++++++- 3 files changed, 26 insertions(+), 10 deletions(-) diff --git a/src/librustc_builtin_macros/test.rs b/src/librustc_builtin_macros/test.rs index 39009ca27f102..bdc4ae2fe274b 100644 --- a/src/librustc_builtin_macros/test.rs +++ b/src/librustc_builtin_macros/test.rs @@ -74,16 +74,16 @@ pub fn expand_test_or_bench( return vec![]; } - let item = if let Annotatable::Item(i) = item { - i - } else { - cx.parse_sess - .span_diagnostic - .span_fatal( - item.span(), + let item = match item { + Annotatable::Item(i) => i, + other => { + cx.struct_span_err( + other.span(), "`#[test]` attribute is only allowed on non associated functions", ) - .raise(); + .emit(); + return vec![other]; + } }; if let ast::ItemKind::MacCall(_) = item.kind { diff --git a/src/test/ui/test-attrs/test-attr-non-associated-functions.rs b/src/test/ui/test-attrs/test-attr-non-associated-functions.rs index e475f5b4a75a5..31e567c396067 100644 --- a/src/test/ui/test-attrs/test-attr-non-associated-functions.rs +++ b/src/test/ui/test-attrs/test-attr-non-associated-functions.rs @@ -6,7 +6,13 @@ struct A {} impl A { #[test] - fn new() -> A { //~ ERROR `#[test]` attribute is only allowed on non associated functions + fn new() -> A { + //~^ ERROR `#[test]` attribute is only allowed on non associated functions + A {} + } + #[test] + fn recovery_witness() -> A { + //~^ ERROR `#[test]` attribute is only allowed on non associated functions A {} } } diff --git a/src/test/ui/test-attrs/test-attr-non-associated-functions.stderr b/src/test/ui/test-attrs/test-attr-non-associated-functions.stderr index cb3ae51823e45..a81b8f3980c37 100644 --- a/src/test/ui/test-attrs/test-attr-non-associated-functions.stderr +++ b/src/test/ui/test-attrs/test-attr-non-associated-functions.stderr @@ -2,9 +2,19 @@ error: `#[test]` attribute is only allowed on non associated functions --> $DIR/test-attr-non-associated-functions.rs:9:5 | LL | / fn new() -> A { +LL | | LL | | A {} LL | | } | |_____^ -error: aborting due to previous error +error: `#[test]` attribute is only allowed on non associated functions + --> $DIR/test-attr-non-associated-functions.rs:14:5 + | +LL | / fn recovery_witness() -> A { +LL | | +LL | | A {} +LL | | } + | |_____^ + +error: aborting due to 2 previous errors From aa9a70cf44dcfd042e6437e56bc0ab493aa573f3 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Tue, 17 Mar 2020 14:13:32 +0100 Subject: [PATCH 27/34] expand: add recovery for parse_nt --- src/librustc_expand/mbe/macro_parser.rs | 29 +++++++++---------- src/librustc_expand/mbe/macro_rules.rs | 6 +++- src/test/ui/parser/issue-62894.stderr | 5 ++++ src/test/ui/parser/nt-parsing-has-recovery.rs | 10 +++++++ .../ui/parser/nt-parsing-has-recovery.stderr | 29 +++++++++++++++++++ 5 files changed, 63 insertions(+), 16 deletions(-) create mode 100644 src/test/ui/parser/nt-parsing-has-recovery.rs create mode 100644 src/test/ui/parser/nt-parsing-has-recovery.stderr diff --git a/src/librustc_expand/mbe/macro_parser.rs b/src/librustc_expand/mbe/macro_parser.rs index 0d777d88cad3a..e868b7e36aac5 100644 --- a/src/librustc_expand/mbe/macro_parser.rs +++ b/src/librustc_expand/mbe/macro_parser.rs @@ -84,7 +84,7 @@ use rustc_parse::parser::{FollowedByType, Parser, PathStyle}; use rustc_session::parse::ParseSess; use rustc_span::symbol::{kw, sym, Ident, MacroRulesNormalizedIdent, Symbol}; -use rustc_errors::{FatalError, PResult}; +use rustc_errors::PResult; use rustc_span::Span; use smallvec::{smallvec, SmallVec}; @@ -271,6 +271,7 @@ crate enum ParseResult { Failure(Token, &'static str), /// Fatal error (malformed macro?). Abort compilation. Error(rustc_span::Span, String), + ErrorReported, } /// A `ParseResult` where the `Success` variant contains a mapping of @@ -652,6 +653,7 @@ pub(super) fn parse_tt(parser: &mut Cow<'_, Parser<'_>>, ms: &[TokenTree]) -> Na Success(_) => {} Failure(token, msg) => return Failure(token, msg), Error(sp, msg) => return Error(sp, msg), + ErrorReported => return ErrorReported, } // inner parse loop handled all cur_items, so it's empty @@ -735,10 +737,11 @@ pub(super) fn parse_tt(parser: &mut Cow<'_, Parser<'_>>, ms: &[TokenTree]) -> Na let mut item = bb_items.pop().unwrap(); if let TokenTree::MetaVarDecl(span, _, ident) = item.top_elts.get_tt(item.idx) { let match_cur = item.match_cur; - item.push_match( - match_cur, - MatchedNonterminal(Lrc::new(parse_nt(parser.to_mut(), span, ident.name))), - ); + let nt = match parse_nt(parser.to_mut(), span, ident.name) { + Err(()) => return ErrorReported, + Ok(nt) => nt, + }; + item.push_match(match_cur, MatchedNonterminal(Lrc::new(nt))); item.idx += 1; item.match_cur += 1; } else { @@ -849,20 +852,16 @@ fn may_begin_with(token: &Token, name: Name) -> bool { /// # Returns /// /// The parsed non-terminal. -fn parse_nt(p: &mut Parser<'_>, sp: Span, name: Symbol) -> Nonterminal { +fn parse_nt(p: &mut Parser<'_>, sp: Span, name: Symbol) -> Result { // FIXME(Centril): Consider moving this to `parser.rs` to make // the visibilities of the methods used below `pub(super)` at most. - if name == sym::tt { - return token::NtTT(p.parse_token_tree()); - } - match parse_nt_inner(p, sp, name) { - Ok(nt) => nt, - Err(mut err) => { - err.emit(); - FatalError.raise(); - } + return Ok(token::NtTT(p.parse_token_tree())); } + parse_nt_inner(p, sp, name).map_err(|mut err| { + err.span_label(sp, format!("while parsing argument for this `{}` macro fragment", name)) + .emit() + }) } fn parse_nt_inner<'a>(p: &mut Parser<'a>, sp: Span, name: Symbol) -> PResult<'a, Nonterminal> { diff --git a/src/librustc_expand/mbe/macro_rules.rs b/src/librustc_expand/mbe/macro_rules.rs index 4cf429fe7f3f9..056d61dd7a447 100644 --- a/src/librustc_expand/mbe/macro_rules.rs +++ b/src/librustc_expand/mbe/macro_rules.rs @@ -4,7 +4,7 @@ use crate::expand::{ensure_complete_parse, parse_ast_fragment, AstFragment, AstF use crate::mbe; use crate::mbe::macro_check; use crate::mbe::macro_parser::parse_tt; -use crate::mbe::macro_parser::{Error, Failure, Success}; +use crate::mbe::macro_parser::{Error, ErrorReported, Failure, Success}; use crate::mbe::macro_parser::{MatchedNonterminal, MatchedSeq}; use crate::mbe::transcribe::transcribe; @@ -319,6 +319,7 @@ fn generic_extension<'cx>( cx.struct_span_err(span, &msg).emit(); return DummyResult::any(span); } + ErrorReported => return DummyResult::any(sp), } // The matcher was not `Success(..)`ful. @@ -450,6 +451,9 @@ pub fn compile_declarative_macro( sess.span_diagnostic.struct_span_err(sp.substitute_dummy(def.span), &msg).emit(); return mk_syn_ext(Box::new(MacroRulesDummyExpander)); } + ErrorReported => { + return mk_syn_ext(Box::new(MacroRulesDummyExpander)); + } }; let mut valid = true; diff --git a/src/test/ui/parser/issue-62894.stderr b/src/test/ui/parser/issue-62894.stderr index 6db380f7a7fe2..73e3552e3ec7a 100644 --- a/src/test/ui/parser/issue-62894.stderr +++ b/src/test/ui/parser/issue-62894.stderr @@ -42,6 +42,11 @@ LL | fn f() { assert_eq!(f(), (), assert_eq!(assert_eq! LL | LL | fn main() {} | ^^ unexpected token + | + ::: $SRC_DIR/libcore/macros/mod.rs:LL:COL + | +LL | ($left:expr, $right:expr) => ({ + | ---------- while parsing argument for this `expr` macro fragment error: aborting due to 4 previous errors diff --git a/src/test/ui/parser/nt-parsing-has-recovery.rs b/src/test/ui/parser/nt-parsing-has-recovery.rs new file mode 100644 index 0000000000000..ccbeb398af5ba --- /dev/null +++ b/src/test/ui/parser/nt-parsing-has-recovery.rs @@ -0,0 +1,10 @@ +macro_rules! foo { + ($e:expr) => {} +} + +foo!(1 + @); //~ ERROR expected expression, found `@` +foo!(1 + @); //~ ERROR expected expression, found `@` + +fn main() { + let _recovery_witness: () = 0; //~ ERROR mismatched types +} diff --git a/src/test/ui/parser/nt-parsing-has-recovery.stderr b/src/test/ui/parser/nt-parsing-has-recovery.stderr new file mode 100644 index 0000000000000..263c4ad53612e --- /dev/null +++ b/src/test/ui/parser/nt-parsing-has-recovery.stderr @@ -0,0 +1,29 @@ +error: expected expression, found `@` + --> $DIR/nt-parsing-has-recovery.rs:5:10 + | +LL | ($e:expr) => {} + | ------- while parsing argument for this `expr` macro fragment +... +LL | foo!(1 + @); + | ^ expected expression + +error: expected expression, found `@` + --> $DIR/nt-parsing-has-recovery.rs:6:10 + | +LL | ($e:expr) => {} + | ------- while parsing argument for this `expr` macro fragment +... +LL | foo!(1 + @); + | ^ expected expression + +error[E0308]: mismatched types + --> $DIR/nt-parsing-has-recovery.rs:9:33 + | +LL | let _recovery_witness: () = 0; + | -- ^ expected `()`, found integer + | | + | expected due to this + +error: aborting due to 3 previous errors + +For more information about this error, try `rustc --explain E0308`. From 7c5dcc9ef69204c80f533573f19062c5ad8af9d0 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Wed, 18 Mar 2020 13:34:11 +0100 Subject: [PATCH 28/34] expand: address review comments --- src/librustc_expand/mbe/macro_rules.rs | 29 +++++++------------ .../edition-keywords-2018-2015-parsing.rs | 6 +++- .../edition-keywords-2018-2015-parsing.stderr | 25 ++++++++-------- .../edition-keywords-2018-2018-parsing.rs | 6 +++- .../edition-keywords-2018-2018-parsing.stderr | 25 ++++++++-------- src/test/ui/parser/macro/issue-33569.rs | 4 +-- src/test/ui/parser/macro/issue-33569.stderr | 6 ++-- .../ui/proc-macro/invalid-punct-ident-4.rs | 8 +++-- .../proc-macro/invalid-punct-ident-4.stderr | 19 ++++++------ 9 files changed, 64 insertions(+), 64 deletions(-) diff --git a/src/librustc_expand/mbe/macro_rules.rs b/src/librustc_expand/mbe/macro_rules.rs index 056d61dd7a447..87d029a045ef6 100644 --- a/src/librustc_expand/mbe/macro_rules.rs +++ b/src/librustc_expand/mbe/macro_rules.rs @@ -180,17 +180,12 @@ impl TTMacroExpander for MacroRulesMacroExpander { } } -struct MacroRulesDummyExpander; - -impl TTMacroExpander for MacroRulesDummyExpander { - fn expand<'cx>( - &self, - _: &'cx mut ExtCtxt<'_>, - sp: Span, - _: TokenStream, - ) -> Box { - DummyResult::any(sp) - } +fn macro_rules_dummy_expander<'cx>( + _: &'cx mut ExtCtxt<'_>, + span: Span, + _: TokenStream, +) -> Box { + DummyResult::any(span) } fn trace_macros_note(cx_expansions: &mut FxHashMap>, sp: Span, message: String) { @@ -445,14 +440,14 @@ pub fn compile_declarative_macro( let s = parse_failure_msg(&token); let sp = token.span.substitute_dummy(def.span); sess.span_diagnostic.struct_span_err(sp, &s).span_label(sp, msg).emit(); - return mk_syn_ext(Box::new(MacroRulesDummyExpander)); + return mk_syn_ext(Box::new(macro_rules_dummy_expander)); } Error(sp, msg) => { sess.span_diagnostic.struct_span_err(sp.substitute_dummy(def.span), &msg).emit(); - return mk_syn_ext(Box::new(MacroRulesDummyExpander)); + return mk_syn_ext(Box::new(macro_rules_dummy_expander)); } ErrorReported => { - return mk_syn_ext(Box::new(MacroRulesDummyExpander)); + return mk_syn_ext(Box::new(macro_rules_dummy_expander)); } }; @@ -515,16 +510,14 @@ pub fn compile_declarative_macro( None => {} } - let expander: Box<_> = Box::new(MacroRulesMacroExpander { + mk_syn_ext(Box::new(MacroRulesMacroExpander { name: def.ident, span: def.span, transparency, lhses, rhses, valid, - }); - - mk_syn_ext(expander) + })) } fn check_lhs_nt_follows( diff --git a/src/test/ui/editions/edition-keywords-2018-2015-parsing.rs b/src/test/ui/editions/edition-keywords-2018-2015-parsing.rs index a7a10d0f677af..d5ed9fb9a285e 100644 --- a/src/test/ui/editions/edition-keywords-2018-2015-parsing.rs +++ b/src/test/ui/editions/edition-keywords-2018-2015-parsing.rs @@ -1,6 +1,8 @@ // edition:2018 // aux-build:edition-kw-macro-2015.rs +#![feature(async_closure)] + fn main() {} #[macro_use] @@ -19,8 +21,10 @@ pub fn check_async() { r#async = consumes_async_raw!(async); //~ ERROR no rules expected the token `async` r#async = consumes_async_raw!(r#async); // OK - if passes_ident!(async) == 1 {} //~ ERROR async closures are unstable + if passes_ident!(async) == 1 {} if passes_ident!(r#async) == 1 {} // OK module::async(); //~ ERROR expected identifier, found keyword `async` module::r#async(); // OK + + let _recovery_witness: () = 0; //~ ERROR mismatched types } diff --git a/src/test/ui/editions/edition-keywords-2018-2015-parsing.stderr b/src/test/ui/editions/edition-keywords-2018-2015-parsing.stderr index 3c3b934b531c8..28663563c6ccd 100644 --- a/src/test/ui/editions/edition-keywords-2018-2015-parsing.stderr +++ b/src/test/ui/editions/edition-keywords-2018-2015-parsing.stderr @@ -1,5 +1,5 @@ error: expected identifier, found keyword `async` - --> $DIR/edition-keywords-2018-2015-parsing.rs:14:13 + --> $DIR/edition-keywords-2018-2015-parsing.rs:16:13 | LL | let mut async = 1; | ^^^^^ expected identifier, found keyword @@ -10,7 +10,7 @@ LL | let mut r#async = 1; | ^^^^^^^ error: expected identifier, found keyword `async` - --> $DIR/edition-keywords-2018-2015-parsing.rs:24:13 + --> $DIR/edition-keywords-2018-2015-parsing.rs:26:13 | LL | module::async(); | ^^^^^ expected identifier, found keyword @@ -21,13 +21,13 @@ LL | module::r#async(); | ^^^^^^^ error: no rules expected the token `r#async` - --> $DIR/edition-keywords-2018-2015-parsing.rs:18:31 + --> $DIR/edition-keywords-2018-2015-parsing.rs:20:31 | LL | r#async = consumes_async!(r#async); | ^^^^^^^ no rules expected this token in macro call error: no rules expected the token `async` - --> $DIR/edition-keywords-2018-2015-parsing.rs:19:35 + --> $DIR/edition-keywords-2018-2015-parsing.rs:21:35 | LL | r#async = consumes_async_raw!(async); | ^^^^^ no rules expected this token in macro call @@ -38,20 +38,19 @@ error: macro expansion ends with an incomplete expression: expected one of `move LL | ($i: ident) => ($i) | ^ expected one of `move`, `|`, or `||` | - ::: $DIR/edition-keywords-2018-2015-parsing.rs:22:8 + ::: $DIR/edition-keywords-2018-2015-parsing.rs:24:8 | LL | if passes_ident!(async) == 1 {} | -------------------- in this macro invocation -error[E0658]: async closures are unstable - --> $DIR/edition-keywords-2018-2015-parsing.rs:22:22 +error[E0308]: mismatched types + --> $DIR/edition-keywords-2018-2015-parsing.rs:29:33 | -LL | if passes_ident!(async) == 1 {} - | ^^^^^ - | - = note: see issue #62290 for more information - = help: add `#![feature(async_closure)]` to the crate attributes to enable +LL | let _recovery_witness: () = 0; + | -- ^ expected `()`, found integer + | | + | expected due to this error: aborting due to 6 previous errors -For more information about this error, try `rustc --explain E0658`. +For more information about this error, try `rustc --explain E0308`. diff --git a/src/test/ui/editions/edition-keywords-2018-2018-parsing.rs b/src/test/ui/editions/edition-keywords-2018-2018-parsing.rs index b12ad76a74798..044ab249f2c26 100644 --- a/src/test/ui/editions/edition-keywords-2018-2018-parsing.rs +++ b/src/test/ui/editions/edition-keywords-2018-2018-parsing.rs @@ -1,6 +1,8 @@ // edition:2018 // aux-build:edition-kw-macro-2018.rs +#![feature(async_closure)] + fn main() {} #[macro_use] @@ -19,8 +21,10 @@ pub fn check_async() { r#async = consumes_async_raw!(async); //~ ERROR no rules expected the token `async` r#async = consumes_async_raw!(r#async); // OK - if passes_ident!(async) == 1 {} //~ ERROR async closures are unstable + if passes_ident!(async) == 1 {} if passes_ident!(r#async) == 1 {} // OK module::async(); //~ ERROR expected identifier, found keyword `async` module::r#async(); // OK + + let _recovery_witness: () = 0; //~ ERROR mismatched types } diff --git a/src/test/ui/editions/edition-keywords-2018-2018-parsing.stderr b/src/test/ui/editions/edition-keywords-2018-2018-parsing.stderr index a2b129d17e0be..cda7e65e437e8 100644 --- a/src/test/ui/editions/edition-keywords-2018-2018-parsing.stderr +++ b/src/test/ui/editions/edition-keywords-2018-2018-parsing.stderr @@ -1,5 +1,5 @@ error: expected identifier, found keyword `async` - --> $DIR/edition-keywords-2018-2018-parsing.rs:14:13 + --> $DIR/edition-keywords-2018-2018-parsing.rs:16:13 | LL | let mut async = 1; | ^^^^^ expected identifier, found keyword @@ -10,7 +10,7 @@ LL | let mut r#async = 1; | ^^^^^^^ error: expected identifier, found keyword `async` - --> $DIR/edition-keywords-2018-2018-parsing.rs:24:13 + --> $DIR/edition-keywords-2018-2018-parsing.rs:26:13 | LL | module::async(); | ^^^^^ expected identifier, found keyword @@ -21,13 +21,13 @@ LL | module::r#async(); | ^^^^^^^ error: no rules expected the token `r#async` - --> $DIR/edition-keywords-2018-2018-parsing.rs:18:31 + --> $DIR/edition-keywords-2018-2018-parsing.rs:20:31 | LL | r#async = consumes_async!(r#async); | ^^^^^^^ no rules expected this token in macro call error: no rules expected the token `async` - --> $DIR/edition-keywords-2018-2018-parsing.rs:19:35 + --> $DIR/edition-keywords-2018-2018-parsing.rs:21:35 | LL | r#async = consumes_async_raw!(async); | ^^^^^ no rules expected this token in macro call @@ -38,20 +38,19 @@ error: macro expansion ends with an incomplete expression: expected one of `move LL | ($i: ident) => ($i) | ^ expected one of `move`, `|`, or `||` | - ::: $DIR/edition-keywords-2018-2018-parsing.rs:22:8 + ::: $DIR/edition-keywords-2018-2018-parsing.rs:24:8 | LL | if passes_ident!(async) == 1 {} | -------------------- in this macro invocation -error[E0658]: async closures are unstable - --> $DIR/edition-keywords-2018-2018-parsing.rs:22:22 +error[E0308]: mismatched types + --> $DIR/edition-keywords-2018-2018-parsing.rs:29:33 | -LL | if passes_ident!(async) == 1 {} - | ^^^^^ - | - = note: see issue #62290 for more information - = help: add `#![feature(async_closure)]` to the crate attributes to enable +LL | let _recovery_witness: () = 0; + | -- ^ expected `()`, found integer + | | + | expected due to this error: aborting due to 6 previous errors -For more information about this error, try `rustc --explain E0658`. +For more information about this error, try `rustc --explain E0308`. diff --git a/src/test/ui/parser/macro/issue-33569.rs b/src/test/ui/parser/macro/issue-33569.rs index e32825ad3e064..80e2d7c6545ba 100644 --- a/src/test/ui/parser/macro/issue-33569.rs +++ b/src/test/ui/parser/macro/issue-33569.rs @@ -1,5 +1,3 @@ -fn main() {} - macro_rules! foo { { $+ } => { //~ ERROR expected identifier, found `+` //~^ ERROR missing fragment specifier @@ -8,3 +6,5 @@ macro_rules! foo { } foo!(); + +fn main() {} diff --git a/src/test/ui/parser/macro/issue-33569.stderr b/src/test/ui/parser/macro/issue-33569.stderr index a08d26095f564..b4d38d3ce4806 100644 --- a/src/test/ui/parser/macro/issue-33569.stderr +++ b/src/test/ui/parser/macro/issue-33569.stderr @@ -1,17 +1,17 @@ error: expected identifier, found `+` - --> $DIR/issue-33569.rs:4:8 + --> $DIR/issue-33569.rs:2:8 | LL | { $+ } => { | ^ error: expected one of: `*`, `+`, or `?` - --> $DIR/issue-33569.rs:6:13 + --> $DIR/issue-33569.rs:4:13 | LL | $(x)(y) | ^^^ error: missing fragment specifier - --> $DIR/issue-33569.rs:4:8 + --> $DIR/issue-33569.rs:2:8 | LL | { $+ } => { | ^ diff --git a/src/test/ui/proc-macro/invalid-punct-ident-4.rs b/src/test/ui/proc-macro/invalid-punct-ident-4.rs index ab0250f53f699..59b347dac679c 100644 --- a/src/test/ui/proc-macro/invalid-punct-ident-4.rs +++ b/src/test/ui/proc-macro/invalid-punct-ident-4.rs @@ -1,10 +1,12 @@ // aux-build:invalid-punct-ident.rs -// We use `main` not found below as a witness for error recovery in proc macro expansion. - -#[macro_use] //~ ERROR `main` function not found +#[macro_use] extern crate invalid_punct_ident; lexer_failure!(); //~^ ERROR proc macro panicked //~| ERROR unexpected closing delimiter: `)` + +fn main() { + let _recovery_witness: () = 0; //~ ERROR mismatched types +} diff --git a/src/test/ui/proc-macro/invalid-punct-ident-4.stderr b/src/test/ui/proc-macro/invalid-punct-ident-4.stderr index 296e2fb094280..3b357aecea864 100644 --- a/src/test/ui/proc-macro/invalid-punct-ident-4.stderr +++ b/src/test/ui/proc-macro/invalid-punct-ident-4.stderr @@ -1,5 +1,5 @@ error: unexpected closing delimiter: `)` - --> $DIR/invalid-punct-ident-4.rs:8:1 + --> $DIR/invalid-punct-ident-4.rs:6:1 | LL | lexer_failure!(); | ^^^^^^^^^^^^^^^^^ unexpected closing delimiter @@ -7,20 +7,19 @@ LL | lexer_failure!(); = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) error: proc macro panicked - --> $DIR/invalid-punct-ident-4.rs:8:1 + --> $DIR/invalid-punct-ident-4.rs:6:1 | LL | lexer_failure!(); | ^^^^^^^^^^^^^^^^^ -error[E0601]: `main` function not found in crate `invalid_punct_ident_4` - --> $DIR/invalid-punct-ident-4.rs:5:1 +error[E0308]: mismatched types + --> $DIR/invalid-punct-ident-4.rs:11:33 | -LL | / #[macro_use] -LL | | extern crate invalid_punct_ident; -LL | | -LL | | lexer_failure!(); - | |_________________^ consider adding a `main` function to `$DIR/invalid-punct-ident-4.rs` +LL | let _recovery_witness: () = 0; + | -- ^ expected `()`, found integer + | | + | expected due to this error: aborting due to 3 previous errors -For more information about this error, try `rustc --explain E0601`. +For more information about this error, try `rustc --explain E0308`. From 11106905d9d02591ce0564af60771a7aef4ea596 Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Fri, 20 Mar 2020 17:01:53 +0100 Subject: [PATCH 29/34] fix rebase fallout --- src/test/ui/span/transitive-dep-span.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/test/ui/span/transitive-dep-span.rs b/src/test/ui/span/transitive-dep-span.rs index b445d389c561a..2d46f74ad9bc9 100644 --- a/src/test/ui/span/transitive-dep-span.rs +++ b/src/test/ui/span/transitive-dep-span.rs @@ -11,3 +11,5 @@ extern crate transitive_dep_two; transitive_dep_two::parse_error!(); //~ ERROR expected one of + +fn main() {} From 4a67a1b4c8dc21d2e1c242e74e5fabc9e47658eb Mon Sep 17 00:00:00 2001 From: Mazdak Farrokhzad Date: Sat, 21 Mar 2020 22:12:24 +0100 Subject: [PATCH 30/34] fix rebase fallout due to #69497. --- src/test/ui/macros/trace_faulty_macros.rs | 12 ++++------ src/test/ui/macros/trace_faulty_macros.stderr | 23 ++++++++++++++++--- 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/test/ui/macros/trace_faulty_macros.rs b/src/test/ui/macros/trace_faulty_macros.rs index a55f05414b206..5a8e2f50ce33d 100644 --- a/src/test/ui/macros/trace_faulty_macros.rs +++ b/src/test/ui/macros/trace_faulty_macros.rs @@ -1,6 +1,6 @@ // compile-flags: -Z trace-macros -#![recursion_limit="4"] +#![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { @@ -24,9 +24,7 @@ macro_rules! my_recursive_macro { } macro_rules! my_macro { - () => { - - }; + () => {}; } fn main() { @@ -39,7 +37,7 @@ fn main() { } #[my_macro] -fn use_bang_macro_as_attr(){} +fn use_bang_macro_as_attr() {} -#[derive(Debug)] -fn use_derive_macro_as_attr(){} +#[derive(Debug)] //~ ERROR `derive` may only be applied to structs +fn use_derive_macro_as_attr() {} diff --git a/src/test/ui/macros/trace_faulty_macros.stderr b/src/test/ui/macros/trace_faulty_macros.stderr index 109b493b43717..aec9d1ab191af 100644 --- a/src/test/ui/macros/trace_faulty_macros.stderr +++ b/src/test/ui/macros/trace_faulty_macros.stderr @@ -13,7 +13,7 @@ LL | my_faulty_macro!(); = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) note: trace_macro - --> $DIR/trace_faulty_macros.rs:33:5 + --> $DIR/trace_faulty_macros.rs:31:5 | LL | my_faulty_macro!(); | ^^^^^^^^^^^^^^^^^^^ @@ -35,7 +35,7 @@ LL | my_recursive_macro!(); = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) note: trace_macro - --> $DIR/trace_faulty_macros.rs:34:5 + --> $DIR/trace_faulty_macros.rs:32:5 | LL | my_recursive_macro!(); | ^^^^^^^^^^^^^^^^^^^^^^ @@ -60,5 +60,22 @@ LL | let a = pat_macro!(); | = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info) -error: aborting due to 3 previous errors +error: `derive` may only be applied to structs, enums and unions + --> $DIR/trace_faulty_macros.rs:42:1 + | +LL | #[derive(Debug)] + | ^^^^^^^^^^^^^^^^ + +note: trace_macro + --> $DIR/trace_faulty_macros.rs:36:13 + | +LL | let a = pat_macro!(); + | ^^^^^^^^^^^^ + | + = note: expanding `pat_macro! { }` + = note: to `pat_macro ! (A { a : a, b : 0, c : _, .. }) ;` + = note: expanding `pat_macro! { A { a : a, b : 0, c : _, .. } }` + = note: to `A { a: a, b: 0, c: _, .. }` + +error: aborting due to 4 previous errors From c746d93e145ac19358b2d846cdbc61e7c7d22a15 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sat, 21 Mar 2020 23:33:33 +0100 Subject: [PATCH 31/34] Remove wrong entry from RELEASES.md --- RELEASES.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/RELEASES.md b/RELEASES.md index 7e18f1befddec..a767dc1955cae 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -4957,8 +4957,6 @@ Version 1.10.0 (2016-07-07) Language -------- -* [Allow `concat_idents!` in type positions as well as in expression - positions](https://github.com/rust-lang/rust/pull/33735). * [`Copy` types are required to have a trivial implementation of `Clone`](https://github.com/rust-lang/rust/pull/33420). [RFC 1521](https://github.com/rust-lang/rfcs/blob/master/text/1521-copy-clone-semantics.md). * [Single-variant enums support the `#[repr(..)]` attribute](https://github.com/rust-lang/rust/pull/33355). From 3f42104cef01e2c12a6fbe8a1322bd36d920bd01 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Sun, 22 Mar 2020 00:29:12 +0100 Subject: [PATCH 32/34] Remove another wrong entry from RELEASES.md --- RELEASES.md | 1 - 1 file changed, 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index 7e18f1befddec..bc19a776c9196 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -4838,7 +4838,6 @@ Version 1.11.0 (2016-08-18) Language -------- -* [`cfg_attr` works on `path` attributes](https://github.com/rust-lang/rust/pull/34546) * [Support nested `cfg_attr` attributes](https://github.com/rust-lang/rust/pull/34216) * [Allow statement-generating braced macro invocations at the end of blocks](https://github.com/rust-lang/rust/pull/34436) * [Macros can be expanded inside of trait definitions](https://github.com/rust-lang/rust/pull/34213) From 3599fd389de25af78a4616015fa937ff3aeb661a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sat, 21 Mar 2020 23:58:21 +0100 Subject: [PATCH 33/34] summarize if-else-code with identical blocks (clippy::if_same_then_else) --- src/librustc_parse/parser/stmt.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/librustc_parse/parser/stmt.rs b/src/librustc_parse/parser/stmt.rs index d43f5d67113a1..fddfe48bf8670 100644 --- a/src/librustc_parse/parser/stmt.rs +++ b/src/librustc_parse/parser/stmt.rs @@ -217,13 +217,7 @@ impl<'a> Parser<'a> { /// Parses the RHS of a local variable declaration (e.g., '= 14;'). fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option>> { - if self.eat(&token::Eq) { - Ok(Some(self.parse_expr()?)) - } else if skip_eq { - Ok(Some(self.parse_expr()?)) - } else { - Ok(None) - } + if self.eat(&token::Eq) || skip_eq { Ok(Some(self.parse_expr()?)) } else { Ok(None) } } /// Parses a block. No inner attributes are allowed. From 74d68ea7ebe2085bba2758ccce366f1fa4fc6210 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Sun, 22 Mar 2020 00:20:58 +0100 Subject: [PATCH 34/34] don't create variable bindings just to return the bound value immediately (clippy::let_and_return) --- src/liballoc/slice.rs | 3 +-- src/librustc/hir/map/mod.rs | 4 +--- src/librustc_codegen_ssa/back/rpath.rs | 4 +--- src/librustc_codegen_ssa/back/write.rs | 6 ++---- .../infer/canonical/canonicalizer.rs | 6 ++---- src/librustc_metadata/dynamic_lib.rs | 6 ++---- src/librustc_mir/dataflow/move_paths/builder.rs | 5 ++--- src/librustc_mir/transform/const_prop.rs | 5 ++--- src/librustc_parse/lexer/mod.rs | 12 ++++-------- src/librustc_resolve/diagnostics.rs | 3 +-- src/librustc_resolve/lib.rs | 5 ++--- src/librustc_typeck/check/expr.rs | 17 +++++++---------- src/librustc_typeck/check/mod.rs | 6 ++---- src/librustdoc/clean/utils.rs | 6 ++---- src/librustdoc/html/render/cache.rs | 5 ++--- 15 files changed, 33 insertions(+), 60 deletions(-) diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs index 7b83658fca60d..d8fc1faca3a39 100644 --- a/src/liballoc/slice.rs +++ b/src/liballoc/slice.rs @@ -145,8 +145,7 @@ mod hack { unsafe { let len = b.len(); let b = Box::into_raw(b); - let xs = Vec::from_raw_parts(b as *mut T, len, len); - xs + Vec::from_raw_parts(b as *mut T, len, len) } } diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 13257e7bf4770..546b0bbf44ced 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -1038,9 +1038,7 @@ pub(super) fn index_hir<'tcx>(tcx: TyCtxt<'tcx>, cnum: CrateNum) -> &'tcx Indexe collector.finalize_and_compute_crate_hash(crate_disambiguator, &*tcx.cstore, cmdline_args) }; - let map = tcx.arena.alloc(IndexedHir { crate_hash, map }); - - map + tcx.arena.alloc(IndexedHir { crate_hash, map }) } /// Identical to the `PpAnn` implementation for `hir::Crate`, diff --git a/src/librustc_codegen_ssa/back/rpath.rs b/src/librustc_codegen_ssa/back/rpath.rs index 9d19cc25a32bc..0a0e975e5a54c 100644 --- a/src/librustc_codegen_ssa/back/rpath.rs +++ b/src/librustc_codegen_ssa/back/rpath.rs @@ -81,9 +81,7 @@ fn get_rpaths(config: &mut RPathConfig<'_>, libs: &[PathBuf]) -> Vec { rpaths.extend_from_slice(&fallback_rpaths); // Remove duplicates - let rpaths = minimize_rpaths(&rpaths); - - rpaths + minimize_rpaths(&rpaths) } fn get_rpaths_relative_to_output(config: &mut RPathConfig<'_>, libs: &[PathBuf]) -> Vec { diff --git a/src/librustc_codegen_ssa/back/write.rs b/src/librustc_codegen_ssa/back/write.rs index 303ee38565848..746ab34d2844d 100644 --- a/src/librustc_codegen_ssa/back/write.rs +++ b/src/librustc_codegen_ssa/back/write.rs @@ -288,7 +288,7 @@ fn generate_lto_work( B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise()) }; - let result = lto_modules + lto_modules .into_iter() .map(|module| { let cost = module.cost(); @@ -303,9 +303,7 @@ fn generate_lto_work( 0, ) })) - .collect(); - - result + .collect() } pub struct CompiledModules { diff --git a/src/librustc_infer/infer/canonical/canonicalizer.rs b/src/librustc_infer/infer/canonical/canonicalizer.rs index 964e378f7abc8..7b01f39d810b5 100644 --- a/src/librustc_infer/infer/canonical/canonicalizer.rs +++ b/src/librustc_infer/infer/canonical/canonicalizer.rs @@ -555,7 +555,7 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> { // avoid allocations in those cases. We also don't use `indices` to // determine if a kind has been seen before until the limit of 8 has // been exceeded, to also avoid allocations for `indices`. - let var = if !var_values.spilled() { + if !var_values.spilled() { // `var_values` is stack-allocated. `indices` isn't used yet. Do a // direct linear search of `var_values`. if let Some(idx) = var_values.iter().position(|&k| k == kind) { @@ -589,9 +589,7 @@ impl<'cx, 'tcx> Canonicalizer<'cx, 'tcx> { assert_eq!(variables.len(), var_values.len()); BoundVar::new(variables.len() - 1) }) - }; - - var + } } /// Shorthand helper that creates a canonical region variable for diff --git a/src/librustc_metadata/dynamic_lib.rs b/src/librustc_metadata/dynamic_lib.rs index f04d0239d4923..3e78a5852354f 100644 --- a/src/librustc_metadata/dynamic_lib.rs +++ b/src/librustc_metadata/dynamic_lib.rs @@ -94,14 +94,12 @@ mod dl { let result = f(); let last_error = libc::dlerror() as *const _; - let ret = if ptr::null() == last_error { + if ptr::null() == last_error { Ok(result) } else { let s = CStr::from_ptr(last_error).to_bytes(); Err(str::from_utf8(s).unwrap().to_owned()) - }; - - ret + } } } diff --git a/src/librustc_mir/dataflow/move_paths/builder.rs b/src/librustc_mir/dataflow/move_paths/builder.rs index 7c449ad119796..276aabec13da0 100644 --- a/src/librustc_mir/dataflow/move_paths/builder.rs +++ b/src/librustc_mir/dataflow/move_paths/builder.rs @@ -184,14 +184,13 @@ impl<'b, 'a, 'tcx> Gatherer<'b, 'a, 'tcx> { .. } = self.builder; *rev_lookup.projections.entry((base, elem.lift())).or_insert_with(move || { - let path = MoveDataBuilder::new_move_path( + MoveDataBuilder::new_move_path( move_paths, path_map, init_path_map, Some(base), mk_place(*tcx), - ); - path + ) }) } diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 8d7cafc34b356..a1b86db1aedbd 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -400,7 +400,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { where F: FnOnce(&mut Self) -> InterpResult<'tcx, T>, { - let r = match f(self) { + match f(self) { Ok(val) => Some(val), Err(error) => { // Some errors shouldn't come up because creating them causes @@ -414,8 +414,7 @@ impl<'mir, 'tcx> ConstPropagator<'mir, 'tcx> { ); None } - }; - r + } } fn eval_constant(&mut self, c: &Constant<'tcx>, source_info: SourceInfo) -> Option> { diff --git a/src/librustc_parse/lexer/mod.rs b/src/librustc_parse/lexer/mod.rs index f7fb704fcbc2c..7593158dc4f4c 100644 --- a/src/librustc_parse/lexer/mod.rs +++ b/src/librustc_parse/lexer/mod.rs @@ -179,14 +179,12 @@ impl<'a> StringReader<'a> { rustc_lexer::TokenKind::LineComment => { let string = self.str_from(start); // comments with only more "/"s are not doc comments - let tok = if comments::is_line_doc_comment(string) { + if comments::is_line_doc_comment(string) { self.forbid_bare_cr(start, string, "bare CR not allowed in doc-comment"); token::DocComment(Symbol::intern(string)) } else { token::Comment - }; - - tok + } } rustc_lexer::TokenKind::BlockComment { terminated } => { let string = self.str_from(start); @@ -204,14 +202,12 @@ impl<'a> StringReader<'a> { self.fatal_span_(start, last_bpos, msg).raise(); } - let tok = if is_doc_comment { + if is_doc_comment { self.forbid_bare_cr(start, string, "bare CR not allowed in block doc-comment"); token::DocComment(Symbol::intern(string)) } else { token::Comment - }; - - tok + } } rustc_lexer::TokenKind::Whitespace => token::Whitespace, rustc_lexer::TokenKind::Ident | rustc_lexer::TokenKind::RawIdent => { diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 6f567ab65a70c..9e5ff32391486 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -59,8 +59,7 @@ crate struct ImportSuggestion { /// `source_map` functions and this function to something more robust. fn reduce_impl_span_to_impl_keyword(sm: &SourceMap, impl_span: Span) -> Span { let impl_span = sm.span_until_char(impl_span, '<'); - let impl_span = sm.span_until_whitespace(impl_span); - impl_span + sm.span_until_whitespace(impl_span) } impl<'a> Resolver<'a> { diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 4a2a2a296faea..5b112677cf77f 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -1871,7 +1871,7 @@ impl<'a> Resolver<'a> { // No adjustments } } - let result = self.resolve_ident_in_module_unadjusted_ext( + self.resolve_ident_in_module_unadjusted_ext( module, ident, ns, @@ -1879,8 +1879,7 @@ impl<'a> Resolver<'a> { false, record_used, path_span, - ); - result + ) } fn resolve_crate_root(&mut self, ident: Ident) -> Module<'a> { diff --git a/src/librustc_typeck/check/expr.rs b/src/librustc_typeck/check/expr.rs index 617c54a738e6e..7203980b2388f 100644 --- a/src/librustc_typeck/check/expr.rs +++ b/src/librustc_typeck/check/expr.rs @@ -1069,16 +1069,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { } }); - let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| { - let t = match flds { - Some(ref fs) if i < fs.len() => { - let ety = fs[i].expect_ty(); - self.check_expr_coercable_to_type(&e, ety); - ety - } - _ => self.check_expr_with_expectation(&e, NoExpectation), - }; - t + let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| match flds { + Some(ref fs) if i < fs.len() => { + let ety = fs[i].expect_ty(); + self.check_expr_coercable_to_type(&e, ety); + ety + } + _ => self.check_expr_with_expectation(&e, NoExpectation), }); let tuple = self.tcx.mk_tup(elt_ts_iter); if tuple.references_error() { diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index e4bd42f61c321..32f0f578d057f 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -3654,14 +3654,12 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { // Otherwise, fall back to the immutable version. let (imm_tr, imm_op) = self.resolve_place_op(op, false); - let method = match (method, imm_tr) { + match (method, imm_tr) { (None, Some(trait_did)) => { self.lookup_method_in_trait(span, imm_op, trait_did, base_ty, Some(arg_tys)) } (method, _) => method, - }; - - method + } } fn check_method_argument_types( diff --git a/src/librustdoc/clean/utils.rs b/src/librustdoc/clean/utils.rs index b54af49918709..82e34710f0cbf 100644 --- a/src/librustdoc/clean/utils.rs +++ b/src/librustdoc/clean/utils.rs @@ -507,7 +507,7 @@ pub fn print_const(cx: &DocContext<'_>, n: &'tcx ty::Const<'_>) -> String { } pub fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option { - let value = cx.tcx.const_eval_poly(def_id).ok().and_then(|val| { + cx.tcx.const_eval_poly(def_id).ok().and_then(|val| { let ty = cx.tcx.type_of(def_id); match (val, &ty.kind) { (_, &ty::Ref(..)) => None, @@ -518,9 +518,7 @@ pub fn print_evaluated_const(cx: &DocContext<'_>, def_id: DefId) -> Option None, } - }); - - value + }) } fn format_integer_with_underscore_sep(num: &str) -> String { diff --git a/src/librustdoc/html/render/cache.rs b/src/librustdoc/html/render/cache.rs index ed0de2b311955..b93738319a634 100644 --- a/src/librustdoc/html/render/cache.rs +++ b/src/librustdoc/html/render/cache.rs @@ -666,13 +666,12 @@ fn get_index_search_type(item: &clean::Item) -> Option { } fn get_index_type(clean_type: &clean::Type) -> RenderType { - let t = RenderType { + RenderType { ty: clean_type.def_id(), idx: None, name: get_index_type_name(clean_type, true).map(|s| s.to_ascii_lowercase()), generics: get_generics(clean_type), - }; - t + } } fn get_index_type_name(clean_type: &clean::Type, accept_generic: bool) -> Option {