From 8de1ec9ce0a53b8ad9987e923e833c82fda05603 Mon Sep 17 00:00:00 2001 From: Kornel Date: Thu, 27 Feb 2020 16:28:27 +0000 Subject: [PATCH 01/21] Make error message clearer about creating new module --- src/librustc_parse/parser/diagnostics.rs | 26 +++++-------------- src/librustc_parse/parser/module.rs | 9 +++---- src/test/ui/error-codes/E0583.stderr | 2 +- .../invalid-module-declaration.stderr | 2 +- .../missing_non_modrs_mod.stderr | 2 +- .../missing_non_modrs_mod_inline.stderr | 2 +- src/test/ui/parser/mod_file_not_exist.rs | 2 +- src/test/ui/parser/mod_file_not_exist.stderr | 2 +- .../ui/parser/mod_file_not_exist_windows.rs | 2 +- .../parser/mod_file_not_exist_windows.stderr | 2 +- 10 files changed, 18 insertions(+), 33 deletions(-) diff --git a/src/librustc_parse/parser/diagnostics.rs b/src/librustc_parse/parser/diagnostics.rs index 8b43b424f5502..0618587bac1c1 100644 --- a/src/librustc_parse/parser/diagnostics.rs +++ b/src/librustc_parse/parser/diagnostics.rs @@ -18,6 +18,7 @@ use rustc_span::{MultiSpan, Span, SpanSnippetError, DUMMY_SP}; use log::{debug, trace}; use std::mem; +use std::path::PathBuf; const TURBOFISH: &str = "use `::<...>` instead of `<...>` to specify type arguments"; @@ -40,29 +41,15 @@ pub(super) fn dummy_arg(ident: Ident) -> Param { } pub enum Error { - FileNotFoundForModule { - mod_name: String, - default_path: String, - secondary_path: String, - dir_path: String, - }, - DuplicatePaths { - mod_name: String, - default_path: String, - secondary_path: String, - }, + FileNotFoundForModule { mod_name: String, default_path: PathBuf }, + DuplicatePaths { mod_name: String, default_path: String, secondary_path: String }, UselessDocComment, } impl Error { fn span_err(self, sp: impl Into, handler: &Handler) -> DiagnosticBuilder<'_> { match self { - Error::FileNotFoundForModule { - ref mod_name, - ref default_path, - ref secondary_path, - ref dir_path, - } => { + Error::FileNotFoundForModule { ref mod_name, ref default_path } => { let mut err = struct_span_err!( handler, sp, @@ -71,8 +58,9 @@ impl Error { mod_name, ); err.help(&format!( - "name the file either {} or {} inside the directory \"{}\"", - default_path, secondary_path, dir_path, + "to create the module `{}`, create file \"{}\"", + mod_name, + default_path.display(), )); err } diff --git a/src/librustc_parse/parser/module.rs b/src/librustc_parse/parser/module.rs index b436f1969bb48..7b46601cc7d80 100644 --- a/src/librustc_parse/parser/module.rs +++ b/src/librustc_parse/parser/module.rs @@ -234,12 +234,9 @@ impl<'a> Parser<'a> { path: secondary_path, directory_ownership: DirectoryOwnership::Owned { relative: None }, }), - (false, false) => Err(Error::FileNotFoundForModule { - mod_name: mod_name.clone(), - default_path: default_path_str, - secondary_path: secondary_path_str, - dir_path: dir_path.display().to_string(), - }), + (false, false) => { + Err(Error::FileNotFoundForModule { mod_name: mod_name.clone(), default_path }) + } (true, true) => Err(Error::DuplicatePaths { mod_name: mod_name.clone(), default_path: default_path_str, diff --git a/src/test/ui/error-codes/E0583.stderr b/src/test/ui/error-codes/E0583.stderr index ef7a48bc8a48f..5d47b633e78db 100644 --- a/src/test/ui/error-codes/E0583.stderr +++ b/src/test/ui/error-codes/E0583.stderr @@ -4,7 +4,7 @@ error[E0583]: file not found for module `module_that_doesnt_exist` LL | mod module_that_doesnt_exist; | ^^^^^^^^^^^^^^^^^^^^^^^^ | - = help: name the file either module_that_doesnt_exist.rs or module_that_doesnt_exist/mod.rs inside the directory "$DIR" + = help: to create the module `module_that_doesnt_exist`, create file "$DIR/module_that_doesnt_exist.rs" error: aborting due to previous error diff --git a/src/test/ui/invalid-module-declaration/invalid-module-declaration.stderr b/src/test/ui/invalid-module-declaration/invalid-module-declaration.stderr index c95df5b4534c1..5d2cdaef1a761 100644 --- a/src/test/ui/invalid-module-declaration/invalid-module-declaration.stderr +++ b/src/test/ui/invalid-module-declaration/invalid-module-declaration.stderr @@ -4,7 +4,7 @@ error[E0583]: file not found for module `baz` LL | pub mod baz; | ^^^ | - = help: name the file either bar/baz.rs or bar/baz/mod.rs inside the directory "$DIR/auxiliary/foo" + = help: to create the module `baz`, create file "$DIR/auxiliary/foo/bar/baz.rs" error: aborting due to previous error diff --git a/src/test/ui/missing_non_modrs_mod/missing_non_modrs_mod.stderr b/src/test/ui/missing_non_modrs_mod/missing_non_modrs_mod.stderr index 98b74e5f5cbca..e8d997e6de091 100644 --- a/src/test/ui/missing_non_modrs_mod/missing_non_modrs_mod.stderr +++ b/src/test/ui/missing_non_modrs_mod/missing_non_modrs_mod.stderr @@ -4,7 +4,7 @@ error[E0583]: file not found for module `missing` LL | mod missing; | ^^^^^^^ | - = help: name the file either foo/missing.rs or foo/missing/mod.rs inside the directory "$DIR" + = help: to create the module `missing`, create file "$DIR/foo/missing.rs" error: aborting due to previous error diff --git a/src/test/ui/missing_non_modrs_mod/missing_non_modrs_mod_inline.stderr b/src/test/ui/missing_non_modrs_mod/missing_non_modrs_mod_inline.stderr index 457e8fcccbfb3..b2b0f8b466a04 100644 --- a/src/test/ui/missing_non_modrs_mod/missing_non_modrs_mod_inline.stderr +++ b/src/test/ui/missing_non_modrs_mod/missing_non_modrs_mod_inline.stderr @@ -4,7 +4,7 @@ error[E0583]: file not found for module `missing` LL | mod missing; | ^^^^^^^ | - = help: name the file either missing.rs or missing/mod.rs inside the directory "$DIR/foo_inline/inline" + = help: to create the module `missing`, create file "$DIR/foo_inline/inline/missing.rs" error: aborting due to previous error diff --git a/src/test/ui/parser/mod_file_not_exist.rs b/src/test/ui/parser/mod_file_not_exist.rs index e662c707a38b9..71fbc7aea45eb 100644 --- a/src/test/ui/parser/mod_file_not_exist.rs +++ b/src/test/ui/parser/mod_file_not_exist.rs @@ -1,7 +1,7 @@ // ignore-windows mod not_a_real_file; //~ ERROR file not found for module `not_a_real_file` -//~^ HELP name the file either not_a_real_file.rs or not_a_real_file/mod.rs inside the directory +//~^ HELP to create the module `not_a_real_file`, create file " fn main() { assert_eq!(mod_file_aux::bar(), 10); diff --git a/src/test/ui/parser/mod_file_not_exist.stderr b/src/test/ui/parser/mod_file_not_exist.stderr index dadf4b29dcf39..db3ea04ac7655 100644 --- a/src/test/ui/parser/mod_file_not_exist.stderr +++ b/src/test/ui/parser/mod_file_not_exist.stderr @@ -4,7 +4,7 @@ error[E0583]: file not found for module `not_a_real_file` LL | mod not_a_real_file; | ^^^^^^^^^^^^^^^ | - = help: name the file either not_a_real_file.rs or not_a_real_file/mod.rs inside the directory "$DIR" + = help: to create the module `not_a_real_file`, create file "$DIR/not_a_real_file.rs" error: aborting due to previous error diff --git a/src/test/ui/parser/mod_file_not_exist_windows.rs b/src/test/ui/parser/mod_file_not_exist_windows.rs index 0cd9e9c799f1d..97cadab675f51 100644 --- a/src/test/ui/parser/mod_file_not_exist_windows.rs +++ b/src/test/ui/parser/mod_file_not_exist_windows.rs @@ -1,7 +1,7 @@ // only-windows mod not_a_real_file; //~ ERROR file not found for module `not_a_real_file` -//~^ HELP name the file either not_a_real_file.rs or not_a_real_file\mod.rs inside the directory +//~^ HELP to create the module `not_a_real_file`, create file fn main() { assert_eq!(mod_file_aux::bar(), 10); diff --git a/src/test/ui/parser/mod_file_not_exist_windows.stderr b/src/test/ui/parser/mod_file_not_exist_windows.stderr index 60ae00abab1ed..a58db80f73d7d 100644 --- a/src/test/ui/parser/mod_file_not_exist_windows.stderr +++ b/src/test/ui/parser/mod_file_not_exist_windows.stderr @@ -4,7 +4,7 @@ error[E0583]: file not found for module `not_a_real_file` LL | mod not_a_real_file; | ^^^^^^^^^^^^^^^ | - = help: name the file either not_a_real_file.rs or not_a_real_file/mod.rs inside the directory "$DIR" + = help: to create the module `not_a_real_file`, create file "$DIR/not_a_real_file.rs" error: aborting due to previous error From 3ba89e87503e25aece0318a9851f8dba5ccd94a2 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 13 Feb 2020 00:11:16 -0800 Subject: [PATCH 02/21] Remove quotes around unknown fn placeholder in backtrace --- src/libstd/backtrace.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/backtrace.rs b/src/libstd/backtrace.rs index 97db0ff3791d7..b14486471ffd7 100644 --- a/src/libstd/backtrace.rs +++ b/src/libstd/backtrace.rs @@ -193,7 +193,7 @@ impl fmt::Debug for BacktraceSymbol { if let Some(fn_name) = self.name.as_ref().map(|b| backtrace::SymbolName::new(b)) { write!(fmt, "fn: \"{:#}\"", fn_name)?; } else { - write!(fmt, "fn: \"\"")?; + write!(fmt, "fn: ")?; } if let Some(fname) = self.filename.as_ref() { From db75b6a91f67008ec789d9934f8a73e09fd0d472 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 13 Feb 2020 00:11:52 -0800 Subject: [PATCH 03/21] Add quotes around filename in Backtrace debug --- src/libstd/backtrace.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libstd/backtrace.rs b/src/libstd/backtrace.rs index b14486471ffd7..cc842ebd5894c 100644 --- a/src/libstd/backtrace.rs +++ b/src/libstd/backtrace.rs @@ -197,7 +197,7 @@ impl fmt::Debug for BacktraceSymbol { } if let Some(fname) = self.filename.as_ref() { - write!(fmt, ", file: {:?}", fname)?; + write!(fmt, ", file: \"{:?}\"", fname)?; } if let Some(line) = self.lineno.as_ref() { From 1f1ca877b7002e3ac45916df5415fde1584775ab Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 13 Feb 2020 00:12:26 -0800 Subject: [PATCH 04/21] Change disabled and unsupported backtraces to print using placeholder style --- src/libstd/backtrace.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libstd/backtrace.rs b/src/libstd/backtrace.rs index cc842ebd5894c..c64eb9f8e409b 100644 --- a/src/libstd/backtrace.rs +++ b/src/libstd/backtrace.rs @@ -162,8 +162,8 @@ enum BytesOrWide { impl fmt::Debug for Backtrace { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { let mut capture = match &self.inner { - Inner::Unsupported => return fmt.write_str("unsupported backtrace"), - Inner::Disabled => return fmt.write_str("disabled backtrace"), + Inner::Unsupported => return fmt.write_str(""), + Inner::Disabled => return fmt.write_str(""), Inner::Captured(c) => c.lock().unwrap(), }; capture.resolve(); From a9cc010c4883bafba1304f6fd581343f5b1b3ba2 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 13 Feb 2020 00:13:48 -0800 Subject: [PATCH 05/21] Make it possible to instantiate hardcoded Backtrace from test --- src/libstd/backtrace.rs | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/src/libstd/backtrace.rs b/src/libstd/backtrace.rs index c64eb9f8e409b..04fd80ecbdb23 100644 --- a/src/libstd/backtrace.rs +++ b/src/libstd/backtrace.rs @@ -92,6 +92,7 @@ // a backtrace or actually symbolizing it. use crate::env; +use crate::ffi::c_void; use crate::fmt; use crate::sync::atomic::{AtomicUsize, Ordering::SeqCst}; use crate::sync::Mutex; @@ -144,10 +145,16 @@ fn _assert_send_sync() { } struct BacktraceFrame { - frame: backtrace::Frame, + frame: RawFrame, symbols: Vec, } +enum RawFrame { + Actual(backtrace::Frame), + #[cfg(test)] + Fake, +} + struct BacktraceSymbol { name: Option>, filename: Option, @@ -293,7 +300,10 @@ impl Backtrace { let mut actual_start = None; unsafe { backtrace::trace_unsynchronized(|frame| { - frames.push(BacktraceFrame { frame: frame.clone(), symbols: Vec::new() }); + frames.push(BacktraceFrame { + frame: RawFrame::Actual(frame.clone()), + symbols: Vec::new(), + }); if frame.symbol_address() as usize == ip && actual_start.is_none() { actual_start = Some(frames.len()); } @@ -393,8 +403,13 @@ impl Capture { let _lock = lock(); for frame in self.frames.iter_mut() { let symbols = &mut frame.symbols; + let frame = match &frame.frame { + RawFrame::Actual(frame) => frame, + #[cfg(test)] + RawFrame::Fake => unimplemented!(), + }; unsafe { - backtrace::resolve_frame_unsynchronized(&frame.frame, |symbol| { + backtrace::resolve_frame_unsynchronized(frame, |symbol| { symbols.push(BacktraceSymbol { name: symbol.name().map(|m| m.as_bytes().to_vec()), filename: symbol.filename_raw().map(|b| match b { @@ -408,3 +423,13 @@ impl Capture { } } } + +impl RawFrame { + fn ip(&self) -> *mut c_void { + match self { + RawFrame::Actual(frame) => frame.ip(), + #[cfg(test)] + RawFrame::Fake => 1 as *mut c_void, + } + } +} From 33600e4d2d7a61f7dcb1b278bb1ccb8f04690db3 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Thu, 13 Feb 2020 00:16:28 -0800 Subject: [PATCH 06/21] Add test of Debug representation of Backtrace --- src/libstd/backtrace.rs | 52 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/libstd/backtrace.rs b/src/libstd/backtrace.rs index 04fd80ecbdb23..f3dd7a62fcbb8 100644 --- a/src/libstd/backtrace.rs +++ b/src/libstd/backtrace.rs @@ -433,3 +433,55 @@ impl RawFrame { } } } + +#[test] +fn test_debug() { + let backtrace = Backtrace { + inner: Inner::Captured(Mutex::new(Capture { + actual_start: 1, + resolved: true, + frames: vec![ + BacktraceFrame { + frame: RawFrame::Fake, + symbols: vec![BacktraceSymbol { + name: Some(b"std::backtrace::Backtrace::create".to_vec()), + filename: Some(BytesOrWide::Bytes(b"/rust/backtrace.rs".to_vec())), + lineno: Some(100), + }], + }, + BacktraceFrame { + frame: RawFrame::Fake, + symbols: vec![BacktraceSymbol { + name: Some(b"__rust_maybe_catch_panic".to_vec()), + filename: None, + lineno: None, + }], + }, + BacktraceFrame { + frame: RawFrame::Fake, + symbols: vec![ + BacktraceSymbol { + name: Some(b"std::rt::lang_start_internal".to_vec()), + filename: Some(BytesOrWide::Bytes(b"/rust/rt.rs".to_vec())), + lineno: Some(300), + }, + BacktraceSymbol { + name: Some(b"std::rt::lang_start".to_vec()), + filename: Some(BytesOrWide::Bytes(b"/rust/rt.rs".to_vec())), + lineno: Some(400), + }, + ], + }, + ], + })), + }; + + #[rustfmt::skip] + let expected = "Backtrace [\ + \n { fn: \"__rust_maybe_catch_panic\" },\ + \n { fn: \"std::rt::lang_start_internal\", file: \"/rust/rt.rs\", line: 300 },\ + \n { fn: \"std::rt::lang_start\", file: \"/rust/rt.rs\", line: 400 },\ + \n]"; + + assert_eq!(format!("{:#?}", backtrace), expected); +} From a2364dc85fb505487c272988b8c5073a3f6fef2a Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Mon, 9 Mar 2020 12:23:19 -0700 Subject: [PATCH 07/21] Write backtrace fmt test using relative paths For some reason the absolute paths were formatted differently on the armhf-gnu target. thread '' panicked at 'assertion failed: `(left == right)` left: `"Backtrace [\n { fn: \"__rust_maybe_catch_panic\" },\n { fn: \"std::rt::lang_start_internal\", file: \"./rust/rt.rs\", line: 300 },\n { fn: \"std::rt::lang_start\", file: \"./rust/rt.rs\", line: 400 },\n]"`, right: `"Backtrace [\n { fn: \"__rust_maybe_catch_panic\" },\n { fn: \"std::rt::lang_start_internal\", file: \"/rust/rt.rs\", line: 300 },\n { fn: \"std::rt::lang_start\", file: \"/rust/rt.rs\", line: 400 },\n]"`', src/libstd/backtrace.rs:486:5 --- src/libstd/backtrace.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/libstd/backtrace.rs b/src/libstd/backtrace.rs index f3dd7a62fcbb8..34317c7a2ee3d 100644 --- a/src/libstd/backtrace.rs +++ b/src/libstd/backtrace.rs @@ -445,7 +445,7 @@ fn test_debug() { frame: RawFrame::Fake, symbols: vec![BacktraceSymbol { name: Some(b"std::backtrace::Backtrace::create".to_vec()), - filename: Some(BytesOrWide::Bytes(b"/rust/backtrace.rs".to_vec())), + filename: Some(BytesOrWide::Bytes(b"rust/backtrace.rs".to_vec())), lineno: Some(100), }], }, @@ -462,12 +462,12 @@ fn test_debug() { symbols: vec![ BacktraceSymbol { name: Some(b"std::rt::lang_start_internal".to_vec()), - filename: Some(BytesOrWide::Bytes(b"/rust/rt.rs".to_vec())), + filename: Some(BytesOrWide::Bytes(b"rust/rt.rs".to_vec())), lineno: Some(300), }, BacktraceSymbol { name: Some(b"std::rt::lang_start".to_vec()), - filename: Some(BytesOrWide::Bytes(b"/rust/rt.rs".to_vec())), + filename: Some(BytesOrWide::Bytes(b"rust/rt.rs".to_vec())), lineno: Some(400), }, ], @@ -479,8 +479,8 @@ fn test_debug() { #[rustfmt::skip] let expected = "Backtrace [\ \n { fn: \"__rust_maybe_catch_panic\" },\ - \n { fn: \"std::rt::lang_start_internal\", file: \"/rust/rt.rs\", line: 300 },\ - \n { fn: \"std::rt::lang_start\", file: \"/rust/rt.rs\", line: 400 },\ + \n { fn: \"std::rt::lang_start_internal\", file: \"rust/rt.rs\", line: 300 },\ + \n { fn: \"std::rt::lang_start\", file: \"rust/rt.rs\", line: 400 },\ \n]"; assert_eq!(format!("{:#?}", backtrace), expected); From 7b75c346d56e07634effc56acebac8c0698773b1 Mon Sep 17 00:00:00 2001 From: Ayush Kumar Mishra Date: Tue, 10 Mar 2020 02:04:48 +0530 Subject: [PATCH 08/21] Add long error explanation for E0628 #61137 --- src/librustc_error_codes/error_codes.rs | 2 +- src/librustc_error_codes/error_codes/E0628.md | 30 +++++++++++++++++++ .../ui/generator/too-many-parameters.stderr | 1 + 3 files changed, 32 insertions(+), 1 deletion(-) create mode 100644 src/librustc_error_codes/error_codes/E0628.md diff --git a/src/librustc_error_codes/error_codes.rs b/src/librustc_error_codes/error_codes.rs index 11d1209923fb2..57fb236d9d6f5 100644 --- a/src/librustc_error_codes/error_codes.rs +++ b/src/librustc_error_codes/error_codes.rs @@ -349,6 +349,7 @@ E0623: include_str!("./error_codes/E0623.md"), E0624: include_str!("./error_codes/E0624.md"), E0626: include_str!("./error_codes/E0626.md"), E0627: include_str!("./error_codes/E0627.md"), +E0628: include_str!("./error_codes/E0628.md"), E0631: include_str!("./error_codes/E0631.md"), E0633: include_str!("./error_codes/E0633.md"), E0635: include_str!("./error_codes/E0635.md"), @@ -580,7 +581,6 @@ E0748: include_str!("./error_codes/E0748.md"), // E0612, // merged into E0609 // E0613, // Removed (merged with E0609) E0625, // thread-local statics cannot be accessed at compile-time - E0628, // generators cannot have explicit parameters E0629, // missing 'feature' (rustc_const_unstable) // rustc_const_unstable attribute must be paired with stable/unstable // attribute diff --git a/src/librustc_error_codes/error_codes/E0628.md b/src/librustc_error_codes/error_codes/E0628.md new file mode 100644 index 0000000000000..8aa0724bac7e5 --- /dev/null +++ b/src/librustc_error_codes/error_codes/E0628.md @@ -0,0 +1,30 @@ +More than one parameter was used for a generator. + +Erroneous code example: + +```compile_fail,E0628 +#![feature(generators, generator_trait)] + +fn main() { + let generator = |a: i32, b: i32| { + // error: too many parameters for a generator + // Allowed only 0 or 1 parameter + yield a; + }; +} +``` + +At present, it is not permitted to pass more than one explicit +parameter for a generator.This can be fixed by using only +0 or 1 parameter for generator. So, for example, we might resolve +the previous example by passing only one parameter. + +``` +#![feature(generators, generator_trait)] + +fn main() { + let generator = |a: i32| { + yield a; + }; +} +``` diff --git a/src/test/ui/generator/too-many-parameters.stderr b/src/test/ui/generator/too-many-parameters.stderr index a297ee43de969..22d40db3f2678 100644 --- a/src/test/ui/generator/too-many-parameters.stderr +++ b/src/test/ui/generator/too-many-parameters.stderr @@ -6,3 +6,4 @@ LL | |(), ()| { error: aborting due to previous error +For more information about this error, try `rustc --explain E0628`. From 1305ae6813d66a5c2898f67224d20d00604f37a7 Mon Sep 17 00:00:00 2001 From: Ayush Mishra Date: Fri, 13 Mar 2020 08:14:32 +0530 Subject: [PATCH 09/21] Update src/librustc_error_codes/error_codes/E0628.md Co-Authored-By: Dylan DPC --- src/librustc_error_codes/error_codes/E0628.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc_error_codes/error_codes/E0628.md b/src/librustc_error_codes/error_codes/E0628.md index 8aa0724bac7e5..75214d69b8859 100644 --- a/src/librustc_error_codes/error_codes/E0628.md +++ b/src/librustc_error_codes/error_codes/E0628.md @@ -15,7 +15,7 @@ fn main() { ``` At present, it is not permitted to pass more than one explicit -parameter for a generator.This can be fixed by using only +parameter for a generator.This can be fixed by using 0 or 1 parameter for generator. So, for example, we might resolve the previous example by passing only one parameter. From f7fcb589cf88bdd10f8573554de065142f9e5e70 Mon Sep 17 00:00:00 2001 From: Ayush Mishra Date: Fri, 13 Mar 2020 08:14:45 +0530 Subject: [PATCH 10/21] Update src/librustc_error_codes/error_codes/E0628.md Co-Authored-By: Dylan DPC --- src/librustc_error_codes/error_codes/E0628.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc_error_codes/error_codes/E0628.md b/src/librustc_error_codes/error_codes/E0628.md index 75214d69b8859..40040c9a56aac 100644 --- a/src/librustc_error_codes/error_codes/E0628.md +++ b/src/librustc_error_codes/error_codes/E0628.md @@ -16,7 +16,7 @@ fn main() { At present, it is not permitted to pass more than one explicit parameter for a generator.This can be fixed by using -0 or 1 parameter for generator. So, for example, we might resolve +at most 1 parameter for the generator. For example, we might resolve the previous example by passing only one parameter. ``` From 00c6abe92fdde4d2385413b656ad34e883c54fbc Mon Sep 17 00:00:00 2001 From: Ayush Kumar Mishra Date: Fri, 13 Mar 2020 10:49:49 +0530 Subject: [PATCH 11/21] Minor change --- src/librustc_error_codes/error_codes/E0628.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc_error_codes/error_codes/E0628.md b/src/librustc_error_codes/error_codes/E0628.md index 40040c9a56aac..2ae4d833fd5a2 100644 --- a/src/librustc_error_codes/error_codes/E0628.md +++ b/src/librustc_error_codes/error_codes/E0628.md @@ -16,7 +16,7 @@ fn main() { At present, it is not permitted to pass more than one explicit parameter for a generator.This can be fixed by using -at most 1 parameter for the generator. For example, we might resolve +at most one parameter for the generator. For example, we might resolve the previous example by passing only one parameter. ``` From c33c88bcbd5d9d41262f23d637fcad1ec3ab7c53 Mon Sep 17 00:00:00 2001 From: Ayush Kumar Mishra Date: Fri, 13 Mar 2020 10:52:41 +0530 Subject: [PATCH 12/21] Minor change --- src/librustc_error_codes/error_codes/E0628.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc_error_codes/error_codes/E0628.md b/src/librustc_error_codes/error_codes/E0628.md index 2ae4d833fd5a2..40040c9a56aac 100644 --- a/src/librustc_error_codes/error_codes/E0628.md +++ b/src/librustc_error_codes/error_codes/E0628.md @@ -16,7 +16,7 @@ fn main() { At present, it is not permitted to pass more than one explicit parameter for a generator.This can be fixed by using -at most one parameter for the generator. For example, we might resolve +at most 1 parameter for the generator. For example, we might resolve the previous example by passing only one parameter. ``` From 6f75d3fcc04e6da1f10424e29da978a81698e81b Mon Sep 17 00:00:00 2001 From: Dylan MacKenzie Date: Fri, 13 Dec 2019 13:20:16 -0800 Subject: [PATCH 13/21] Simplify `Qualif` interface --- .../transform/check_consts/qualifs.rs | 335 ++++++++---------- .../transform/check_consts/resolver.rs | 31 +- .../transform/check_consts/validation.rs | 2 +- src/librustc_mir/transform/promote_consts.rs | 12 +- 4 files changed, 178 insertions(+), 202 deletions(-) diff --git a/src/librustc_mir/transform/check_consts/qualifs.rs b/src/librustc_mir/transform/check_consts/qualifs.rs index baff8383c20a4..9359ec16533a5 100644 --- a/src/librustc_mir/transform/check_consts/qualifs.rs +++ b/src/librustc_mir/transform/check_consts/qualifs.rs @@ -1,7 +1,9 @@ -//! A copy of the `Qualif` trait in `qualify_consts.rs` that is suitable for the new validator. +//! Structural const qualification. +//! +//! See the `Qualif` trait for more info. use rustc::mir::*; -use rustc::ty::{self, Ty}; +use rustc::ty::{self, AdtDef, Ty}; use rustc_span::DUMMY_SP; use super::Item as ConstCx; @@ -14,11 +16,16 @@ pub fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> ConstQualifs } /// A "qualif"(-ication) is a way to look for something "bad" in the MIR that would disqualify some -/// code for promotion or prevent it from evaluating at compile time. So `return true` means -/// "I found something bad, no reason to go on searching". `false` is only returned if we -/// definitely cannot find anything bad anywhere. +/// code for promotion or prevent it from evaluating at compile time. /// -/// The default implementations proceed structurally. +/// Normally, we would determine what qualifications apply to each type and error when an illegal +/// operation is performed on such a type. However, this was found to be too imprecise, especially +/// in the presence of `enum`s. If only a single variant of an enum has a certain qualification, we +/// needn't reject code unless it actually constructs and operates on the qualifed variant. +/// +/// To accomplish this, const-checking and promotion use a value-based analysis (as opposed to a +/// type-based one). Qualifications propagate structurally across variables: If a local (or a +/// projection of a local) is assigned a qualifed value, that local itself becomes qualifed. pub trait Qualif { /// The name of the file used to debug the dataflow analysis that computes this qualif. const ANALYSIS_NAME: &'static str; @@ -26,157 +33,27 @@ pub trait Qualif { /// Whether this `Qualif` is cleared when a local is moved from. const IS_CLEARED_ON_MOVE: bool = false; + /// Extracts the field of `ConstQualifs` that corresponds to this `Qualif`. fn in_qualifs(qualifs: &ConstQualifs) -> bool; - /// Return the qualification that is (conservatively) correct for any value - /// of the type. - fn in_any_value_of_ty(_cx: &ConstCx<'_, 'tcx>, _ty: Ty<'tcx>) -> bool; - - fn in_projection_structurally( - cx: &ConstCx<'_, 'tcx>, - per_local: &mut impl FnMut(Local) -> bool, - place: PlaceRef<'tcx>, - ) -> bool { - if let [proj_base @ .., elem] = place.projection { - let base_qualif = Self::in_place( - cx, - per_local, - PlaceRef { local: place.local, projection: proj_base }, - ); - let qualif = base_qualif - && Self::in_any_value_of_ty( - cx, - Place::ty_from(place.local, proj_base, *cx.body, cx.tcx) - .projection_ty(cx.tcx, elem) - .ty, - ); - match elem { - ProjectionElem::Deref - | ProjectionElem::Subslice { .. } - | ProjectionElem::Field(..) - | ProjectionElem::ConstantIndex { .. } - | ProjectionElem::Downcast(..) => qualif, - - ProjectionElem::Index(local) => qualif || per_local(*local), - } - } else { - bug!("This should be called if projection is not empty"); - } - } - - fn in_projection( - cx: &ConstCx<'_, 'tcx>, - per_local: &mut impl FnMut(Local) -> bool, - place: PlaceRef<'tcx>, - ) -> bool { - Self::in_projection_structurally(cx, per_local, place) - } - - fn in_place( - cx: &ConstCx<'_, 'tcx>, - per_local: &mut impl FnMut(Local) -> bool, - place: PlaceRef<'tcx>, - ) -> bool { - match place { - PlaceRef { local, projection: [] } => per_local(local), - PlaceRef { local: _, projection: [.., _] } => Self::in_projection(cx, per_local, place), - } - } - - fn in_operand( - cx: &ConstCx<'_, 'tcx>, - per_local: &mut impl FnMut(Local) -> bool, - operand: &Operand<'tcx>, - ) -> bool { - match *operand { - Operand::Copy(ref place) | Operand::Move(ref place) => { - Self::in_place(cx, per_local, place.as_ref()) - } - - Operand::Constant(ref constant) => { - // Check the qualifs of the value of `const` items. - if let ty::ConstKind::Unevaluated(def_id, _, promoted) = constant.literal.val { - assert!(promoted.is_none()); - // Don't peek inside trait associated constants. - if cx.tcx.trait_of_item(def_id).is_none() { - let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def_id); - if !Self::in_qualifs(&qualifs) { - return false; - } - - // Just in case the type is more specific than - // the definition, e.g., impl associated const - // with type parameters, take it into account. - } - } - // Otherwise use the qualifs of the type. - Self::in_any_value_of_ty(cx, constant.literal.ty) - } - } - } - - fn in_rvalue_structurally( - cx: &ConstCx<'_, 'tcx>, - per_local: &mut impl FnMut(Local) -> bool, - rvalue: &Rvalue<'tcx>, - ) -> bool { - match *rvalue { - Rvalue::NullaryOp(..) => false, - - Rvalue::Discriminant(ref place) | Rvalue::Len(ref place) => { - Self::in_place(cx, per_local, place.as_ref()) - } - - Rvalue::Use(ref operand) - | Rvalue::Repeat(ref operand, _) - | Rvalue::UnaryOp(_, ref operand) - | Rvalue::Cast(_, ref operand, _) => Self::in_operand(cx, per_local, operand), - - Rvalue::BinaryOp(_, ref lhs, ref rhs) - | Rvalue::CheckedBinaryOp(_, ref lhs, ref rhs) => { - Self::in_operand(cx, per_local, lhs) || Self::in_operand(cx, per_local, rhs) - } - - Rvalue::Ref(_, _, ref place) | Rvalue::AddressOf(_, ref place) => { - // Special-case reborrows to be more like a copy of the reference. - if let [proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() { - let base_ty = Place::ty_from(place.local, proj_base, *cx.body, cx.tcx).ty; - if let ty::Ref(..) = base_ty.kind { - return Self::in_place( - cx, - per_local, - PlaceRef { local: place.local, projection: proj_base }, - ); - } - } - - Self::in_place(cx, per_local, place.as_ref()) - } - - Rvalue::Aggregate(_, ref operands) => { - operands.iter().any(|o| Self::in_operand(cx, per_local, o)) - } - } - } - - fn in_rvalue( - cx: &ConstCx<'_, 'tcx>, - per_local: &mut impl FnMut(Local) -> bool, - rvalue: &Rvalue<'tcx>, - ) -> bool { - Self::in_rvalue_structurally(cx, per_local, rvalue) - } - - fn in_call( - cx: &ConstCx<'_, 'tcx>, - _per_local: &mut impl FnMut(Local) -> bool, - _callee: &Operand<'tcx>, - _args: &[Operand<'tcx>], - return_ty: Ty<'tcx>, - ) -> bool { - // Be conservative about the returned value of a const fn. - Self::in_any_value_of_ty(cx, return_ty) - } + /// Returns `true` if *any* value of the given type could possibly have this `Qualif`. + /// + /// This function determines `Qualif`s when we cannot do a value-based analysis. Since qualif + /// propagation is context-insenstive, this includes function arguments and values returned + /// from a call to another function. + /// + /// It also determines the `Qualif`s for primitive types. + fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> bool; + + /// Returns `true` if this `Qualif` is inherent to the given struct or enum. + /// + /// By default, `Qualif`s propagate into ADTs in a structural way: An ADT only becomes + /// qualified if part of it is assigned a value with that `Qualif`. However, some ADTs *always* + /// have a certain `Qualif`, regardless of whether their fields have it. For example, a type + /// with a custom `Drop` impl is inherently `NeedsDrop`. + /// + /// Returning `true` for `in_adt_inherently` but `false` for `in_any_value_of_ty` is unsound. + fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &AdtDef) -> bool; } /// Constant containing interior mutability (`UnsafeCell`). @@ -197,26 +74,10 @@ impl Qualif for HasMutInterior { !ty.is_freeze(cx.tcx, cx.param_env, DUMMY_SP) } - fn in_rvalue( - cx: &ConstCx<'_, 'tcx>, - per_local: &mut impl FnMut(Local) -> bool, - rvalue: &Rvalue<'tcx>, - ) -> bool { - match *rvalue { - Rvalue::Aggregate(ref kind, _) => { - if let AggregateKind::Adt(def, ..) = **kind { - if Some(def.did) == cx.tcx.lang_items().unsafe_cell_type() { - let ty = rvalue.ty(*cx.body, cx.tcx); - assert_eq!(Self::in_any_value_of_ty(cx, ty), true); - return true; - } - } - } - - _ => {} - } - - Self::in_rvalue_structurally(cx, per_local, rvalue) + fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &AdtDef) -> bool { + // Exactly one type, `UnsafeCell`, has the `HasMutInterior` qualif inherently. + // It arises structurally for all other types. + Some(adt.did) == cx.tcx.lang_items().unsafe_cell_type() } } @@ -238,19 +99,127 @@ impl Qualif for NeedsDrop { ty.needs_drop(cx.tcx, cx.param_env) } - fn in_rvalue( - cx: &ConstCx<'_, 'tcx>, - per_local: &mut impl FnMut(Local) -> bool, - rvalue: &Rvalue<'tcx>, - ) -> bool { - if let Rvalue::Aggregate(ref kind, _) = *rvalue { + fn in_adt_inherently(cx: &ConstCx<'_, 'tcx>, adt: &AdtDef) -> bool { + adt.has_dtor(cx.tcx) + } +} + +// FIXME: Use `mir::visit::Visitor` for the `in_*` functions if/when it supports early return. + +/// Returns `true` if this `Rvalue` contains qualif `Q`. +pub fn in_rvalue(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, rvalue: &Rvalue<'tcx>) -> bool +where + Q: Qualif, + F: FnMut(Local) -> bool, +{ + match rvalue { + Rvalue::NullaryOp(..) => Q::in_any_value_of_ty(cx, rvalue.ty(*cx.body, cx.tcx)), + + Rvalue::Discriminant(place) | Rvalue::Len(place) => { + in_place::(cx, in_local, place.as_ref()) + } + + Rvalue::Use(operand) + | Rvalue::Repeat(operand, _) + | Rvalue::UnaryOp(_, operand) + | Rvalue::Cast(_, operand, _) => in_operand::(cx, in_local, operand), + + Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => { + in_operand::(cx, in_local, lhs) || in_operand::(cx, in_local, rhs) + } + + Rvalue::Ref(_, _, place) | Rvalue::AddressOf(_, place) => { + // Special-case reborrows to be more like a copy of the reference. + if let &[ref proj_base @ .., ProjectionElem::Deref] = place.projection.as_ref() { + let base_ty = Place::ty_from(place.local, proj_base, *cx.body, cx.tcx).ty; + if let ty::Ref(..) = base_ty.kind { + return in_place::( + cx, + in_local, + PlaceRef { local: place.local, projection: proj_base }, + ); + } + } + + in_place::(cx, in_local, place.as_ref()) + } + + Rvalue::Aggregate(kind, operands) => { + // Return early if we know that the struct or enum being constructed is always + // qualified. if let AggregateKind::Adt(def, ..) = **kind { - if def.has_dtor(cx.tcx) { + if Q::in_adt_inherently(cx, def) { return true; } } + + // Otherwise, proceed structurally... + operands.iter().any(|o| in_operand::(cx, in_local, o)) } + } +} - Self::in_rvalue_structurally(cx, per_local, rvalue) +/// Returns `true` if this `Place` contains qualif `Q`. +pub fn in_place(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, place: PlaceRef<'tcx>) -> bool +where + Q: Qualif, + F: FnMut(Local) -> bool, +{ + let mut projection = place.projection; + while let [ref proj_base @ .., proj_elem] = projection { + match *proj_elem { + ProjectionElem::Index(index) if in_local(index) => return true, + + ProjectionElem::Deref + | ProjectionElem::Field(_, _) + | ProjectionElem::ConstantIndex { .. } + | ProjectionElem::Subslice { .. } + | ProjectionElem::Downcast(_, _) + | ProjectionElem::Index(_) => {} + } + + let base_ty = Place::ty_from(place.local, proj_base, *cx.body, cx.tcx); + let proj_ty = base_ty.projection_ty(cx.tcx, proj_elem).ty; + if !Q::in_any_value_of_ty(cx, proj_ty) { + return false; + } + + projection = proj_base; + } + + assert!(projection.is_empty()); + in_local(place.local) +} + +/// Returns `true` if this `Operand` contains qualif `Q`. +pub fn in_operand(cx: &ConstCx<'_, 'tcx>, in_local: &mut F, operand: &Operand<'tcx>) -> bool +where + Q: Qualif, + F: FnMut(Local) -> bool, +{ + let constant = match operand { + Operand::Copy(place) | Operand::Move(place) => { + return in_place::(cx, in_local, place.as_ref()); + } + + Operand::Constant(c) => c, + }; + + // Check the qualifs of the value of `const` items. + if let ty::ConstKind::Unevaluated(def_id, _, promoted) = constant.literal.val { + assert!(promoted.is_none()); + // Don't peek inside trait associated constants. + if cx.tcx.trait_of_item(def_id).is_none() { + let qualifs = cx.tcx.at(constant.span).mir_const_qualif(def_id); + if !Q::in_qualifs(&qualifs) { + return false; + } + + // Just in case the type is more specific than + // the definition, e.g., impl associated const + // with type parameters, take it into account. + } } + // Otherwise use the qualifs of the type. + Q::in_any_value_of_ty(cx, constant.literal.ty) } diff --git a/src/librustc_mir/transform/check_consts/resolver.rs b/src/librustc_mir/transform/check_consts/resolver.rs index 3e14cc6d32a67..e42f64b5c7384 100644 --- a/src/librustc_mir/transform/check_consts/resolver.rs +++ b/src/librustc_mir/transform/check_consts/resolver.rs @@ -8,7 +8,7 @@ use rustc_index::bit_set::BitSet; use std::marker::PhantomData; -use super::{Item, Qualif}; +use super::{qualifs, Item, Qualif}; use crate::dataflow::{self as old_dataflow, generic as dataflow}; /// A `Visitor` that propagates qualifs between locals. This defines the transfer function of @@ -66,18 +66,15 @@ where fn apply_call_return_effect( &mut self, _block: BasicBlock, - func: &mir::Operand<'tcx>, - args: &[mir::Operand<'tcx>], + _func: &mir::Operand<'tcx>, + _args: &[mir::Operand<'tcx>], return_place: &mir::Place<'tcx>, ) { + // We cannot reason about another function's internals, so use conservative type-based + // qualification for the result of a function call. let return_ty = return_place.ty(*self.item.body, self.item.tcx).ty; - let qualif = Q::in_call( - self.item, - &mut |l| self.qualifs_per_local.contains(l), - func, - args, - return_ty, - ); + let qualif = Q::in_any_value_of_ty(self.item, return_ty); + if !return_place.is_indirect() { self.assign_qualif_direct(return_place, qualif); } @@ -110,7 +107,11 @@ where rvalue: &mir::Rvalue<'tcx>, location: Location, ) { - let qualif = Q::in_rvalue(self.item, &mut |l| self.qualifs_per_local.contains(l), rvalue); + let qualif = qualifs::in_rvalue::( + self.item, + &mut |l| self.qualifs_per_local.contains(l), + rvalue, + ); if !place.is_indirect() { self.assign_qualif_direct(place, qualif); } @@ -125,8 +126,12 @@ where // here; that occurs in `apply_call_return_effect`. if let mir::TerminatorKind::DropAndReplace { value, location: dest, .. } = kind { - let qualif = - Q::in_operand(self.item, &mut |l| self.qualifs_per_local.contains(l), value); + let qualif = qualifs::in_operand::( + self.item, + &mut |l| self.qualifs_per_local.contains(l), + value, + ); + if !dest.is_indirect() { self.assign_qualif_direct(dest, qualif); } diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs index adffd444eb68b..48367fc24654d 100644 --- a/src/librustc_mir/transform/check_consts/validation.rs +++ b/src/librustc_mir/transform/check_consts/validation.rs @@ -344,7 +344,7 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> { Rvalue::Ref(_, BorrowKind::Shared, ref place) | Rvalue::Ref(_, BorrowKind::Shallow, ref place) | Rvalue::AddressOf(Mutability::Not, ref place) => { - let borrowed_place_has_mut_interior = HasMutInterior::in_place( + let borrowed_place_has_mut_interior = qualifs::in_place::( &self.item, &mut |local| self.qualifs.has_mut_interior(local, location), place.as_ref(), diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs index 7dd134a35d909..1336206e18626 100644 --- a/src/librustc_mir/transform/promote_consts.rs +++ b/src/librustc_mir/transform/promote_consts.rs @@ -407,15 +407,17 @@ impl<'tcx> Validator<'_, 'tcx> { // FIXME(eddyb) maybe cache this? fn qualif_local(&self, local: Local) -> bool { - let per_local = &mut |l| self.qualif_local::(l); - if let TempState::Defined { location: loc, .. } = self.temps[local] { let num_stmts = self.body[loc.block].statements.len(); if loc.statement_index < num_stmts { let statement = &self.body[loc.block].statements[loc.statement_index]; match &statement.kind { - StatementKind::Assign(box (_, rhs)) => Q::in_rvalue(&self.item, per_local, rhs), + StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::( + &self.item, + &mut |l| self.qualif_local::(l), + rhs, + ), _ => { span_bug!( statement.source_info.span, @@ -427,9 +429,9 @@ impl<'tcx> Validator<'_, 'tcx> { } else { let terminator = self.body[loc.block].terminator(); match &terminator.kind { - TerminatorKind::Call { func, args, .. } => { + TerminatorKind::Call { .. } => { let return_ty = self.body.local_decls[local].ty; - Q::in_call(&self.item, per_local, func, args, return_ty) + Q::in_any_value_of_ty(&self.item, return_ty) } kind => { span_bug!(terminator.source_info.span, "{:?} not promotable", kind); From 65bf4831d22d3c0eee639a6536bb0bcd191ec915 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sat, 14 Mar 2020 00:52:24 +0300 Subject: [PATCH 14/21] ast/hir: `MacroDef::legacy` -> `MacroDef::macro_rules` --- src/librustc_ast/ast.rs | 2 +- src/librustc_ast/mut_visit.rs | 2 +- src/librustc_ast_lowering/item.rs | 6 +++--- src/librustc_ast_passes/feature_gate.rs | 2 +- src/librustc_ast_pretty/pprust.rs | 2 +- src/librustc_expand/mbe/macro_rules.rs | 10 +++++----- src/librustc_parse/parser/item.rs | 4 ++-- src/librustc_privacy/lib.rs | 2 +- src/librustc_resolve/build_reduced_graph.rs | 6 +++--- 9 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/librustc_ast/ast.rs b/src/librustc_ast/ast.rs index 08ce0cc2c56be..68960ba9fe920 100644 --- a/src/librustc_ast/ast.rs +++ b/src/librustc_ast/ast.rs @@ -1450,7 +1450,7 @@ impl MacDelimiter { pub struct MacroDef { pub body: P, /// `true` if macro was defined with `macro_rules`. - pub legacy: bool, + pub macro_rules: bool, } #[derive(Clone, RustcEncodable, RustcDecodable, Debug, Copy, Hash, Eq, PartialEq)] diff --git a/src/librustc_ast/mut_visit.rs b/src/librustc_ast/mut_visit.rs index a1a5b9debc50d..aa2968b3cbe44 100644 --- a/src/librustc_ast/mut_visit.rs +++ b/src/librustc_ast/mut_visit.rs @@ -591,7 +591,7 @@ pub fn noop_visit_mac(mac: &mut MacCall, vis: &mut T) { } pub fn noop_visit_macro_def(macro_def: &mut MacroDef, vis: &mut T) { - let MacroDef { body, legacy: _ } = macro_def; + let MacroDef { body, macro_rules: _ } = macro_def; visit_mac_args(body, vis); } diff --git a/src/librustc_ast_lowering/item.rs b/src/librustc_ast_lowering/item.rs index 2c60fe9c07779..458cb721d4834 100644 --- a/src/librustc_ast_lowering/item.rs +++ b/src/librustc_ast_lowering/item.rs @@ -220,8 +220,8 @@ impl<'hir> LoweringContext<'_, 'hir> { let mut vis = self.lower_visibility(&i.vis, None); let attrs = self.lower_attrs(&i.attrs); - if let ItemKind::MacroDef(MacroDef { ref body, legacy }) = i.kind { - if !legacy || attr::contains_name(&i.attrs, sym::macro_export) { + if let ItemKind::MacroDef(MacroDef { ref body, macro_rules }) = i.kind { + if !macro_rules || attr::contains_name(&i.attrs, sym::macro_export) { let hir_id = self.lower_node_id(i.id); let body = P(self.lower_mac_args(body)); self.exported_macros.push(hir::MacroDef { @@ -230,7 +230,7 @@ impl<'hir> LoweringContext<'_, 'hir> { attrs, hir_id, span: i.span, - ast: MacroDef { body, legacy }, + ast: MacroDef { body, macro_rules }, }); } else { self.non_exported_macro_attrs.extend(attrs.iter().cloned()); diff --git a/src/librustc_ast_passes/feature_gate.rs b/src/librustc_ast_passes/feature_gate.rs index 66be2b49adab7..2a9847c900e94 100644 --- a/src/librustc_ast_passes/feature_gate.rs +++ b/src/librustc_ast_passes/feature_gate.rs @@ -366,7 +366,7 @@ impl<'a> Visitor<'a> for PostExpansionVisitor<'a> { gate_feature_post!(&self, trait_alias, i.span, "trait aliases are experimental"); } - ast::ItemKind::MacroDef(ast::MacroDef { legacy: false, .. }) => { + ast::ItemKind::MacroDef(ast::MacroDef { macro_rules: false, .. }) => { let msg = "`macro` is experimental"; gate_feature_post!(&self, decl_macro, i.span, msg); } diff --git a/src/librustc_ast_pretty/pprust.rs b/src/librustc_ast_pretty/pprust.rs index a81b28d7c393b..b2e6ab7c5e777 100644 --- a/src/librustc_ast_pretty/pprust.rs +++ b/src/librustc_ast_pretty/pprust.rs @@ -1238,7 +1238,7 @@ impl<'a> State<'a> { } } ast::ItemKind::MacroDef(ref macro_def) => { - let (kw, has_bang) = if macro_def.legacy { + let (kw, has_bang) = if macro_def.macro_rules { ("macro_rules", true) } else { self.print_visibility(&item.vis); diff --git a/src/librustc_expand/mbe/macro_rules.rs b/src/librustc_expand/mbe/macro_rules.rs index 3040a9aefbb30..3cad3ff55d910 100644 --- a/src/librustc_expand/mbe/macro_rules.rs +++ b/src/librustc_expand/mbe/macro_rules.rs @@ -350,8 +350,8 @@ pub fn compile_declarative_macro( let tt_spec = ast::Ident::new(sym::tt, def.span); // Parse the macro_rules! invocation - let (is_legacy, body) = match &def.kind { - ast::ItemKind::MacroDef(macro_def) => (macro_def.legacy, macro_def.body.inner_tokens()), + let (macro_rules, body) = match &def.kind { + ast::ItemKind::MacroDef(def) => (def.macro_rules, def.body.inner_tokens()), _ => unreachable!(), }; @@ -370,7 +370,7 @@ pub fn compile_declarative_macro( mbe::TokenTree::MetaVarDecl(def.span, rhs_nm, tt_spec), ], separator: Some(Token::new( - if is_legacy { token::Semi } else { token::Comma }, + if macro_rules { token::Semi } else { token::Comma }, def.span, )), kleene: mbe::KleeneToken::new(mbe::KleeneOp::OneOrMore, def.span), @@ -382,7 +382,7 @@ pub fn compile_declarative_macro( DelimSpan::dummy(), Lrc::new(mbe::SequenceRepetition { tts: vec![mbe::TokenTree::token( - if is_legacy { token::Semi } else { token::Comma }, + if macro_rules { token::Semi } else { token::Comma }, def.span, )], separator: None, @@ -456,7 +456,7 @@ pub fn compile_declarative_macro( // that is not lint-checked and trigger the "failed to process buffered lint here" bug. valid &= macro_check::check_meta_variables(sess, ast::CRATE_NODE_ID, def.span, &lhses, &rhses); - let (transparency, transparency_error) = attr::find_transparency(&def.attrs, is_legacy); + let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules); match transparency_error { Some(TransparencyError::UnknownTransparency(value, span)) => { diag.span_err(span, &format!("unknown macro transparency: `{}`", value)) diff --git a/src/librustc_parse/parser/item.rs b/src/librustc_parse/parser/item.rs index fe5495fbf8a2b..cb4a98a6b4f46 100644 --- a/src/librustc_parse/parser/item.rs +++ b/src/librustc_parse/parser/item.rs @@ -1260,7 +1260,7 @@ impl<'a> Parser<'a> { }; self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span)); - Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: false }))) + Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false }))) } /// Is this unambiguously the start of a `macro_rules! foo` item defnition? @@ -1280,7 +1280,7 @@ impl<'a> Parser<'a> { self.eat_semi_for_macro_if_needed(&body); self.complain_if_pub_macro(vis, true); - Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, legacy: true }))) + Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: true }))) } /// Item macro invocations or `macro_rules!` definitions need inherited visibility. diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index d61ba60da3154..5c3631687848c 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -920,7 +920,7 @@ impl Visitor<'tcx> for EmbargoVisitor<'tcx> { } fn visit_macro_def(&mut self, md: &'tcx hir::MacroDef<'tcx>) { - if attr::find_transparency(&md.attrs, md.ast.legacy).0 != Transparency::Opaque { + if attr::find_transparency(&md.attrs, md.ast.macro_rules).0 != Transparency::Opaque { self.update(md.hir_id, Some(AccessLevel::Public)); return; } diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 0c6edd3e47d89..e85741c114e16 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -1098,10 +1098,10 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { fn define_macro(&mut self, item: &ast::Item) -> LegacyScope<'a> { let parent_scope = self.parent_scope; let expansion = parent_scope.expansion; - let (ext, ident, span, is_legacy) = match &item.kind { + let (ext, ident, span, macro_rules) = match &item.kind { ItemKind::MacroDef(def) => { let ext = Lrc::new(self.r.compile_macro(item, self.r.session.edition())); - (ext, item.ident, item.span, def.legacy) + (ext, item.ident, item.span, def.macro_rules) } ItemKind::Fn(..) => match Self::proc_macro_stub(item) { Some((macro_kind, ident, span)) => { @@ -1118,7 +1118,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { self.r.macro_map.insert(def_id, ext); self.r.local_macro_def_scopes.insert(item.id, parent_scope.module); - if is_legacy { + if macro_rules { let ident = ident.modern(); self.r.macro_names.insert(ident); let is_macro_export = attr::contains_name(&item.attrs, sym::macro_export); From 3fbb2549ce66e83583bb3bad83bbd15436b10d35 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sat, 14 Mar 2020 01:06:36 +0300 Subject: [PATCH 15/21] resolve: `Legacy(Scope,Binding)` -> `MacroRules(Scope,Binding)` --- src/librustc_resolve/build_reduced_graph.rs | 34 ++++++++-------- src/librustc_resolve/diagnostics.rs | 12 +++--- src/librustc_resolve/lib.rs | 44 +++++++++++++-------- src/librustc_resolve/macros.rs | 30 +++++++------- 4 files changed, 67 insertions(+), 53 deletions(-) diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index e85741c114e16..324669963f684 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -7,7 +7,7 @@ use crate::def_collector::collect_definitions; use crate::imports::{Import, ImportKind}; -use crate::macros::{LegacyBinding, LegacyScope}; +use crate::macros::{MacroRulesBinding, MacroRulesScope}; use crate::Namespace::{self, MacroNS, TypeNS, ValueNS}; use crate::{CrateLint, Determinacy, PathResult, ResolutionError, VisResolutionError}; use crate::{ @@ -165,11 +165,11 @@ impl<'a> Resolver<'a> { &mut self, fragment: &AstFragment, parent_scope: ParentScope<'a>, - ) -> LegacyScope<'a> { + ) -> MacroRulesScope<'a> { collect_definitions(&mut self.definitions, fragment, parent_scope.expansion); let mut visitor = BuildReducedGraphVisitor { r: self, parent_scope }; fragment.visit_with(&mut visitor); - visitor.parent_scope.legacy + visitor.parent_scope.macro_rules } crate fn build_reduced_graph_external(&mut self, module: Module<'a>) { @@ -1060,7 +1060,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { false } - fn visit_invoc(&mut self, id: NodeId) -> LegacyScope<'a> { + fn visit_invoc(&mut self, id: NodeId) -> MacroRulesScope<'a> { let invoc_id = id.placeholder_to_expn_id(); self.parent_scope.module.unexpanded_invocations.borrow_mut().insert(invoc_id); @@ -1068,7 +1068,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { let old_parent_scope = self.r.invocation_parent_scopes.insert(invoc_id, self.parent_scope); assert!(old_parent_scope.is_none(), "invocation data is reset for an invocation"); - LegacyScope::Invocation(invoc_id) + MacroRulesScope::Invocation(invoc_id) } fn proc_macro_stub(item: &ast::Item) -> Option<(MacroKind, Ident, Span)> { @@ -1095,7 +1095,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { } } - fn define_macro(&mut self, item: &ast::Item) -> LegacyScope<'a> { + fn define_macro(&mut self, item: &ast::Item) -> MacroRulesScope<'a> { let parent_scope = self.parent_scope; let expansion = parent_scope.expansion; let (ext, ident, span, macro_rules) = match &item.kind { @@ -1108,7 +1108,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { self.r.proc_macro_stubs.insert(item.id); (self.r.dummy_ext(macro_kind), ident, span, false) } - None => return parent_scope.legacy, + None => return parent_scope.macro_rules, }, _ => unreachable!(), }; @@ -1137,8 +1137,8 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { self.r.check_reserved_macro_name(ident, res); self.insert_unused_macro(ident, item.id, span); } - LegacyScope::Binding(self.r.arenas.alloc_legacy_binding(LegacyBinding { - parent_legacy_scope: parent_scope.legacy, + MacroRulesScope::Binding(self.r.arenas.alloc_macro_rules_binding(MacroRulesBinding { + parent_macro_rules_scope: parent_scope.macro_rules, binding, ident, })) @@ -1149,7 +1149,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { self.insert_unused_macro(ident, item.id, span); } self.r.define(module, ident, MacroNS, (res, vis, span, expansion)); - self.parent_scope.legacy + self.parent_scope.macro_rules } } } @@ -1174,29 +1174,29 @@ impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> { fn visit_item(&mut self, item: &'b Item) { let macro_use = match item.kind { ItemKind::MacroDef(..) => { - self.parent_scope.legacy = self.define_macro(item); + self.parent_scope.macro_rules = self.define_macro(item); return; } ItemKind::MacCall(..) => { - self.parent_scope.legacy = self.visit_invoc(item.id); + self.parent_scope.macro_rules = self.visit_invoc(item.id); return; } ItemKind::Mod(..) => self.contains_macro_use(&item.attrs), _ => false, }; let orig_current_module = self.parent_scope.module; - let orig_current_legacy_scope = self.parent_scope.legacy; + let orig_current_macro_rules_scope = self.parent_scope.macro_rules; self.build_reduced_graph_for_item(item); visit::walk_item(self, item); self.parent_scope.module = orig_current_module; if !macro_use { - self.parent_scope.legacy = orig_current_legacy_scope; + self.parent_scope.macro_rules = orig_current_macro_rules_scope; } } fn visit_stmt(&mut self, stmt: &'b ast::Stmt) { if let ast::StmtKind::MacCall(..) = stmt.kind { - self.parent_scope.legacy = self.visit_invoc(stmt.id); + self.parent_scope.macro_rules = self.visit_invoc(stmt.id); } else { visit::walk_stmt(self, stmt); } @@ -1214,11 +1214,11 @@ impl<'a, 'b> Visitor<'b> for BuildReducedGraphVisitor<'a, 'b> { fn visit_block(&mut self, block: &'b Block) { let orig_current_module = self.parent_scope.module; - let orig_current_legacy_scope = self.parent_scope.legacy; + let orig_current_macro_rules_scope = self.parent_scope.macro_rules; self.build_reduced_graph_for_block(block); visit::walk_block(self, block); self.parent_scope.module = orig_current_module; - self.parent_scope.legacy = orig_current_legacy_scope; + self.parent_scope.macro_rules = orig_current_macro_rules_scope; } fn visit_assoc_item(&mut self, item: &'b AssocItem, ctxt: AssocCtxt) { diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 47a05ec90d42f..d50f88b59edc3 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -21,7 +21,9 @@ use rustc_span::{BytePos, MultiSpan, Span}; use crate::imports::{Import, ImportKind, ImportResolver}; use crate::path_names_to_string; use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind}; -use crate::{BindingError, CrateLint, HasGenericParams, LegacyScope, Module, ModuleOrUniformRoot}; +use crate::{ + BindingError, CrateLint, HasGenericParams, MacroRulesScope, Module, ModuleOrUniformRoot, +}; use crate::{NameBinding, NameBindingKind, PrivacyError, VisResolutionError}; use crate::{ParentScope, PathResult, ResolutionError, Resolver, Scope, ScopeSet, Segment}; @@ -498,12 +500,12 @@ impl<'a> Resolver<'a> { } } } - Scope::MacroRules(legacy_scope) => { - if let LegacyScope::Binding(legacy_binding) = legacy_scope { - let res = legacy_binding.binding.res(); + Scope::MacroRules(macro_rules_scope) => { + if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope { + let res = macro_rules_binding.binding.res(); if filter_fn(res) { suggestions - .push(TypoSuggestion::from_res(legacy_binding.ident.name, res)) + .push(TypoSuggestion::from_res(macro_rules_binding.ident.name, res)) } } } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 37a800a0b7bdb..0d02b8ea074ee 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -58,7 +58,7 @@ use diagnostics::{extend_span_to_previous_binding, find_span_of_binding_until_ne use diagnostics::{ImportSuggestion, Suggestion}; use imports::{Import, ImportKind, ImportResolver, NameResolution}; use late::{HasGenericParams, PathSource, Rib, RibKind::*}; -use macros::{LegacyBinding, LegacyScope}; +use macros::{MacroRulesBinding, MacroRulesScope}; type Res = def::Res; @@ -94,7 +94,7 @@ impl Determinacy { enum Scope<'a> { DeriveHelpers(ExpnId), DeriveHelpersCompat, - MacroRules(LegacyScope<'a>), + MacroRules(MacroRulesScope<'a>), CrateRoot, Module(Module<'a>), RegisteredAttrs, @@ -127,7 +127,7 @@ enum ScopeSet { pub struct ParentScope<'a> { module: Module<'a>, expansion: ExpnId, - legacy: LegacyScope<'a>, + macro_rules: MacroRulesScope<'a>, derives: &'a [ast::Path], } @@ -135,7 +135,12 @@ impl<'a> ParentScope<'a> { /// Creates a parent scope with the passed argument used as the module scope component, /// and other scope components set to default empty values. pub fn module(module: Module<'a>) -> ParentScope<'a> { - ParentScope { module, expansion: ExpnId::root(), legacy: LegacyScope::Empty, derives: &[] } + ParentScope { + module, + expansion: ExpnId::root(), + macro_rules: MacroRulesScope::Empty, + derives: &[], + } } } @@ -930,9 +935,9 @@ pub struct Resolver<'a> { /// Parent scopes in which the macros were invoked. /// FIXME: `derives` are missing in these parent scopes and need to be taken from elsewhere. invocation_parent_scopes: FxHashMap>, - /// Legacy scopes *produced* by expanding the macro invocations, + /// `macro_rules` scopes *produced* by expanding the macro invocations, /// include all the `macro_rules` items and other invocations generated by them. - output_legacy_scopes: FxHashMap>, + output_macro_rules_scopes: FxHashMap>, /// Helper attributes that are in scope for the given expansion. helper_attrs: FxHashMap>, @@ -965,7 +970,7 @@ pub struct ResolverArenas<'a> { name_bindings: arena::TypedArena>, imports: arena::TypedArena>, name_resolutions: arena::TypedArena>>, - legacy_bindings: arena::TypedArena>, + macro_rules_bindings: arena::TypedArena>, ast_paths: arena::TypedArena, } @@ -989,8 +994,11 @@ impl<'a> ResolverArenas<'a> { fn alloc_name_resolution(&'a self) -> &'a RefCell> { self.name_resolutions.alloc(Default::default()) } - fn alloc_legacy_binding(&'a self, binding: LegacyBinding<'a>) -> &'a LegacyBinding<'a> { - self.legacy_bindings.alloc(binding) + fn alloc_macro_rules_binding( + &'a self, + binding: MacroRulesBinding<'a>, + ) -> &'a MacroRulesBinding<'a> { + self.macro_rules_bindings.alloc(binding) } fn alloc_ast_paths(&'a self, paths: &[ast::Path]) -> &'a [ast::Path] { self.ast_paths.alloc_from_iter(paths.iter().cloned()) @@ -1210,7 +1218,7 @@ impl<'a> Resolver<'a> { dummy_ext_derive: Lrc::new(SyntaxExtension::dummy_derive(session.edition())), non_macro_attrs: [non_macro_attr(false), non_macro_attr(true)], invocation_parent_scopes, - output_legacy_scopes: Default::default(), + output_macro_rules_scopes: Default::default(), helper_attrs: Default::default(), macro_defs, local_macro_def_scopes: FxHashMap::default(), @@ -1530,16 +1538,18 @@ impl<'a> Resolver<'a> { } } Scope::DeriveHelpers(..) => Scope::DeriveHelpersCompat, - Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.legacy), - Scope::MacroRules(legacy_scope) => match legacy_scope { - LegacyScope::Binding(binding) => Scope::MacroRules(binding.parent_legacy_scope), - LegacyScope::Invocation(invoc_id) => Scope::MacroRules( - self.output_legacy_scopes + Scope::DeriveHelpersCompat => Scope::MacroRules(parent_scope.macro_rules), + Scope::MacroRules(macro_rules_scope) => match macro_rules_scope { + MacroRulesScope::Binding(binding) => { + Scope::MacroRules(binding.parent_macro_rules_scope) + } + MacroRulesScope::Invocation(invoc_id) => Scope::MacroRules( + self.output_macro_rules_scopes .get(&invoc_id) .cloned() - .unwrap_or(self.invocation_parent_scopes[&invoc_id].legacy), + .unwrap_or(self.invocation_parent_scopes[&invoc_id].macro_rules), ), - LegacyScope::Empty => Scope::Module(module), + MacroRulesScope::Empty => Scope::Module(module), }, Scope::CrateRoot => match ns { TypeNS => { diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index e11aec906693e..d8ef148bacff2 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -33,26 +33,26 @@ use std::{mem, ptr}; type Res = def::Res; /// Binding produced by a `macro_rules` item. -/// Not modularized, can shadow previous legacy bindings, etc. +/// Not modularized, can shadow previous `macro_rules` bindings, etc. #[derive(Debug)] -pub struct LegacyBinding<'a> { +pub struct MacroRulesBinding<'a> { crate binding: &'a NameBinding<'a>, - /// Legacy scope into which the `macro_rules` item was planted. - crate parent_legacy_scope: LegacyScope<'a>, + /// `macro_rules` scope into which the `macro_rules` item was planted. + crate parent_macro_rules_scope: MacroRulesScope<'a>, crate ident: Ident, } /// The scope introduced by a `macro_rules!` macro. /// This starts at the macro's definition and ends at the end of the macro's parent /// module (named or unnamed), or even further if it escapes with `#[macro_use]`. -/// Some macro invocations need to introduce legacy scopes too because they +/// Some macro invocations need to introduce `macro_rules` scopes too because they /// can potentially expand into macro definitions. #[derive(Copy, Clone, Debug)] -pub enum LegacyScope<'a> { +pub enum MacroRulesScope<'a> { /// Empty "root" scope at the crate start containing no names. Empty, /// The scope introduced by a `macro_rules!` macro definition. - Binding(&'a LegacyBinding<'a>), + Binding(&'a MacroRulesBinding<'a>), /// The scope introduced by a macro invocation that can potentially /// create a `macro_rules!` macro definition. Invocation(ExpnId), @@ -159,8 +159,8 @@ impl<'a> base::Resolver for Resolver<'a> { // Integrate the new AST fragment into all the definition and module structures. // We are inside the `expansion` now, but other parent scope components are still the same. let parent_scope = ParentScope { expansion, ..self.invocation_parent_scopes[&expansion] }; - let output_legacy_scope = self.build_reduced_graph(fragment, parent_scope); - self.output_legacy_scopes.insert(expansion, output_legacy_scope); + let output_macro_rules_scope = self.build_reduced_graph(fragment, parent_scope); + self.output_macro_rules_scopes.insert(expansion, output_macro_rules_scope); parent_scope.module.unexpanded_invocations.borrow_mut().remove(&expansion); } @@ -608,12 +608,14 @@ impl<'a> Resolver<'a> { } result } - Scope::MacroRules(legacy_scope) => match legacy_scope { - LegacyScope::Binding(legacy_binding) if ident == legacy_binding.ident => { - Ok((legacy_binding.binding, Flags::MACRO_RULES)) + Scope::MacroRules(macro_rules_scope) => match macro_rules_scope { + MacroRulesScope::Binding(macro_rules_binding) + if ident == macro_rules_binding.ident => + { + Ok((macro_rules_binding.binding, Flags::MACRO_RULES)) } - LegacyScope::Invocation(invoc_id) - if !this.output_legacy_scopes.contains_key(&invoc_id) => + MacroRulesScope::Invocation(invoc_id) + if !this.output_macro_rules_scopes.contains_key(&invoc_id) => { Err(Determinacy::Undetermined) } From 8c9a38f679a0dd70c65e094f3063318616eb8387 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sat, 14 Mar 2020 01:23:24 +0300 Subject: [PATCH 16/21] Other `legacy` -> `macro_rules` --- src/librustc_attr/builtin.rs | 4 +-- src/librustc_expand/mbe/macro_check.rs | 12 ++++----- src/librustc_parse/parser/item.rs | 2 +- src/librustc_resolve/build_reduced_graph.rs | 10 ++++---- src/librustc_resolve/lib.rs | 28 +++++++++++---------- src/librustc_resolve/macros.rs | 10 +++++--- 6 files changed, 35 insertions(+), 31 deletions(-) diff --git a/src/librustc_attr/builtin.rs b/src/librustc_attr/builtin.rs index 08eae24da9b68..99083cca6cb34 100644 --- a/src/librustc_attr/builtin.rs +++ b/src/librustc_attr/builtin.rs @@ -1024,7 +1024,7 @@ pub enum TransparencyError { pub fn find_transparency( attrs: &[Attribute], - is_legacy: bool, + macro_rules: bool, ) -> (Transparency, Option) { let mut transparency = None; let mut error = None; @@ -1049,7 +1049,7 @@ pub fn find_transparency( } } } - let fallback = if is_legacy { Transparency::SemiTransparent } else { Transparency::Opaque }; + let fallback = if macro_rules { Transparency::SemiTransparent } else { Transparency::Opaque }; (transparency.map_or(fallback, |t| t.0), error) } diff --git a/src/librustc_expand/mbe/macro_check.rs b/src/librustc_expand/mbe/macro_check.rs index 6eb834beac652..8c6bfbec90277 100644 --- a/src/librustc_expand/mbe/macro_check.rs +++ b/src/librustc_expand/mbe/macro_check.rs @@ -419,10 +419,10 @@ fn check_nested_occurrences( | (NestedMacroState::MacroName, &TokenTree::Delimited(_, ref del)) if del.delim == DelimToken::Brace => { - let legacy = state == NestedMacroState::MacroRulesNotName; + let macro_rules = state == NestedMacroState::MacroRulesNotName; state = NestedMacroState::Empty; let rest = - check_nested_macro(sess, node_id, legacy, &del.tts, &nested_macros, valid); + check_nested_macro(sess, node_id, macro_rules, &del.tts, &nested_macros, valid); // If we did not check the whole macro definition, then check the rest as if outside // the macro definition. check_nested_occurrences( @@ -493,21 +493,21 @@ fn check_nested_occurrences( /// Arguments: /// - `sess` is used to emit diagnostics and lints /// - `node_id` is used to emit lints -/// - `legacy` specifies whether the macro is legacy +/// - `macro_rules` specifies whether the macro is `macro_rules` /// - `tts` is checked as a list of (LHS) => {RHS} /// - `macros` is the stack of outer macros /// - `valid` is set in case of errors fn check_nested_macro( sess: &ParseSess, node_id: NodeId, - legacy: bool, + macro_rules: bool, tts: &[TokenTree], macros: &Stack<'_, MacroState<'_>>, valid: &mut bool, ) -> usize { let n = tts.len(); let mut i = 0; - let separator = if legacy { TokenKind::Semi } else { TokenKind::Comma }; + let separator = if macro_rules { TokenKind::Semi } else { TokenKind::Comma }; loop { // We expect 3 token trees: `(LHS) => {RHS}`. The separator is checked after. if i + 2 >= n @@ -522,7 +522,7 @@ fn check_nested_macro( let mut binders = Binders::default(); check_binders(sess, node_id, lhs, macros, &mut binders, &Stack::Empty, valid); check_occurrences(sess, node_id, rhs, macros, &binders, &Stack::Empty, valid); - // Since the last semicolon is optional for legacy macros and decl_macro are not terminated, + // Since the last semicolon is optional for `macro_rules` macros and decl_macro are not terminated, // we increment our checked position by how many token trees we already checked (the 3 // above) before checking for the separator. i += 3; diff --git a/src/librustc_parse/parser/item.rs b/src/librustc_parse/parser/item.rs index cb4a98a6b4f46..e927bcd07e2cd 100644 --- a/src/librustc_parse/parser/item.rs +++ b/src/librustc_parse/parser/item.rs @@ -1270,7 +1270,7 @@ impl<'a> Parser<'a> { && self.look_ahead(2, |t| t.is_ident()) } - /// Parses a legacy `macro_rules! foo { ... }` declarative macro. + /// Parses a `macro_rules! foo { ... }` declarative macro. fn parse_item_macro_rules(&mut self, vis: &Visibility) -> PResult<'a, ItemInfo> { self.expect_keyword(kw::MacroRules)?; // `macro_rules` self.expect(&token::Not)?; // `!` diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 324669963f684..f7bbba28c070e 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -624,7 +624,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { self.r.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX }) }; - let used = self.process_legacy_macro_imports(item, module); + let used = self.process_macro_use_imports(item, module); let binding = (module, ty::Visibility::Public, sp, expansion).to_name_binding(self.r.arenas); let import = self.r.arenas.alloc_import(Import { @@ -913,7 +913,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { } } - fn legacy_import_macro( + fn add_macro_use_binding( &mut self, name: ast::Name, binding: &'a NameBinding<'a>, @@ -929,7 +929,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { } /// Returns `true` if we should consider the underlying `extern crate` to be used. - fn process_legacy_macro_imports(&mut self, item: &Item, module: Module<'a>) -> bool { + fn process_macro_use_imports(&mut self, item: &Item, module: Module<'a>) -> bool { let mut import_all = None; let mut single_imports = Vec::new(); for attr in &item.attrs { @@ -1004,7 +1004,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { module.for_each_child(self, |this, ident, ns, binding| { if ns == MacroNS { let imported_binding = this.r.import(binding, import); - this.legacy_import_macro(ident.name, imported_binding, span, allow_shadowing); + this.add_macro_use_binding(ident.name, imported_binding, span, allow_shadowing); } }); } else { @@ -1021,7 +1021,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { let import = macro_use_import(self, ident.span); self.r.potentially_unused_imports.push(import); let imported_binding = self.r.import(binding, import); - self.legacy_import_macro( + self.add_macro_use_binding( ident.name, imported_binding, ident.span, diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index 0d02b8ea074ee..c433871047836 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -618,7 +618,7 @@ enum AmbiguityKind { Import, BuiltinAttr, DeriveHelper, - LegacyVsModern, + MacroRulesVsModularized, GlobVsOuter, GlobVsGlob, GlobVsExpanded, @@ -631,7 +631,9 @@ impl AmbiguityKind { AmbiguityKind::Import => "name vs any other name during import resolution", AmbiguityKind::BuiltinAttr => "built-in attribute vs any other name", AmbiguityKind::DeriveHelper => "derive helper attribute vs any other name", - AmbiguityKind::LegacyVsModern => "`macro_rules` vs non-`macro_rules` from other module", + AmbiguityKind::MacroRulesVsModularized => { + "`macro_rules` vs non-`macro_rules` from other module" + } AmbiguityKind::GlobVsOuter => { "glob import vs any other name from outer scope during import/macro resolution" } @@ -1473,7 +1475,7 @@ impl<'a> Resolver<'a> { // derives (you need to resolve the derive first to add helpers into scope), but they // should be available before the derive is expanded for compatibility. // It's mess in general, so we are being conservative for now. - // 1-3. `macro_rules` (open, not controlled), loop through legacy scopes. Have higher + // 1-3. `macro_rules` (open, not controlled), loop through `macro_rules` scopes. Have higher // priority than prelude macros, but create ambiguities with macros in modules. // 1-3. Names in modules (both normal `mod`ules and blocks), loop through hygienic parents // (open, not controlled). Have higher priority than prelude macros, but create @@ -1639,7 +1641,7 @@ impl<'a> Resolver<'a> { for i in (0..ribs.len()).rev() { debug!("walk rib\n{:?}", ribs[i].bindings); // Use the rib kind to determine whether we are resolving parameters - // (modern hygiene) or local variables (legacy hygiene). + // (modern hygiene) or local variables (`macro_rules` hygiene). let rib_ident = if ribs[i].kind.contains_params() { modern_ident } else { ident }; if let Some(res) = ribs[i].bindings.get(&rib_ident).cloned() { // The ident resolves to a type parameter or local variable. @@ -1898,7 +1900,7 @@ impl<'a> Resolver<'a> { break; } } - // Then find the last legacy mark from the end if it exists. + // Then find the last semi-transparent mark from the end if it exists. for (mark, transparency) in iter { if transparency == Transparency::SemiTransparent { result = Some(mark); @@ -2423,21 +2425,21 @@ impl<'a> Resolver<'a> { } } - fn disambiguate_legacy_vs_modern( + fn disambiguate_macro_rules_vs_modularized( &self, - legacy: &'a NameBinding<'a>, - modern: &'a NameBinding<'a>, + macro_rules: &'a NameBinding<'a>, + modularized: &'a NameBinding<'a>, ) -> bool { // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules" // is disambiguated to mitigate regressions from macro modularization. // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general. match ( - self.binding_parent_modules.get(&PtrKey(legacy)), - self.binding_parent_modules.get(&PtrKey(modern)), + self.binding_parent_modules.get(&PtrKey(macro_rules)), + self.binding_parent_modules.get(&PtrKey(modularized)), ) { - (Some(legacy), Some(modern)) => { - legacy.normal_ancestor_id == modern.normal_ancestor_id - && modern.is_ancestor_of(legacy) + (Some(macro_rules), Some(modularized)) => { + macro_rules.normal_ancestor_id == modularized.normal_ancestor_id + && modularized.is_ancestor_of(macro_rules) } _ => false, } diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index d8ef148bacff2..f4dfa037dae4d 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -761,16 +761,18 @@ impl<'a> Resolver<'a> { Some(AmbiguityKind::DeriveHelper) } else if innermost_flags.contains(Flags::MACRO_RULES) && flags.contains(Flags::MODULE) - && !this - .disambiguate_legacy_vs_modern(innermost_binding, binding) + && !this.disambiguate_macro_rules_vs_modularized( + innermost_binding, + binding, + ) || flags.contains(Flags::MACRO_RULES) && innermost_flags.contains(Flags::MODULE) - && !this.disambiguate_legacy_vs_modern( + && !this.disambiguate_macro_rules_vs_modularized( binding, innermost_binding, ) { - Some(AmbiguityKind::LegacyVsModern) + Some(AmbiguityKind::MacroRulesVsModularized) } else if innermost_binding.is_glob_import() { Some(AmbiguityKind::GlobVsOuter) } else if innermost_binding From db638bd123b7b73be691f7b4daebb61469587a27 Mon Sep 17 00:00:00 2001 From: Vadim Petrochenkov Date: Sat, 14 Mar 2020 01:36:46 +0300 Subject: [PATCH 17/21] hygiene: `modern` -> `normalize_to_macros_2_0` `modern_and_legacy` -> `normalize_to_macro_rules` --- src/librustc/ty/mod.rs | 18 ++++---- src/librustc_ast_lowering/item.rs | 2 +- src/librustc_ast_lowering/lib.rs | 13 ++++-- src/librustc_hir/hir.rs | 10 ++-- src/librustc_mir/monomorphize/collector.rs | 4 +- src/librustc_resolve/build_reduced_graph.rs | 15 +++--- src/librustc_resolve/diagnostics.rs | 2 +- src/librustc_resolve/imports.rs | 3 +- src/librustc_resolve/late.rs | 10 ++-- src/librustc_resolve/late/lifetimes.rs | 27 ++++++----- src/librustc_resolve/lib.rs | 46 +++++++++---------- src/librustc_resolve/macros.rs | 8 +++- src/librustc_span/hygiene.rs | 32 ++++++------- src/librustc_span/lib.rs | 12 ++--- src/librustc_span/symbol.rs | 12 ++--- src/librustc_typeck/astconv.rs | 13 ++++-- src/librustc_typeck/check/expr.rs | 6 ++- src/librustc_typeck/check/pat.rs | 4 +- .../coherence/inherent_impls_overlap.rs | 8 ++-- src/librustc_typeck/collect.rs | 4 +- src/librustc_typeck/impl_wf_check.rs | 2 +- 21 files changed, 141 insertions(+), 110 deletions(-) diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index c2697570dda27..e1df0e6cde3c8 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -3083,7 +3083,7 @@ impl<'tcx> TyCtxt<'tcx> { pub fn hygienic_eq(self, use_name: Ident, def_name: Ident, def_parent_def_id: DefId) -> bool { // We could use `Ident::eq` here, but we deliberately don't. The name // comparison fails frequently, and we want to avoid the expensive - // `modern()` calls required for the span comparison whenever possible. + // `normalize_to_macros_2_0()` calls required for the span comparison whenever possible. use_name.name == def_name.name && use_name .span @@ -3099,7 +3099,7 @@ impl<'tcx> TyCtxt<'tcx> { } pub fn adjust_ident(self, mut ident: Ident, scope: DefId) -> Ident { - ident.span.modernize_and_adjust(self.expansion_that_defined(scope)); + ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope)); ident } @@ -3109,12 +3109,14 @@ impl<'tcx> TyCtxt<'tcx> { scope: DefId, block: hir::HirId, ) -> (Ident, DefId) { - let scope = match ident.span.modernize_and_adjust(self.expansion_that_defined(scope)) { - Some(actual_expansion) => { - self.hir().definitions().parent_module_of_macro_def(actual_expansion) - } - None => self.parent_module(block), - }; + let scope = + match ident.span.normalize_to_macros_2_0_and_adjust(self.expansion_that_defined(scope)) + { + Some(actual_expansion) => { + self.hir().definitions().parent_module_of_macro_def(actual_expansion) + } + None => self.parent_module(block), + }; (ident, scope) } diff --git a/src/librustc_ast_lowering/item.rs b/src/librustc_ast_lowering/item.rs index 458cb721d4834..38089167f5c39 100644 --- a/src/librustc_ast_lowering/item.rs +++ b/src/librustc_ast_lowering/item.rs @@ -115,7 +115,7 @@ impl<'hir> LoweringContext<'_, 'hir> { _ => &[], }; let lt_def_names = parent_generics.iter().filter_map(|param| match param.kind { - hir::GenericParamKind::Lifetime { .. } => Some(param.name.modern()), + hir::GenericParamKind::Lifetime { .. } => Some(param.name.normalize_to_macros_2_0()), _ => None, }); self.in_scope_lifetimes.extend(lt_def_names); diff --git a/src/librustc_ast_lowering/lib.rs b/src/librustc_ast_lowering/lib.rs index 24e547af237d5..97711d8c8ffeb 100644 --- a/src/librustc_ast_lowering/lib.rs +++ b/src/librustc_ast_lowering/lib.rs @@ -153,7 +153,7 @@ struct LoweringContext<'a, 'hir: 'a> { /// against this list to see if it is already in-scope, or if a definition /// needs to be created for it. /// - /// We always store a `modern()` version of the param-name in this + /// We always store a `normalize_to_macros_2_0()` version of the param-name in this /// vector. in_scope_lifetimes: Vec, @@ -805,14 +805,15 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { return; } - if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.modern())) { + if self.in_scope_lifetimes.contains(&ParamName::Plain(ident.normalize_to_macros_2_0())) { return; } let hir_name = ParamName::Plain(ident); - if self.lifetimes_to_define.iter().any(|(_, lt_name)| lt_name.modern() == hir_name.modern()) - { + if self.lifetimes_to_define.iter().any(|(_, lt_name)| { + lt_name.normalize_to_macros_2_0() == hir_name.normalize_to_macros_2_0() + }) { return; } @@ -840,7 +841,9 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { ) -> T { let old_len = self.in_scope_lifetimes.len(); let lt_def_names = params.iter().filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some(ParamName::Plain(param.ident.modern())), + GenericParamKind::Lifetime { .. } => { + Some(ParamName::Plain(param.ident.normalize_to_macros_2_0())) + } _ => None, }); self.in_scope_lifetimes.extend(lt_def_names); diff --git a/src/librustc_hir/hir.rs b/src/librustc_hir/hir.rs index fc6a9e39645cc..797387cdced21 100644 --- a/src/librustc_hir/hir.rs +++ b/src/librustc_hir/hir.rs @@ -79,9 +79,9 @@ impl ParamName { } } - pub fn modern(&self) -> ParamName { + pub fn normalize_to_macros_2_0(&self) -> ParamName { match *self { - ParamName::Plain(ident) => ParamName::Plain(ident.modern()), + ParamName::Plain(ident) => ParamName::Plain(ident.normalize_to_macros_2_0()), param_name => param_name, } } @@ -151,9 +151,11 @@ impl LifetimeName { self == &LifetimeName::Static } - pub fn modern(&self) -> LifetimeName { + pub fn normalize_to_macros_2_0(&self) -> LifetimeName { match *self { - LifetimeName::Param(param_name) => LifetimeName::Param(param_name.modern()), + LifetimeName::Param(param_name) => { + LifetimeName::Param(param_name.normalize_to_macros_2_0()) + } lifetime_name => lifetime_name, } } diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index 862a7ef1e73c0..28fafb126f4c6 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -1088,9 +1088,9 @@ fn create_mono_items_for_default_impls<'tcx>( let param_env = ty::ParamEnv::reveal_all(); let trait_ref = tcx.normalize_erasing_regions(param_env, trait_ref); let overridden_methods: FxHashSet<_> = - items.iter().map(|iiref| iiref.ident.modern()).collect(); + items.iter().map(|iiref| iiref.ident.normalize_to_macros_2_0()).collect(); for method in tcx.provided_trait_methods(trait_ref.def_id) { - if overridden_methods.contains(&method.ident.modern()) { + if overridden_methods.contains(&method.ident.normalize_to_macros_2_0()) { continue; } diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index f7bbba28c070e..ce3b1233a7473 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -645,7 +645,8 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { self.r.potentially_unused_imports.push(import); let imported_binding = self.r.import(binding, import); if ptr::eq(parent, self.r.graph_root) { - if let Some(entry) = self.r.extern_prelude.get(&ident.modern()) { + if let Some(entry) = self.r.extern_prelude.get(&ident.normalize_to_macros_2_0()) + { if expansion != ExpnId::root() && orig_name.is_some() && entry.extern_crate_item.is_none() @@ -656,10 +657,12 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { } } let entry = - self.r.extern_prelude.entry(ident.modern()).or_insert(ExternPreludeEntry { - extern_crate_item: None, - introduced_by_item: true, - }); + self.r.extern_prelude.entry(ident.normalize_to_macros_2_0()).or_insert( + ExternPreludeEntry { + extern_crate_item: None, + introduced_by_item: true, + }, + ); entry.extern_crate_item = Some(imported_binding); if orig_name.is_some() { entry.introduced_by_item = true; @@ -1119,7 +1122,7 @@ impl<'a, 'b> BuildReducedGraphVisitor<'a, 'b> { self.r.local_macro_def_scopes.insert(item.id, parent_scope.module); if macro_rules { - let ident = ident.modern(); + let ident = ident.normalize_to_macros_2_0(); self.r.macro_names.insert(ident); let is_macro_export = attr::contains_name(&item.attrs, sym::macro_export); let vis = if is_macro_export { diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index d50f88b59edc3..63fbc800ff706 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -758,7 +758,7 @@ impl<'a> Resolver<'a> { let msg = format!("unsafe traits like `{}` should be implemented explicitly", ident); err.span_note(ident.span, &msg); } - if self.macro_names.contains(&ident.modern()) { + if self.macro_names.contains(&ident.normalize_to_macros_2_0()) { err.help("have you added the `#[macro_use]` on the module/import?"); } } diff --git a/src/librustc_resolve/imports.rs b/src/librustc_resolve/imports.rs index 485b86636a0ba..681c039211892 100644 --- a/src/librustc_resolve/imports.rs +++ b/src/librustc_resolve/imports.rs @@ -416,7 +416,8 @@ impl<'a> Resolver<'a> { None => return Err((Undetermined, Weak::Yes)), }; let tmp_parent_scope; - let (mut adjusted_parent_scope, mut ident) = (parent_scope, ident.modern()); + let (mut adjusted_parent_scope, mut ident) = + (parent_scope, ident.normalize_to_macros_2_0()); match ident.span.glob_adjust(module.expansion, glob_import.span) { Some(Some(def)) => { tmp_parent_scope = diff --git a/src/librustc_resolve/late.rs b/src/librustc_resolve/late.rs index 7efd9e90cebb9..867aa8c632168 100644 --- a/src/librustc_resolve/late.rs +++ b/src/librustc_resolve/late.rs @@ -935,7 +935,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { _ => unreachable!(), }; - let ident = param.ident.modern(); + let ident = param.ident.normalize_to_macros_2_0(); debug!("with_generic_param_rib: {}", param.id); if seen_bindings.contains_key(&ident) { @@ -1464,7 +1464,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { // Add the binding to the local ribs, if it doesn't already exist in the bindings map. // (We must not add it if it's in the bindings map because that breaks the assumptions // later passes make about or-patterns.) - let ident = ident.modern_and_legacy(); + let ident = ident.normalize_to_macro_rules(); let mut bound_iter = bindings.iter().filter(|(_, set)| set.contains(&ident)); // Already bound in a product pattern? e.g. `(a, a)` which is not allowed. @@ -1873,7 +1873,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { self.diagnostic_metadata.unused_labels.insert(id, label.ident.span); } self.with_label_rib(NormalRibKind, |this| { - let ident = label.ident.modern_and_legacy(); + let ident = label.ident.normalize_to_macro_rules(); this.label_ribs.last_mut().unwrap().bindings.insert(ident, id); f(this); }); @@ -1949,7 +1949,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { ExprKind::Break(Some(label), _) | ExprKind::Continue(Some(label)) => { let node_id = self.search_label(label.ident, |rib, ident| { - rib.bindings.get(&ident.modern_and_legacy()).cloned() + rib.bindings.get(&ident.normalize_to_macro_rules()).cloned() }); match node_id { None => { @@ -2115,7 +2115,7 @@ impl<'a, 'b, 'ast> LateResolutionVisitor<'a, 'b, 'ast> { } } - ident.span = ident.span.modern(); + ident.span = ident.span.normalize_to_macros_2_0(); let mut search_module = self.parent_scope.module; loop { self.get_traits_in_module_containing_item(ident, ns, search_module, &mut found_traits); diff --git a/src/librustc_resolve/late/lifetimes.rs b/src/librustc_resolve/late/lifetimes.rs index 5c0748797f04b..7c5b35381f0ec 100644 --- a/src/librustc_resolve/late/lifetimes.rs +++ b/src/librustc_resolve/late/lifetimes.rs @@ -62,7 +62,7 @@ impl RegionExt for Region { let def_id = hir_map.local_def_id(param.hir_id); let origin = LifetimeDefOrigin::from_param(param); debug!("Region::early: index={} def_id={:?}", i, def_id); - (param.name.modern(), Region::EarlyBound(i, def_id, origin)) + (param.name.normalize_to_macros_2_0(), Region::EarlyBound(i, def_id, origin)) } fn late(hir_map: &Map<'_>, param: &GenericParam<'_>) -> (ParamName, Region) { @@ -73,7 +73,7 @@ impl RegionExt for Region { "Region::late: param={:?} depth={:?} def_id={:?} origin={:?}", param, depth, def_id, origin, ); - (param.name.modern(), Region::LateBound(depth, def_id, origin)) + (param.name.normalize_to_macros_2_0(), Region::LateBound(depth, def_id, origin)) } fn late_anon(index: &Cell) -> Region { @@ -1174,7 +1174,9 @@ fn extract_labels(ctxt: &mut LifetimeContext<'_, '_>, body: &hir::Body<'_>) { Scope::Binder { ref lifetimes, s, .. } => { // FIXME (#24278): non-hygienic comparison - if let Some(def) = lifetimes.get(&hir::ParamName::Plain(label.modern())) { + if let Some(def) = + lifetimes.get(&hir::ParamName::Plain(label.normalize_to_macros_2_0())) + { let hir_id = tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap(); signal_shadowing_problem( @@ -1253,7 +1255,7 @@ fn object_lifetime_defaults_for_item( fn add_bounds(set: &mut Set1, bounds: &[hir::GenericBound<'_>]) { for bound in bounds { if let hir::GenericBound::Outlives(ref lifetime) = *bound { - set.insert(lifetime.name.modern()); + set.insert(lifetime.name.normalize_to_macros_2_0()); } } } @@ -1791,7 +1793,8 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { Scope::Binder { ref lifetimes, s, .. } => { match lifetime_ref.name { LifetimeName::Param(param_name) => { - if let Some(&def) = lifetimes.get(¶m_name.modern()) { + if let Some(&def) = lifetimes.get(¶m_name.normalize_to_macros_2_0()) + { break Some(def.shifted(late_depth)); } } @@ -2544,7 +2547,9 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { let lifetimes: Vec<_> = params .iter() .filter_map(|param| match param.kind { - GenericParamKind::Lifetime { .. } => Some((param, param.name.modern())), + GenericParamKind::Lifetime { .. } => { + Some((param, param.name.normalize_to_macros_2_0())) + } _ => None, }) .collect(); @@ -2661,7 +2666,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } Scope::Binder { ref lifetimes, s, .. } => { - if let Some(&def) = lifetimes.get(¶m.name.modern()) { + if let Some(&def) = lifetimes.get(¶m.name.normalize_to_macros_2_0()) { let hir_id = self.tcx.hir().as_local_hir_id(def.id().unwrap()).unwrap(); signal_shadowing_problem( @@ -2799,7 +2804,7 @@ fn insert_late_bound_lifetimes( // `'a: 'b` means both `'a` and `'b` are referenced appears_in_where_clause .regions - .insert(hir::LifetimeName::Param(param.name.modern())); + .insert(hir::LifetimeName::Param(param.name.normalize_to_macros_2_0())); } } } @@ -2821,7 +2826,7 @@ fn insert_late_bound_lifetimes( hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => continue, } - let lt_name = hir::LifetimeName::Param(param.name.modern()); + let lt_name = hir::LifetimeName::Param(param.name.normalize_to_macros_2_0()); // appears in the where clauses? early-bound. if appears_in_where_clause.regions.contains(<_name) { continue; @@ -2885,7 +2890,7 @@ fn insert_late_bound_lifetimes( } fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) { - self.regions.insert(lifetime_ref.name.modern()); + self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0()); } } @@ -2902,7 +2907,7 @@ fn insert_late_bound_lifetimes( } fn visit_lifetime(&mut self, lifetime_ref: &'v hir::Lifetime) { - self.regions.insert(lifetime_ref.name.modern()); + self.regions.insert(lifetime_ref.name.normalize_to_macros_2_0()); } } } diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index c433871047836..05d0f20645033 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -424,7 +424,7 @@ impl ModuleKind { /// program) if all but one of them come from glob imports. #[derive(Copy, Clone, PartialEq, Eq, Hash)] struct BindingKey { - /// The identifier for the binding, aways the `modern` version of the + /// The identifier for the binding, aways the `normalize_to_macros_2_0` version of the /// identifier. ident: Ident, ns: Namespace, @@ -1362,7 +1362,7 @@ impl<'a> Resolver<'a> { } fn new_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey { - let ident = ident.modern(); + let ident = ident.normalize_to_macros_2_0(); let disambiguator = if ident.name == kw::Underscore { self.underscore_disambiguator += 1; self.underscore_disambiguator @@ -1413,7 +1413,7 @@ impl<'a> Resolver<'a> { // Avoid marking `extern crate` items that refer to a name from extern prelude, // but not introduce it, as used if they are accessed from lexical scope. if is_lexical_scope { - if let Some(entry) = self.extern_prelude.get(&ident.modern()) { + if let Some(entry) = self.extern_prelude.get(&ident.normalize_to_macros_2_0()) { if let Some(crate_item) = entry.extern_crate_item { if ptr::eq(used_binding, crate_item) && !entry.introduced_by_item { return; @@ -1500,7 +1500,7 @@ impl<'a> Resolver<'a> { TypeNS | ValueNS => Scope::Module(module), MacroNS => Scope::DeriveHelpers(parent_scope.expansion), }; - let mut ident = ident.modern(); + let mut ident = ident.normalize_to_macros_2_0(); let mut use_prelude = !module.no_implicit_prelude; loop { @@ -1622,18 +1622,18 @@ impl<'a> Resolver<'a> { if ident.name == kw::Invalid { return Some(LexicalScopeBinding::Res(Res::Err)); } - let (general_span, modern_span) = if ident.name == kw::SelfUpper { + let (general_span, normalized_span) = if ident.name == kw::SelfUpper { // FIXME(jseyfried) improve `Self` hygiene let empty_span = ident.span.with_ctxt(SyntaxContext::root()); (empty_span, empty_span) } else if ns == TypeNS { - let modern_span = ident.span.modern(); - (modern_span, modern_span) + let normalized_span = ident.span.normalize_to_macros_2_0(); + (normalized_span, normalized_span) } else { - (ident.span.modern_and_legacy(), ident.span.modern()) + (ident.span.normalize_to_macro_rules(), ident.span.normalize_to_macros_2_0()) }; ident.span = general_span; - let modern_ident = Ident { span: modern_span, ..ident }; + let normalized_ident = Ident { span: normalized_span, ..ident }; // Walk backwards up the ribs in scope. let record_used = record_used_id.is_some(); @@ -1641,8 +1641,8 @@ impl<'a> Resolver<'a> { for i in (0..ribs.len()).rev() { debug!("walk rib\n{:?}", ribs[i].bindings); // Use the rib kind to determine whether we are resolving parameters - // (modern hygiene) or local variables (`macro_rules` hygiene). - let rib_ident = if ribs[i].kind.contains_params() { modern_ident } else { ident }; + // (macro 2.0 hygiene) or local variables (`macro_rules` hygiene). + let rib_ident = if ribs[i].kind.contains_params() { normalized_ident } else { ident }; if let Some(res) = ribs[i].bindings.get(&rib_ident).cloned() { // The ident resolves to a type parameter or local variable. return Some(LexicalScopeBinding::Res(self.validate_res_from_ribs( @@ -1685,7 +1685,7 @@ impl<'a> Resolver<'a> { } } - ident = modern_ident; + ident = normalized_ident; let mut poisoned = None; loop { let opt_module = if let Some(node_id) = record_used_id { @@ -1854,14 +1854,14 @@ impl<'a> Resolver<'a> { let mut adjusted_parent_scope = parent_scope; match module { ModuleOrUniformRoot::Module(m) => { - if let Some(def) = ident.span.modernize_and_adjust(m.expansion) { + if let Some(def) = ident.span.normalize_to_macros_2_0_and_adjust(m.expansion) { tmp_parent_scope = ParentScope { module: self.macro_def_scope(def), ..*parent_scope }; adjusted_parent_scope = &tmp_parent_scope; } } ModuleOrUniformRoot::ExternPrelude => { - ident.span.modernize_and_adjust(ExpnId::root()); + ident.span.normalize_to_macros_2_0_and_adjust(ExpnId::root()); } ModuleOrUniformRoot::CrateRootAndExternPrelude | ModuleOrUniformRoot::CurrentScope => { // No adjustments @@ -1884,14 +1884,14 @@ impl<'a> Resolver<'a> { let mark = if ident.name == kw::DollarCrate { // When resolving `$crate` from a `macro_rules!` invoked in a `macro`, // we don't want to pretend that the `macro_rules!` definition is in the `macro` - // as described in `SyntaxContext::apply_mark`, so we ignore prepended modern marks. + // as described in `SyntaxContext::apply_mark`, so we ignore prepended opaque marks. // FIXME: This is only a guess and it doesn't work correctly for `macro_rules!` // definitions actually produced by `macro` and `macro` definitions produced by // `macro_rules!`, but at least such configurations are not stable yet. - ctxt = ctxt.modern_and_legacy(); + ctxt = ctxt.normalize_to_macro_rules(); let mut iter = ctxt.marks().into_iter().rev().peekable(); let mut result = None; - // Find the last modern mark from the end if it exists. + // Find the last opaque mark from the end if it exists. while let Some(&(mark, transparency)) = iter.peek() { if transparency == Transparency::Opaque { result = Some(mark); @@ -1910,7 +1910,7 @@ impl<'a> Resolver<'a> { } result } else { - ctxt = ctxt.modern(); + ctxt = ctxt.normalize_to_macros_2_0(); ctxt.adjust(ExpnId::root()) }; let module = match mark { @@ -1922,7 +1922,7 @@ impl<'a> Resolver<'a> { fn resolve_self(&mut self, ctxt: &mut SyntaxContext, module: Module<'a>) -> Module<'a> { let mut module = self.get_module(module.normal_ancestor_id); - while module.span.ctxt().modern() != *ctxt { + while module.span.ctxt().normalize_to_macros_2_0() != *ctxt { let parent = module.parent.unwrap_or_else(|| self.macro_def_scope(ctxt.remove_mark())); module = self.get_module(parent.normal_ancestor_id); } @@ -1990,7 +1990,7 @@ impl<'a> Resolver<'a> { if ns == TypeNS { if allow_super && name == kw::Super { - let mut ctxt = ident.span.ctxt().modern(); + let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); let self_module = match i { 0 => Some(self.resolve_self(&mut ctxt, parent_scope.module)), _ => match module { @@ -2016,7 +2016,7 @@ impl<'a> Resolver<'a> { } if i == 0 { if name == kw::SelfLower { - let mut ctxt = ident.span.ctxt().modern(); + let mut ctxt = ident.span.ctxt().normalize_to_macros_2_0(); module = Some(ModuleOrUniformRoot::Module( self.resolve_self(&mut ctxt, parent_scope.module), )); @@ -2430,7 +2430,7 @@ impl<'a> Resolver<'a> { macro_rules: &'a NameBinding<'a>, modularized: &'a NameBinding<'a>, ) -> bool { - // Some non-controversial subset of ambiguities "modern macro name" vs "macro_rules" + // Some non-controversial subset of ambiguities "modularized macro name" vs "macro_rules" // is disambiguated to mitigate regressions from macro modularization. // Scoping for `macro_rules` behaves like scoping for `let` at module level, in general. match ( @@ -2769,7 +2769,7 @@ impl<'a> Resolver<'a> { // Make sure `self`, `super` etc produce an error when passed to here. return None; } - self.extern_prelude.get(&ident.modern()).cloned().and_then(|entry| { + self.extern_prelude.get(&ident.normalize_to_macros_2_0()).cloned().and_then(|entry| { if let Some(binding) = entry.extern_crate_item { if !speculative && entry.introduced_by_item { self.record_use(ident, TypeNS, binding, false); diff --git a/src/librustc_resolve/macros.rs b/src/librustc_resolve/macros.rs index f4dfa037dae4d..058ead95f50bd 100644 --- a/src/librustc_resolve/macros.rs +++ b/src/librustc_resolve/macros.rs @@ -258,7 +258,13 @@ impl<'a> base::Resolver for Resolver<'a> { force, ) { Ok((Some(ext), _)) => { - let span = path.segments.last().unwrap().ident.span.modern(); + let span = path + .segments + .last() + .unwrap() + .ident + .span + .normalize_to_macros_2_0(); helper_attrs.extend( ext.helper_attrs.iter().map(|name| Ident::new(*name, span)), ); diff --git a/src/librustc_span/hygiene.rs b/src/librustc_span/hygiene.rs index a368a881674d8..e073d735a1225 100644 --- a/src/librustc_span/hygiene.rs +++ b/src/librustc_span/hygiene.rs @@ -201,11 +201,11 @@ impl HygieneData { true } - fn modern(&self, ctxt: SyntaxContext) -> SyntaxContext { + fn normalize_to_macros_2_0(&self, ctxt: SyntaxContext) -> SyntaxContext { self.syntax_context_data[ctxt.0 as usize].opaque } - fn modern_and_legacy(&self, ctxt: SyntaxContext) -> SyntaxContext { + fn normalize_to_macro_rules(&self, ctxt: SyntaxContext) -> SyntaxContext { self.syntax_context_data[ctxt.0 as usize].opaque_and_semitransparent } @@ -266,9 +266,9 @@ impl HygieneData { let call_site_ctxt = self.expn_data(expn_id).call_site.ctxt(); let mut call_site_ctxt = if transparency == Transparency::SemiTransparent { - self.modern(call_site_ctxt) + self.normalize_to_macros_2_0(call_site_ctxt) } else { - self.modern_and_legacy(call_site_ctxt) + self.normalize_to_macro_rules(call_site_ctxt) }; if call_site_ctxt == SyntaxContext::root() { @@ -491,10 +491,10 @@ impl SyntaxContext { HygieneData::with(|data| data.adjust(self, expn_id)) } - /// Like `SyntaxContext::adjust`, but also modernizes `self`. - pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option { + /// Like `SyntaxContext::adjust`, but also normalizes `self` to macros 2.0. + pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { HygieneData::with(|data| { - *self = data.modern(*self); + *self = data.normalize_to_macros_2_0(*self); data.adjust(self, expn_id) }) } @@ -527,7 +527,7 @@ impl SyntaxContext { pub fn glob_adjust(&mut self, expn_id: ExpnId, glob_span: Span) -> Option> { HygieneData::with(|data| { let mut scope = None; - let mut glob_ctxt = data.modern(glob_span.ctxt()); + let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt()); while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) { scope = Some(data.remove_mark(&mut glob_ctxt).0); if data.remove_mark(self).0 != scope.unwrap() { @@ -558,7 +558,7 @@ impl SyntaxContext { return None; } - let mut glob_ctxt = data.modern(glob_span.ctxt()); + let mut glob_ctxt = data.normalize_to_macros_2_0(glob_span.ctxt()); let mut marks = Vec::new(); while !data.is_descendant_of(expn_id, data.outer_expn(glob_ctxt)) { marks.push(data.remove_mark(&mut glob_ctxt)); @@ -574,20 +574,20 @@ impl SyntaxContext { pub fn hygienic_eq(self, other: SyntaxContext, expn_id: ExpnId) -> bool { HygieneData::with(|data| { - let mut self_modern = data.modern(self); - data.adjust(&mut self_modern, expn_id); - self_modern == data.modern(other) + let mut self_normalized = data.normalize_to_macros_2_0(self); + data.adjust(&mut self_normalized, expn_id); + self_normalized == data.normalize_to_macros_2_0(other) }) } #[inline] - pub fn modern(self) -> SyntaxContext { - HygieneData::with(|data| data.modern(self)) + pub fn normalize_to_macros_2_0(self) -> SyntaxContext { + HygieneData::with(|data| data.normalize_to_macros_2_0(self)) } #[inline] - pub fn modern_and_legacy(self) -> SyntaxContext { - HygieneData::with(|data| data.modern_and_legacy(self)) + pub fn normalize_to_macro_rules(self) -> SyntaxContext { + HygieneData::with(|data| data.normalize_to_macro_rules(self)) } #[inline] diff --git a/src/librustc_span/lib.rs b/src/librustc_span/lib.rs index b5224e57cd2b6..caa50e9a41c0c 100644 --- a/src/librustc_span/lib.rs +++ b/src/librustc_span/lib.rs @@ -548,9 +548,9 @@ impl Span { } #[inline] - pub fn modernize_and_adjust(&mut self, expn_id: ExpnId) -> Option { + pub fn normalize_to_macros_2_0_and_adjust(&mut self, expn_id: ExpnId) -> Option { let mut span = self.data(); - let mark = span.ctxt.modernize_and_adjust(expn_id); + let mark = span.ctxt.normalize_to_macros_2_0_and_adjust(expn_id); *self = Span::new(span.lo, span.hi, span.ctxt); mark } @@ -576,15 +576,15 @@ impl Span { } #[inline] - pub fn modern(self) -> Span { + pub fn normalize_to_macros_2_0(self) -> Span { let span = self.data(); - span.with_ctxt(span.ctxt.modern()) + span.with_ctxt(span.ctxt.normalize_to_macros_2_0()) } #[inline] - pub fn modern_and_legacy(self) -> Span { + pub fn normalize_to_macro_rules(self) -> Span { let span = self.data(); - span.with_ctxt(span.ctxt.modern_and_legacy()) + span.with_ctxt(span.ctxt.normalize_to_macro_rules()) } } diff --git a/src/librustc_span/symbol.rs b/src/librustc_span/symbol.rs index bca4bfee85ad8..5760e1d004e03 100644 --- a/src/librustc_span/symbol.rs +++ b/src/librustc_span/symbol.rs @@ -853,12 +853,12 @@ impl Ident { } /// "Normalize" ident for use in comparisons using "item hygiene". - /// Identifiers with same string value become same if they came from the same "modern" macro + /// Identifiers with same string value become same if they came from the same macro 2.0 macro /// (e.g., `macro` item, but not `macro_rules` item) and stay different if they came from - /// different "modern" macros. + /// different macro 2.0 macros. /// Technically, this operation strips all non-opaque marks from ident's syntactic context. - pub fn modern(self) -> Ident { - Ident::new(self.name, self.span.modern()) + pub fn normalize_to_macros_2_0(self) -> Ident { + Ident::new(self.name, self.span.normalize_to_macros_2_0()) } /// "Normalize" ident for use in comparisons using "local variable hygiene". @@ -866,8 +866,8 @@ impl Ident { /// macro (e.g., `macro` or `macro_rules!` items) and stay different if they came from different /// non-transparent macros. /// Technically, this operation strips all transparent marks from ident's syntactic context. - pub fn modern_and_legacy(self) -> Ident { - Ident::new(self.name, self.span.modern_and_legacy()) + pub fn normalize_to_macro_rules(self) -> Ident { + Ident::new(self.name, self.span.normalize_to_macro_rules()) } /// Convert the name to a `SymbolStr`. This is a slowish operation because diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index be8090cf21b9c..b273efa78276d 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -1441,12 +1441,14 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let (assoc_ident, def_scope) = tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id); - // We have already adjusted the item name above, so compare with `ident.modern()` instead + // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead // of calling `filter_by_name_and_kind`. let assoc_ty = tcx .associated_items(candidate.def_id()) .filter_by_name_unhygienic(assoc_ident.name) - .find(|i| i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident) + .find(|i| { + i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident + }) .expect("missing associated type"); if !assoc_ty.vis.is_accessible_from(def_scope, tcx) { @@ -2298,12 +2300,15 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o { let (assoc_ident, def_scope) = tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id); - // We have already adjusted the item name above, so compare with `ident.modern()` instead + // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead // of calling `filter_by_name_and_kind`. let item = tcx .associated_items(trait_did) .in_definition_order() - .find(|i| i.kind.namespace() == Namespace::TypeNS && i.ident.modern() == assoc_ident) + .find(|i| { + i.kind.namespace() == Namespace::TypeNS + && i.ident.normalize_to_macros_2_0() == assoc_ident + }) .expect("missing associated type"); let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound); diff --git a/src/librustc_typeck/check/expr.rs b/src/librustc_typeck/check/expr.rs index 93f9050b26eb9..4531d93c01d27 100644 --- a/src/librustc_typeck/check/expr.rs +++ b/src/librustc_typeck/check/expr.rs @@ -1203,7 +1203,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .fields .iter() .enumerate() - .map(|(i, field)| (field.ident.modern(), (i, field))) + .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field))) .collect::>(); let mut seen_fields = FxHashMap::default(); @@ -1469,7 +1469,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let (ident, def_scope) = self.tcx.adjust_ident_and_get_scope(field, base_def.did, self.body_id); let fields = &base_def.non_enum_variant().fields; - if let Some(index) = fields.iter().position(|f| f.ident.modern() == ident) { + if let Some(index) = + fields.iter().position(|f| f.ident.normalize_to_macros_2_0() == ident) + { let field = &fields[index]; let field_ty = self.field_ty(expr.span, field, substs); // Save the index of all fields regardless of their visibility in case diff --git a/src/librustc_typeck/check/pat.rs b/src/librustc_typeck/check/pat.rs index fabf3dd1153b7..0f3884de84e12 100644 --- a/src/librustc_typeck/check/pat.rs +++ b/src/librustc_typeck/check/pat.rs @@ -1023,7 +1023,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .fields .iter() .enumerate() - .map(|(i, field)| (field.ident.modern(), (i, field))) + .map(|(i, field)| (field.ident.normalize_to_macros_2_0(), (i, field))) .collect::>(); // Keep track of which fields have already appeared in the pattern. @@ -1064,7 +1064,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let mut unmentioned_fields = variant .fields .iter() - .map(|field| field.ident.modern()) + .map(|field| field.ident.normalize_to_macros_2_0()) .filter(|ident| !used_fields.contains_key(&ident)) .collect::>(); diff --git a/src/librustc_typeck/coherence/inherent_impls_overlap.rs b/src/librustc_typeck/coherence/inherent_impls_overlap.rs index 1eae9d3b7fa6c..7513759c76b01 100644 --- a/src/librustc_typeck/coherence/inherent_impls_overlap.rs +++ b/src/librustc_typeck/coherence/inherent_impls_overlap.rs @@ -26,7 +26,8 @@ impl InherentOverlapChecker<'tcx> { let collision = impl_items2.filter_by_name_unhygienic(item1.ident.name).any(|item2| { // Symbols and namespace match, compare hygienically. item1.kind.namespace() == item2.kind.namespace() - && item1.ident.modern() == item2.ident.modern() + && item1.ident.normalize_to_macros_2_0() + == item2.ident.normalize_to_macros_2_0() }); if collision { @@ -50,11 +51,12 @@ impl InherentOverlapChecker<'tcx> { let collision = impl_items2.filter_by_name_unhygienic(item1.ident.name).find(|item2| { // Symbols and namespace match, compare hygienically. item1.kind.namespace() == item2.kind.namespace() - && item1.ident.modern() == item2.ident.modern() + && item1.ident.normalize_to_macros_2_0() + == item2.ident.normalize_to_macros_2_0() }); if let Some(item2) = collision { - let name = item1.ident.modern(); + let name = item1.ident.normalize_to_macros_2_0(); let mut err = struct_span_err!( self.tcx.sess, self.tcx.span_of_impl(item1.def_id).unwrap(), diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index cd63dacdcda0e..1ffcd7f271ef9 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -828,7 +828,7 @@ fn convert_variant( .iter() .map(|f| { let fid = tcx.hir().local_def_id(f.hir_id); - let dup_span = seen_fields.get(&f.ident.modern()).cloned(); + let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned(); if let Some(prev_span) = dup_span { struct_span_err!( tcx.sess, @@ -841,7 +841,7 @@ fn convert_variant( .span_label(prev_span, format!("`{}` first declared here", f.ident)) .emit(); } else { - seen_fields.insert(f.ident.modern(), f.span); + seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span); } ty::FieldDef { diff --git a/src/librustc_typeck/impl_wf_check.rs b/src/librustc_typeck/impl_wf_check.rs index 0a765a1f9c93c..5fb510d6e33df 100644 --- a/src/librustc_typeck/impl_wf_check.rs +++ b/src/librustc_typeck/impl_wf_check.rs @@ -227,7 +227,7 @@ fn enforce_impl_items_are_distinct(tcx: TyCtxt<'_>, impl_item_refs: &[hir::ImplI hir::ImplItemKind::TyAlias(_) => &mut seen_type_items, _ => &mut seen_value_items, }; - match seen_items.entry(impl_item.ident.modern()) { + match seen_items.entry(impl_item.ident.normalize_to_macros_2_0()) { Occupied(entry) => { let mut err = struct_span_err!( tcx.sess, From 7bd8ce2e506ed4c9a1a2214e7a6e9ead36e92631 Mon Sep 17 00:00:00 2001 From: Mark Mansi Date: Thu, 5 Mar 2020 09:57:34 -0600 Subject: [PATCH 18/21] More Method->Fn renaming --- src/librustc/hir/map/blocks.rs | 8 +++--- src/librustc/hir/map/mod.rs | 25 +++++++++++-------- src/librustc_ast_lowering/item.rs | 6 ++--- .../back/symbol_export.rs | 2 +- src/librustc_hir/hir.rs | 10 ++++---- src/librustc_hir/intravisit.rs | 6 ++--- src/librustc_hir/print.rs | 6 ++--- src/librustc_hir/target.rs | 4 +-- .../persist/dirty_clean.rs | 2 +- .../infer/error_reporting/mod.rs | 2 +- .../nice_region_error/find_anon_type.rs | 2 +- src/librustc_lint/builtin.rs | 2 +- src/librustc_lint/nonstandard_style.rs | 2 +- src/librustc_metadata/rmeta/decoder.rs | 10 ++++---- src/librustc_metadata/rmeta/encoder.rs | 12 ++++----- src/librustc_metadata/rmeta/mod.rs | 2 +- .../diagnostics/mutability_errors.rs | 4 +-- .../borrow_check/diagnostics/region_name.rs | 2 +- src/librustc_mir/monomorphize/collector.rs | 2 +- src/librustc_mir_build/build/mod.rs | 4 +-- src/librustc_passes/check_attr.rs | 2 +- src/librustc_passes/dead.rs | 8 +++--- src/librustc_passes/reachable.rs | 14 +++++------ src/librustc_privacy/lib.rs | 5 ++-- src/librustc_resolve/late/lifetimes.rs | 14 +++++------ .../traits/error_reporting/mod.rs | 2 +- .../error_reporting/on_unimplemented.rs | 4 +-- .../traits/error_reporting/suggestions.rs | 2 +- src/librustc_traits/lowering/environment.rs | 2 +- src/librustc_typeck/check/compare_method.rs | 6 ++--- src/librustc_typeck/check/method/suggest.rs | 4 +-- src/librustc_typeck/check/mod.rs | 20 +++++++-------- src/librustc_typeck/check/wfcheck.rs | 2 +- src/librustc_typeck/collect.rs | 8 +++--- src/librustc_typeck/collect/type_of.rs | 2 +- src/librustc_typeck/variance/constraints.rs | 2 +- src/librustc_typeck/variance/mod.rs | 2 +- src/librustc_typeck/variance/terms.rs | 2 +- src/librustdoc/clean/mod.rs | 6 ++--- 39 files changed, 110 insertions(+), 110 deletions(-) diff --git a/src/librustc/hir/map/blocks.rs b/src/librustc/hir/map/blocks.rs index d9ffe4582e7d7..7024e86f95d06 100644 --- a/src/librustc/hir/map/blocks.rs +++ b/src/librustc/hir/map/blocks.rs @@ -51,7 +51,7 @@ impl MaybeFnLike for hir::Item<'_> { impl MaybeFnLike for hir::ImplItem<'_> { fn is_fn_like(&self) -> bool { match self.kind { - hir::ImplItemKind::Method(..) => true, + hir::ImplItemKind::Fn(..) => true, _ => false, } } @@ -60,7 +60,7 @@ impl MaybeFnLike for hir::ImplItem<'_> { impl MaybeFnLike for hir::TraitItem<'_> { fn is_fn_like(&self) -> bool { match self.kind { - hir::TraitItemKind::Fn(_, hir::TraitMethod::Provided(_)) => true, + hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => true, _ => false, } } @@ -239,13 +239,13 @@ impl<'a> FnLikeNode<'a> { _ => bug!("item FnLikeNode that is not fn-like"), }, Node::TraitItem(ti) => match ti.kind { - hir::TraitItemKind::Fn(ref sig, hir::TraitMethod::Provided(body)) => { + hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => { method(ti.hir_id, ti.ident, sig, None, body, ti.span, &ti.attrs) } _ => bug!("trait method FnLikeNode that is not fn-like"), }, Node::ImplItem(ii) => match ii.kind { - hir::ImplItemKind::Method(ref sig, body) => { + hir::ImplItemKind::Fn(ref sig, body) => { method(ii.hir_id, ii.ident, sig, Some(&ii.vis), body, ii.span, &ii.attrs) } _ => bug!("impl method FnLikeNode that is not fn-like"), diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index bcbb6f3ec31e6..af08eb7b04cae 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -56,7 +56,7 @@ fn fn_decl<'hir>(node: Node<'hir>) -> Option<&'hir FnDecl<'hir>> { }, Node::ImplItem(ref item) => match item.kind { - ImplItemKind::Method(ref sig, _) => Some(&sig.decl), + ImplItemKind::Fn(ref sig, _) => Some(&sig.decl), _ => None, }, @@ -82,7 +82,7 @@ fn fn_sig<'hir>(node: Node<'hir>) -> Option<&'hir FnSig<'hir>> { }, Node::ImplItem(item) => match &item.kind { - ImplItemKind::Method(sig, _) => Some(sig), + ImplItemKind::Fn(sig, _) => Some(sig), _ => None, }, @@ -100,13 +100,14 @@ fn associated_body<'hir>(node: Node<'hir>) -> Option { }, Node::TraitItem(item) => match item.kind { - TraitItemKind::Const(_, Some(body)) - | TraitItemKind::Fn(_, TraitMethod::Provided(body)) => Some(body), + TraitItemKind::Const(_, Some(body)) | TraitItemKind::Fn(_, TraitFn::Provided(body)) => { + Some(body) + } _ => None, }, Node::ImplItem(item) => match item.kind { - ImplItemKind::Const(_, body) | ImplItemKind::Method(_, body) => Some(body), + ImplItemKind::Const(_, body) | ImplItemKind::Fn(_, body) => Some(body), _ => None, }, @@ -299,7 +300,7 @@ impl<'hir> Map<'hir> { }, Node::ImplItem(item) => match item.kind { ImplItemKind::Const(..) => DefKind::AssocConst, - ImplItemKind::Method(..) => DefKind::AssocFn, + ImplItemKind::Fn(..) => DefKind::AssocFn, ImplItemKind::TyAlias(..) => DefKind::AssocTy, ImplItemKind::OpaqueTy(..) => DefKind::AssocOpaqueTy, }, @@ -443,7 +444,7 @@ impl<'hir> Map<'hir> { Node::Ctor(..) | Node::Item(&Item { kind: ItemKind::Fn(..), .. }) | Node::TraitItem(&TraitItem { kind: TraitItemKind::Fn(..), .. }) - | Node::ImplItem(&ImplItem { kind: ImplItemKind::Method(..), .. }) => BodyOwnerKind::Fn, + | Node::ImplItem(&ImplItem { kind: ImplItemKind::Fn(..), .. }) => BodyOwnerKind::Fn, Node::Item(&Item { kind: ItemKind::Static(_, m, _), .. }) => BodyOwnerKind::Static(m), Node::Expr(&Expr { kind: ExprKind::Closure(..), .. }) => BodyOwnerKind::Closure, node => bug!("{:#?} is not a body node", node), @@ -541,7 +542,11 @@ impl<'hir> Map<'hir> { /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. pub fn find(&self, hir_id: HirId) -> Option> { let node = self.get_entry(hir_id).node; - if let Node::Crate(..) = node { None } else { Some(node) } + if let Node::Crate(..) = node { + None + } else { + Some(node) + } } /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there @@ -749,7 +754,7 @@ impl<'hir> Map<'hir> { _ => false, }, Node::ImplItem(ii) => match ii.kind { - ImplItemKind::Method(..) => true, + ImplItemKind::Fn(..) => true, _ => false, }, Node::Block(_) => true, @@ -1110,7 +1115,7 @@ fn hir_id_to_string(map: &Map<'_>, id: HirId, include_id: bool) -> String { ImplItemKind::Const(..) => { format!("assoc const {} in {}{}", ii.ident, path_str(), id_str) } - ImplItemKind::Method(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str), + ImplItemKind::Fn(..) => format!("method {} in {}{}", ii.ident, path_str(), id_str), ImplItemKind::TyAlias(_) => { format!("assoc type {} in {}{}", ii.ident, path_str(), id_str) } diff --git a/src/librustc_ast_lowering/item.rs b/src/librustc_ast_lowering/item.rs index 2c60fe9c07779..22d876ae14ec2 100644 --- a/src/librustc_ast_lowering/item.rs +++ b/src/librustc_ast_lowering/item.rs @@ -761,13 +761,13 @@ impl<'hir> LoweringContext<'_, 'hir> { let names = self.lower_fn_params_to_names(&sig.decl); let (generics, sig) = self.lower_method_sig(generics, sig, trait_item_def_id, false, None); - (generics, hir::TraitItemKind::Fn(sig, hir::TraitMethod::Required(names))) + (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names))) } AssocItemKind::Fn(_, ref sig, ref generics, Some(ref body)) => { let body_id = self.lower_fn_body_block(i.span, &sig.decl, Some(body)); let (generics, sig) = self.lower_method_sig(generics, sig, trait_item_def_id, false, None); - (generics, hir::TraitItemKind::Fn(sig, hir::TraitMethod::Provided(body_id))) + (generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id))) } AssocItemKind::TyAlias(_, ref generics, ref bounds, ref default) => { let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed())); @@ -838,7 +838,7 @@ impl<'hir> LoweringContext<'_, 'hir> { asyncness.opt_return_id(), ); - (generics, hir::ImplItemKind::Method(sig, body_id)) + (generics, hir::ImplItemKind::Fn(sig, body_id)) } AssocItemKind::TyAlias(_, generics, _, ty) => { let generics = self.lower_generics(generics, ImplTraitContext::disallowed()); diff --git a/src/librustc_codegen_ssa/back/symbol_export.rs b/src/librustc_codegen_ssa/back/symbol_export.rs index 3fe256ce25b96..178a74c791b4c 100644 --- a/src/librustc_codegen_ssa/back/symbol_export.rs +++ b/src/librustc_codegen_ssa/back/symbol_export.rs @@ -88,7 +88,7 @@ fn reachable_non_generics_provider( // Only consider nodes that actually have exported symbols. Node::Item(&hir::Item { kind: hir::ItemKind::Static(..), .. }) | Node::Item(&hir::Item { kind: hir::ItemKind::Fn(..), .. }) - | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Method(..), .. }) => { + | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => { let def_id = tcx.hir().local_def_id(hir_id); let generics = tcx.generics_of(def_id); if !generics.requires_monomorphization(tcx) && diff --git a/src/librustc_hir/hir.rs b/src/librustc_hir/hir.rs index 48b423de268a7..b189ae1f13d7c 100644 --- a/src/librustc_hir/hir.rs +++ b/src/librustc_hir/hir.rs @@ -1854,7 +1854,7 @@ pub struct TraitItem<'hir> { /// Represents a trait method's body (or just argument names). #[derive(RustcEncodable, RustcDecodable, Debug, HashStable_Generic)] -pub enum TraitMethod<'hir> { +pub enum TraitFn<'hir> { /// No default body in the trait, just a signature. Required(&'hir [Ident]), @@ -1868,7 +1868,7 @@ pub enum TraitItemKind<'hir> { /// An associated constant with an optional value (otherwise `impl`s must contain a value). Const(&'hir Ty<'hir>, Option), /// An associated function with an optional body. - Fn(FnSig<'hir>, TraitMethod<'hir>), + Fn(FnSig<'hir>, TraitFn<'hir>), /// An associated type with (possibly empty) bounds and optional concrete /// type. Type(GenericBounds<'hir>, Option<&'hir Ty<'hir>>), @@ -1902,7 +1902,7 @@ pub enum ImplItemKind<'hir> { /// of the expression. Const(&'hir Ty<'hir>, BodyId), /// A method implementation with the given signature and body. - Method(FnSig<'hir>, BodyId), + Fn(FnSig<'hir>, BodyId), /// An associated type. TyAlias(&'hir Ty<'hir>), /// An associated `type = impl Trait`. @@ -1913,7 +1913,7 @@ impl ImplItemKind<'_> { pub fn namespace(&self) -> Namespace { match self { ImplItemKind::OpaqueTy(..) | ImplItemKind::TyAlias(..) => Namespace::TypeNS, - ImplItemKind::Const(..) | ImplItemKind::Method(..) => Namespace::ValueNS, + ImplItemKind::Const(..) | ImplItemKind::Fn(..) => Namespace::ValueNS, } } } @@ -2704,7 +2704,7 @@ impl Node<'_> { pub fn fn_decl(&self) -> Option<&FnDecl<'_>> { match self { Node::TraitItem(TraitItem { kind: TraitItemKind::Fn(fn_sig, _), .. }) - | Node::ImplItem(ImplItem { kind: ImplItemKind::Method(fn_sig, _), .. }) + | Node::ImplItem(ImplItem { kind: ImplItemKind::Fn(fn_sig, _), .. }) | Node::Item(Item { kind: ItemKind::Fn(fn_sig, _, _), .. }) => Some(fn_sig.decl), Node::ForeignItem(ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => { Some(fn_decl) diff --git a/src/librustc_hir/intravisit.rs b/src/librustc_hir/intravisit.rs index 79c7f34dd5310..b13f1a91b0317 100644 --- a/src/librustc_hir/intravisit.rs +++ b/src/librustc_hir/intravisit.rs @@ -911,14 +911,14 @@ pub fn walk_trait_item<'v, V: Visitor<'v>>(visitor: &mut V, trait_item: &'v Trai visitor.visit_ty(ty); walk_list!(visitor, visit_nested_body, default); } - TraitItemKind::Fn(ref sig, TraitMethod::Required(param_names)) => { + TraitItemKind::Fn(ref sig, TraitFn::Required(param_names)) => { visitor.visit_id(trait_item.hir_id); visitor.visit_fn_decl(&sig.decl); for ¶m_name in param_names { visitor.visit_ident(param_name); } } - TraitItemKind::Fn(ref sig, TraitMethod::Provided(body_id)) => { + TraitItemKind::Fn(ref sig, TraitFn::Provided(body_id)) => { visitor.visit_fn( FnKind::Method(trait_item.ident, sig, None, &trait_item.attrs), &sig.decl, @@ -968,7 +968,7 @@ pub fn walk_impl_item<'v, V: Visitor<'v>>(visitor: &mut V, impl_item: &'v ImplIt visitor.visit_ty(ty); visitor.visit_nested_body(body); } - ImplItemKind::Method(ref sig, body_id) => { + ImplItemKind::Fn(ref sig, body_id) => { visitor.visit_fn( FnKind::Method(impl_item.ident, sig, Some(&impl_item.vis), &impl_item.attrs), &sig.decl, diff --git a/src/librustc_hir/print.rs b/src/librustc_hir/print.rs index 1a2c3a38565c8..4e9618b7676e8 100644 --- a/src/librustc_hir/print.rs +++ b/src/librustc_hir/print.rs @@ -886,13 +886,13 @@ impl<'a> State<'a> { Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited }; self.print_associated_const(ti.ident, &ty, default, &vis); } - hir::TraitItemKind::Fn(ref sig, hir::TraitMethod::Required(ref arg_names)) => { + hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref arg_names)) => { let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited }; self.print_method_sig(ti.ident, sig, &ti.generics, &vis, arg_names, None); self.s.word(";"); } - hir::TraitItemKind::Fn(ref sig, hir::TraitMethod::Provided(body)) => { + hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => { let vis = Spanned { span: rustc_span::DUMMY_SP, node: hir::VisibilityKind::Inherited }; self.head(""); @@ -925,7 +925,7 @@ impl<'a> State<'a> { hir::ImplItemKind::Const(ref ty, expr) => { self.print_associated_const(ii.ident, &ty, Some(expr), &ii.vis); } - hir::ImplItemKind::Method(ref sig, body) => { + hir::ImplItemKind::Fn(ref sig, body) => { self.head(""); self.print_method_sig(ii.ident, sig, &ii.generics, &ii.vis, &[], Some(body)); self.nbsp(); diff --git a/src/librustc_hir/target.rs b/src/librustc_hir/target.rs index b7bc555d7b410..3a4485a1b17fd 100644 --- a/src/librustc_hir/target.rs +++ b/src/librustc_hir/target.rs @@ -105,10 +105,10 @@ impl Target { pub fn from_trait_item(trait_item: &TraitItem<'_>) -> Target { match trait_item.kind { TraitItemKind::Const(..) => Target::AssocConst, - TraitItemKind::Fn(_, hir::TraitMethod::Required(_)) => { + TraitItemKind::Fn(_, hir::TraitFn::Required(_)) => { Target::Method(MethodKind::Trait { body: false }) } - TraitItemKind::Fn(_, hir::TraitMethod::Provided(_)) => { + TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => { Target::Method(MethodKind::Trait { body: true }) } TraitItemKind::Type(..) => Target::AssocTy, diff --git a/src/librustc_incremental/persist/dirty_clean.rs b/src/librustc_incremental/persist/dirty_clean.rs index cfc0a5e1498c8..df5fd110db9b6 100644 --- a/src/librustc_incremental/persist/dirty_clean.rs +++ b/src/librustc_incremental/persist/dirty_clean.rs @@ -333,7 +333,7 @@ impl DirtyCleanVisitor<'tcx> { TraitItemKind::Type(..) => ("NodeTraitType", LABELS_CONST_IN_TRAIT), }, HirNode::ImplItem(item) => match item.kind { - ImplItemKind::Method(..) => ("Node::ImplItem", LABELS_FN_IN_IMPL), + ImplItemKind::Fn(..) => ("Node::ImplItem", LABELS_FN_IN_IMPL), ImplItemKind::Const(..) => ("NodeImplConst", LABELS_CONST_IN_IMPL), ImplItemKind::TyAlias(..) => ("NodeImplType", LABELS_CONST_IN_IMPL), ImplItemKind::OpaqueTy(..) => ("NodeImplType", LABELS_CONST_IN_IMPL), diff --git a/src/librustc_infer/infer/error_reporting/mod.rs b/src/librustc_infer/infer/error_reporting/mod.rs index 4a39403f211cc..a544381f33da1 100644 --- a/src/librustc_infer/infer/error_reporting/mod.rs +++ b/src/librustc_infer/infer/error_reporting/mod.rs @@ -275,7 +275,7 @@ fn trait_item_scope_tag(item: &hir::TraitItem<'_>) -> &'static str { fn impl_item_scope_tag(item: &hir::ImplItem<'_>) -> &'static str { match item.kind { - hir::ImplItemKind::Method(..) => "method body", + hir::ImplItemKind::Fn(..) => "method body", hir::ImplItemKind::Const(..) | hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(..) => "associated item", diff --git a/src/librustc_infer/infer/error_reporting/nice_region_error/find_anon_type.rs b/src/librustc_infer/infer/error_reporting/nice_region_error/find_anon_type.rs index 47d6f5ccbb16d..15acf632b2c98 100644 --- a/src/librustc_infer/infer/error_reporting/nice_region_error/find_anon_type.rs +++ b/src/librustc_infer/infer/error_reporting/nice_region_error/find_anon_type.rs @@ -37,7 +37,7 @@ impl<'a, 'tcx> NiceRegionError<'a, 'tcx> { .. }) | Node::ImplItem(&hir::ImplItem { - kind: hir::ImplItemKind::Method(ref m, ..), + kind: hir::ImplItemKind::Fn(ref m, ..), .. }) => &m.decl, _ => return None, diff --git a/src/librustc_lint/builtin.rs b/src/librustc_lint/builtin.rs index ab8a607072123..54b8fad393079 100644 --- a/src/librustc_lint/builtin.rs +++ b/src/librustc_lint/builtin.rs @@ -486,7 +486,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for MissingDoc { let desc = match impl_item.kind { hir::ImplItemKind::Const(..) => "an associated constant", - hir::ImplItemKind::Method(..) => "a method", + hir::ImplItemKind::Fn(..) => "a method", hir::ImplItemKind::TyAlias(_) => "an associated type", hir::ImplItemKind::OpaqueTy(_) => "an associated `impl Trait` type", }; diff --git a/src/librustc_lint/nonstandard_style.rs b/src/librustc_lint/nonstandard_style.rs index 37fefe680d7d2..afab55358d938 100644 --- a/src/librustc_lint/nonstandard_style.rs +++ b/src/librustc_lint/nonstandard_style.rs @@ -343,7 +343,7 @@ impl<'a, 'tcx> LateLintPass<'a, 'tcx> for NonSnakeCase { } fn check_trait_item(&mut self, cx: &LateContext<'_, '_>, item: &hir::TraitItem<'_>) { - if let hir::TraitItemKind::Fn(_, hir::TraitMethod::Required(pnames)) = item.kind { + if let hir::TraitItemKind::Fn(_, hir::TraitFn::Required(pnames)) = item.kind { self.check_snake_case(cx, "trait method", &item.ident); for param_name in pnames { self.check_snake_case(cx, "variable", param_name); diff --git a/src/librustc_metadata/rmeta/decoder.rs b/src/librustc_metadata/rmeta/decoder.rs index 7126f86c326c6..b37e339bab3fc 100644 --- a/src/librustc_metadata/rmeta/decoder.rs +++ b/src/librustc_metadata/rmeta/decoder.rs @@ -505,7 +505,7 @@ impl EntryKind { EntryKind::Struct(_, _) => DefKind::Struct, EntryKind::Union(_, _) => DefKind::Union, EntryKind::Fn(_) | EntryKind::ForeignFn(_) => DefKind::Fn, - EntryKind::Method(_) => DefKind::AssocFn, + EntryKind::AssocFn(_) => DefKind::AssocFn, EntryKind::Type => DefKind::TyAlias, EntryKind::TypeParam => DefKind::TyParam, EntryKind::ConstParam => DefKind::ConstParam, @@ -1067,7 +1067,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { let (kind, container, has_self) = match self.kind(id) { EntryKind::AssocConst(container, _, _) => (ty::AssocKind::Const, container, false), - EntryKind::Method(data) => { + EntryKind::AssocFn(data) => { let data = data.decode(self); (ty::AssocKind::Method, data.container, data.has_self) } @@ -1249,7 +1249,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { fn get_fn_param_names(&self, id: DefIndex) -> Vec { let param_names = match self.kind(id) { EntryKind::Fn(data) | EntryKind::ForeignFn(data) => data.decode(self).param_names, - EntryKind::Method(data) => data.decode(self).fn_data.param_names, + EntryKind::AssocFn(data) => data.decode(self).fn_data.param_names, _ => Lazy::empty(), }; param_names.decode(self).collect() @@ -1286,7 +1286,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { // don't serialize constness for tuple variant and tuple struct constructors. fn is_const_fn_raw(&self, id: DefIndex) -> bool { let constness = match self.kind(id) { - EntryKind::Method(data) => data.decode(self).fn_data.constness, + EntryKind::AssocFn(data) => data.decode(self).fn_data.constness, EntryKind::Fn(data) => data.decode(self).constness, // Some intrinsics can be const fn. While we could recompute this (at least until we // stop having hardcoded whitelists and move to stability attributes), it seems cleaner @@ -1301,7 +1301,7 @@ impl<'a, 'tcx> CrateMetadataRef<'a> { fn asyncness(&self, id: DefIndex) -> hir::IsAsync { match self.kind(id) { EntryKind::Fn(data) => data.decode(self).asyncness, - EntryKind::Method(data) => data.decode(self).fn_data.asyncness, + EntryKind::AssocFn(data) => data.decode(self).fn_data.asyncness, EntryKind::ForeignFn(data) => data.decode(self).asyncness, _ => bug!("asyncness: expected function kind"), } diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs index 8b589f70651e4..441a4afe197aa 100644 --- a/src/librustc_metadata/rmeta/encoder.rs +++ b/src/librustc_metadata/rmeta/encoder.rs @@ -807,10 +807,10 @@ impl EncodeContext<'tcx> { ty::AssocKind::Method => { let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind { let param_names = match *m { - hir::TraitMethod::Required(ref names) => { + hir::TraitFn::Required(ref names) => { self.encode_fn_param_names(names) } - hir::TraitMethod::Provided(body) => { + hir::TraitFn::Provided(body) => { self.encode_fn_param_names_for_body(body) } }; @@ -822,7 +822,7 @@ impl EncodeContext<'tcx> { } else { bug!() }; - EntryKind::Method(self.lazy(MethodData { + EntryKind::AssocFn(self.lazy(MethodData { fn_data, container, has_self: trait_item.method_has_self_argument, @@ -894,7 +894,7 @@ impl EncodeContext<'tcx> { } } ty::AssocKind::Method => { - let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.kind { + let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind { FnData { asyncness: sig.header.asyncness, constness: sig.header.constness, @@ -903,7 +903,7 @@ impl EncodeContext<'tcx> { } else { bug!() }; - EntryKind::Method(self.lazy(MethodData { + EntryKind::AssocFn(self.lazy(MethodData { fn_data, container, has_self: impl_item.method_has_self_argument, @@ -928,7 +928,7 @@ impl EncodeContext<'tcx> { self.encode_inferred_outlives(def_id); let mir = match ast_item.kind { hir::ImplItemKind::Const(..) => true, - hir::ImplItemKind::Method(ref sig, _) => { + hir::ImplItemKind::Fn(ref sig, _) => { let generics = self.tcx.generics_of(def_id); let needs_inline = (generics.requires_monomorphization(self.tcx) || tcx.codegen_fn_attrs(def_id).requests_inline()) diff --git a/src/librustc_metadata/rmeta/mod.rs b/src/librustc_metadata/rmeta/mod.rs index 152bb257fa22c..55723ec08faa7 100644 --- a/src/librustc_metadata/rmeta/mod.rs +++ b/src/librustc_metadata/rmeta/mod.rs @@ -305,7 +305,7 @@ enum EntryKind { Generator(hir::GeneratorKind), Trait(Lazy), Impl(Lazy), - Method(Lazy), + AssocFn(Lazy), AssocType(AssocContainer), AssocOpaqueTy(AssocContainer), AssocConst(AssocContainer, mir::ConstQualifs, Lazy), diff --git a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs index 5d22ef46c41b1..c462f93414874 100644 --- a/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs +++ b/src/librustc_mir/borrow_check/diagnostics/mutability_errors.rs @@ -485,7 +485,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { })) | Some(hir::Node::ImplItem(hir::ImplItem { ident, - kind: hir::ImplItemKind::Method(sig, _), + kind: hir::ImplItemKind::Fn(sig, _), .. })) => Some( arg_pos @@ -527,7 +527,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { }) | hir::Node::ImplItem(hir::ImplItem { ident, - kind: hir::ImplItemKind::Method(sig, _), + kind: hir::ImplItemKind::Fn(sig, _), .. }) => { err.span_label(ident.span, ""); diff --git a/src/librustc_mir/borrow_check/diagnostics/region_name.rs b/src/librustc_mir/borrow_check/diagnostics/region_name.rs index 01ace74287622..7103fc596c922 100644 --- a/src/librustc_mir/borrow_check/diagnostics/region_name.rs +++ b/src/librustc_mir/borrow_check/diagnostics/region_name.rs @@ -651,7 +651,7 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> { if gen_move.is_some() { " of generator" } else { " of closure" }, ), hir::Node::ImplItem(hir::ImplItem { - kind: hir::ImplItemKind::Method(method_sig, _), + kind: hir::ImplItemKind::Fn(method_sig, _), .. }) => (method_sig.decl.output.span(), ""), _ => (self.body.span, ""), diff --git a/src/librustc_mir/monomorphize/collector.rs b/src/librustc_mir/monomorphize/collector.rs index 862a7ef1e73c0..8892794ffa9d9 100644 --- a/src/librustc_mir/monomorphize/collector.rs +++ b/src/librustc_mir/monomorphize/collector.rs @@ -983,7 +983,7 @@ impl ItemLikeVisitor<'v> for RootCollector<'_, 'v> { fn visit_impl_item(&mut self, ii: &'v hir::ImplItem<'v>) { match ii.kind { - hir::ImplItemKind::Method(hir::FnSig { .. }, _) => { + hir::ImplItemKind::Fn(hir::FnSig { .. }, _) => { let def_id = self.tcx.hir().local_def_id(ii.hir_id); self.push_if_root(def_id); } diff --git a/src/librustc_mir_build/build/mod.rs b/src/librustc_mir_build/build/mod.rs index c6bc86942957c..821c4d68c7e8a 100644 --- a/src/librustc_mir_build/build/mod.rs +++ b/src/librustc_mir_build/build/mod.rs @@ -39,12 +39,12 @@ fn mir_build(tcx: TyCtxt<'_>, def_id: DefId) -> BodyAndCache<'_> { .. }) | Node::ImplItem(hir::ImplItem { - kind: hir::ImplItemKind::Method(hir::FnSig { decl, .. }, body_id), + kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id), .. }) | Node::TraitItem(hir::TraitItem { kind: - hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitMethod::Provided(body_id)), + hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)), .. }) => (*body_id, decl.output.span()), Node::Item(hir::Item { kind: hir::ItemKind::Static(ty, _, body_id), .. }) diff --git a/src/librustc_passes/check_attr.rs b/src/librustc_passes/check_attr.rs index 702872400c45e..373b7c56d3802 100644 --- a/src/librustc_passes/check_attr.rs +++ b/src/librustc_passes/check_attr.rs @@ -25,7 +25,7 @@ use rustc_span::Span; fn target_from_impl_item<'tcx>(tcx: TyCtxt<'tcx>, impl_item: &hir::ImplItem<'_>) -> Target { match impl_item.kind { hir::ImplItemKind::Const(..) => Target::AssocConst, - hir::ImplItemKind::Method(..) => { + hir::ImplItemKind::Fn(..) => { let parent_hir_id = tcx.hir().get_parent_item(impl_item.hir_id); let containing_item = tcx.hir().expect_item(parent_hir_id); let containing_impl_is_for_trait = match &containing_item.kind { diff --git a/src/librustc_passes/dead.rs b/src/librustc_passes/dead.rs index 7460b8e2fe930..587b57eb3225c 100644 --- a/src/librustc_passes/dead.rs +++ b/src/librustc_passes/dead.rs @@ -391,7 +391,7 @@ impl<'v, 'k, 'tcx> ItemLikeVisitor<'v> for LifeSeeder<'k, 'tcx> { let trait_item = self.krate.trait_item(trait_item_ref.id); match trait_item.kind { hir::TraitItemKind::Const(_, Some(_)) - | hir::TraitItemKind::Fn(_, hir::TraitMethod::Provided(_)) => { + | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => { if has_allow_dead_code_or_lang_attr( self.tcx, trait_item.hir_id, @@ -661,7 +661,7 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { } self.visit_nested_body(body_id) } - hir::ImplItemKind::Method(_, body_id) => { + hir::ImplItemKind::Fn(_, body_id) => { if !self.symbol_is_live(impl_item.hir_id) { let span = self.tcx.sess.source_map().def_span(impl_item.span); self.warn_dead_code( @@ -682,11 +682,11 @@ impl Visitor<'tcx> for DeadVisitor<'tcx> { fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem<'tcx>) { match trait_item.kind { hir::TraitItemKind::Const(_, Some(body_id)) - | hir::TraitItemKind::Fn(_, hir::TraitMethod::Provided(body_id)) => { + | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => { self.visit_nested_body(body_id) } hir::TraitItemKind::Const(_, None) - | hir::TraitItemKind::Fn(_, hir::TraitMethod::Required(_)) + | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_)) | hir::TraitItemKind::Type(..) => {} } } diff --git a/src/librustc_passes/reachable.rs b/src/librustc_passes/reachable.rs index ad415ed8f62cf..4643add5ac3fd 100644 --- a/src/librustc_passes/reachable.rs +++ b/src/librustc_passes/reachable.rs @@ -53,7 +53,7 @@ fn method_might_be_inlined( if codegen_fn_attrs.requests_inline() || generics.requires_monomorphization(tcx) { return true; } - if let hir::ImplItemKind::Method(method_sig, _) = &impl_item.kind { + if let hir::ImplItemKind::Fn(method_sig, _) = &impl_item.kind { if method_sig.header.is_const() { return true; } @@ -162,14 +162,14 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { }, Some(Node::TraitItem(trait_method)) => match trait_method.kind { hir::TraitItemKind::Const(_, ref default) => default.is_some(), - hir::TraitItemKind::Fn(_, hir::TraitMethod::Provided(_)) => true, - hir::TraitItemKind::Fn(_, hir::TraitMethod::Required(_)) + hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(_)) => true, + hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_)) | hir::TraitItemKind::Type(..) => false, }, Some(Node::ImplItem(impl_item)) => { match impl_item.kind { hir::ImplItemKind::Const(..) => true, - hir::ImplItemKind::Method(..) => { + hir::ImplItemKind::Fn(..) => { let attrs = self.tcx.codegen_fn_attrs(def_id); let generics = self.tcx.generics_of(def_id); if generics.requires_monomorphization(self.tcx) || attrs.requests_inline() { @@ -278,11 +278,11 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { Node::TraitItem(trait_method) => { match trait_method.kind { hir::TraitItemKind::Const(_, None) - | hir::TraitItemKind::Fn(_, hir::TraitMethod::Required(_)) => { + | hir::TraitItemKind::Fn(_, hir::TraitFn::Required(_)) => { // Keep going, nothing to get exported } hir::TraitItemKind::Const(_, Some(body_id)) - | hir::TraitItemKind::Fn(_, hir::TraitMethod::Provided(body_id)) => { + | hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)) => { self.visit_nested_body(body_id); } hir::TraitItemKind::Type(..) => {} @@ -292,7 +292,7 @@ impl<'a, 'tcx> ReachableContext<'a, 'tcx> { hir::ImplItemKind::Const(_, body) => { self.visit_nested_body(body); } - hir::ImplItemKind::Method(_, body) => { + hir::ImplItemKind::Fn(_, body) => { let did = self.tcx.hir().get_parent_did(search_item); if method_might_be_inlined(self.tcx, impl_item, did) { self.visit_nested_body(body) diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 28a2987301f50..bf407b82cbe21 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -1556,7 +1556,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { || items.iter().any(|impl_item_ref| { let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); match impl_item.kind { - hir::ImplItemKind::Const(..) | hir::ImplItemKind::Method(..) => { + hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) => { self.access_levels.is_reachable(impl_item_ref.id.hir_id) } hir::ImplItemKind::OpaqueTy(..) | hir::ImplItemKind::TyAlias(_) => { @@ -1578,8 +1578,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { // types in private items. let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); match impl_item.kind { - hir::ImplItemKind::Const(..) - | hir::ImplItemKind::Method(..) + hir::ImplItemKind::Const(..) | hir::ImplItemKind::Fn(..) if self .item_is_public(&impl_item.hir_id, &impl_item.vis) => { diff --git a/src/librustc_resolve/late/lifetimes.rs b/src/librustc_resolve/late/lifetimes.rs index ddee73e72a409..767ca5f887b54 100644 --- a/src/librustc_resolve/late/lifetimes.rs +++ b/src/librustc_resolve/late/lifetimes.rs @@ -771,7 +771,7 @@ impl<'a, 'tcx> Visitor<'tcx> for LifetimeContext<'a, 'tcx> { use self::hir::ImplItemKind::*; self.missing_named_lifetime_spots.push((&impl_item.generics).into()); match impl_item.kind { - Method(ref sig, _) => { + Fn(ref sig, _) => { let tcx = self.tcx; self.visit_early_late( Some(tcx.hir().get_parent_item(impl_item.hir_id)), @@ -1466,7 +1466,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } } Node::ImplItem(impl_item) => { - if let hir::ImplItemKind::Method(sig, _) = &impl_item.kind { + if let hir::ImplItemKind::Fn(sig, _) = &impl_item.kind { find_arg_use_span(sig.decl.inputs); } } @@ -1818,9 +1818,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { | Node::TraitItem(&hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. }) - | Node::ImplItem(&hir::ImplItem { - kind: hir::ImplItemKind::Method(..), .. - }) => { + | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }) => { let scope = self.tcx.hir().local_def_id(fn_id); def = Region::Free(scope, def.id().unwrap()); } @@ -2100,12 +2098,12 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { trait_items.iter().find(|ti| ti.id.hir_id == parent).map(|ti| ti.kind); } match *m { - hir::TraitMethod::Required(_) => None, - hir::TraitMethod::Provided(body) => Some(body), + hir::TraitFn::Required(_) => None, + hir::TraitFn::Provided(body) => Some(body), } } - Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Method(_, body), .. }) => { + Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body), .. }) => { if let hir::ItemKind::Impl { ref self_ty, ref items, .. } = self.tcx.hir().expect_item(self.tcx.hir().get_parent_item(parent)).kind { diff --git a/src/librustc_trait_selection/traits/error_reporting/mod.rs b/src/librustc_trait_selection/traits/error_reporting/mod.rs index abd9638bfa78b..46654a4e8b4ae 100644 --- a/src/librustc_trait_selection/traits/error_reporting/mod.rs +++ b/src/librustc_trait_selection/traits/error_reporting/mod.rs @@ -715,7 +715,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { Node::Item(&hir::Item { span, kind: hir::ItemKind::Fn(ref sig, ..), .. }) | Node::ImplItem(&hir::ImplItem { span, - kind: hir::ImplItemKind::Method(ref sig, _), + kind: hir::ImplItemKind::Fn(ref sig, _), .. }) | Node::TraitItem(&hir::TraitItem { diff --git a/src/librustc_trait_selection/traits/error_reporting/on_unimplemented.rs b/src/librustc_trait_selection/traits/error_reporting/on_unimplemented.rs index 6e3074cd3ca98..3d0dd73f03c18 100644 --- a/src/librustc_trait_selection/traits/error_reporting/on_unimplemented.rs +++ b/src/librustc_trait_selection/traits/error_reporting/on_unimplemented.rs @@ -90,11 +90,11 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { }) } hir::Node::TraitItem(hir::TraitItem { - kind: hir::TraitItemKind::Fn(_, hir::TraitMethod::Provided(body_id)), + kind: hir::TraitItemKind::Fn(_, hir::TraitFn::Provided(body_id)), .. }) => self.describe_generator(*body_id).or_else(|| Some("a trait method")), hir::Node::ImplItem(hir::ImplItem { - kind: hir::ImplItemKind::Method(sig, body_id), + kind: hir::ImplItemKind::Fn(sig, body_id), .. }) => self.describe_generator(*body_id).or_else(|| { Some(if let hir::FnHeader { asyncness: hir::IsAsync::Async, .. } = sig.header { diff --git a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs index 656c3c7e6138f..6fe6d7aab2832 100644 --- a/src/librustc_trait_selection/traits/error_reporting/suggestions.rs +++ b/src/librustc_trait_selection/traits/error_reporting/suggestions.rs @@ -203,7 +203,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> { }) | hir::Node::ImplItem(hir::ImplItem { generics, - kind: hir::ImplItemKind::Method(..), + kind: hir::ImplItemKind::Fn(..), .. }) | hir::Node::Item(hir::Item { diff --git a/src/librustc_traits/lowering/environment.rs b/src/librustc_traits/lowering/environment.rs index db392ede432e1..69d0bd0929687 100644 --- a/src/librustc_traits/lowering/environment.rs +++ b/src/librustc_traits/lowering/environment.rs @@ -190,7 +190,7 @@ crate fn environment(tcx: TyCtxt<'_>, def_id: DefId) -> Environment<'_> { }, Node::ImplItem(item) => match item.kind { - ImplItemKind::Method(..) => NodeKind::Fn, + ImplItemKind::Fn(..) => NodeKind::Fn, _ => NodeKind::Other, }, diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 1dde57124ee0a..779b87f662375 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -403,7 +403,7 @@ fn extract_spans_for_error_reporting<'a, 'tcx>( let tcx = infcx.tcx; let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap(); let (impl_m_output, impl_m_iter) = match tcx.hir().expect_impl_item(impl_m_hir_id).kind { - ImplItemKind::Method(ref impl_m_sig, _) => { + ImplItemKind::Fn(ref impl_m_sig, _) => { (&impl_m_sig.decl.output, impl_m_sig.decl.inputs.iter()) } _ => bug!("{:?} is not a method", impl_m), @@ -732,7 +732,7 @@ fn compare_number_of_method_arguments<'tcx>( }; let impl_m_hir_id = tcx.hir().as_local_hir_id(impl_m.def_id).unwrap(); let impl_span = match tcx.hir().expect_impl_item(impl_m_hir_id).kind { - ImplItemKind::Method(ref impl_m_sig, _) => { + ImplItemKind::Fn(ref impl_m_sig, _) => { let pos = if impl_number_args > 0 { impl_number_args - 1 } else { 0 }; if let Some(arg) = impl_m_sig.decl.inputs.get(pos) { if pos == 0 { @@ -873,7 +873,7 @@ fn compare_synthetic_generics<'tcx>( let impl_m = tcx.hir().as_local_hir_id(impl_m.def_id)?; let impl_m = tcx.hir().impl_item(hir::ImplItemId { hir_id: impl_m }); let input_tys = match impl_m.kind { - hir::ImplItemKind::Method(ref sig, _) => sig.decl.inputs, + hir::ImplItemKind::Fn(ref sig, _) => sig.decl.inputs, _ => unreachable!(), }; struct Visitor(Option, hir::def_id::DefId); diff --git a/src/librustc_typeck/check/method/suggest.rs b/src/librustc_typeck/check/method/suggest.rs index ef779cfa83431..3eb3624a29665 100644 --- a/src/librustc_typeck/check/method/suggest.rs +++ b/src/librustc_typeck/check/method/suggest.rs @@ -939,10 +939,10 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { })) = id.map(|id| self.tcx.hir().get(id)) { let self_first_arg = match method { - hir::TraitMethod::Required([ident, ..]) => { + hir::TraitFn::Required([ident, ..]) => { ident.name == kw::SelfLower } - hir::TraitMethod::Provided(body_id) => { + hir::TraitFn::Provided(body_id) => { match &self.tcx.hir().body(*body_id).params[..] { [hir::Param { pat: diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index d0d421746ae8f..55e395afad911 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -816,14 +816,14 @@ fn primary_body_of( }, Node::TraitItem(item) => match item.kind { hir::TraitItemKind::Const(ref ty, Some(body)) => Some((body, Some(ty), None, None)), - hir::TraitItemKind::Fn(ref sig, hir::TraitMethod::Provided(body)) => { + hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => { Some((body, None, Some(&sig.header), Some(&sig.decl))) } _ => None, }, Node::ImplItem(item) => match item.kind { hir::ImplItemKind::Const(ref ty, body) => Some((body, Some(ty), None, None)), - hir::ImplItemKind::Method(ref sig, body) => { + hir::ImplItemKind::Fn(ref sig, body) => { Some((body, None, Some(&sig.header), Some(&sig.decl))) } _ => None, @@ -1896,7 +1896,7 @@ fn check_specialization_validity<'tcx>( ) { let kind = match impl_item.kind { hir::ImplItemKind::Const(..) => ty::AssocKind::Const, - hir::ImplItemKind::Method(..) => ty::AssocKind::Method, + hir::ImplItemKind::Fn(..) => ty::AssocKind::Method, hir::ImplItemKind::OpaqueTy(..) => ty::AssocKind::OpaqueTy, hir::ImplItemKind::TyAlias(_) => ty::AssocKind::Type, }; @@ -2019,7 +2019,7 @@ fn check_impl_items_against_trait<'tcx>( err.emit() } } - hir::ImplItemKind::Method(..) => { + hir::ImplItemKind::Fn(..) => { let opt_trait_span = tcx.hir().span_if_local(ty_trait_item.def_id); if ty_trait_item.kind == ty::AssocKind::Method { compare_impl_method( @@ -4738,9 +4738,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let node = self.tcx.hir().get(self.tcx.hir().get_parent_item(id)); match node { Node::Item(&hir::Item { kind: hir::ItemKind::Fn(_, _, body_id), .. }) - | Node::ImplItem(&hir::ImplItem { - kind: hir::ImplItemKind::Method(_, body_id), .. - }) => { + | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(_, body_id), .. }) => { let body = self.tcx.hir().body(body_id); if let ExprKind::Block(block, _) = &body.value.kind { return Some(block.span); @@ -4779,7 +4777,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { }) => Some((&sig.decl, ident, true)), Node::ImplItem(&hir::ImplItem { ident, - kind: hir::ImplItemKind::Method(ref sig, ..), + kind: hir::ImplItemKind::Fn(ref sig, ..), .. }) => Some((&sig.decl, ident, false)), _ => None, @@ -4864,11 +4862,11 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { match hir.get_if_local(def_id) { Some(Node::Item(hir::Item { kind: ItemKind::Fn(.., body_id), .. })) | Some(Node::ImplItem(hir::ImplItem { - kind: hir::ImplItemKind::Method(_, body_id), + kind: hir::ImplItemKind::Fn(_, body_id), .. })) | Some(Node::TraitItem(hir::TraitItem { - kind: hir::TraitItemKind::Fn(.., hir::TraitMethod::Provided(body_id)), + kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Provided(body_id)), .. })) => { let body = hir.body(*body_id); @@ -4939,7 +4937,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { .join(", ") } Some(Node::TraitItem(hir::TraitItem { - kind: hir::TraitItemKind::Fn(.., hir::TraitMethod::Required(idents)), + kind: hir::TraitItemKind::Fn(.., hir::TraitFn::Required(idents)), .. })) => { sugg_call = idents diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index 026e68e10e04d..23826c845091f 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -248,7 +248,7 @@ pub fn check_impl_item(tcx: TyCtxt<'_>, def_id: DefId) { let impl_item = tcx.hir().expect_impl_item(hir_id); let method_sig = match impl_item.kind { - hir::ImplItemKind::Method(ref sig, _) => Some(sig), + hir::ImplItemKind::Fn(ref sig, _) => Some(sig), _ => None, }; diff --git a/src/librustc_typeck/collect.rs b/src/librustc_typeck/collect.rs index 779b30c55e12d..7594ad5c43a8d 100644 --- a/src/librustc_typeck/collect.rs +++ b/src/librustc_typeck/collect.rs @@ -745,7 +745,7 @@ fn convert_impl_item(tcx: TyCtxt<'_>, impl_item_id: hir::HirId) { tcx.predicates_of(def_id); let impl_item = tcx.hir().expect_impl_item(impl_item_id); match impl_item.kind { - hir::ImplItemKind::Method(..) => { + hir::ImplItemKind::Fn(..) => { tcx.fn_sig(def_id); } hir::ImplItemKind::TyAlias(_) | hir::ImplItemKind::OpaqueTy(_) => { @@ -1127,7 +1127,7 @@ fn has_late_bound_regions<'tcx>(tcx: TyCtxt<'tcx>, node: Node<'tcx>) -> Option None, }, Node::ImplItem(item) => match item.kind { - hir::ImplItemKind::Method(ref sig, _) => { + hir::ImplItemKind::Fn(ref sig, _) => { has_late_bound_regions(tcx, &item.generics, &sig.decl) } _ => None, @@ -1437,12 +1437,12 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: DefId) -> ty::PolyFnSig<'_> { match tcx.hir().get(hir_id) { TraitItem(hir::TraitItem { - kind: TraitItemKind::Fn(sig, TraitMethod::Provided(_)), + kind: TraitItemKind::Fn(sig, TraitFn::Provided(_)), ident, generics, .. }) - | ImplItem(hir::ImplItem { kind: ImplItemKind::Method(sig, _), ident, generics, .. }) + | ImplItem(hir::ImplItem { kind: ImplItemKind::Fn(sig, _), ident, generics, .. }) | Item(hir::Item { kind: ItemKind::Fn(sig, generics, _), ident, .. }) => { match get_infer_ret_ty(&sig.decl.output) { Some(ty) => { diff --git a/src/librustc_typeck/collect/type_of.rs b/src/librustc_typeck/collect/type_of.rs index c4a8edd86f83f..c5d3d276721ff 100644 --- a/src/librustc_typeck/collect/type_of.rs +++ b/src/librustc_typeck/collect/type_of.rs @@ -47,7 +47,7 @@ pub(super) fn type_of(tcx: TyCtxt<'_>, def_id: DefId) -> Ty<'_> { }, Node::ImplItem(item) => match item.kind { - ImplItemKind::Method(..) => { + ImplItemKind::Fn(..) => { let substs = InternalSubsts::identity_for_item(tcx, def_id); tcx.mk_fn_def(def_id, substs) } diff --git a/src/librustc_typeck/variance/constraints.rs b/src/librustc_typeck/variance/constraints.rs index fc3b7201a1e63..54f84272ae8e0 100644 --- a/src/librustc_typeck/variance/constraints.rs +++ b/src/librustc_typeck/variance/constraints.rs @@ -111,7 +111,7 @@ impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for ConstraintContext<'a, 'tcx> { } fn visit_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) { - if let hir::ImplItemKind::Method(..) = impl_item.kind { + if let hir::ImplItemKind::Fn(..) = impl_item.kind { self.visit_node_helper(impl_item.hir_id); } } diff --git a/src/librustc_typeck/variance/mod.rs b/src/librustc_typeck/variance/mod.rs index b1fcc3d3fe8f9..3cbb42bb5f309 100644 --- a/src/librustc_typeck/variance/mod.rs +++ b/src/librustc_typeck/variance/mod.rs @@ -60,7 +60,7 @@ fn variances_of(tcx: TyCtxt<'_>, item_def_id: DefId) -> &[ty::Variance] { }, Node::ImplItem(item) => match item.kind { - hir::ImplItemKind::Method(..) => {} + hir::ImplItemKind::Fn(..) => {} _ => unsupported(), }, diff --git a/src/librustc_typeck/variance/terms.rs b/src/librustc_typeck/variance/terms.rs index bd44a3eda98ce..7e6ec96b379d8 100644 --- a/src/librustc_typeck/variance/terms.rs +++ b/src/librustc_typeck/variance/terms.rs @@ -170,7 +170,7 @@ impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for TermsContext<'a, 'tcx> { } fn visit_impl_item(&mut self, impl_item: &hir::ImplItem<'_>) { - if let hir::ImplItemKind::Method(..) = impl_item.kind { + if let hir::ImplItemKind::Fn(..) = impl_item.kind { self.add_inferreds_for_item(impl_item.hir_id); } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index e2fca8f39a398..c4ad4554a0048 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -1084,10 +1084,10 @@ impl Clean for hir::TraitItem<'_> { hir::TraitItemKind::Const(ref ty, default) => { AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e))) } - hir::TraitItemKind::Fn(ref sig, hir::TraitMethod::Provided(body)) => { + hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(body)) => { MethodItem((sig, &self.generics, body, None).clean(cx)) } - hir::TraitItemKind::Fn(ref sig, hir::TraitMethod::Required(ref names)) => { + hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Required(ref names)) => { let (generics, decl) = enter_impl_trait(cx, || { (self.generics.clean(cx), (&*sig.decl, &names[..]).clean(cx)) }); @@ -1118,7 +1118,7 @@ impl Clean for hir::ImplItem<'_> { hir::ImplItemKind::Const(ref ty, expr) => { AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr))) } - hir::ImplItemKind::Method(ref sig, body) => { + hir::ImplItemKind::Fn(ref sig, body) => { MethodItem((sig, &self.generics, body, Some(self.defaultness)).clean(cx)) } hir::ImplItemKind::TyAlias(ref ty) => { From e3c15ae6bc508b754af222a4d47f756e2827cdfe Mon Sep 17 00:00:00 2001 From: Mark Mansi Date: Fri, 6 Mar 2020 18:00:46 -0600 Subject: [PATCH 19/21] update comment --- src/librustc/hir/map/mod.rs | 6 +----- src/librustc_hir/hir.rs | 2 +- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index af08eb7b04cae..55ed07a97d168 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -542,11 +542,7 @@ impl<'hir> Map<'hir> { /// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found. pub fn find(&self, hir_id: HirId) -> Option> { let node = self.get_entry(hir_id).node; - if let Node::Crate(..) = node { - None - } else { - Some(node) - } + if let Node::Crate(..) = node { None } else { Some(node) } } /// Similar to `get_parent`; returns the parent HIR Id, or just `hir_id` if there diff --git a/src/librustc_hir/hir.rs b/src/librustc_hir/hir.rs index b189ae1f13d7c..5fee6920ddfe0 100644 --- a/src/librustc_hir/hir.rs +++ b/src/librustc_hir/hir.rs @@ -1901,7 +1901,7 @@ pub enum ImplItemKind<'hir> { /// An associated constant of the given type, set to the constant result /// of the expression. Const(&'hir Ty<'hir>, BodyId), - /// A method implementation with the given signature and body. + /// An associated function implementation with the given signature and body. Fn(FnSig<'hir>, BodyId), /// An associated type. TyAlias(&'hir Ty<'hir>), From 1b92e86a1c70533d76b5ea3937bdaabba9653f2c Mon Sep 17 00:00:00 2001 From: Mark Mansi Date: Sun, 15 Mar 2020 11:19:17 -0500 Subject: [PATCH 20/21] MethodData -> AssocFnData --- src/librustc_metadata/rmeta/encoder.rs | 4 ++-- src/librustc_metadata/rmeta/mod.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/librustc_metadata/rmeta/encoder.rs b/src/librustc_metadata/rmeta/encoder.rs index 441a4afe197aa..005bebbe1e246 100644 --- a/src/librustc_metadata/rmeta/encoder.rs +++ b/src/librustc_metadata/rmeta/encoder.rs @@ -822,7 +822,7 @@ impl EncodeContext<'tcx> { } else { bug!() }; - EntryKind::AssocFn(self.lazy(MethodData { + EntryKind::AssocFn(self.lazy(AssocFnData { fn_data, container, has_self: trait_item.method_has_self_argument, @@ -903,7 +903,7 @@ impl EncodeContext<'tcx> { } else { bug!() }; - EntryKind::AssocFn(self.lazy(MethodData { + EntryKind::AssocFn(self.lazy(AssocFnData { fn_data, container, has_self: impl_item.method_has_self_argument, diff --git a/src/librustc_metadata/rmeta/mod.rs b/src/librustc_metadata/rmeta/mod.rs index 55723ec08faa7..43a1515da32ce 100644 --- a/src/librustc_metadata/rmeta/mod.rs +++ b/src/librustc_metadata/rmeta/mod.rs @@ -305,7 +305,7 @@ enum EntryKind { Generator(hir::GeneratorKind), Trait(Lazy), Impl(Lazy), - AssocFn(Lazy), + AssocFn(Lazy), AssocType(AssocContainer), AssocOpaqueTy(AssocContainer), AssocConst(AssocContainer, mir::ConstQualifs, Lazy), @@ -392,7 +392,7 @@ impl AssocContainer { } #[derive(RustcEncodable, RustcDecodable)] -struct MethodData { +struct AssocFnData { fn_data: FnData, container: AssocContainer, has_self: bool, From 2c2d41dc000714ed3b8b734e608862ff6c74a8d4 Mon Sep 17 00:00:00 2001 From: mark Date: Sun, 15 Mar 2020 23:31:17 -0500 Subject: [PATCH 21/21] make article_and_description primarily use def_kind --- src/librustc/ty/context.rs | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/src/librustc/ty/context.rs b/src/librustc/ty/context.rs index 6fab55e9fd935..ada14ec4d0b25 100644 --- a/src/librustc/ty/context.rs +++ b/src/librustc/ty/context.rs @@ -1515,20 +1515,21 @@ impl<'tcx> TyCtxt<'tcx> { /// Returns a displayable description and article for the given `def_id` (e.g. `("a", "struct")`). pub fn article_and_description(&self, def_id: DefId) -> (&'static str, &'static str) { - match self.def_key(def_id).disambiguated_data.data { - DefPathData::TypeNs(..) | DefPathData::ValueNs(..) | DefPathData::MacroNs(..) => { - let kind = self.def_kind(def_id).unwrap(); - (kind.article(), kind.descr(def_id)) - } - DefPathData::ClosureExpr => match self.generator_kind(def_id) { - None => ("a", "closure"), - Some(rustc_hir::GeneratorKind::Async(..)) => ("an", "async closure"), - Some(rustc_hir::GeneratorKind::Gen) => ("a", "generator"), - }, - DefPathData::LifetimeNs(..) => ("a", "lifetime"), - DefPathData::Impl => ("an", "implementation"), - _ => bug!("article_and_description called on def_id {:?}", def_id), - } + self.def_kind(def_id) + .map(|def_kind| (def_kind.article(), def_kind.descr(def_id))) + .unwrap_or_else(|| match self.def_key(def_id).disambiguated_data.data { + DefPathData::ClosureExpr => match self.generator_kind(def_id) { + None => ("a", "closure"), + Some(rustc_hir::GeneratorKind::Async(..)) => ("an", "async closure"), + Some(rustc_hir::GeneratorKind::Gen) => ("a", "generator"), + }, + DefPathData::LifetimeNs(..) => ("a", "lifetime"), + DefPathData::Impl => ("an", "implementation"), + DefPathData::TypeNs(..) | DefPathData::ValueNs(..) | DefPathData::MacroNs(..) => { + unreachable!() + } + _ => bug!("article_and_description called on def_id {:?}", def_id), + }) } }