From d0873c7a11e71a46ad58c1d152fb0599281d98df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20Kr=C3=BCger?= Date: Mon, 12 Feb 2024 16:24:31 +0100 Subject: [PATCH 01/18] constify a couple thread_local statics --- compiler/rustc_data_structures/src/sync/worker_local.rs | 2 +- compiler/rustc_errors/src/markdown/term.rs | 4 ++-- library/proc_macro/src/bridge/client.rs | 2 +- library/proc_macro/src/bridge/server.rs | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/compiler/rustc_data_structures/src/sync/worker_local.rs b/compiler/rustc_data_structures/src/sync/worker_local.rs index b34d3dd904400..ba9f88b912eef 100644 --- a/compiler/rustc_data_structures/src/sync/worker_local.rs +++ b/compiler/rustc_data_structures/src/sync/worker_local.rs @@ -42,7 +42,7 @@ pub struct Registry(Arc); thread_local! { /// The registry associated with the thread. /// This allows the `WorkerLocal` type to clone the registry in its constructor. - static REGISTRY: OnceCell = OnceCell::new(); + static REGISTRY: OnceCell = const { OnceCell::new() }; } struct ThreadData { diff --git a/compiler/rustc_errors/src/markdown/term.rs b/compiler/rustc_errors/src/markdown/term.rs index 88c3c8b9ff2c4..06c1333d93dd0 100644 --- a/compiler/rustc_errors/src/markdown/term.rs +++ b/compiler/rustc_errors/src/markdown/term.rs @@ -9,9 +9,9 @@ const DEFAULT_COLUMN_WIDTH: usize = 140; thread_local! { /// Track the position of viewable characters in our buffer - static CURSOR: Cell = Cell::new(0); + static CURSOR: Cell = const { Cell::new(0) }; /// Width of the terminal - static WIDTH: Cell = Cell::new(DEFAULT_COLUMN_WIDTH); + static WIDTH: Cell = const { Cell::new(DEFAULT_COLUMN_WIDTH) }; } /// Print to terminal output to a buffer diff --git a/library/proc_macro/src/bridge/client.rs b/library/proc_macro/src/bridge/client.rs index 9255c3abc8a02..b6a75f72c749e 100644 --- a/library/proc_macro/src/bridge/client.rs +++ b/library/proc_macro/src/bridge/client.rs @@ -284,7 +284,7 @@ impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL { thread_local! { static BRIDGE_STATE: scoped_cell::ScopedCell = - scoped_cell::ScopedCell::new(BridgeState::NotConnected); + const { scoped_cell::ScopedCell::new(BridgeState::NotConnected) }; } impl BridgeState<'_> { diff --git a/library/proc_macro/src/bridge/server.rs b/library/proc_macro/src/bridge/server.rs index 2ea87d866ff3e..eee64e69b37b1 100644 --- a/library/proc_macro/src/bridge/server.rs +++ b/library/proc_macro/src/bridge/server.rs @@ -152,7 +152,7 @@ thread_local! { /// This is required as the thread-local state in the proc_macro client does /// not handle being re-entered, and will invalidate all `Symbol`s when /// entering a nested macro. - static ALREADY_RUNNING_SAME_THREAD: Cell = Cell::new(false); + static ALREADY_RUNNING_SAME_THREAD: Cell = const { Cell::new(false) }; } /// Keep `ALREADY_RUNNING_SAME_THREAD` (see also its documentation) From e4781115f2a5e50d60673d5c64d49182fc190247 Mon Sep 17 00:00:00 2001 From: Lukas Bergdoll Date: Wed, 28 Feb 2024 11:51:27 +0100 Subject: [PATCH 02/18] Improve assert_matches! documentation This new documentation tries to avoid to limit the impact of the conceptual pitfall, that the if guard relaxes the constraint, when really it tightens it. This is achieved by changing the text and examples. The previous documentation also chose a rather weird and non-representative example for the if guard, that made it needlessly complicated to understand. --- library/core/src/macros/mod.rs | 79 +++++++++++++++++++++------------- 1 file changed, 50 insertions(+), 29 deletions(-) diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index d818889f36402..949b07dfb77d2 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -112,16 +112,19 @@ macro_rules! assert_ne { }; } -/// Asserts that an expression matches any of the given patterns. +/// Asserts that an expression matches the provided pattern. /// -/// Like in a `match` expression, the pattern can be optionally followed by `if` -/// and a guard expression that has access to names bound by the pattern. +/// This macro is generally preferable to `assert!(matches!(value, pattern))`, because it can print +/// the debug representation, of the actual value shape that did not meet expectation. In contrast +/// using [`assert!`] will only print that the expectation was not met, but not why. /// -/// On panic, this macro will print the value of the expression with its -/// debug representation. +/// The pattern syntax is exactly the same as found in a match arm and the [`matches!`] macro. The +/// optional if guard can be used to add additional checks that must be true for the matched value, +/// otherwise this macro will panic. /// -/// Like [`assert!`], this macro has a second form, where a custom -/// panic message can be provided. +/// On panic, this macro will print the value of the expression with its debug representation. +/// +/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided. /// /// # Examples /// @@ -130,13 +133,20 @@ macro_rules! assert_ne { /// /// use std::assert_matches::assert_matches; /// -/// let a = 1u32.checked_add(2); -/// let b = 1u32.checked_sub(2); +/// let a = Some(345); +/// let b = Some(56); /// assert_matches!(a, Some(_)); -/// assert_matches!(b, None); +/// assert_matches!(b, Some(_)); +/// +/// assert_matches!(a, Some(345)); +/// assert_matches!(a, Some(345) | None); +/// +/// // assert_matches!(a, None); // panics +/// // assert_matches!(b, Some(345)); // panics +/// // assert_matches!(b, Some(345) | None); // panics /// -/// let c = Ok("abc".to_string()); -/// assert_matches!(c, Ok(x) | Err(x) if x.len() < 100); +/// assert_matches!(a, Some(x) if x > 100); +/// // assert_matches!(a, Some(x) if x < 100); // panics /// ``` #[unstable(feature = "assert_matches", issue = "82775")] #[allow_internal_unstable(panic_internals)] @@ -369,21 +379,25 @@ macro_rules! debug_assert_ne { }; } -/// Asserts that an expression matches any of the given patterns. +/// Asserts that an expression matches the provided pattern. /// -/// Like in a `match` expression, the pattern can be optionally followed by `if` -/// and a guard expression that has access to names bound by the pattern. +/// This macro is generally preferable to `debug_assert!(matches!(value, pattern))`, because it can +/// print the debug representation, of the actual value shape that did not meet expectation. In +/// contrast using [`debug_assert!`] will only print that the expectation was not met, but not why. +/// +/// The pattern syntax is exactly the same as found in a match arm and the [`matches!`] macro. The +/// optional if guard can be used to add additional checks that must be true for the matched value, +/// otherwise this macro will panic. /// -/// On panic, this macro will print the value of the expression with its -/// debug representation. +/// On panic, this macro will print the value of the expression with its debug representation. /// -/// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only -/// enabled in non optimized builds by default. An optimized build will not -/// execute `debug_assert_matches!` statements unless `-C debug-assertions` is -/// passed to the compiler. This makes `debug_assert_matches!` useful for -/// checks that are too expensive to be present in a release build but may be -/// helpful during development. The result of expanding `debug_assert_matches!` -/// is always type checked. +/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided. +/// +/// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only enabled in non optimized +/// builds by default. An optimized build will not execute `debug_assert_matches!` statements unless +/// `-C debug-assertions` is passed to the compiler. This makes `debug_assert_matches!` useful for +/// checks that are too expensive to be present in a release build but may be helpful during +/// development. The result of expanding `debug_assert_matches!` is always type checked. /// /// # Examples /// @@ -392,13 +406,20 @@ macro_rules! debug_assert_ne { /// /// use std::assert_matches::debug_assert_matches; /// -/// let a = 1u32.checked_add(2); -/// let b = 1u32.checked_sub(2); +/// let a = Some(345); +/// let b = Some(56); /// debug_assert_matches!(a, Some(_)); -/// debug_assert_matches!(b, None); +/// debug_assert_matches!(b, Some(_)); +/// +/// debug_assert_matches!(a, Some(345)); +/// debug_assert_matches!(a, Some(345) | None); +/// +/// // debug_assert_matches!(a, None); // panics +/// // debug_assert_matches!(b, Some(345)); // panics +/// // debug_assert_matches!(b, Some(345) | None); // panics /// -/// let c = Ok("abc".to_string()); -/// debug_assert_matches!(c, Ok(x) | Err(x) if x.len() < 100); +/// debug_assert_matches!(a, Some(x) if x > 100); +/// // debug_assert_matches!(a, Some(x) if x < 100); // panics /// ``` #[unstable(feature = "assert_matches", issue = "82775")] #[allow_internal_unstable(assert_matches)] From d2495facb14b6e79b70d98847fd8dfd6f0023e70 Mon Sep 17 00:00:00 2001 From: Lukas Bergdoll Date: Thu, 29 Feb 2024 09:52:02 +0100 Subject: [PATCH 03/18] Drop link to matches macro and link matches macro to assert_matches. --- library/core/src/macros/mod.rs | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 949b07dfb77d2..62ff3181ef801 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -118,7 +118,7 @@ macro_rules! assert_ne { /// the debug representation, of the actual value shape that did not meet expectation. In contrast /// using [`assert!`] will only print that the expectation was not met, but not why. /// -/// The pattern syntax is exactly the same as found in a match arm and the [`matches!`] macro. The +/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The /// optional if guard can be used to add additional checks that must be true for the matched value, /// otherwise this macro will panic. /// @@ -385,7 +385,7 @@ macro_rules! debug_assert_ne { /// print the debug representation, of the actual value shape that did not meet expectation. In /// contrast using [`debug_assert!`] will only print that the expectation was not met, but not why. /// -/// The pattern syntax is exactly the same as found in a match arm and the [`matches!`] macro. The +/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The /// optional if guard can be used to add additional checks that must be true for the matched value, /// otherwise this macro will panic. /// @@ -430,10 +430,15 @@ pub macro debug_assert_matches($($arg:tt)*) { } } -/// Returns whether the given expression matches any of the given patterns. +/// Returns whether the given expression matches the provided pattern. /// -/// Like in a `match` expression, the pattern can be optionally followed by `if` -/// and a guard expression that has access to names bound by the pattern. +/// The pattern syntax is exactly the same as found in a match arm. The optional if guard can be +/// used to add additional checks that must be true for the matched value, otherwise this macro will +/// return `false`. +/// +/// When testing that a value matches a pattern, it's generally preferable to use +/// [`assert_matches!`] as it will print the debug representation of the value if the assertion +/// fails. /// /// # Examples /// From d6438f526681703641610549910e9db5d1d5a392 Mon Sep 17 00:00:00 2001 From: Lukas Bergdoll Date: Sat, 2 Mar 2024 14:07:25 +0100 Subject: [PATCH 04/18] Apply review comments --- library/core/src/macros/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 62ff3181ef801..3e25418f14fe5 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -115,7 +115,7 @@ macro_rules! assert_ne { /// Asserts that an expression matches the provided pattern. /// /// This macro is generally preferable to `assert!(matches!(value, pattern))`, because it can print -/// the debug representation, of the actual value shape that did not meet expectation. In contrast +/// the debug representation, of the actual value shape that did not meet expectation. In contrast, /// using [`assert!`] will only print that the expectation was not met, but not why. /// /// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The @@ -383,7 +383,7 @@ macro_rules! debug_assert_ne { /// /// This macro is generally preferable to `debug_assert!(matches!(value, pattern))`, because it can /// print the debug representation, of the actual value shape that did not meet expectation. In -/// contrast using [`debug_assert!`] will only print that the expectation was not met, but not why. +/// contrast, using [`debug_assert!`] will only print that the expectation was not met, but not why. /// /// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The /// optional if guard can be used to add additional checks that must be true for the matched value, From fb2b918866e0457857c17f71911df31da1d2dac3 Mon Sep 17 00:00:00 2001 From: Jonas Pleyer Date: Sun, 3 Mar 2024 15:21:39 +0100 Subject: [PATCH 05/18] Small enhancement to description of From trait - fix small typo - avoid repetition of formulations --- library/core/src/convert/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/convert/mod.rs b/library/core/src/convert/mod.rs index 85740dce8668c..4dddf92b3e0be 100644 --- a/library/core/src/convert/mod.rs +++ b/library/core/src/convert/mod.rs @@ -466,9 +466,9 @@ pub trait Into: Sized { /// Prefer using [`Into`] over using `From` when specifying trait bounds on a generic function. /// This way, types that directly implement [`Into`] can be used as arguments as well. /// -/// The `From` is also very useful when performing error handling. When constructing a function +/// The `From` trait is also very useful when performing error handling. When constructing a function /// that is capable of failing, the return type will generally be of the form `Result`. -/// The `From` trait simplifies error handling by allowing a function to return a single error type +/// It simplifies error handling by allowing a function to return a single error type /// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more /// details. /// From c45f0a977abc021ad3454930e2728d815def4938 Mon Sep 17 00:00:00 2001 From: Lukas Bergdoll Date: Sun, 3 Mar 2024 15:30:46 +0100 Subject: [PATCH 06/18] Apply suggestions from code review Co-authored-by: Josh Stone --- library/core/src/macros/mod.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/library/core/src/macros/mod.rs b/library/core/src/macros/mod.rs index 3e25418f14fe5..643968c35e849 100644 --- a/library/core/src/macros/mod.rs +++ b/library/core/src/macros/mod.rs @@ -115,8 +115,8 @@ macro_rules! assert_ne { /// Asserts that an expression matches the provided pattern. /// /// This macro is generally preferable to `assert!(matches!(value, pattern))`, because it can print -/// the debug representation, of the actual value shape that did not meet expectation. In contrast, -/// using [`assert!`] will only print that the expectation was not met, but not why. +/// the debug representation of the actual value shape that did not meet expectations. In contrast, +/// using [`assert!`] will only print that expectations were not met, but not why. /// /// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The /// optional if guard can be used to add additional checks that must be true for the matched value, @@ -382,8 +382,8 @@ macro_rules! debug_assert_ne { /// Asserts that an expression matches the provided pattern. /// /// This macro is generally preferable to `debug_assert!(matches!(value, pattern))`, because it can -/// print the debug representation, of the actual value shape that did not meet expectation. In -/// contrast, using [`debug_assert!`] will only print that the expectation was not met, but not why. +/// print the debug representation of the actual value shape that did not meet expectations. In +/// contrast, using [`debug_assert!`] will only print that expectations were not met, but not why. /// /// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The /// optional if guard can be used to add additional checks that must be true for the matched value, From aa38c26bbf84aa36e280cc120736c47a36cb467d Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Wed, 20 Dec 2023 15:05:30 +1100 Subject: [PATCH 07/18] Tweak `parse_asm_args`. It doesn't need a `Parser` and a `ParseSess`, because the former contains the latter. --- compiler/rustc_builtin_macros/src/asm.rs | 7 ++----- src/tools/rustfmt/src/parse/macros/asm.rs | 2 +- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index 29bf5e9f30493..359222afaeced 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -10,7 +10,6 @@ use rustc_index::bit_set::GrowableBitSet; use rustc_parse::parser::Parser; use rustc_parse_format as parse; use rustc_session::lint; -use rustc_session::parse::ParseSess; use rustc_span::symbol::Ident; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{ErrorGuaranteed, InnerSpan, Span}; @@ -36,19 +35,17 @@ fn parse_args<'a>( is_global_asm: bool, ) -> PResult<'a, AsmArgs> { let mut p = ecx.new_parser_from_tts(tts); - let sess = &ecx.sess.parse_sess; - parse_asm_args(&mut p, sess, sp, is_global_asm) + parse_asm_args(&mut p, sp, is_global_asm) } // Primarily public for rustfmt consumption. // Internal consumers should continue to leverage `expand_asm`/`expand__global_asm` pub fn parse_asm_args<'a>( p: &mut Parser<'a>, - sess: &'a ParseSess, sp: Span, is_global_asm: bool, ) -> PResult<'a, AsmArgs> { - let dcx = &sess.dcx; + let dcx = &p.sess.dcx; if p.token == token::Eof { return Err(dcx.create_err(errors::AsmRequiresTemplate { span: sp })); diff --git a/src/tools/rustfmt/src/parse/macros/asm.rs b/src/tools/rustfmt/src/parse/macros/asm.rs index 01edfab36547c..6373d0251f896 100644 --- a/src/tools/rustfmt/src/parse/macros/asm.rs +++ b/src/tools/rustfmt/src/parse/macros/asm.rs @@ -7,5 +7,5 @@ use crate::rewrite::RewriteContext; pub(crate) fn parse_asm(context: &RewriteContext<'_>, mac: &ast::MacCall) -> Option { let ts = mac.args.tokens.clone(); let mut parser = super::build_parser(context, ts); - parse_asm_args(&mut parser, context.parse_sess.inner(), mac.span(), false).ok() + parse_asm_args(&mut parser, mac.span(), false).ok() } From 3996447b37d5a061fba2f6009ec275f657467743 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 4 Mar 2024 16:18:17 +1100 Subject: [PATCH 08/18] Remove `file_path_mapping` param from `ParseSess::new`. It's always empty. --- compiler/rustc_expand/src/parse/tests.rs | 6 +----- compiler/rustc_expand/src/tests.rs | 12 ++++-------- compiler/rustc_session/src/parse.rs | 4 ++-- src/librustdoc/clean/render_macro_matchers.rs | 4 +--- tests/ui-fulldeps/mod_dir_path_canonicalized.rs | 6 +----- tests/ui-fulldeps/pprust-expr-roundtrip.rs | 4 ++-- 6 files changed, 11 insertions(+), 25 deletions(-) diff --git a/compiler/rustc_expand/src/parse/tests.rs b/compiler/rustc_expand/src/parse/tests.rs index 0e07b41b43c7d..997144e477f6e 100644 --- a/compiler/rustc_expand/src/parse/tests.rs +++ b/compiler/rustc_expand/src/parse/tests.rs @@ -14,17 +14,13 @@ use rustc_parse::new_parser_from_source_str; use rustc_parse::parser::ForceCollect; use rustc_session::parse::ParseSess; use rustc_span::create_default_session_globals_then; -use rustc_span::source_map::FilePathMapping; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{BytePos, FileName, Pos, Span}; use std::path::PathBuf; fn sess() -> ParseSess { - ParseSess::new( - vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE], - FilePathMapping::empty(), - ) + ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE]) } /// Parses an item. diff --git a/compiler/rustc_expand/src/tests.rs b/compiler/rustc_expand/src/tests.rs index b242ce795fd05..ad60e5691ef84 100644 --- a/compiler/rustc_expand/src/tests.rs +++ b/compiler/rustc_expand/src/tests.rs @@ -72,10 +72,8 @@ where /// Maps a string to tts, using a made-up filename. pub(crate) fn string_to_stream(source_str: String) -> TokenStream { - let ps = ParseSess::new( - vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE], - FilePathMapping::empty(), - ); + let ps = + ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE]); source_file_to_stream( &ps, ps.source_map().new_source_file(PathBuf::from("bogofile").into(), source_str), @@ -85,10 +83,8 @@ pub(crate) fn string_to_stream(source_str: String) -> TokenStream { /// Parses a string, returns a crate. pub(crate) fn string_to_crate(source_str: String) -> ast::Crate { - let ps = ParseSess::new( - vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE], - FilePathMapping::empty(), - ); + let ps = + ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE]); with_error_checking_parse(source_str, &ps, |p| p.parse_crate_mod()) } diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 9170b265748e1..656781353ea76 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -233,9 +233,9 @@ pub struct ParseSess { impl ParseSess { /// Used for testing. - pub fn new(locale_resources: Vec<&'static str>, file_path_mapping: FilePathMapping) -> Self { + pub fn new(locale_resources: Vec<&'static str>) -> Self { let fallback_bundle = fallback_fluent_bundle(locale_resources, false); - let sm = Lrc::new(SourceMap::new(file_path_mapping)); + let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let emitter = Box::new( HumanEmitter::new(stderr_destination(ColorConfig::Auto), fallback_bundle) .sm(Some(sm.clone())), diff --git a/src/librustdoc/clean/render_macro_matchers.rs b/src/librustdoc/clean/render_macro_matchers.rs index b6880cfc60fbf..97e094bb3fb3a 100644 --- a/src/librustdoc/clean/render_macro_matchers.rs +++ b/src/librustdoc/clean/render_macro_matchers.rs @@ -4,7 +4,6 @@ use rustc_ast_pretty::pprust::state::State as Printer; use rustc_ast_pretty::pprust::PrintState; use rustc_middle::ty::TyCtxt; use rustc_session::parse::ParseSess; -use rustc_span::source_map::FilePathMapping; use rustc_span::symbol::{kw, Ident, Symbol}; use rustc_span::Span; @@ -63,8 +62,7 @@ fn snippet_equal_to_token(tcx: TyCtxt<'_>, matcher: &TokenTree) -> Option Date: Mon, 4 Mar 2024 16:26:51 +1100 Subject: [PATCH 09/18] Move `sess` function and use it more. --- compiler/rustc_expand/src/parse/tests.rs | 8 ++------ compiler/rustc_expand/src/tests.rs | 10 ++++++---- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/compiler/rustc_expand/src/parse/tests.rs b/compiler/rustc_expand/src/parse/tests.rs index 997144e477f6e..5ffe8f3c73e6a 100644 --- a/compiler/rustc_expand/src/parse/tests.rs +++ b/compiler/rustc_expand/src/parse/tests.rs @@ -1,5 +1,6 @@ use crate::tests::{ - matches_codepattern, string_to_stream, with_error_checking_parse, with_expected_parse_error, + matches_codepattern, sess, string_to_stream, with_error_checking_parse, + with_expected_parse_error, }; use ast::token::IdentIsRaw; @@ -16,13 +17,8 @@ use rustc_session::parse::ParseSess; use rustc_span::create_default_session_globals_then; use rustc_span::symbol::{kw, sym, Symbol}; use rustc_span::{BytePos, FileName, Pos, Span}; - use std::path::PathBuf; -fn sess() -> ParseSess { - ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE]) -} - /// Parses an item. /// /// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err` diff --git a/compiler/rustc_expand/src/tests.rs b/compiler/rustc_expand/src/tests.rs index ad60e5691ef84..7d19ca13c9701 100644 --- a/compiler/rustc_expand/src/tests.rs +++ b/compiler/rustc_expand/src/tests.rs @@ -18,6 +18,10 @@ use std::path::{Path, PathBuf}; use std::str; use std::sync::{Arc, Mutex}; +pub(crate) fn sess() -> ParseSess { + ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE]) +} + /// Map string to parser (via tts). fn string_to_parser(ps: &ParseSess, source_str: String) -> Parser<'_> { new_parser_from_source_str(ps, PathBuf::from("bogofile").into(), source_str) @@ -72,8 +76,7 @@ where /// Maps a string to tts, using a made-up filename. pub(crate) fn string_to_stream(source_str: String) -> TokenStream { - let ps = - ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE]); + let ps = sess(); source_file_to_stream( &ps, ps.source_map().new_source_file(PathBuf::from("bogofile").into(), source_str), @@ -83,8 +86,7 @@ pub(crate) fn string_to_stream(source_str: String) -> TokenStream { /// Parses a string, returns a crate. pub(crate) fn string_to_crate(source_str: String) -> ast::Crate { - let ps = - ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE]); + let ps = sess(); with_error_checking_parse(source_str, &ps, |p| p.parse_crate_mod()) } From 4260f7ec679dca38911e983113a0243fb8f905dc Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 4 Mar 2024 16:32:37 +1100 Subject: [PATCH 10/18] Rename a misnamed `Session` parameter. --- compiler/rustc_expand/src/base.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 485f0e7e46deb..984c740372042 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1217,7 +1217,7 @@ impl<'a> ExtCtxt<'a> { /// /// This unifies the logic used for resolving `include_X!`. pub fn resolve_path( - parse_sess: &Session, + sess: &Session, path: impl Into, span: Span, ) -> PResult<'_, PathBuf> { @@ -1227,15 +1227,15 @@ pub fn resolve_path( // after macro expansion (that is, they are unhygienic). if !path.is_absolute() { let callsite = span.source_callsite(); - let mut result = match parse_sess.source_map().span_to_filename(callsite) { + let mut result = match sess.source_map().span_to_filename(callsite) { FileName::Real(name) => name .into_local_path() .expect("attempting to resolve a file path in an external file"), FileName::DocTest(path, _) => path, other => { - return Err(parse_sess.dcx().create_err(errors::ResolveRelativePath { + return Err(sess.dcx().create_err(errors::ResolveRelativePath { span, - path: parse_sess.source_map().filename_for_diagnostics(&other).to_string(), + path: sess.source_map().filename_for_diagnostics(&other).to_string(), })); } }; From 4146136d6dfd3a41f674b71bece81a33c74d824a Mon Sep 17 00:00:00 2001 From: Zalathar Date: Tue, 27 Feb 2024 17:43:07 +1100 Subject: [PATCH 11/18] Extract an arguments struct for `Builder::then_else_break` Most of this method's arguments are usually or always forwarded as-is to recursive invocations. Wrapping them in a dedicated struct allows us to document each struct field, and lets us use struct-update syntax to indicate which arguments are being modified when making a recursive call. --- .../rustc_mir_build/src/build/expr/into.rs | 8 +- .../rustc_mir_build/src/build/matches/mod.rs | 130 +++++++++--------- 2 files changed, 72 insertions(+), 66 deletions(-) diff --git a/compiler/rustc_mir_build/src/build/expr/into.rs b/compiler/rustc_mir_build/src/build/expr/into.rs index f2cf6fe613c33..9a6d44983520b 100644 --- a/compiler/rustc_mir_build/src/build/expr/into.rs +++ b/compiler/rustc_mir_build/src/build/expr/into.rs @@ -81,10 +81,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let then_blk = unpack!(this.then_else_break( block, cond, - Some(condition_scope), + Some(condition_scope), // Temp scope condition_scope, source_info, - true, + true, // Declare `let` bindings normally )); this.expr_into_dest(destination, then_blk, then) @@ -146,9 +146,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { this.then_else_break( block, lhs, - Some(condition_scope), + Some(condition_scope), // Temp scope condition_scope, source_info, + // This flag controls how inner `let` expressions are lowered, + // but either way there shouldn't be any of those in here. true, ) }); diff --git a/compiler/rustc_mir_build/src/build/matches/mod.rs b/compiler/rustc_mir_build/src/build/matches/mod.rs index a6273b92e5d69..29ee07f5d79b7 100644 --- a/compiler/rustc_mir_build/src/build/matches/mod.rs +++ b/compiler/rustc_mir_build/src/build/matches/mod.rs @@ -30,21 +30,55 @@ mod util; use std::borrow::Borrow; use std::mem; +/// Arguments to [`Builder::then_else_break_inner`] that are usually forwarded +/// to recursive invocations. +#[derive(Clone, Copy)] +struct ThenElseArgs { + /// Used as the temp scope for lowering `expr`. If absent (for match guards), + /// `self.local_scope()` is used. + temp_scope_override: Option, + /// Scope to pass to [`Builder::break_for_else`]. Must match the scope used + /// by the enclosing call to [`Builder::in_if_then_scope`]. + break_scope: region::Scope, + variable_source_info: SourceInfo, + /// Forwarded to [`Builder::lower_let_expr`] when lowering [`ExprKind::Let`]. + /// When false (for match guards), `let` bindings won't be declared. + declare_let_bindings: bool, +} + impl<'a, 'tcx> Builder<'a, 'tcx> { /// Lowers a condition in a way that ensures that variables bound in any let /// expressions are definitely initialized in the if body. /// - /// If `declare_bindings` is false then variables created in `let` + /// If `declare_let_bindings` is false then variables created in `let` /// expressions will not be declared. This is for if let guards on arms with /// an or pattern, where the guard is lowered multiple times. pub(crate) fn then_else_break( &mut self, - mut block: BasicBlock, + block: BasicBlock, expr_id: ExprId, temp_scope_override: Option, break_scope: region::Scope, variable_source_info: SourceInfo, - declare_bindings: bool, + declare_let_bindings: bool, + ) -> BlockAnd<()> { + self.then_else_break_inner( + block, + expr_id, + ThenElseArgs { + temp_scope_override, + break_scope, + variable_source_info, + declare_let_bindings, + }, + ) + } + + fn then_else_break_inner( + &mut self, + block: BasicBlock, // Block that the condition and branch will be lowered into + expr_id: ExprId, // Condition expression to lower + args: ThenElseArgs, ) -> BlockAnd<()> { let this = self; let expr = &this.thir[expr_id]; @@ -52,54 +86,36 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { match expr.kind { ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => { - let lhs_then_block = unpack!(this.then_else_break( - block, - lhs, - temp_scope_override, - break_scope, - variable_source_info, - declare_bindings, - )); - - let rhs_then_block = unpack!(this.then_else_break( - lhs_then_block, - rhs, - temp_scope_override, - break_scope, - variable_source_info, - declare_bindings, - )); - + let lhs_then_block = unpack!(this.then_else_break_inner(block, lhs, args)); + let rhs_then_block = unpack!(this.then_else_break_inner(lhs_then_block, rhs, args)); rhs_then_block.unit() } ExprKind::LogicalOp { op: LogicalOp::Or, lhs, rhs } => { let local_scope = this.local_scope(); let (lhs_success_block, failure_block) = this.in_if_then_scope(local_scope, expr_span, |this| { - this.then_else_break( + this.then_else_break_inner( block, lhs, - temp_scope_override, - local_scope, - variable_source_info, - true, + ThenElseArgs { + break_scope: local_scope, + declare_let_bindings: true, + ..args + }, ) }); - let rhs_success_block = unpack!(this.then_else_break( + let rhs_success_block = unpack!(this.then_else_break_inner( failure_block, rhs, - temp_scope_override, - break_scope, - variable_source_info, - true, + ThenElseArgs { declare_let_bindings: true, ..args }, )); // Make the LHS and RHS success arms converge to a common block. // (We can't just make LHS goto RHS, because `rhs_success_block` // might contain statements that we don't want on the LHS path.) let success_block = this.cfg.start_new_block(); - this.cfg.goto(lhs_success_block, variable_source_info, success_block); - this.cfg.goto(rhs_success_block, variable_source_info, success_block); + this.cfg.goto(lhs_success_block, args.variable_source_info, success_block); + this.cfg.goto(rhs_success_block, args.variable_source_info, success_block); success_block.unit() } ExprKind::Unary { op: UnOp::Not, arg } => { @@ -111,50 +127,38 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { if this.tcx.sess.instrument_coverage() { this.cfg.push_coverage_span_marker(block, this.source_info(expr_span)); } - this.then_else_break( + this.then_else_break_inner( block, arg, - temp_scope_override, - local_scope, - variable_source_info, - true, + ThenElseArgs { + break_scope: local_scope, + declare_let_bindings: true, + ..args + }, ) }); - this.break_for_else(success_block, break_scope, variable_source_info); + this.break_for_else(success_block, args.break_scope, args.variable_source_info); failure_block.unit() } ExprKind::Scope { region_scope, lint_level, value } => { let region_scope = (region_scope, this.source_info(expr_span)); this.in_scope(region_scope, lint_level, |this| { - this.then_else_break( - block, - value, - temp_scope_override, - break_scope, - variable_source_info, - declare_bindings, - ) + this.then_else_break_inner(block, value, args) }) } - ExprKind::Use { source } => this.then_else_break( - block, - source, - temp_scope_override, - break_scope, - variable_source_info, - declare_bindings, - ), + ExprKind::Use { source } => this.then_else_break_inner(block, source, args), ExprKind::Let { expr, ref pat } => this.lower_let_expr( block, expr, pat, - break_scope, - Some(variable_source_info.scope), - variable_source_info.span, - declare_bindings, + args.break_scope, + Some(args.variable_source_info.scope), + args.variable_source_info.span, + args.declare_let_bindings, ), _ => { - let temp_scope = temp_scope_override.unwrap_or_else(|| this.local_scope()); + let mut block = block; + let temp_scope = args.temp_scope_override.unwrap_or_else(|| this.local_scope()); let mutability = Mutability::Mut; let place = unpack!(block = this.as_temp(block, Some(temp_scope), expr_id, mutability)); @@ -166,7 +170,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { let source_info = this.source_info(expr_span); this.cfg.terminate(block, source_info, term); - this.break_for_else(else_block, break_scope, source_info); + this.break_for_else(else_block, args.break_scope, source_info); then_block.unit() } @@ -2105,10 +2109,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> { this.then_else_break( block, guard, - None, + None, // Use `self.local_scope()` as the temp scope match_scope, this.source_info(arm.span), - false, + false, // For guards, `let` bindings are declared separately ) }); From 9eb927e025d37c4a04c1e147e94205736f02e8c3 Mon Sep 17 00:00:00 2001 From: roblabla Date: Mon, 4 Mar 2024 09:24:41 +0100 Subject: [PATCH 12/18] Don't run test_get_os_named_thread on win7 This test won't work on windows 7, as the Thread::set_name function is not implemented there (win7 does not provide a documented mechanism to set thread names). --- library/std/src/thread/tests.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library/std/src/thread/tests.rs b/library/std/src/thread/tests.rs index efd06c8df6e29..813ede0641530 100644 --- a/library/std/src/thread/tests.rs +++ b/library/std/src/thread/tests.rs @@ -70,7 +70,7 @@ fn test_named_thread_truncation() { } #[cfg(any( - target_os = "windows", + all(target_os = "windows", not(target_vendor = "win7")), target_os = "linux", target_os = "macos", target_os = "ios", From e46306043b8e8270b1cace5bec7cd563e8ea9ae1 Mon Sep 17 00:00:00 2001 From: Jonas Pleyer <59249415+jonaspleyer@users.noreply.github.com> Date: Mon, 4 Mar 2024 10:04:46 +0100 Subject: [PATCH 13/18] include feedback from workingjubilee - Refer to trait directly - small typo in encapsulate Co-authored-by: Jubilee <46493976+workingjubilee@users.noreply.github.com> --- library/core/src/convert/mod.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/convert/mod.rs b/library/core/src/convert/mod.rs index 4dddf92b3e0be..63fd23ea9a9d3 100644 --- a/library/core/src/convert/mod.rs +++ b/library/core/src/convert/mod.rs @@ -468,8 +468,8 @@ pub trait Into: Sized { /// /// The `From` trait is also very useful when performing error handling. When constructing a function /// that is capable of failing, the return type will generally be of the form `Result`. -/// It simplifies error handling by allowing a function to return a single error type -/// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more +/// `From` simplifies error handling by allowing a function to return a single error type +/// that encapsulates multiple error types. See the "Examples" section and [the book][book] for more /// details. /// /// **Note: This trait must not fail**. The `From` trait is intended for perfect conversions. From ede25ad31966212d8f747abf33001231e63f9ab3 Mon Sep 17 00:00:00 2001 From: Raoul Strackx Date: Tue, 27 Feb 2024 16:29:21 +0100 Subject: [PATCH 14/18] Fix LVI tests after making frame pointers easily enableable --- .../cmake_plus_one_cxx_global_asm.checks | 7 ++++++- .../print.with_frame_pointers.checks | 7 +++++++ .../{print.checks => print.without_frame_pointers.checks} | 0 tests/run-make/x86_64-fortanix-unknown-sgx-lvi/script.sh | 8 +++++--- 4 files changed, 18 insertions(+), 4 deletions(-) create mode 100644 tests/run-make/x86_64-fortanix-unknown-sgx-lvi/print.with_frame_pointers.checks rename tests/run-make/x86_64-fortanix-unknown-sgx-lvi/{print.checks => print.without_frame_pointers.checks} (100%) diff --git a/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/cmake_plus_one_cxx_global_asm.checks b/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/cmake_plus_one_cxx_global_asm.checks index d4a3d4479014c..1d8fc96ad50cd 100644 --- a/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/cmake_plus_one_cxx_global_asm.checks +++ b/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/cmake_plus_one_cxx_global_asm.checks @@ -1,2 +1,7 @@ CHECK: cmake_plus_one_cxx_global_asm -CHECK: lfence +CHECK-NEXT: movl +CHECK-NEXT: lfence +CHECK-NEXT: incl +CHECK-NEXT: shlq $0x0, (%rsp) +CHECK-NEXT: lfence +CHECK-NEXT: retq diff --git a/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/print.with_frame_pointers.checks b/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/print.with_frame_pointers.checks new file mode 100644 index 0000000000000..485e20e3111f7 --- /dev/null +++ b/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/print.with_frame_pointers.checks @@ -0,0 +1,7 @@ +CHECK: print +CHECK: lfence +CHECK: popq +CHECK: popq +CHECK-NEXT: popq [[REGISTER:%[a-z]+]] +CHECK-NEXT: lfence +CHECK-NEXT: jmpq *[[REGISTER]] diff --git a/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/print.checks b/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/print.without_frame_pointers.checks similarity index 100% rename from tests/run-make/x86_64-fortanix-unknown-sgx-lvi/print.checks rename to tests/run-make/x86_64-fortanix-unknown-sgx-lvi/print.without_frame_pointers.checks diff --git a/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/script.sh b/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/script.sh index 04a34724518e8..a36ad916bebe3 100644 --- a/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/script.sh +++ b/tests/run-make/x86_64-fortanix-unknown-sgx-lvi/script.sh @@ -34,8 +34,9 @@ function check { ${enclave} > ${asm} ${filecheck} --input-file ${asm} ${checks} - if [ "${func_re}" != "rust_plus_one_global_asm" && - "${func_re}" != "cmake_plus_one_c_global_asm" ]; then + if [ "${func_re}" != "rust_plus_one_global_asm" ] && + [ "${func_re}" != "cmake_plus_one_c_global_asm" ] && + [ "${func_re}" != "cmake_plus_one_cxx_global_asm" ]; then # The assembler cannot avoid explicit `ret` instructions. Sequences # of `shlq $0x0, (%rsp); lfence; retq` are used instead. # https://www.intel.com/content/www/us/en/developer/articles/technical/ @@ -48,7 +49,8 @@ build check "unw_getcontext" unw_getcontext.checks check "__libunwind_Registers_x86_64_jumpto" jumpto.checks -check 'std::io::stdio::_print::[[:alnum:]]+' print.checks +check 'std::io::stdio::_print::[[:alnum:]]+' print.with_frame_pointers.checks || + check 'std::io::stdio::_print::[[:alnum:]]+' print.without_frame_pointers.checks check rust_plus_one_global_asm rust_plus_one_global_asm.checks check cc_plus_one_c cc_plus_one_c.checks From 05e68facbb196126d01719111296f07bc264b915 Mon Sep 17 00:00:00 2001 From: Janggun Lee Date: Mon, 4 Mar 2024 22:15:05 +0900 Subject: [PATCH 15/18] Fix comment in Atomic{Ptr,Bool}::as_ptr. --- library/core/src/sync/atomic.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/library/core/src/sync/atomic.rs b/library/core/src/sync/atomic.rs index 45193c11e1d6b..00e75ec9a2540 100644 --- a/library/core/src/sync/atomic.rs +++ b/library/core/src/sync/atomic.rs @@ -1092,7 +1092,7 @@ impl AtomicBool { /// Returns a mutable pointer to the underlying [`bool`]. /// - /// Doing non-atomic reads and writes on the resulting integer can be a data race. + /// Doing non-atomic reads and writes on the resulting boolean can be a data race. /// This method is mostly useful for FFI, where the function signature may use /// `*mut bool` instead of `&AtomicBool`. /// @@ -2031,7 +2031,7 @@ impl AtomicPtr { /// Returns a mutable pointer to the underlying pointer. /// - /// Doing non-atomic reads and writes on the resulting integer can be a data race. + /// Doing non-atomic reads and writes on the resulting pointer can be a data race. /// This method is mostly useful for FFI, where the function signature may use /// `*mut *mut T` instead of `&AtomicPtr`. /// From 1eedca8bdf0020b673957bfbb2c787583f474128 Mon Sep 17 00:00:00 2001 From: Michael Goulet Date: Tue, 27 Feb 2024 20:22:13 +0000 Subject: [PATCH 16/18] Allow a way to add constructors for rustc_type_ir types --- compiler/rustc_middle/src/ty/consts.rs | 13 ++++++++++++ compiler/rustc_middle/src/ty/context.rs | 21 ------------------- compiler/rustc_middle/src/ty/region.rs | 6 ++++++ compiler/rustc_middle/src/ty/sty.rs | 9 +++++++- .../src/canonicalizer.rs | 7 ++++--- compiler/rustc_type_ir/src/interner.rs | 18 +++++++--------- compiler/rustc_type_ir/src/lib.rs | 1 + compiler/rustc_type_ir/src/new.rs | 13 ++++++++++++ 8 files changed, 53 insertions(+), 35 deletions(-) create mode 100644 compiler/rustc_type_ir/src/new.rs diff --git a/compiler/rustc_middle/src/ty/consts.rs b/compiler/rustc_middle/src/ty/consts.rs index 5e4d899f51768..5b62c0bf931af 100644 --- a/compiler/rustc_middle/src/ty/consts.rs +++ b/compiler/rustc_middle/src/ty/consts.rs @@ -175,7 +175,20 @@ impl<'tcx> Const<'tcx> { let reported = tcx.dcx().span_delayed_bug(span, msg); Const::new_error(tcx, reported, ty) } +} +impl<'tcx> rustc_type_ir::new::Const> for Const<'tcx> { + fn new_anon_bound( + tcx: TyCtxt<'tcx>, + debruijn: ty::DebruijnIndex, + var: ty::BoundVar, + ty: Ty<'tcx>, + ) -> Self { + Const::new_bound(tcx, debruijn, var, ty) + } +} + +impl<'tcx> Const<'tcx> { /// Literals and const generic parameters are eagerly converted to a constant, everything else /// becomes `Unevaluated`. #[instrument(skip(tcx), level = "debug")] diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index b2a7f5599b643..96b4797f4fa98 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -130,27 +130,6 @@ impl<'tcx> Interner for TyCtxt<'tcx> { fn mk_canonical_var_infos(self, infos: &[ty::CanonicalVarInfo]) -> Self::CanonicalVars { self.mk_canonical_var_infos(infos) } - - fn mk_bound_ty(self, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self::Ty { - Ty::new_bound(self, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon }) - } - - fn mk_bound_region(self, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self::Region { - Region::new_bound( - self, - debruijn, - ty::BoundRegion { var, kind: ty::BoundRegionKind::BrAnon }, - ) - } - - fn mk_bound_const( - self, - debruijn: ty::DebruijnIndex, - var: ty::BoundVar, - ty: Self::Ty, - ) -> Self::Const { - Const::new_bound(self, debruijn, var, ty) - } } type InternedSet<'tcx, T> = ShardedHashMap, ()>; diff --git a/compiler/rustc_middle/src/ty/region.rs b/compiler/rustc_middle/src/ty/region.rs index 51a4a9f411c02..7abc3cd283888 100644 --- a/compiler/rustc_middle/src/ty/region.rs +++ b/compiler/rustc_middle/src/ty/region.rs @@ -136,6 +136,12 @@ impl<'tcx> Region<'tcx> { } } +impl<'tcx> rustc_type_ir::new::Region> for Region<'tcx> { + fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self { + Region::new_bound(tcx, debruijn, ty::BoundRegion { var, kind: ty::BoundRegionKind::BrAnon }) + } +} + /// Region utilities impl<'tcx> Region<'tcx> { pub fn kind(self) -> RegionKind<'tcx> { diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 53690cc58111f..03c61803572c6 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -1426,7 +1426,8 @@ impl From for BoundTy { /// Constructors for `Ty` impl<'tcx> Ty<'tcx> { - // Avoid this in favour of more specific `new_*` methods, where possible. + /// Avoid using this in favour of more specific `new_*` methods, where possible. + /// The more specific methods will often optimize their creation. #[allow(rustc::usage_of_ty_tykind)] #[inline] pub fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> { @@ -1813,6 +1814,12 @@ impl<'tcx> Ty<'tcx> { } } +impl<'tcx> rustc_type_ir::new::Ty> for Ty<'tcx> { + fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self { + Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon }) + } +} + /// Type utilities impl<'tcx> Ty<'tcx> { #[inline(always)] diff --git a/compiler/rustc_next_trait_solver/src/canonicalizer.rs b/compiler/rustc_next_trait_solver/src/canonicalizer.rs index 7b73e2aebf039..95b3006666202 100644 --- a/compiler/rustc_next_trait_solver/src/canonicalizer.rs +++ b/compiler/rustc_next_trait_solver/src/canonicalizer.rs @@ -1,6 +1,7 @@ use std::cmp::Ordering; use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable}; +use rustc_type_ir::new::{Const, Region, Ty}; use rustc_type_ir::visit::TypeVisitableExt; use rustc_type_ir::{ self as ty, Canonical, CanonicalTyVarKind, CanonicalVarInfo, CanonicalVarKind, ConstTy, @@ -293,7 +294,7 @@ impl, I: Interner> TypeFolder var }); - self.interner().mk_bound_region(self.binder_index, var) + Region::new_anon_bound(self.interner(), self.binder_index, var) } fn fold_ty(&mut self, t: I::Ty) -> I::Ty @@ -375,7 +376,7 @@ impl, I: Interner> TypeFolder }), ); - self.interner().mk_bound_ty(self.binder_index, var) + Ty::new_anon_bound(self.interner(), self.binder_index, var) } fn fold_const(&mut self, c: I::Const) -> I::Const @@ -435,6 +436,6 @@ impl, I: Interner> TypeFolder }), ); - self.interner().mk_bound_const(self.binder_index, var, c.ty()) + Const::new_anon_bound(self.interner(), self.binder_index, var, c.ty()) } } diff --git a/compiler/rustc_type_ir/src/interner.rs b/compiler/rustc_type_ir/src/interner.rs index 7d2c42a6dbe91..373540de05e0e 100644 --- a/compiler/rustc_type_ir/src/interner.rs +++ b/compiler/rustc_type_ir/src/interner.rs @@ -4,8 +4,8 @@ use std::hash::Hash; use crate::visit::{Flags, TypeSuperVisitable, TypeVisitable}; use crate::{ - BoundVar, BoundVars, CanonicalVarInfo, ConstKind, DebruijnIndex, DebugWithInfcx, RegionKind, - TyKind, UniverseIndex, + new, BoundVar, BoundVars, CanonicalVarInfo, ConstKind, DebugWithInfcx, RegionKind, TyKind, + UniverseIndex, }; pub trait Interner: Sized { @@ -34,7 +34,8 @@ pub trait Interner: Sized { + Into + IntoKind> + TypeSuperVisitable - + Flags; + + Flags + + new::Ty; type Tys: Copy + Debug + Hash + Ord + IntoIterator; type AliasTy: Copy + DebugWithInfcx + Hash + Ord; type ParamTy: Copy + Debug + Hash + Ord; @@ -56,7 +57,8 @@ pub trait Interner: Sized { + IntoKind> + ConstTy + TypeSuperVisitable - + Flags; + + Flags + + new::Const; type AliasConst: Copy + DebugWithInfcx + Hash + Ord; type PlaceholderConst: Copy + Debug + Hash + Ord + PlaceholderLike; type ParamConst: Copy + Debug + Hash + Ord; @@ -71,7 +73,8 @@ pub trait Interner: Sized { + Ord + Into + IntoKind> - + Flags; + + Flags + + new::Region; type EarlyParamRegion: Copy + Debug + Hash + Ord; type LateParamRegion: Copy + Debug + Hash + Ord; type BoundRegion: Copy + Debug + Hash + Ord; @@ -90,11 +93,6 @@ pub trait Interner: Sized { type ClosureKind: Copy + Debug + Hash + Eq; fn mk_canonical_var_infos(self, infos: &[CanonicalVarInfo]) -> Self::CanonicalVars; - - // FIXME: We should not have all these constructors on `Interner`, but as functions on some trait. - fn mk_bound_ty(self, debruijn: DebruijnIndex, var: BoundVar) -> Self::Ty; - fn mk_bound_region(self, debruijn: DebruijnIndex, var: BoundVar) -> Self::Region; - fn mk_bound_const(self, debruijn: DebruijnIndex, var: BoundVar, ty: Self::Ty) -> Self::Const; } /// Common capabilities of placeholder kinds diff --git a/compiler/rustc_type_ir/src/lib.rs b/compiler/rustc_type_ir/src/lib.rs index 94ccbcbd8a570..01bf79bce1c64 100644 --- a/compiler/rustc_type_ir/src/lib.rs +++ b/compiler/rustc_type_ir/src/lib.rs @@ -24,6 +24,7 @@ use std::sync::Arc as Lrc; #[cfg(feature = "nightly")] pub mod codec; pub mod fold; +pub mod new; pub mod ty_info; pub mod ty_kind; pub mod visit; diff --git a/compiler/rustc_type_ir/src/new.rs b/compiler/rustc_type_ir/src/new.rs new file mode 100644 index 0000000000000..e7e695e59085a --- /dev/null +++ b/compiler/rustc_type_ir/src/new.rs @@ -0,0 +1,13 @@ +use crate::{BoundVar, DebruijnIndex, Interner}; + +pub trait Ty> { + fn new_anon_bound(interner: I, debruijn: DebruijnIndex, var: BoundVar) -> Self; +} + +pub trait Region> { + fn new_anon_bound(interner: I, debruijn: DebruijnIndex, var: BoundVar) -> Self; +} + +pub trait Const> { + fn new_anon_bound(interner: I, debruijn: DebruijnIndex, var: BoundVar, ty: I::Ty) -> Self; +} From 748da32efbed567369c8fabac97212d4b5210e59 Mon Sep 17 00:00:00 2001 From: Wesley Wiser Date: Mon, 4 Mar 2024 13:50:22 -0600 Subject: [PATCH 17/18] Update platform-support.md with supported musl version --- src/doc/rustc/src/platform-support.md | 46 +++++++++++++-------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/src/doc/rustc/src/platform-support.md b/src/doc/rustc/src/platform-support.md index 5500dca9dc244..741ba2d973191 100644 --- a/src/doc/rustc/src/platform-support.md +++ b/src/doc/rustc/src/platform-support.md @@ -94,7 +94,7 @@ target | notes -------|------- `aarch64-apple-darwin` | ARM64 macOS (11.0+, Big Sur+) `aarch64-pc-windows-msvc` | ARM64 Windows MSVC -`aarch64-unknown-linux-musl` | ARM64 Linux with MUSL +`aarch64-unknown-linux-musl` | ARM64 Linux with musl 1.2.3 `arm-unknown-linux-gnueabi` | ARMv6 Linux (kernel 3.2, glibc 2.17) `arm-unknown-linux-gnueabihf` | ARMv6 Linux, hardfloat (kernel 3.2, glibc 2.17) `armv7-unknown-linux-gnueabihf` | ARMv7-A Linux, hardfloat (kernel 3.2, glibc 2.17) @@ -106,7 +106,7 @@ target | notes `s390x-unknown-linux-gnu` | S390x Linux (kernel 3.2, glibc 2.17) `x86_64-unknown-freebsd` | 64-bit FreeBSD `x86_64-unknown-illumos` | illumos -`x86_64-unknown-linux-musl` | 64-bit Linux with MUSL +`x86_64-unknown-linux-musl` | 64-bit Linux with musl 1.2.3 [`x86_64-unknown-netbsd`](platform-support/netbsd.md) | NetBSD/amd64 ## Tier 2 without Host Tools @@ -148,26 +148,26 @@ target | std | notes `aarch64-unknown-none` | * | Bare ARM64, hardfloat [`aarch64-unknown-uefi`](platform-support/unknown-uefi.md) | * | ARM64 UEFI [`arm-linux-androideabi`](platform-support/android.md) | ✓ | ARMv6 Android -`arm-unknown-linux-musleabi` | ✓ | ARMv6 Linux with MUSL -`arm-unknown-linux-musleabihf` | ✓ | ARMv6 Linux with MUSL, hardfloat +`arm-unknown-linux-musleabi` | ✓ | ARMv6 Linux with musl 1.2.3 +`arm-unknown-linux-musleabihf` | ✓ | ARMv6 Linux with musl 1.2.3, hardfloat [`armebv7r-none-eabi`](platform-support/armv7r-none-eabi.md) | * | Bare ARMv7-R, Big Endian [`armebv7r-none-eabihf`](platform-support/armv7r-none-eabi.md) | * | Bare ARMv7-R, Big Endian, hardfloat `armv5te-unknown-linux-gnueabi` | ✓ | ARMv5TE Linux (kernel 4.4, glibc 2.23) -`armv5te-unknown-linux-musleabi` | ✓ | ARMv5TE Linux with MUSL +`armv5te-unknown-linux-musleabi` | ✓ | ARMv5TE Linux with musl 1.2.3 [`armv7-linux-androideabi`](platform-support/android.md) | ✓ | ARMv7-A Android `armv7-unknown-linux-gnueabi` | ✓ | ARMv7-A Linux (kernel 4.15, glibc 2.27) -`armv7-unknown-linux-musleabi` | ✓ | ARMv7-A Linux with MUSL -`armv7-unknown-linux-musleabihf` | ✓ | ARMv7-A Linux with MUSL, hardfloat +`armv7-unknown-linux-musleabi` | ✓ | ARMv7-A Linux with musl 1.2.3 +`armv7-unknown-linux-musleabihf` | ✓ | ARMv7-A Linux with musl 1.2.3, hardfloat [`armv7-unknown-linux-ohos`](platform-support/openharmony.md) | ✓ | ARMv7-A OpenHarmony [`armv7a-none-eabi`](platform-support/arm-none-eabi.md) | * | Bare ARMv7-A [`armv7r-none-eabi`](platform-support/armv7r-none-eabi.md) | * | Bare ARMv7-R [`armv7r-none-eabihf`](platform-support/armv7r-none-eabi.md) | * | Bare ARMv7-R, hardfloat `i586-pc-windows-msvc` | * | 32-bit Windows w/o SSE [^x86_32-floats-x87] `i586-unknown-linux-gnu` | ✓ | 32-bit Linux w/o SSE (kernel 3.2, glibc 2.17) [^x86_32-floats-x87] -`i586-unknown-linux-musl` | ✓ | 32-bit Linux w/o SSE, MUSL [^x86_32-floats-x87] +`i586-unknown-linux-musl` | ✓ | 32-bit Linux w/o SSE, musl 1.2.3 [^x86_32-floats-x87] [`i686-linux-android`](platform-support/android.md) | ✓ | 32-bit x86 Android [^x86_32-floats-return-ABI] `i686-unknown-freebsd` | ✓ | 32-bit FreeBSD [^x86_32-floats-return-ABI] -`i686-unknown-linux-musl` | ✓ | 32-bit Linux with MUSL [^x86_32-floats-return-ABI] +`i686-unknown-linux-musl` | ✓ | 32-bit Linux with musl 1.2.3 [^x86_32-floats-return-ABI] [`i686-unknown-uefi`](platform-support/unknown-uefi.md) | * | 32-bit UEFI [`loongarch64-unknown-none`](platform-support/loongarch-none.md) | * | | LoongArch64 Bare-metal (LP64D ABI) [`loongarch64-unknown-none-softfloat`](platform-support/loongarch-none.md) | * | | LoongArch64 Bare-metal (LP64S ABI) @@ -288,7 +288,7 @@ target | std | host | notes `csky-unknown-linux-gnuabiv2` | ✓ | | C-SKY abiv2 Linux (little endian) `csky-unknown-linux-gnuabiv2hf` | ✓ | | C-SKY abiv2 Linux, hardfloat (little endian) [`hexagon-unknown-none-elf`](platform-support/hexagon-unknown-none-elf.md)| * | | Bare Hexagon (v60+, HVX) -[`hexagon-unknown-linux-musl`](platform-support/hexagon-unknown-linux-musl.md) | ✓ | | Hexagon Linux +[`hexagon-unknown-linux-musl`](platform-support/hexagon-unknown-linux-musl.md) | ✓ | | Hexagon Linux with musl 1.2.3 `i386-apple-ios` | ✓ | | 32-bit x86 iOS [^x86_32-floats-return-ABI] [`i586-pc-nto-qnx700`](platform-support/nto-qnx.md) | * | | 32-bit x86 QNX Neutrino 7.0 RTOS [^x86_32-floats-return-ABI] [`i586-unknown-netbsd`](platform-support/netbsd.md) | ✓ | | 32-bit x86, restricted to Pentium @@ -305,15 +305,15 @@ target | std | host | notes `i686-wrs-vxworks` | ? | | [^x86_32-floats-return-ABI] [`m68k-unknown-linux-gnu`](platform-support/m68k-unknown-linux-gnu.md) | ? | | Motorola 680x0 Linux `mips-unknown-linux-gnu` | ✓ | ✓ | MIPS Linux (kernel 4.4, glibc 2.23) -`mips-unknown-linux-musl` | ✓ | | MIPS Linux with musl libc +`mips-unknown-linux-musl` | ✓ | | MIPS Linux with musl 1.2.3 `mips-unknown-linux-uclibc` | ✓ | | MIPS Linux with uClibc -[`mips64-openwrt-linux-musl`](platform-support/mips64-openwrt-linux-musl.md) | ? | | MIPS64 for OpenWrt Linux MUSL +[`mips64-openwrt-linux-musl`](platform-support/mips64-openwrt-linux-musl.md) | ? | | MIPS64 for OpenWrt Linux musl 1.2.3 `mips64-unknown-linux-gnuabi64` | ✓ | ✓ | MIPS64 Linux, N64 ABI (kernel 4.4, glibc 2.23) -`mips64-unknown-linux-muslabi64` | ✓ | | MIPS64 Linux, N64 ABI, musl libc +`mips64-unknown-linux-muslabi64` | ✓ | | MIPS64 Linux, N64 ABI, musl 1.2.3 `mips64el-unknown-linux-gnuabi64` | ✓ | ✓ | MIPS64 (little endian) Linux, N64 ABI (kernel 4.4, glibc 2.23) -`mips64el-unknown-linux-muslabi64` | ✓ | | MIPS64 (little endian) Linux, N64 ABI, musl libc +`mips64el-unknown-linux-muslabi64` | ✓ | | MIPS64 (little endian) Linux, N64 ABI, musl 1.2.3 `mipsel-unknown-linux-gnu` | ✓ | ✓ | MIPS (little endian) Linux (kernel 4.4, glibc 2.23) -`mipsel-unknown-linux-musl` | ✓ | | MIPS (little endian) Linux with musl libc +`mipsel-unknown-linux-musl` | ✓ | | MIPS (little endian) Linux with musl 1.2.3 [`mipsel-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | 32-bit MIPS (LE), requires mips32 cpu support `mipsel-sony-psp` | * | | MIPS (LE) Sony PlayStation Portable (PSP) [`mipsel-sony-psx`](platform-support/mipsel-sony-psx.md) | * | | MIPS (LE) Sony PlayStation 1 (PSX) @@ -325,7 +325,7 @@ target | std | host | notes [`mipsisa64r6el-unknown-linux-gnuabi64`](platform-support/mips-release-6.md) | ✓ | ✓ | 64-bit MIPS Release 6 Little Endian `msp430-none-elf` | * | | 16-bit MSP430 microcontrollers `powerpc-unknown-linux-gnuspe` | ✓ | | PowerPC SPE Linux -`powerpc-unknown-linux-musl` | ? | | +`powerpc-unknown-linux-musl` | ? | | PowerPC Linux with musl 1.2.3 [`powerpc-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD 32-bit powerpc systems `powerpc-unknown-openbsd` | ? | | `powerpc-wrs-vxworks-spe` | ? | | @@ -333,13 +333,13 @@ target | std | host | notes `powerpc64-unknown-freebsd` | ✓ | ✓ | PPC64 FreeBSD (ELFv1 and ELFv2) `powerpc64le-unknown-freebsd` | | | PPC64LE FreeBSD `powerpc-unknown-freebsd` | | | PowerPC FreeBSD -`powerpc64-unknown-linux-musl` | ? | | +`powerpc64-unknown-linux-musl` | ? | | 64-bit PowerPC Linux with musl 1.2.3 `powerpc64-wrs-vxworks` | ? | | -`powerpc64le-unknown-linux-musl` | ? | | +`powerpc64le-unknown-linux-musl` | ? | | 64-bit PowerPC Linux with musl 1.2.3, Little Endian [`powerpc64-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | OpenBSD/powerpc64 [`powerpc64-ibm-aix`](platform-support/aix.md) | ? | | 64-bit AIX (7.2 and newer) `riscv32gc-unknown-linux-gnu` | | | RISC-V Linux (kernel 5.4, glibc 2.33) -`riscv32gc-unknown-linux-musl` | | | RISC-V Linux (kernel 5.4, musl + RISCV32 support patches) +`riscv32gc-unknown-linux-musl` | | | RISC-V Linux (kernel 5.4, musl 1.2.3 + RISCV32 support patches) [`riscv32im-risc0-zkvm-elf`](platform-support/riscv32im-risc0-zkvm-elf.md) | ? | | RISC Zero's zero-knowledge Virtual Machine (RV32IM ISA) [`riscv32imac-unknown-xous-elf`](platform-support/riscv32imac-unknown-xous-elf.md) | ? | | RISC-V Xous (RV32IMAC ISA) [`riscv32imc-esp-espidf`](platform-support/esp-idf.md) | ✓ | | RISC-V ESP-IDF @@ -348,11 +348,11 @@ target | std | host | notes [`riscv64gc-unknown-hermit`](platform-support/hermit.md) | ✓ | | RISC-V Hermit `riscv64gc-unknown-freebsd` | | | RISC-V FreeBSD `riscv64gc-unknown-fuchsia` | | | RISC-V Fuchsia -`riscv64gc-unknown-linux-musl` | | | RISC-V Linux (kernel 4.20, musl 1.2.0) +`riscv64gc-unknown-linux-musl` | | | RISC-V Linux (kernel 4.20, musl 1.2.3) [`riscv64gc-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | RISC-V NetBSD [`riscv64gc-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | OpenBSD/riscv64 [`riscv64-linux-android`](platform-support/android.md) | | | RISC-V 64-bit Android -`s390x-unknown-linux-musl` | | | S390x Linux (kernel 3.2, MUSL) +`s390x-unknown-linux-musl` | | | S390x Linux (kernel 3.2, musl 1.2.3) `sparc-unknown-linux-gnu` | ✓ | | 32-bit SPARC Linux [`sparc-unknown-none-elf`](./platform-support/sparc-unknown-none-elf.md) | * | | Bare 32-bit SPARC V7+ [`sparc64-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD/sparc64 @@ -361,7 +361,7 @@ target | std | host | notes [`thumbv5te-none-eabi`](platform-support/armv5te-none-eabi.md) | * | | Thumb-mode Bare ARMv5TE `thumbv7a-pc-windows-msvc` | ? | | `thumbv7a-uwp-windows-msvc` | ✓ | | -`thumbv7neon-unknown-linux-musleabihf` | ? | | Thumb2-mode ARMv7-A Linux with NEON, MUSL +`thumbv7neon-unknown-linux-musleabihf` | ? | | Thumb2-mode ARMv7-A Linux with NEON, musl 1.2.3 [`wasm32-wasip2`](platform-support/wasm32-wasip2.md) | ✓ | | WebAssembly [`wasm64-unknown-unknown`](platform-support/wasm64-unknown-unknown.md) | ? | | WebAssembly `x86_64-apple-ios-macabi` | ✓ | | Apple Catalyst on x86_64 @@ -370,7 +370,7 @@ target | std | host | notes [`x86_64-pc-nto-qnx710`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS | [`x86_64-pc-windows-gnullvm`](platform-support/pc-windows-gnullvm.md) | ✓ | ✓ | `x86_64-pc-windows-msvc` | * | | 64-bit Windows XP support -[`x86_64-unikraft-linux-musl`](platform-support/unikraft-linux-musl.md) | ✓ | | 64-bit Unikraft with musl +[`x86_64-unikraft-linux-musl`](platform-support/unikraft-linux-musl.md) | ✓ | | 64-bit Unikraft with musl 1.2.3 `x86_64-unknown-dragonfly` | ✓ | ✓ | 64-bit DragonFlyBSD `x86_64-unknown-haiku` | ✓ | ✓ | 64-bit Haiku [`x86_64-unknown-hermit`](platform-support/hermit.md) | ✓ | | x86_64 Hermit From 80d2bdb6191609c8a3940a1a7959ac1ac16e8ed6 Mon Sep 17 00:00:00 2001 From: Nicholas Nethercote Date: Mon, 4 Mar 2024 16:31:49 +1100 Subject: [PATCH 18/18] Rename all `ParseSess` variables/fields/lifetimes as `psess`. Existing names for values of this type are `sess`, `parse_sess`, `parse_session`, and `ps`. `sess` is particularly annoying because that's also used for `Session` values, which are often co-located, and it can be difficult to know which type a value named `sess` refers to. (That annoyance is the main motivation for this change.) `psess` is nice and short, which is good for a name used this much. The commit also renames some `parse_sess_created` values as `psess_created`. --- compiler/rustc_ast_lowering/src/expr.rs | 12 +-- .../rustc_ast_passes/src/ast_validation.rs | 2 +- compiler/rustc_ast_passes/src/feature_gate.rs | 2 +- compiler/rustc_attr/src/builtin.rs | 14 +-- compiler/rustc_builtin_macros/src/asm.rs | 12 +-- .../src/cfg_accessible.rs | 2 +- compiler/rustc_builtin_macros/src/cfg_eval.rs | 3 +- .../rustc_builtin_macros/src/cmdline_attrs.rs | 8 +- compiler/rustc_builtin_macros/src/concat.rs | 4 +- .../rustc_builtin_macros/src/concat_bytes.rs | 2 +- compiler/rustc_builtin_macros/src/derive.rs | 2 +- .../src/deriving/generic/mod.rs | 2 +- compiler/rustc_builtin_macros/src/env.rs | 4 +- .../rustc_builtin_macros/src/source_util.rs | 4 +- .../src/standard_library_imports.rs | 2 +- .../rustc_builtin_macros/src/test_harness.rs | 4 +- compiler/rustc_builtin_macros/src/util.rs | 4 +- .../src/assert_module_sources.rs | 2 +- compiler/rustc_driver_impl/src/lib.rs | 14 ++- compiler/rustc_driver_impl/src/pretty.rs | 6 +- compiler/rustc_expand/src/base.rs | 18 ++-- compiler/rustc_expand/src/build.rs | 6 +- compiler/rustc_expand/src/config.rs | 12 +-- compiler/rustc_expand/src/expand.rs | 24 ++--- compiler/rustc_expand/src/mbe/diagnostics.rs | 14 +-- compiler/rustc_expand/src/mbe/macro_check.rs | 91 ++++++++++--------- compiler/rustc_expand/src/mbe/macro_rules.rs | 34 +++---- compiler/rustc_expand/src/mbe/metavar_expr.rs | 76 ++++++++-------- compiler/rustc_expand/src/mbe/quoted.rs | 3 +- compiler/rustc_expand/src/module.rs | 16 ++-- compiler/rustc_expand/src/parse/tests.rs | 30 +++--- compiler/rustc_expand/src/proc_macro.rs | 2 +- .../rustc_expand/src/proc_macro_server.rs | 34 +++---- compiler/rustc_expand/src/tests.rs | 26 +++--- compiler/rustc_hir_analysis/src/check/errs.rs | 2 +- compiler/rustc_hir_typeck/src/expr.rs | 2 +- .../src/fn_ctxt/suggestions.rs | 2 +- compiler/rustc_hir_typeck/src/op.rs | 2 +- .../src/persist/dirty_clean.rs | 2 +- compiler/rustc_interface/src/interface.rs | 20 ++-- compiler/rustc_interface/src/passes.rs | 16 ++-- compiler/rustc_interface/src/queries.rs | 2 +- compiler/rustc_interface/src/util.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 2 +- .../rustc_lint/src/context/diagnostics.rs | 12 +-- compiler/rustc_lint/src/non_ascii_idents.rs | 2 +- compiler/rustc_lint/src/non_fmt_panic.rs | 4 +- compiler/rustc_metadata/src/creader.rs | 2 +- compiler/rustc_metadata/src/rmeta/decoder.rs | 2 +- compiler/rustc_metadata/src/rmeta/encoder.rs | 2 +- compiler/rustc_middle/src/middle/stability.rs | 2 +- compiler/rustc_parse/src/lexer/mod.rs | 36 ++++---- compiler/rustc_parse/src/lexer/tokentrees.rs | 34 +++---- .../rustc_parse/src/lexer/unicode_chars.rs | 2 +- compiler/rustc_parse/src/lib.rs | 86 +++++++++--------- compiler/rustc_parse/src/parser/attr.rs | 6 +- .../rustc_parse/src/parser/attr_wrapper.rs | 4 +- .../rustc_parse/src/parser/diagnostics.rs | 26 +++--- compiler/rustc_parse/src/parser/expr.rs | 60 ++++++------ compiler/rustc_parse/src/parser/generics.rs | 2 +- compiler/rustc_parse/src/parser/item.rs | 24 ++--- compiler/rustc_parse/src/parser/mod.rs | 18 ++-- compiler/rustc_parse/src/parser/pat.rs | 21 +++-- compiler/rustc_parse/src/parser/path.rs | 12 +-- compiler/rustc_parse/src/parser/stmt.rs | 6 +- compiler/rustc_parse/src/parser/ty.rs | 14 +-- compiler/rustc_parse/src/validate_attr.rs | 48 +++++----- compiler/rustc_resolve/src/macros.rs | 4 +- compiler/rustc_session/src/errors.rs | 4 +- compiler/rustc_session/src/parse.rs | 9 +- compiler/rustc_session/src/session.rs | 12 +-- src/librustdoc/clean/cfg.rs | 10 +- src/librustdoc/clean/render_macro_matchers.rs | 4 +- src/librustdoc/core.rs | 2 +- src/librustdoc/doctest.rs | 16 ++-- .../passes/lint/check_code_block_syntax.rs | 4 +- .../src/disallowed_script_idents.rs | 2 +- .../src/doc/needless_doctest_main.rs | 4 +- src/tools/clippy/src/driver.rs | 20 ++-- src/tools/rustfmt/src/comment.rs | 4 +- src/tools/rustfmt/src/formatting.rs | 53 +++++------ src/tools/rustfmt/src/macros.rs | 4 +- src/tools/rustfmt/src/missed_spans.rs | 6 +- src/tools/rustfmt/src/modules.rs | 30 +++--- src/tools/rustfmt/src/modules/visitor.rs | 8 +- src/tools/rustfmt/src/parse/macros/cfg_if.rs | 10 +- .../rustfmt/src/parse/macros/lazy_static.rs | 6 +- src/tools/rustfmt/src/parse/macros/mod.rs | 12 +-- src/tools/rustfmt/src/parse/parser.rs | 46 +++++----- src/tools/rustfmt/src/parse/session.rs | 40 ++++---- src/tools/rustfmt/src/reorder.rs | 4 +- src/tools/rustfmt/src/rewrite.rs | 2 +- src/tools/rustfmt/src/source_file.rs | 4 +- src/tools/rustfmt/src/utils.rs | 2 +- src/tools/rustfmt/src/visitor.rs | 36 +++----- tests/run-make-fulldeps/issue-19371/foo.rs | 2 +- .../ui-fulldeps/mod_dir_path_canonicalized.rs | 4 +- tests/ui-fulldeps/pprust-expr-roundtrip.rs | 8 +- 98 files changed, 653 insertions(+), 687 deletions(-) diff --git a/compiler/rustc_ast_lowering/src/expr.rs b/compiler/rustc_ast_lowering/src/expr.rs index 9950db4784b9c..0b1cb12408003 100644 --- a/compiler/rustc_ast_lowering/src/expr.rs +++ b/compiler/rustc_ast_lowering/src/expr.rs @@ -125,12 +125,8 @@ impl<'hir> LoweringContext<'_, 'hir> { let lit_kind = match LitKind::from_token_lit(*token_lit) { Ok(lit_kind) => lit_kind, Err(err) => { - let guar = report_lit_error( - &self.tcx.sess.parse_sess, - err, - *token_lit, - e.span, - ); + let guar = + report_lit_error(&self.tcx.sess.psess, err, *token_lit, e.span); LitKind::Err(guar) } }; @@ -721,7 +717,7 @@ impl<'hir> LoweringContext<'_, 'hir> { sym::track_caller, span, )))), - id: self.tcx.sess.parse_sess.attr_id_generator.mk_attr_id(), + id: self.tcx.sess.psess.attr_id_generator.mk_attr_id(), style: AttrStyle::Outer, span: unstable_span, }], @@ -1756,7 +1752,7 @@ impl<'hir> LoweringContext<'_, 'hir> { // `#[allow(unreachable_code)]` let attr = attr::mk_attr_nested_word( - &self.tcx.sess.parse_sess.attr_id_generator, + &self.tcx.sess.psess.attr_id_generator, AttrStyle::Outer, sym::allow, sym::unreachable_code, diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index b56d695c6716a..f5ce9dedac93c 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -835,7 +835,7 @@ fn validate_generic_param_order( impl<'a> Visitor<'a> for AstValidator<'a> { fn visit_attribute(&mut self, attr: &Attribute) { - validate_attr::check_attr(&self.session.parse_sess, attr); + validate_attr::check_attr(&self.session.psess, attr); } fn visit_ty(&mut self, ty: &'a Ty) { diff --git a/compiler/rustc_ast_passes/src/feature_gate.rs b/compiler/rustc_ast_passes/src/feature_gate.rs index 1b0dd9acc3782..a28fcb0077948 100644 --- a/compiler/rustc_ast_passes/src/feature_gate.rs +++ b/compiler/rustc_ast_passes/src/feature_gate.rs @@ -507,7 +507,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) { check_incompatible_features(sess, features); let mut visitor = PostExpansionVisitor { sess, features }; - let spans = sess.parse_sess.gated_spans.spans.borrow(); + let spans = sess.psess.gated_spans.spans.borrow(); macro_rules! gate_all { ($gate:ident, $msg:literal) => { if let Some(spans) = spans.get(&sym::$gate) { diff --git a/compiler/rustc_attr/src/builtin.rs b/compiler/rustc_attr/src/builtin.rs index f414ff746bb82..6adfc57c09556 100644 --- a/compiler/rustc_attr/src/builtin.rs +++ b/compiler/rustc_attr/src/builtin.rs @@ -524,9 +524,9 @@ pub fn cfg_matches( ) -> bool { eval_condition(cfg, sess, features, &mut |cfg| { try_gate_cfg(cfg.name, cfg.span, sess, features); - match sess.parse_sess.check_config.expecteds.get(&cfg.name) { + match sess.psess.check_config.expecteds.get(&cfg.name) { Some(ExpectedValues::Some(values)) if !values.contains(&cfg.value) => { - sess.parse_sess.buffer_lint_with_diagnostic( + sess.psess.buffer_lint_with_diagnostic( UNEXPECTED_CFGS, cfg.span, lint_node_id, @@ -541,8 +541,8 @@ pub fn cfg_matches( ), ); } - None if sess.parse_sess.check_config.exhaustive_names => { - sess.parse_sess.buffer_lint_with_diagnostic( + None if sess.psess.check_config.exhaustive_names => { + sess.psess.buffer_lint_with_diagnostic( UNEXPECTED_CFGS, cfg.span, lint_node_id, @@ -555,7 +555,7 @@ pub fn cfg_matches( } _ => { /* not unexpected */ } } - sess.parse_sess.config.contains(&(cfg.name, cfg.value)) + sess.psess.config.contains(&(cfg.name, cfg.value)) }) } @@ -598,7 +598,7 @@ pub fn eval_condition( features: Option<&Features>, eval: &mut impl FnMut(Condition) -> bool, ) -> bool { - let dcx = &sess.parse_sess.dcx; + let dcx = &sess.psess.dcx; match &cfg.kind { ast::MetaItemKind::List(mis) if cfg.name_or_empty() == sym::version => { try_gate_cfg(sym::version, cfg.span, sess, features); @@ -626,7 +626,7 @@ pub fn eval_condition( }; // See https://github.com/rust-lang/rust/issues/64796#issuecomment-640851454 for details - if sess.parse_sess.assume_incomplete_release { + if sess.psess.assume_incomplete_release { RustcVersion::CURRENT > min_version } else { RustcVersion::CURRENT >= min_version diff --git a/compiler/rustc_builtin_macros/src/asm.rs b/compiler/rustc_builtin_macros/src/asm.rs index 359222afaeced..38fa1ac593528 100644 --- a/compiler/rustc_builtin_macros/src/asm.rs +++ b/compiler/rustc_builtin_macros/src/asm.rs @@ -45,7 +45,7 @@ pub fn parse_asm_args<'a>( sp: Span, is_global_asm: bool, ) -> PResult<'a, AsmArgs> { - let dcx = &p.sess.dcx; + let dcx = &p.psess.dcx; if p.token == token::Eof { return Err(dcx.create_err(errors::AsmRequiresTemplate { span: sp })); @@ -296,7 +296,7 @@ pub fn parse_asm_args<'a>( fn err_duplicate_option(p: &mut Parser<'_>, symbol: Symbol, span: Span) { // Tool-only output let full_span = if p.token.kind == token::Comma { span.to(p.token.span) } else { span }; - p.sess.dcx.emit_err(errors::AsmOptAlreadyprovided { span, symbol, full_span }); + p.psess.dcx.emit_err(errors::AsmOptAlreadyprovided { span, symbol, full_span }); } /// Try to set the provided option in the provided `AsmArgs`. @@ -368,7 +368,7 @@ fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a, p.expect(&token::OpenDelim(Delimiter::Parenthesis))?; if p.eat(&token::CloseDelim(Delimiter::Parenthesis)) { - return Err(p.sess.dcx.create_err(errors::NonABI { span: p.token.span })); + return Err(p.psess.dcx.create_err(errors::NonABI { span: p.token.span })); } let mut new_abis = Vec::new(); @@ -379,7 +379,7 @@ fn parse_clobber_abi<'a>(p: &mut Parser<'a>, args: &mut AsmArgs) -> PResult<'a, } Err(opt_lit) => { let span = opt_lit.map_or(p.token.span, |lit| lit.span); - let mut err = p.sess.dcx.struct_span_err(span, "expected string literal"); + let mut err = p.psess.dcx.struct_span_err(span, "expected string literal"); err.span_label(span, "not a string literal"); return Err(err); } @@ -495,7 +495,7 @@ fn expand_preparsed_asm( }; if template_str.contains(".intel_syntax") { - ecx.parse_sess().buffer_lint( + ecx.psess().buffer_lint( lint::builtin::BAD_ASM_STYLE, find_span(".intel_syntax"), ecx.current_expansion.lint_node_id, @@ -503,7 +503,7 @@ fn expand_preparsed_asm( ); } if template_str.contains(".att_syntax") { - ecx.parse_sess().buffer_lint( + ecx.psess().buffer_lint( lint::builtin::BAD_ASM_STYLE, find_span(".att_syntax"), ecx.current_expansion.lint_node_id, diff --git a/compiler/rustc_builtin_macros/src/cfg_accessible.rs b/compiler/rustc_builtin_macros/src/cfg_accessible.rs index ceb5f86107845..1933b2e1fb7fe 100644 --- a/compiler/rustc_builtin_macros/src/cfg_accessible.rs +++ b/compiler/rustc_builtin_macros/src/cfg_accessible.rs @@ -46,7 +46,7 @@ impl MultiItemModifier for Expander { ) -> ExpandResult, Annotatable> { let template = AttributeTemplate { list: Some("path"), ..Default::default() }; validate_attr::check_builtin_meta_item( - &ecx.sess.parse_sess, + &ecx.sess.psess, meta_item, ast::AttrStyle::Outer, sym::cfg_accessible, diff --git a/compiler/rustc_builtin_macros/src/cfg_eval.rs b/compiler/rustc_builtin_macros/src/cfg_eval.rs index cfa94b0e78085..1de95ca81f729 100644 --- a/compiler/rustc_builtin_macros/src/cfg_eval.rs +++ b/compiler/rustc_builtin_macros/src/cfg_eval.rs @@ -195,8 +195,7 @@ impl CfgEval<'_, '_> { // Re-parse the tokens, setting the `capture_cfg` flag to save extra information // to the captured `AttrTokenStream` (specifically, we capture // `AttrTokenTree::AttributesData` for all occurrences of `#[cfg]` and `#[cfg_attr]`) - let mut parser = - rustc_parse::stream_to_parser(&self.cfg.sess.parse_sess, orig_tokens, None); + let mut parser = rustc_parse::stream_to_parser(&self.cfg.sess.psess, orig_tokens, None); parser.capture_cfg = true; match parse_annotatable_with(&mut parser) { Ok(a) => annotatable = a, diff --git a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs index d956c096d24a1..ada82e45712d8 100644 --- a/compiler/rustc_builtin_macros/src/cmdline_attrs.rs +++ b/compiler/rustc_builtin_macros/src/cmdline_attrs.rs @@ -7,10 +7,10 @@ use rustc_ast::{self as ast, AttrItem, AttrStyle}; use rustc_session::parse::ParseSess; use rustc_span::FileName; -pub fn inject(krate: &mut ast::Crate, parse_sess: &ParseSess, attrs: &[String]) { +pub fn inject(krate: &mut ast::Crate, psess: &ParseSess, attrs: &[String]) { for raw_attr in attrs { let mut parser = rustc_parse::new_parser_from_source_str( - parse_sess, + psess, FileName::cli_crate_attr_source_code(raw_attr), raw_attr.clone(), ); @@ -25,12 +25,12 @@ pub fn inject(krate: &mut ast::Crate, parse_sess: &ParseSess, attrs: &[String]) }; let end_span = parser.token.span; if parser.token != token::Eof { - parse_sess.dcx.emit_err(errors::InvalidCrateAttr { span: start_span.to(end_span) }); + psess.dcx.emit_err(errors::InvalidCrateAttr { span: start_span.to(end_span) }); continue; } krate.attrs.push(mk_attr( - &parse_sess.attr_id_generator, + &psess.attr_id_generator, AttrStyle::Inner, path, args, diff --git a/compiler/rustc_builtin_macros/src/concat.rs b/compiler/rustc_builtin_macros/src/concat.rs index abfaa9b006edb..0bfb848859bd8 100644 --- a/compiler/rustc_builtin_macros/src/concat.rs +++ b/compiler/rustc_builtin_macros/src/concat.rs @@ -43,7 +43,7 @@ pub fn expand_concat( guar = Some(guarantee); } Err(err) => { - guar = Some(report_lit_error(&cx.sess.parse_sess, err, token_lit, e.span)); + guar = Some(report_lit_error(&cx.sess.psess, err, token_lit, e.span)); } }, // We also want to allow negative numeric literals. @@ -52,7 +52,7 @@ pub fn expand_concat( Ok(LitKind::Int(i, _)) => accumulator.push_str(&format!("-{i}")), Ok(LitKind::Float(f, _)) => accumulator.push_str(&format!("-{f}")), Err(err) => { - guar = Some(report_lit_error(&cx.sess.parse_sess, err, token_lit, e.span)); + guar = Some(report_lit_error(&cx.sess.psess, err, token_lit, e.span)); } _ => missing_literal.push(e.span), } diff --git a/compiler/rustc_builtin_macros/src/concat_bytes.rs b/compiler/rustc_builtin_macros/src/concat_bytes.rs index 3fb0b50f41756..502bfb4467e52 100644 --- a/compiler/rustc_builtin_macros/src/concat_bytes.rs +++ b/compiler/rustc_builtin_macros/src/concat_bytes.rs @@ -55,7 +55,7 @@ fn invalid_type_err( Ok(LitKind::Int(_, _)) => dcx.emit_err(ConcatBytesNonU8 { span }), Ok(LitKind::ByteStr(..) | LitKind::Byte(_)) => unreachable!(), Ok(LitKind::Err(guar)) => guar, - Err(err) => report_lit_error(&cx.sess.parse_sess, err, token_lit, span), + Err(err) => report_lit_error(&cx.sess.psess, err, token_lit, span), } } diff --git a/compiler/rustc_builtin_macros/src/derive.rs b/compiler/rustc_builtin_macros/src/derive.rs index 7388e133c53e2..4f412cf79d91f 100644 --- a/compiler/rustc_builtin_macros/src/derive.rs +++ b/compiler/rustc_builtin_macros/src/derive.rs @@ -34,7 +34,7 @@ impl MultiItemModifier for Expander { let template = AttributeTemplate { list: Some("Trait1, Trait2, ..."), ..Default::default() }; validate_attr::check_builtin_meta_item( - &sess.parse_sess, + &sess.psess, meta_item, ast::AttrStyle::Outer, sym::derive, diff --git a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs index eb664b571ba85..0adab6c4322eb 100644 --- a/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs +++ b/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs @@ -1624,7 +1624,7 @@ impl<'a> TraitDef<'a> { }; if let Some(ty) = exception { - cx.sess.parse_sess.buffer_lint_with_diagnostic( + cx.sess.psess.buffer_lint_with_diagnostic( BYTE_SLICE_IN_PACKED_STRUCT_WITH_DERIVE, sp, ast::CRATE_NODE_ID, diff --git a/compiler/rustc_builtin_macros/src/env.rs b/compiler/rustc_builtin_macros/src/env.rs index f057d44bf710a..193b38a83238a 100644 --- a/compiler/rustc_builtin_macros/src/env.rs +++ b/compiler/rustc_builtin_macros/src/env.rs @@ -39,7 +39,7 @@ pub fn expand_option_env<'cx>( let sp = cx.with_def_site_ctxt(sp); let value = lookup_env(cx, var); - cx.sess.parse_sess.env_depinfo.borrow_mut().insert((var, value)); + cx.sess.psess.env_depinfo.borrow_mut().insert((var, value)); let e = match value { None => { let lt = cx.lifetime(sp, Ident::new(kw::StaticLifetime, sp)); @@ -94,7 +94,7 @@ pub fn expand_env<'cx>( let span = cx.with_def_site_ctxt(sp); let value = lookup_env(cx, var); - cx.sess.parse_sess.env_depinfo.borrow_mut().insert((var, value)); + cx.sess.psess.env_depinfo.borrow_mut().insert((var, value)); let e = match value { None => { let ExprKind::Lit(token::Lit { diff --git a/compiler/rustc_builtin_macros/src/source_util.rs b/compiler/rustc_builtin_macros/src/source_util.rs index 8e0978de23748..2da9bda19e034 100644 --- a/compiler/rustc_builtin_macros/src/source_util.rs +++ b/compiler/rustc_builtin_macros/src/source_util.rs @@ -118,7 +118,7 @@ pub fn expand_include<'cx>( return DummyResult::any(sp, guar); } }; - let p = new_parser_from_file(cx.parse_sess(), &file, Some(sp)); + let p = new_parser_from_file(cx.psess(), &file, Some(sp)); // If in the included file we have e.g., `mod bar;`, // then the path of `bar.rs` should be relative to the directory of `file`. @@ -136,7 +136,7 @@ pub fn expand_include<'cx>( fn make_expr(mut self: Box>) -> Option> { let expr = parse_expr(&mut self.p).ok()?; if self.p.token != token::Eof { - self.p.sess.buffer_lint( + self.p.psess.buffer_lint( INCOMPLETE_INCLUDE, self.p.token.span, self.node_id, diff --git a/compiler/rustc_builtin_macros/src/standard_library_imports.rs b/compiler/rustc_builtin_macros/src/standard_library_imports.rs index 3ee3112f021ca..9bcd793c45041 100644 --- a/compiler/rustc_builtin_macros/src/standard_library_imports.rs +++ b/compiler/rustc_builtin_macros/src/standard_library_imports.rs @@ -17,7 +17,7 @@ pub fn inject( features: &Features, ) -> usize { let orig_num_items = krate.items.len(); - let edition = sess.parse_sess.edition; + let edition = sess.psess.edition; // the first name in this list is the crate name of the crate with the prelude let names: &[Symbol] = if attr::contains_name(pre_configured_attrs, sym::no_core) { diff --git a/compiler/rustc_builtin_macros/src/test_harness.rs b/compiler/rustc_builtin_macros/src/test_harness.rs index dc28cd2ea31c4..a2015445b42c9 100644 --- a/compiler/rustc_builtin_macros/src/test_harness.rs +++ b/compiler/rustc_builtin_macros/src/test_harness.rs @@ -159,7 +159,7 @@ struct InnerItemLinter<'a> { impl<'a> Visitor<'a> for InnerItemLinter<'_> { fn visit_item(&mut self, i: &'a ast::Item) { if let Some(attr) = attr::find_by_name(&i.attrs, sym::rustc_test_marker) { - self.sess.parse_sess.buffer_lint( + self.sess.psess.buffer_lint( UNNAMEABLE_TEST_ITEMS, attr.span, i.id, @@ -200,7 +200,7 @@ impl<'a> MutVisitor for EntryPointCleaner<'a> { EntryPointType::MainNamed | EntryPointType::RustcMainAttr | EntryPointType::Start => { item.map(|ast::Item { id, ident, attrs, kind, vis, span, tokens }| { let allow_dead_code = attr::mk_attr_nested_word( - &self.sess.parse_sess.attr_id_generator, + &self.sess.psess.attr_id_generator, ast::AttrStyle::Outer, sym::allow, sym::dead_code, diff --git a/compiler/rustc_builtin_macros/src/util.rs b/compiler/rustc_builtin_macros/src/util.rs index eeaf00004e630..ad6b09ba57458 100644 --- a/compiler/rustc_builtin_macros/src/util.rs +++ b/compiler/rustc_builtin_macros/src/util.rs @@ -9,7 +9,7 @@ pub fn check_builtin_macro_attribute(ecx: &ExtCtxt<'_>, meta_item: &MetaItem, na // All the built-in macro attributes are "words" at the moment. let template = AttributeTemplate { word: true, ..Default::default() }; validate_attr::check_builtin_meta_item( - &ecx.sess.parse_sess, + &ecx.sess.psess, meta_item, AttrStyle::Outer, name, @@ -37,7 +37,7 @@ pub fn warn_on_duplicate_attribute(ecx: &ExtCtxt<'_>, item: &Annotatable, name: }; if let Some(attrs) = attrs { if let Some(attr) = attr::find_by_name(attrs, name) { - ecx.parse_sess().buffer_lint( + ecx.psess().buffer_lint( DUPLICATE_MACRO_ATTRIBUTES, attr.span, ecx.current_expansion.lint_node_id, diff --git a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs index cbee4877122f0..7ecc386434778 100644 --- a/compiler/rustc_codegen_ssa/src/assert_module_sources.rs +++ b/compiler/rustc_codegen_ssa/src/assert_module_sources.rs @@ -176,7 +176,7 @@ impl<'tcx> AssertModuleSource<'tcx> { /// Scan for a `cfg="foo"` attribute and check whether we have a /// cfg flag called `foo`. fn check_config(&self, attr: &ast::Attribute) -> bool { - let config = &self.tcx.sess.parse_sess.config; + let config = &self.tcx.sess.psess.config; let value = self.field(attr, sym::cfg); debug!("check_config(config={:?}, value={:?})", config, value); if config.iter().any(|&(name, _)| name == value) { diff --git a/compiler/rustc_driver_impl/src/lib.rs b/compiler/rustc_driver_impl/src/lib.rs index 410e7eba30a9c..ab1e37e4ac221 100644 --- a/compiler/rustc_driver_impl/src/lib.rs +++ b/compiler/rustc_driver_impl/src/lib.rs @@ -314,7 +314,7 @@ fn run_compiler( file_loader, locale_resources: DEFAULT_LOCALE_RESOURCES, lint_caps: Default::default(), - parse_sess_created: None, + psess_created: None, hash_untracked_state: None, register_lints: None, override_queries: None, @@ -768,7 +768,7 @@ fn print_crate_info( } Cfg => { let mut cfgs = sess - .parse_sess + .psess .config .iter() .filter_map(|&(name, value)| { @@ -1215,12 +1215,10 @@ pub fn handle_options(early_dcx: &EarlyDiagCtxt, args: &[String]) -> Option(sess: &'a Session) -> PResult<'a, ast::AttrVec> { match &sess.io.input { - Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.parse_sess), - Input::Str { name, input } => rustc_parse::parse_crate_attrs_from_source_str( - name.clone(), - input.clone(), - &sess.parse_sess, - ), + Input::File(ifile) => rustc_parse::parse_crate_attrs_from_file(ifile, &sess.psess), + Input::Str { name, input } => { + rustc_parse::parse_crate_attrs_from_source_str(name.clone(), input.clone(), &sess.psess) + } } } diff --git a/compiler/rustc_driver_impl/src/pretty.rs b/compiler/rustc_driver_impl/src/pretty.rs index ff5ffd2454a1f..768d98ce01efe 100644 --- a/compiler/rustc_driver_impl/src/pretty.rs +++ b/compiler/rustc_driver_impl/src/pretty.rs @@ -260,7 +260,7 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) { ExpandedIdentified => Box::new(AstIdentifiedAnn), ExpandedHygiene => Box::new(AstHygieneAnn { sess }), }; - let parse = &sess.parse_sess; + let psess = &sess.psess; let is_expanded = ppm.needs_ast_map(); ex.with_krate(|krate| { pprust_ast::print_crate( @@ -270,8 +270,8 @@ pub fn print<'tcx>(sess: &Session, ppm: PpMode, ex: PrintExtra<'tcx>) { src, &*annotation, is_expanded, - parse.edition, - &sess.parse_sess.attr_id_generator, + psess.edition, + &sess.psess.attr_id_generator, ) }) } diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index 984c740372042..6d205a82675c0 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -1135,13 +1135,13 @@ impl<'a> ExtCtxt<'a> { expand::MacroExpander::new(self, true) } pub fn new_parser_from_tts(&self, stream: TokenStream) -> parser::Parser<'a> { - rustc_parse::stream_to_parser(&self.sess.parse_sess, stream, MACRO_ARGUMENTS) + rustc_parse::stream_to_parser(&self.sess.psess, stream, MACRO_ARGUMENTS) } pub fn source_map(&self) -> &'a SourceMap { - self.sess.parse_sess.source_map() + self.sess.psess.source_map() } - pub fn parse_sess(&self) -> &'a ParseSess { - &self.sess.parse_sess + pub fn psess(&self) -> &'a ParseSess { + &self.sess.psess } pub fn call_site(&self) -> Span { self.current_expansion.id.expn_data().call_site @@ -1216,11 +1216,7 @@ impl<'a> ExtCtxt<'a> { /// Resolves a `path` mentioned inside Rust code, returning an absolute path. /// /// This unifies the logic used for resolving `include_X!`. -pub fn resolve_path( - sess: &Session, - path: impl Into, - span: Span, -) -> PResult<'_, PathBuf> { +pub fn resolve_path(sess: &Session, path: impl Into, span: Span) -> PResult<'_, PathBuf> { let path = path.into(); // Relative paths are resolved relative to the file in which they are found @@ -1281,7 +1277,7 @@ pub fn expr_to_spanned_string<'a>( Ok((err, true)) } Ok(ast::LitKind::Err(guar)) => Err(guar), - Err(err) => Err(report_lit_error(&cx.sess.parse_sess, err, token_lit, expr.span)), + Err(err) => Err(report_lit_error(&cx.sess.psess, err, token_lit, expr.span)), _ => Ok((cx.dcx().struct_span_err(expr.span, err_msg), false)), }, ast::ExprKind::Err(guar) => Err(guar), @@ -1487,7 +1483,7 @@ fn pretty_printing_compatibility_hack(item: &Item, sess: &Session) -> bool { }; if crate_matches { - sess.parse_sess.buffer_lint_with_diagnostic( + sess.psess.buffer_lint_with_diagnostic( PROC_MACRO_BACK_COMPAT, item.ident.span, ast::CRATE_NODE_ID, diff --git a/compiler/rustc_expand/src/build.rs b/compiler/rustc_expand/src/build.rs index 9ce2084c84704..989b7b485c992 100644 --- a/compiler/rustc_expand/src/build.rs +++ b/compiler/rustc_expand/src/build.rs @@ -665,7 +665,7 @@ impl<'a> ExtCtxt<'a> { // Builds `#[name]`. pub fn attr_word(&self, name: Symbol, span: Span) -> ast::Attribute { - let g = &self.sess.parse_sess.attr_id_generator; + let g = &self.sess.psess.attr_id_generator; attr::mk_attr_word(g, ast::AttrStyle::Outer, name, span) } @@ -673,13 +673,13 @@ impl<'a> ExtCtxt<'a> { // // Note: `span` is used for both the identifier and the value. pub fn attr_name_value_str(&self, name: Symbol, val: Symbol, span: Span) -> ast::Attribute { - let g = &self.sess.parse_sess.attr_id_generator; + let g = &self.sess.psess.attr_id_generator; attr::mk_attr_name_value_str(g, ast::AttrStyle::Outer, name, val, span) } // Builds `#[outer(inner)]`. pub fn attr_nested_word(&self, outer: Symbol, inner: Symbol, span: Span) -> ast::Attribute { - let g = &self.sess.parse_sess.attr_id_generator; + let g = &self.sess.psess.attr_id_generator; attr::mk_attr_nested_word(g, ast::AttrStyle::Outer, outer, inner, span) } } diff --git a/compiler/rustc_expand/src/config.rs b/compiler/rustc_expand/src/config.rs index 435135d195989..921fea143124a 100644 --- a/compiler/rustc_expand/src/config.rs +++ b/compiler/rustc_expand/src/config.rs @@ -241,14 +241,14 @@ impl<'a> StripUnconfigured<'a> { /// the attribute is incorrect. pub(crate) fn expand_cfg_attr(&self, attr: &Attribute, recursive: bool) -> Vec { let Some((cfg_predicate, expanded_attrs)) = - rustc_parse::parse_cfg_attr(attr, &self.sess.parse_sess) + rustc_parse::parse_cfg_attr(attr, &self.sess.psess) else { return vec![]; }; // Lint on zero attributes in source. if expanded_attrs.is_empty() { - self.sess.parse_sess.buffer_lint( + self.sess.psess.buffer_lint( rustc_lint_defs::builtin::UNUSED_ATTRIBUTES, attr.span, ast::CRATE_NODE_ID, @@ -324,14 +324,14 @@ impl<'a> StripUnconfigured<'a> { }; let tokens = Some(LazyAttrTokenStream::new(AttrTokenStream::new(trees))); let attr = attr::mk_attr_from_item( - &self.sess.parse_sess.attr_id_generator, + &self.sess.psess.attr_id_generator, item, tokens, attr.style, item_span, ); if attr.has_name(sym::crate_type) { - self.sess.parse_sess.buffer_lint( + self.sess.psess.buffer_lint( rustc_lint_defs::builtin::DEPRECATED_CFG_ATTR_CRATE_TYPE_NAME, attr.span, ast::CRATE_NODE_ID, @@ -339,7 +339,7 @@ impl<'a> StripUnconfigured<'a> { ); } if attr.has_name(sym::crate_name) { - self.sess.parse_sess.buffer_lint( + self.sess.psess.buffer_lint( rustc_lint_defs::builtin::DEPRECATED_CFG_ATTR_CRATE_TYPE_NAME, attr.span, ast::CRATE_NODE_ID, @@ -355,7 +355,7 @@ impl<'a> StripUnconfigured<'a> { } pub(crate) fn cfg_true(&self, attr: &Attribute) -> (bool, Option) { - let meta_item = match validate_attr::parse_meta(&self.sess.parse_sess, attr) { + let meta_item = match validate_attr::parse_meta(&self.sess.psess, attr) { Ok(meta_item) => meta_item, Err(err) => { err.emit(); diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index 9bc7b4bdd1e13..8a01704b766eb 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -691,10 +691,9 @@ impl<'a, 'b> MacroExpander<'a, 'b> { // fixed prior to stabilization // Fake tokens when we are invoking an inner attribute, and // we are invoking it on an out-of-line module or crate. - Annotatable::Crate(krate) => rustc_parse::fake_token_stream_for_crate( - &self.cx.sess.parse_sess, - krate, - ), + Annotatable::Crate(krate) => { + rustc_parse::fake_token_stream_for_crate(&self.cx.sess.psess, krate) + } Annotatable::Item(item_inner) if matches!(attr.style, AttrStyle::Inner) && matches!( @@ -705,10 +704,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { ) ) => { - rustc_parse::fake_token_stream_for_item( - &self.cx.sess.parse_sess, - item_inner, - ) + rustc_parse::fake_token_stream_for_item(&self.cx.sess.psess, item_inner) } _ => item.to_tokens(), }; @@ -728,7 +724,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { } } SyntaxExtensionKind::LegacyAttr(expander) => { - match validate_attr::parse_meta(&self.cx.sess.parse_sess, &attr) { + match validate_attr::parse_meta(&self.cx.sess.psess, &attr) { Ok(meta) => { let items = match expander.expand(self.cx, span, &meta, item, false) { ExpandResult::Ready(items) => items, @@ -962,8 +958,8 @@ pub fn ensure_complete_parse<'a>( // Avoid emitting backtrace info twice. let def_site_span = parser.token.span.with_ctxt(SyntaxContext::root()); - let semi_span = parser.sess.source_map().next_point(span); - let add_semicolon = match &parser.sess.source_map().span_to_snippet(semi_span) { + let semi_span = parser.psess.source_map().next_point(span); + let add_semicolon = match &parser.psess.source_map().span_to_snippet(semi_span) { Ok(snippet) if &snippet[..] != ";" && kind_name == "expression" => { Some(span.shrink_to_hi()) } @@ -1700,7 +1696,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { let mut span: Option = None; while let Some(attr) = attrs.next() { rustc_ast_passes::feature_gate::check_attribute(attr, self.cx.sess, features); - validate_attr::check_attr(&self.cx.sess.parse_sess, attr); + validate_attr::check_attr(&self.cx.sess.psess, attr); let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span }; span = Some(current_span); @@ -1710,7 +1706,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { } if attr.is_doc_comment() { - self.cx.sess.parse_sess.buffer_lint_with_diagnostic( + self.cx.sess.psess.buffer_lint_with_diagnostic( UNUSED_DOC_COMMENTS, current_span, self.cx.current_expansion.lint_node_id, @@ -1722,7 +1718,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { // `#[cfg]` and `#[cfg_attr]` are special - they are // eagerly evaluated. if attr_name != sym::cfg && attr_name != sym::cfg_attr { - self.cx.sess.parse_sess.buffer_lint_with_diagnostic( + self.cx.sess.psess.buffer_lint_with_diagnostic( UNUSED_ATTRIBUTES, attr.span, self.cx.current_expansion.lint_node_id, diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 053063b690e62..d8b8a0fa96ad8 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -24,12 +24,12 @@ pub(super) fn failed_to_match_macro<'cx>( arg: TokenStream, lhses: &[Vec], ) -> Box { - let sess = &cx.sess.parse_sess; + let psess = &cx.sess.psess; // An error occurred, try the expansion again, tracking the expansion closely for better diagnostics. let mut tracker = CollectTrackerAndEmitter::new(cx, sp); - let try_success_result = try_match_macro(sess, name, &arg, lhses, &mut tracker); + let try_success_result = try_match_macro(psess, name, &arg, lhses, &mut tracker); if try_success_result.is_ok() { // Nonterminal parser recovery might turn failed matches into successful ones, @@ -58,7 +58,7 @@ pub(super) fn failed_to_match_macro<'cx>( err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro"); } - annotate_doc_comment(cx.sess.dcx(), &mut err, sess.source_map(), span); + annotate_doc_comment(cx.sess.dcx(), &mut err, psess.source_map(), span); if let Some(span) = remaining_matcher.span() { err.span_note(span, format!("while trying to match {remaining_matcher}")); @@ -87,7 +87,7 @@ pub(super) fn failed_to_match_macro<'cx>( // Check whether there's a missing comma in this macro call, like `println!("{}" a);` if let Some((arg, comma_span)) = arg.add_comma() { for lhs in lhses { - let parser = parser_from_cx(sess, arg.clone(), Recovery::Allowed); + let parser = parser_from_cx(psess, arg.clone(), Recovery::Allowed); let mut tt_parser = TtParser::new(name); if let Success(_) = @@ -246,10 +246,10 @@ pub(super) fn emit_frag_parse_err( if e.span.is_dummy() { // Get around lack of span in error (#30128) e.replace_span_with(site_span, true); - if !parser.sess.source_map().is_imported(arm_span) { + if !parser.psess.source_map().is_imported(arm_span) { e.span_label(arm_span, "in this macro arm"); } - } else if parser.sess.source_map().is_imported(parser.token.span) { + } else if parser.psess.source_map().is_imported(parser.token.span) { e.span_label(site_span, "in this macro invocation"); } match kind { @@ -262,7 +262,7 @@ pub(super) fn emit_frag_parse_err( ); if parser.token == token::Semi { - if let Ok(snippet) = parser.sess.source_map().span_to_snippet(site_span) { + if let Ok(snippet) = parser.psess.source_map().span_to_snippet(site_span) { e.span_suggestion_verbose( site_span, "surround the macro invocation with `{}` to interpret the expansion as a statement", diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 8174cb03d337b..19405dcfd6cb2 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -193,25 +193,25 @@ struct MacroState<'a> { /// Checks that meta-variables are used correctly in a macro definition. /// /// Arguments: -/// - `sess` is used to emit diagnostics and lints +/// - `psess` is used to emit diagnostics and lints /// - `node_id` is used to emit lints /// - `span` is used when no spans are available /// - `lhses` and `rhses` should have the same length and represent the macro definition pub(super) fn check_meta_variables( - sess: &ParseSess, + psess: &ParseSess, node_id: NodeId, span: Span, lhses: &[TokenTree], rhses: &[TokenTree], ) -> Result<(), ErrorGuaranteed> { if lhses.len() != rhses.len() { - sess.dcx.span_bug(span, "length mismatch between LHSes and RHSes") + psess.dcx.span_bug(span, "length mismatch between LHSes and RHSes") } let mut guar = None; for (lhs, rhs) in iter::zip(lhses, rhses) { let mut binders = Binders::default(); - check_binders(sess, node_id, lhs, &Stack::Empty, &mut binders, &Stack::Empty, &mut guar); - check_occurrences(sess, node_id, rhs, &Stack::Empty, &binders, &Stack::Empty, &mut guar); + check_binders(psess, node_id, lhs, &Stack::Empty, &mut binders, &Stack::Empty, &mut guar); + check_occurrences(psess, node_id, rhs, &Stack::Empty, &binders, &Stack::Empty, &mut guar); } guar.map_or(Ok(()), Err) } @@ -220,7 +220,7 @@ pub(super) fn check_meta_variables( /// sets `valid` to false in case of errors. /// /// Arguments: -/// - `sess` is used to emit diagnostics and lints +/// - `psess` is used to emit diagnostics and lints /// - `node_id` is used to emit lints /// - `lhs` is checked as part of a LHS /// - `macros` is the stack of possible outer macros @@ -228,7 +228,7 @@ pub(super) fn check_meta_variables( /// - `ops` is the stack of Kleene operators from the LHS /// - `guar` is set in case of errors fn check_binders( - sess: &ParseSess, + psess: &ParseSess, node_id: NodeId, lhs: &TokenTree, macros: &Stack<'_, MacroState<'_>>, @@ -244,7 +244,7 @@ fn check_binders( // MetaVar(fragment) and not as MetaVarDecl(y, fragment). TokenTree::MetaVar(span, name) => { if macros.is_empty() { - sess.dcx.span_bug(span, "unexpected MetaVar in lhs"); + psess.dcx.span_bug(span, "unexpected MetaVar in lhs"); } let name = MacroRulesNormalizedIdent::new(name); // There are 3 possibilities: @@ -252,13 +252,13 @@ fn check_binders( // 1. The meta-variable is already bound in the current LHS: This is an error. let mut span = MultiSpan::from_span(span); span.push_span_label(prev_info.span, "previous declaration"); - buffer_lint(sess, span, node_id, "duplicate matcher binding"); + buffer_lint(psess, span, node_id, "duplicate matcher binding"); } else if get_binder_info(macros, binders, name).is_none() { // 2. The meta-variable is free: This is a binder. binders.insert(name, BinderInfo { span, ops: ops.into() }); } else { // 3. The meta-variable is bound: This is an occurrence. - check_occurrences(sess, node_id, lhs, macros, binders, ops, guar); + check_occurrences(psess, node_id, lhs, macros, binders, ops, guar); } } // Similarly, this can only happen when checking a toplevel macro. @@ -267,7 +267,7 @@ fn check_binders( // FIXME: Report this as a hard error eventually and remove equivalent errors from // `parse_tt_inner` and `nameize`. Until then the error may be reported twice, once // as a hard error and then once as a buffered lint. - sess.buffer_lint( + psess.buffer_lint( MISSING_FRAGMENT_SPECIFIER, span, node_id, @@ -275,14 +275,15 @@ fn check_binders( ); } if !macros.is_empty() { - sess.dcx.span_bug(span, "unexpected MetaVarDecl in nested lhs"); + psess.dcx.span_bug(span, "unexpected MetaVarDecl in nested lhs"); } let name = MacroRulesNormalizedIdent::new(name); if let Some(prev_info) = get_binder_info(macros, binders, name) { // Duplicate binders at the top-level macro definition are errors. The lint is only // for nested macro definitions. *guar = Some( - sess.dcx + psess + .dcx .emit_err(errors::DuplicateMatcherBinding { span, prev: prev_info.span }), ); } else { @@ -293,13 +294,13 @@ fn check_binders( TokenTree::MetaVarExpr(..) => {} TokenTree::Delimited(.., ref del) => { for tt in &del.tts { - check_binders(sess, node_id, tt, macros, binders, ops, guar); + check_binders(psess, node_id, tt, macros, binders, ops, guar); } } TokenTree::Sequence(_, ref seq) => { let ops = ops.push(seq.kleene); for tt in &seq.tts { - check_binders(sess, node_id, tt, macros, binders, &ops, guar); + check_binders(psess, node_id, tt, macros, binders, &ops, guar); } } } @@ -323,7 +324,7 @@ fn get_binder_info<'a>( /// errors. /// /// Arguments: -/// - `sess` is used to emit diagnostics and lints +/// - `psess` is used to emit diagnostics and lints /// - `node_id` is used to emit lints /// - `rhs` is checked as part of a RHS /// - `macros` is the stack of possible outer macros @@ -331,7 +332,7 @@ fn get_binder_info<'a>( /// - `ops` is the stack of Kleene operators from the RHS /// - `guar` is set in case of errors fn check_occurrences( - sess: &ParseSess, + psess: &ParseSess, node_id: NodeId, rhs: &TokenTree, macros: &Stack<'_, MacroState<'_>>, @@ -342,24 +343,24 @@ fn check_occurrences( match *rhs { TokenTree::Token(..) => {} TokenTree::MetaVarDecl(span, _name, _kind) => { - sess.dcx.span_bug(span, "unexpected MetaVarDecl in rhs") + psess.dcx.span_bug(span, "unexpected MetaVarDecl in rhs") } TokenTree::MetaVar(span, name) => { let name = MacroRulesNormalizedIdent::new(name); - check_ops_is_prefix(sess, node_id, macros, binders, ops, span, name); + check_ops_is_prefix(psess, node_id, macros, binders, ops, span, name); } TokenTree::MetaVarExpr(dl, ref mve) => { let Some(name) = mve.ident().map(MacroRulesNormalizedIdent::new) else { return; }; - check_ops_is_prefix(sess, node_id, macros, binders, ops, dl.entire(), name); + check_ops_is_prefix(psess, node_id, macros, binders, ops, dl.entire(), name); } TokenTree::Delimited(.., ref del) => { - check_nested_occurrences(sess, node_id, &del.tts, macros, binders, ops, guar); + check_nested_occurrences(psess, node_id, &del.tts, macros, binders, ops, guar); } TokenTree::Sequence(_, ref seq) => { let ops = ops.push(seq.kleene); - check_nested_occurrences(sess, node_id, &seq.tts, macros, binders, &ops, guar); + check_nested_occurrences(psess, node_id, &seq.tts, macros, binders, &ops, guar); } } } @@ -388,7 +389,7 @@ enum NestedMacroState { /// definitions, and sets `valid` to false in case of errors. /// /// Arguments: -/// - `sess` is used to emit diagnostics and lints +/// - `psess` is used to emit diagnostics and lints /// - `node_id` is used to emit lints /// - `tts` is checked as part of a RHS and may contain macro definitions /// - `macros` is the stack of possible outer macros @@ -396,7 +397,7 @@ enum NestedMacroState { /// - `ops` is the stack of Kleene operators from the RHS /// - `guar` is set in case of errors fn check_nested_occurrences( - sess: &ParseSess, + psess: &ParseSess, node_id: NodeId, tts: &[TokenTree], macros: &Stack<'_, MacroState<'_>>, @@ -434,7 +435,7 @@ fn check_nested_occurrences( (NestedMacroState::MacroRulesNot, &TokenTree::MetaVar(..)) => { state = NestedMacroState::MacroRulesNotName; // We check that the meta-variable is correctly used. - check_occurrences(sess, node_id, tt, macros, binders, ops, guar); + check_occurrences(psess, node_id, tt, macros, binders, ops, guar); } (NestedMacroState::MacroRulesNotName, TokenTree::Delimited(.., del)) | (NestedMacroState::MacroName, TokenTree::Delimited(.., del)) @@ -443,11 +444,11 @@ fn check_nested_occurrences( let macro_rules = state == NestedMacroState::MacroRulesNotName; state = NestedMacroState::Empty; let rest = - check_nested_macro(sess, node_id, macro_rules, &del.tts, &nested_macros, guar); + check_nested_macro(psess, node_id, macro_rules, &del.tts, &nested_macros, guar); // If we did not check the whole macro definition, then check the rest as if outside // the macro definition. check_nested_occurrences( - sess, + psess, node_id, &del.tts[rest..], macros, @@ -465,7 +466,7 @@ fn check_nested_occurrences( (NestedMacroState::Macro, &TokenTree::MetaVar(..)) => { state = NestedMacroState::MacroName; // We check that the meta-variable is correctly used. - check_occurrences(sess, node_id, tt, macros, binders, ops, guar); + check_occurrences(psess, node_id, tt, macros, binders, ops, guar); } (NestedMacroState::MacroName, TokenTree::Delimited(.., del)) if del.delim == Delimiter::Parenthesis => @@ -473,7 +474,7 @@ fn check_nested_occurrences( state = NestedMacroState::MacroNameParen; nested_binders = Binders::default(); check_binders( - sess, + psess, node_id, tt, &nested_macros, @@ -487,7 +488,7 @@ fn check_nested_occurrences( { state = NestedMacroState::Empty; check_occurrences( - sess, + psess, node_id, tt, &nested_macros, @@ -498,7 +499,7 @@ fn check_nested_occurrences( } (_, tt) => { state = NestedMacroState::Empty; - check_occurrences(sess, node_id, tt, macros, binders, ops, guar); + check_occurrences(psess, node_id, tt, macros, binders, ops, guar); } } } @@ -512,14 +513,14 @@ fn check_nested_occurrences( /// stopped checking because we detected we were not in a macro definition anymore. /// /// Arguments: -/// - `sess` is used to emit diagnostics and lints +/// - `psess` is used to emit diagnostics and lints /// - `node_id` is used to emit lints /// - `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 /// - `guar` is set in case of errors fn check_nested_macro( - sess: &ParseSess, + psess: &ParseSess, node_id: NodeId, macro_rules: bool, tts: &[TokenTree], @@ -541,8 +542,8 @@ fn check_nested_macro( let lhs = &tts[i]; let rhs = &tts[i + 2]; let mut binders = Binders::default(); - check_binders(sess, node_id, lhs, macros, &mut binders, &Stack::Empty, guar); - check_occurrences(sess, node_id, rhs, macros, &binders, &Stack::Empty, guar); + check_binders(psess, node_id, lhs, macros, &mut binders, &Stack::Empty, guar); + check_occurrences(psess, node_id, rhs, macros, &binders, &Stack::Empty, guar); // 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. @@ -559,7 +560,7 @@ fn check_nested_macro( /// Checks that a meta-variable occurrence is valid. /// /// Arguments: -/// - `sess` is used to emit diagnostics and lints +/// - `psess` is used to emit diagnostics and lints /// - `node_id` is used to emit lints /// - `macros` is the stack of possible outer macros /// - `binders` contains the binders of the associated LHS @@ -567,7 +568,7 @@ fn check_nested_macro( /// - `span` is the span of the meta-variable to check /// - `name` is the name of the meta-variable to check fn check_ops_is_prefix( - sess: &ParseSess, + psess: &ParseSess, node_id: NodeId, macros: &Stack<'_, MacroState<'_>>, binders: &Binders, @@ -590,11 +591,11 @@ fn check_ops_is_prefix( for ops in acc.iter().rev() { occurrence_ops.extend_from_slice(ops); } - ops_is_prefix(sess, node_id, span, name, &binder.ops, &occurrence_ops); + ops_is_prefix(psess, node_id, span, name, &binder.ops, &occurrence_ops); return; } } - buffer_lint(sess, span.into(), node_id, format!("unknown macro variable `{name}`")); + buffer_lint(psess, span.into(), node_id, format!("unknown macro variable `{name}`")); } /// Returns whether `binder_ops` is a prefix of `occurrence_ops`. @@ -609,14 +610,14 @@ fn check_ops_is_prefix( /// It occurs under the Kleene stack ["*", "+"] and is bound under ["*"] only. /// /// Arguments: -/// - `sess` is used to emit diagnostics and lints +/// - `psess` is used to emit diagnostics and lints /// - `node_id` is used to emit lints /// - `span` is the span of the meta-variable being check /// - `name` is the name of the meta-variable being check /// - `binder_ops` is the stack of Kleene operators for the binder /// - `occurrence_ops` is the stack of Kleene operators for the occurrence fn ops_is_prefix( - sess: &ParseSess, + psess: &ParseSess, node_id: NodeId, span: Span, name: MacroRulesNormalizedIdent, @@ -628,7 +629,7 @@ fn ops_is_prefix( let mut span = MultiSpan::from_span(span); span.push_span_label(binder.span, "expected repetition"); let message = format!("variable '{name}' is still repeating at this depth"); - buffer_lint(sess, span, node_id, message); + buffer_lint(psess, span, node_id, message); return; } let occurrence = &occurrence_ops[i]; @@ -637,20 +638,20 @@ fn ops_is_prefix( span.push_span_label(binder.span, "expected repetition"); span.push_span_label(occurrence.span, "conflicting repetition"); let message = "meta-variable repeats with different Kleene operator"; - buffer_lint(sess, span, node_id, message); + buffer_lint(psess, span, node_id, message); return; } } } fn buffer_lint( - sess: &ParseSess, + psess: &ParseSess, span: MultiSpan, node_id: NodeId, message: impl Into, ) { // Macros loaded from other crates have dummy node ids. if node_id != DUMMY_NODE_ID { - sess.buffer_lint(META_VARIABLE_MISUSE, span, node_id, message); + psess.buffer_lint(META_VARIABLE_MISUSE, span, node_id, message); } } diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index c11d538048aa9..c8631d9681053 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -78,7 +78,7 @@ impl<'a> ParserAnyMacro<'a> { // but `m!()` is allowed in expression positions (cf. issue #34706). if kind == AstFragmentKind::Expr && parser.token == token::Semi { if is_local { - parser.sess.buffer_lint_with_diagnostic( + parser.psess.buffer_lint_with_diagnostic( SEMICOLON_IN_EXPRESSIONS_FROM_MACROS, parser.token.span, lint_node_id, @@ -195,7 +195,7 @@ fn expand_macro<'cx>( lhses: &[Vec], rhses: &[mbe::TokenTree], ) -> Box { - let sess = &cx.sess.parse_sess; + let psess = &cx.sess.psess; // Macros defined in the current crate have a real node id, // whereas macros from an external crate have a dummy id. let is_local = node_id != DUMMY_NODE_ID; @@ -206,7 +206,7 @@ fn expand_macro<'cx>( } // Track nothing for the best performance. - let try_success_result = try_match_macro(sess, name, &arg, lhses, &mut NoopTracker); + let try_success_result = try_match_macro(psess, name, &arg, lhses, &mut NoopTracker); match try_success_result { Ok((i, named_matches)) => { @@ -230,7 +230,7 @@ fn expand_macro<'cx>( trace_macros_note(&mut cx.expansions, sp, msg); } - let p = Parser::new(sess, tts, None); + let p = Parser::new(psess, tts, None); if is_local { cx.resolver.record_macro_rule_usage(node_id, i); @@ -272,9 +272,9 @@ pub(super) enum CanRetry { /// Try expanding the macro. Returns the index of the successful arm and its named_matches if it was successful, /// and nothing if it failed. On failure, it's the callers job to use `track` accordingly to record all errors /// correctly. -#[instrument(level = "debug", skip(sess, arg, lhses, track), fields(tracking = %T::description()))] +#[instrument(level = "debug", skip(psess, arg, lhses, track), fields(tracking = %T::description()))] pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( - sess: &ParseSess, + psess: &ParseSess, name: Ident, arg: &TokenStream, lhses: &'matcher [Vec], @@ -299,7 +299,7 @@ pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( // hacky, but speeds up the `html5ever` benchmark significantly. (Issue // 68836 suggests a more comprehensive but more complex change to deal with // this situation.) - let parser = parser_from_cx(sess, arg.clone(), T::recovery()); + let parser = parser_from_cx(psess, arg.clone(), T::recovery()); // Try each arm's matchers. let mut tt_parser = TtParser::new(name); for (i, lhs) in lhses.iter().enumerate() { @@ -309,7 +309,7 @@ pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( // This is used so that if a matcher is not `Success(..)`ful, // then the spans which became gated when parsing the unsuccessful matcher // are not recorded. On the first `Success(..)`ful matcher, the spans are merged. - let mut gated_spans_snapshot = mem::take(&mut *sess.gated_spans.spans.borrow_mut()); + let mut gated_spans_snapshot = mem::take(&mut *psess.gated_spans.spans.borrow_mut()); let result = tt_parser.parse_tt(&mut Cow::Borrowed(&parser), lhs, track); @@ -320,7 +320,7 @@ pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( debug!("Parsed arm successfully"); // The matcher was `Success(..)`ful. // Merge the gated spans from parsing the matcher with the preexisting ones. - sess.gated_spans.merge(gated_spans_snapshot); + psess.gated_spans.merge(gated_spans_snapshot); return Ok((i, named_matches)); } @@ -342,7 +342,7 @@ pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( // The matcher was not `Success(..)`ful. // Restore to the state before snapshotting and maybe try again. - mem::swap(&mut gated_spans_snapshot, &mut sess.gated_spans.spans.borrow_mut()); + mem::swap(&mut gated_spans_snapshot, &mut psess.gated_spans.spans.borrow_mut()); } Err(CanRetry::Yes) @@ -376,7 +376,7 @@ pub fn compile_declarative_macro( }; let dummy_syn_ext = |guar| (mk_syn_ext(Box::new(DummyExpander(guar))), Vec::new()); - let dcx = &sess.parse_sess.dcx; + let dcx = &sess.psess.dcx; let lhs_nm = Ident::new(sym::lhs, def.span); let rhs_nm = Ident::new(sym::rhs, def.span); let tt_spec = Some(NonterminalKind::TT); @@ -430,7 +430,7 @@ pub fn compile_declarative_macro( let create_parser = || { let body = macro_def.body.tokens.clone(); - Parser::new(&sess.parse_sess, body, rustc_parse::MACRO_ARGUMENTS) + Parser::new(&sess.psess, body, rustc_parse::MACRO_ARGUMENTS) }; let parser = create_parser(); @@ -533,7 +533,7 @@ pub fn compile_declarative_macro( } check_emission(macro_check::check_meta_variables( - &sess.parse_sess, + &sess.psess, def.id, def.span, &lhses, @@ -1149,7 +1149,7 @@ fn check_matcher_core<'tt>( name, Some(NonterminalKind::PatParam { inferred: false }), )); - sess.parse_sess.buffer_lint_with_diagnostic( + sess.psess.buffer_lint_with_diagnostic( RUST_2021_INCOMPATIBLE_OR_PATTERNS, span, ast::CRATE_NODE_ID, @@ -1182,7 +1182,7 @@ fn check_matcher_core<'tt>( err.span_label(sp, format!("not allowed after `{kind}` fragments")); if kind == NonterminalKind::PatWithOr - && sess.parse_sess.edition.at_least_rust_2021() + && sess.psess.edition.at_least_rust_2021() && next_token.is_token(&BinOp(token::BinOpToken::Or)) { let suggestion = quoted_tt_to_string(&TokenTree::MetaVarDecl( @@ -1406,10 +1406,10 @@ fn quoted_tt_to_string(tt: &mbe::TokenTree) -> String { } pub(super) fn parser_from_cx( - sess: &ParseSess, + psess: &ParseSess, mut tts: TokenStream, recovery: Recovery, ) -> Parser<'_> { tts.desugar_doc_comments(); - Parser::new(sess, tts, rustc_parse::MACRO_ARGUMENTS).recovery(recovery) + Parser::new(psess, tts, rustc_parse::MACRO_ARGUMENTS).recovery(recovery) } diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs index 84f7dc4771a9e..81e1de5b09544 100644 --- a/compiler/rustc_expand/src/mbe/metavar_expr.rs +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -27,30 +27,30 @@ pub(crate) enum MetaVarExpr { impl MetaVarExpr { /// Attempt to parse a meta-variable expression from a token stream. - pub(crate) fn parse<'sess>( + pub(crate) fn parse<'psess>( input: &TokenStream, outer_span: Span, - sess: &'sess ParseSess, - ) -> PResult<'sess, MetaVarExpr> { + psess: &'psess ParseSess, + ) -> PResult<'psess, MetaVarExpr> { let mut tts = input.trees(); - let ident = parse_ident(&mut tts, sess, outer_span)?; + let ident = parse_ident(&mut tts, psess, outer_span)?; let Some(TokenTree::Delimited(.., Delimiter::Parenthesis, args)) = tts.next() else { let msg = "meta-variable expression parameter must be wrapped in parentheses"; - return Err(sess.dcx.struct_span_err(ident.span, msg)); + return Err(psess.dcx.struct_span_err(ident.span, msg)); }; - check_trailing_token(&mut tts, sess)?; + check_trailing_token(&mut tts, psess)?; let mut iter = args.trees(); let rslt = match ident.as_str() { - "count" => parse_count(&mut iter, sess, ident.span)?, + "count" => parse_count(&mut iter, psess, ident.span)?, "ignore" => { - eat_dollar(&mut iter, sess, ident.span)?; - MetaVarExpr::Ignore(parse_ident(&mut iter, sess, ident.span)?) + eat_dollar(&mut iter, psess, ident.span)?; + MetaVarExpr::Ignore(parse_ident(&mut iter, psess, ident.span)?) } - "index" => MetaVarExpr::Index(parse_depth(&mut iter, sess, ident.span)?), - "length" => MetaVarExpr::Length(parse_depth(&mut iter, sess, ident.span)?), + "index" => MetaVarExpr::Index(parse_depth(&mut iter, psess, ident.span)?), + "length" => MetaVarExpr::Length(parse_depth(&mut iter, psess, ident.span)?), _ => { let err_msg = "unrecognized meta-variable expression"; - let mut err = sess.dcx.struct_span_err(ident.span, err_msg); + let mut err = psess.dcx.struct_span_err(ident.span, err_msg); err.span_suggestion( ident.span, "supported expressions are count, ignore, index and length", @@ -60,7 +60,7 @@ impl MetaVarExpr { return Err(err); } }; - check_trailing_token(&mut iter, sess)?; + check_trailing_token(&mut iter, psess)?; Ok(rslt) } @@ -73,12 +73,12 @@ impl MetaVarExpr { } // Checks if there are any remaining tokens. For example, `${ignore(ident ... a b c ...)}` -fn check_trailing_token<'sess>( +fn check_trailing_token<'psess>( iter: &mut RefTokenTreeCursor<'_>, - sess: &'sess ParseSess, -) -> PResult<'sess, ()> { + psess: &'psess ParseSess, +) -> PResult<'psess, ()> { if let Some(tt) = iter.next() { - let mut diag = sess + let mut diag = psess .dcx .struct_span_err(tt.span(), format!("unexpected token: {}", pprust::tt_to_string(tt))); diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens"); @@ -89,21 +89,21 @@ fn check_trailing_token<'sess>( } /// Parse a meta-variable `count` expression: `count(ident[, depth])` -fn parse_count<'sess>( +fn parse_count<'psess>( iter: &mut RefTokenTreeCursor<'_>, - sess: &'sess ParseSess, + psess: &'psess ParseSess, span: Span, -) -> PResult<'sess, MetaVarExpr> { - eat_dollar(iter, sess, span)?; - let ident = parse_ident(iter, sess, span)?; +) -> PResult<'psess, MetaVarExpr> { + eat_dollar(iter, psess, span)?; + let ident = parse_ident(iter, psess, span)?; let depth = if try_eat_comma(iter) { if iter.look_ahead(0).is_none() { - return Err(sess.dcx.struct_span_err( + return Err(psess.dcx.struct_span_err( span, "`count` followed by a comma must have an associated index indicating its depth", )); } - parse_depth(iter, sess, span)? + parse_depth(iter, psess, span)? } else { 0 }; @@ -111,14 +111,14 @@ fn parse_count<'sess>( } /// Parses the depth used by index(depth) and length(depth). -fn parse_depth<'sess>( +fn parse_depth<'psess>( iter: &mut RefTokenTreeCursor<'_>, - sess: &'sess ParseSess, + psess: &'psess ParseSess, span: Span, -) -> PResult<'sess, usize> { +) -> PResult<'psess, usize> { let Some(tt) = iter.next() else { return Ok(0) }; let TokenTree::Token(token::Token { kind: token::TokenKind::Literal(lit), .. }, _) = tt else { - return Err(sess + return Err(psess .dcx .struct_span_err(span, "meta-variable expression depth must be a literal")); }; @@ -129,16 +129,16 @@ fn parse_depth<'sess>( Ok(n_usize) } else { let msg = "only unsuffixes integer literals are supported in meta-variable expressions"; - Err(sess.dcx.struct_span_err(span, msg)) + Err(psess.dcx.struct_span_err(span, msg)) } } /// Parses an generic ident -fn parse_ident<'sess>( +fn parse_ident<'psess>( iter: &mut RefTokenTreeCursor<'_>, - sess: &'sess ParseSess, + psess: &'psess ParseSess, span: Span, -) -> PResult<'sess, Ident> { +) -> PResult<'psess, Ident> { if let Some(tt) = iter.next() && let TokenTree::Token(token, _) = tt { @@ -147,7 +147,7 @@ fn parse_ident<'sess>( } let token_str = pprust::token_to_string(token); let mut err = - sess.dcx.struct_span_err(span, format!("expected identifier, found `{}`", &token_str)); + psess.dcx.struct_span_err(span, format!("expected identifier, found `{}`", &token_str)); err.span_suggestion( token.span, format!("try removing `{}`", &token_str), @@ -156,7 +156,7 @@ fn parse_ident<'sess>( ); return Err(err); } - Err(sess.dcx.struct_span_err(span, "expected identifier")) + Err(psess.dcx.struct_span_err(span, "expected identifier")) } /// Tries to move the iterator forward returning `true` if there is a comma. If not, then the @@ -170,17 +170,17 @@ fn try_eat_comma(iter: &mut RefTokenTreeCursor<'_>) -> bool { } /// Expects that the next item is a dollar sign. -fn eat_dollar<'sess>( +fn eat_dollar<'psess>( iter: &mut RefTokenTreeCursor<'_>, - sess: &'sess ParseSess, + psess: &'psess ParseSess, span: Span, -) -> PResult<'sess, ()> { +) -> PResult<'psess, ()> { if let Some(TokenTree::Token(token::Token { kind: token::Dollar, .. }, _)) = iter.look_ahead(0) { let _ = iter.next(); return Ok(()); } - Err(sess.dcx.struct_span_err( + Err(psess.dcx.struct_span_err( span, "meta-variables within meta-variable expressions must be referenced using a dollar sign", )) diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index ec1dd807d1a4f..5fd3716743b22 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -175,8 +175,7 @@ fn parse_tree<'a>( // The delimiter is `{`. This indicates the beginning // of a meta-variable expression (e.g. `${count(ident)}`). // Try to parse the meta-variable expression. - match MetaVarExpr::parse(tts, delim_span.entire(), &sess.parse_sess) - { + match MetaVarExpr::parse(tts, delim_span.entire(), &sess.psess) { Err(err) => { err.emit(); // Returns early the same read `$` to avoid spanning diff --git a/compiler/rustc_expand/src/module.rs b/compiler/rustc_expand/src/module.rs index 1282cf2c03a00..8a68b39e4965e 100644 --- a/compiler/rustc_expand/src/module.rs +++ b/compiler/rustc_expand/src/module.rs @@ -66,7 +66,7 @@ pub(crate) fn parse_external_mod( } // Actually parse the external file as a module. - let mut parser = new_parser_from_file(&sess.parse_sess, &mp.file_path, Some(span)); + let mut parser = new_parser_from_file(&sess.psess, &mp.file_path, Some(span)); let (inner_attrs, items, inner_span) = parser.parse_mod(&token::Eof).map_err(|err| ModError::ParserError(err))?; attrs.extend(inner_attrs); @@ -157,7 +157,7 @@ fn mod_file_path<'a>( DirOwnership::Owned { relative } => relative, DirOwnership::UnownedViaBlock => None, }; - let result = default_submod_path(&sess.parse_sess, ident, relative, dir_path); + let result = default_submod_path(&sess.psess, ident, relative, dir_path); match dir_ownership { DirOwnership::Owned { .. } => result, DirOwnership::UnownedViaBlock => Err(ModError::ModInBlock(match result { @@ -185,11 +185,7 @@ fn mod_file_path_from_attr( // complexity). Usually bad forms are checked in AstValidator (via // `check_builtin_attribute`), but by the time that runs the macro // is expanded, and it doesn't give an error. - validate_attr::emit_fatal_malformed_builtin_attribute( - &sess.parse_sess, - first_path, - sym::path, - ); + validate_attr::emit_fatal_malformed_builtin_attribute(&sess.psess, first_path, sym::path); }; let path_str = path_sym.as_str(); @@ -207,7 +203,7 @@ fn mod_file_path_from_attr( /// Returns a path to a module. // Public for rustfmt usage. pub fn default_submod_path<'a>( - sess: &'a ParseSess, + psess: &'a ParseSess, ident: Ident, relative: Option, dir_path: &Path, @@ -229,8 +225,8 @@ pub fn default_submod_path<'a>( format!("{}{}{}mod.rs", relative_prefix, ident.name, path::MAIN_SEPARATOR); let default_path = dir_path.join(&default_path_str); let secondary_path = dir_path.join(&secondary_path_str); - let default_exists = sess.source_map().file_exists(&default_path); - let secondary_exists = sess.source_map().file_exists(&secondary_path); + let default_exists = psess.source_map().file_exists(&default_path); + let secondary_exists = psess.source_map().file_exists(&secondary_path); match (default_exists, secondary_exists) { (true, false) => Ok(ModulePathSuccess { diff --git a/compiler/rustc_expand/src/parse/tests.rs b/compiler/rustc_expand/src/parse/tests.rs index 5ffe8f3c73e6a..066afd7a41d28 100644 --- a/compiler/rustc_expand/src/parse/tests.rs +++ b/compiler/rustc_expand/src/parse/tests.rs @@ -1,5 +1,5 @@ use crate::tests::{ - matches_codepattern, sess, string_to_stream, with_error_checking_parse, + matches_codepattern, psess, string_to_stream, with_error_checking_parse, with_expected_parse_error, }; @@ -26,9 +26,9 @@ use std::path::PathBuf; fn parse_item_from_source_str( name: FileName, source: String, - sess: &ParseSess, + psess: &ParseSess, ) -> PResult<'_, Option>> { - new_parser_from_source_str(sess, name, source).parse_item(ForceCollect::No) + new_parser_from_source_str(psess, name, source).parse_item(ForceCollect::No) } // Produces a `rustc_span::span`. @@ -38,12 +38,12 @@ fn sp(a: u32, b: u32) -> Span { /// Parses a string, return an expression. fn string_to_expr(source_str: String) -> P { - with_error_checking_parse(source_str, &sess(), |p| p.parse_expr()) + with_error_checking_parse(source_str, &psess(), |p| p.parse_expr()) } /// Parses a string, returns an item. fn string_to_item(source_str: String) -> Option> { - with_error_checking_parse(source_str, &sess(), |p| p.parse_item(ForceCollect::No)) + with_error_checking_parse(source_str, &psess(), |p| p.parse_item(ForceCollect::No)) } #[test] @@ -279,24 +279,24 @@ let mut fflags: c_int = wb(); #[test] fn crlf_doc_comments() { create_default_session_globals_then(|| { - let sess = sess(); + let psess = psess(); let name_1 = FileName::Custom("crlf_source_1".to_string()); let source = "/// doc comment\r\nfn foo() {}".to_string(); - let item = parse_item_from_source_str(name_1, source, &sess).unwrap().unwrap(); + let item = parse_item_from_source_str(name_1, source, &psess).unwrap().unwrap(); let doc = item.attrs.iter().filter_map(|at| at.doc_str()).next().unwrap(); assert_eq!(doc.as_str(), " doc comment"); let name_2 = FileName::Custom("crlf_source_2".to_string()); let source = "/// doc comment\r\n/// line 2\r\nfn foo() {}".to_string(); - let item = parse_item_from_source_str(name_2, source, &sess).unwrap().unwrap(); + let item = parse_item_from_source_str(name_2, source, &psess).unwrap().unwrap(); let docs = item.attrs.iter().filter_map(|at| at.doc_str()).collect::>(); let b: &[_] = &[Symbol::intern(" doc comment"), Symbol::intern(" line 2")]; assert_eq!(&docs[..], b); let name_3 = FileName::Custom("clrf_source_3".to_string()); let source = "/** doc comment\r\n * with CRLF */\r\nfn foo() {}".to_string(); - let item = parse_item_from_source_str(name_3, source, &sess).unwrap().unwrap(); + let item = parse_item_from_source_str(name_3, source, &psess).unwrap().unwrap(); let doc = item.attrs.iter().filter_map(|at| at.doc_str()).next().unwrap(); assert_eq!(doc.as_str(), " doc comment\n * with CRLF "); }); @@ -307,24 +307,24 @@ fn ttdelim_span() { fn parse_expr_from_source_str( name: FileName, source: String, - sess: &ParseSess, + psess: &ParseSess, ) -> PResult<'_, P> { - new_parser_from_source_str(sess, name, source).parse_expr() + new_parser_from_source_str(psess, name, source).parse_expr() } create_default_session_globals_then(|| { - let sess = sess(); + let psess = psess(); let expr = parse_expr_from_source_str( PathBuf::from("foo").into(), "foo!( fn main() { body } )".to_string(), - &sess, + &psess, ) .unwrap(); let ast::ExprKind::MacCall(mac) = &expr.kind else { panic!("not a macro") }; let span = mac.args.tokens.trees().last().unwrap().span(); - match sess.source_map().span_to_snippet(span) { + match psess.source_map().span_to_snippet(span) { Ok(s) => assert_eq!(&s[..], "{ body }"), Err(_) => panic!("could not get snippet"), } @@ -340,7 +340,7 @@ fn out_of_line_mod() { let item = parse_item_from_source_str( PathBuf::from("foo").into(), "mod foo { struct S; mod this_does_not_exist; }".to_owned(), - &sess(), + &psess(), ) .unwrap() .unwrap(); diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 23caf2f193aad..4b5c148cb555d 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -162,7 +162,7 @@ impl MultiItemModifier for DeriveProcMacro { let error_count_before = ecx.dcx().err_count(); let mut parser = - rustc_parse::stream_to_parser(&ecx.sess.parse_sess, stream, Some("proc-macro derive")); + rustc_parse::stream_to_parser(&ecx.sess.psess, stream, Some("proc-macro derive")); let mut items = vec![]; loop { diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 6fe0d61136322..efe35c252d84a 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -354,7 +354,7 @@ impl ToInternal> )] } TokenTree::Ident(self::Ident { sym, is_raw, span }) => { - rustc.sess().symbol_gallery.insert(sym, span); + rustc.psess().symbol_gallery.insert(sym, span); smallvec![tokenstream::TokenTree::token_alone(Ident(sym, is_raw.into()), span)] } TokenTree::Literal(self::Literal { @@ -429,8 +429,8 @@ impl<'a, 'b> Rustc<'a, 'b> { } } - fn sess(&self) -> &ParseSess { - self.ecx.parse_sess() + fn psess(&self) -> &ParseSess { + self.ecx.psess() } } @@ -448,19 +448,19 @@ impl server::FreeFunctions for Rustc<'_, '_> { } fn track_env_var(&mut self, var: &str, value: Option<&str>) { - self.sess() + self.psess() .env_depinfo .borrow_mut() .insert((Symbol::intern(var), value.map(Symbol::intern))); } fn track_path(&mut self, path: &str) { - self.sess().file_depinfo.borrow_mut().insert(Symbol::intern(path)); + self.psess().file_depinfo.borrow_mut().insert(Symbol::intern(path)); } fn literal_from_str(&mut self, s: &str) -> Result, ()> { let name = FileName::proc_macro_source_code(s); - let mut parser = rustc_parse::new_parser_from_source_str(self.sess(), name, s.to_owned()); + let mut parser = rustc_parse::new_parser_from_source_str(self.psess(), name, s.to_owned()); let first_span = parser.token.span.data(); let minus_present = parser.eat(&token::BinOp(token::Minus)); @@ -514,7 +514,7 @@ impl server::FreeFunctions for Rustc<'_, '_> { fn emit_diagnostic(&mut self, diagnostic: Diagnostic) { let message = rustc_errors::DiagnosticMessage::from(diagnostic.message); let mut diag: Diag<'_, ()> = - Diag::new(&self.sess().dcx, diagnostic.level.to_internal(), message); + Diag::new(&self.psess().dcx, diagnostic.level.to_internal(), message); diag.span(MultiSpan::from_spans(diagnostic.spans)); for child in diagnostic.children { diag.sub(child.level.to_internal(), child.message, MultiSpan::from_spans(child.spans)); @@ -532,7 +532,7 @@ impl server::TokenStream for Rustc<'_, '_> { parse_stream_from_source_str( FileName::proc_macro_source_code(src), src.to_string(), - self.sess(), + self.psess(), Some(self.call_site), ) } @@ -545,7 +545,7 @@ impl server::TokenStream for Rustc<'_, '_> { // Parse the expression from our tokenstream. let expr: PResult<'_, _> = try { let mut p = rustc_parse::stream_to_parser( - self.sess(), + self.psess(), stream.clone(), Some("proc_macro expand expr"), ); @@ -680,7 +680,7 @@ impl server::Span for Rustc<'_, '_> { } fn source_file(&mut self, span: Self::Span) -> Self::SourceFile { - self.sess().source_map().lookup_char_pos(span.lo()).file + self.psess().source_map().lookup_char_pos(span.lo()).file } fn parent(&mut self, span: Self::Span) -> Option { @@ -692,7 +692,7 @@ impl server::Span for Rustc<'_, '_> { } fn byte_range(&mut self, span: Self::Span) -> Range { - let source_map = self.sess().source_map(); + let source_map = self.psess().source_map(); let relative_start_pos = source_map.lookup_byte_offset(span.lo()).pos; let relative_end_pos = source_map.lookup_byte_offset(span.hi()).pos; @@ -708,18 +708,18 @@ impl server::Span for Rustc<'_, '_> { } fn line(&mut self, span: Self::Span) -> usize { - let loc = self.sess().source_map().lookup_char_pos(span.lo()); + let loc = self.psess().source_map().lookup_char_pos(span.lo()); loc.line } fn column(&mut self, span: Self::Span) -> usize { - let loc = self.sess().source_map().lookup_char_pos(span.lo()); + let loc = self.psess().source_map().lookup_char_pos(span.lo()); loc.col.to_usize() + 1 } fn join(&mut self, first: Self::Span, second: Self::Span) -> Option { - let self_loc = self.sess().source_map().lookup_char_pos(first.lo()); - let other_loc = self.sess().source_map().lookup_char_pos(second.lo()); + let self_loc = self.psess().source_map().lookup_char_pos(first.lo()); + let other_loc = self.psess().source_map().lookup_char_pos(second.lo()); if self_loc.file.name != other_loc.file.name { return None; @@ -769,7 +769,7 @@ impl server::Span for Rustc<'_, '_> { } fn source_text(&mut self, span: Self::Span) -> Option { - self.sess().source_map().span_to_snippet(span).ok() + self.psess().source_map().span_to_snippet(span).ok() } /// Saves the provided span into the metadata of @@ -797,7 +797,7 @@ impl server::Span for Rustc<'_, '_> { /// since we've loaded `my_proc_macro` from disk in order to execute it). /// In this way, we have obtained a span pointing into `my_proc_macro` fn save_span(&mut self, span: Self::Span) -> usize { - self.sess().save_proc_macro_span(span) + self.psess().save_proc_macro_span(span) } fn recover_proc_macro_span(&mut self, id: usize) -> Self::Span { diff --git a/compiler/rustc_expand/src/tests.rs b/compiler/rustc_expand/src/tests.rs index 7d19ca13c9701..8c47b7594535c 100644 --- a/compiler/rustc_expand/src/tests.rs +++ b/compiler/rustc_expand/src/tests.rs @@ -18,13 +18,13 @@ use std::path::{Path, PathBuf}; use std::str; use std::sync::{Arc, Mutex}; -pub(crate) fn sess() -> ParseSess { +pub(crate) fn psess() -> ParseSess { ParseSess::new(vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE]) } /// Map string to parser (via tts). -fn string_to_parser(ps: &ParseSess, source_str: String) -> Parser<'_> { - new_parser_from_source_str(ps, PathBuf::from("bogofile").into(), source_str) +fn string_to_parser(psess: &ParseSess, source_str: String) -> Parser<'_> { + new_parser_from_source_str(psess, PathBuf::from("bogofile").into(), source_str) } fn create_test_handler() -> (DiagCtxt, Lrc, Arc>>) { @@ -44,13 +44,13 @@ fn create_test_handler() -> (DiagCtxt, Lrc, Arc>>) { /// Returns the result of parsing the given string via the given callback. /// /// If there are any errors, this will panic. -pub(crate) fn with_error_checking_parse<'a, T, F>(s: String, ps: &'a ParseSess, f: F) -> T +pub(crate) fn with_error_checking_parse<'a, T, F>(s: String, psess: &'a ParseSess, f: F) -> T where F: FnOnce(&mut Parser<'a>) -> PResult<'a, T>, { - let mut p = string_to_parser(&ps, s); + let mut p = string_to_parser(&psess, s); let x = f(&mut p).unwrap(); - p.sess.dcx.abort_if_errors(); + p.psess.dcx.abort_if_errors(); x } @@ -61,8 +61,8 @@ where F: for<'a> FnOnce(&mut Parser<'a>) -> PResult<'a, T>, { let (handler, source_map, output) = create_test_handler(); - let ps = ParseSess::with_dcx(handler, source_map); - let mut p = string_to_parser(&ps, source_str.to_string()); + let psess = ParseSess::with_dcx(handler, source_map); + let mut p = string_to_parser(&psess, source_str.to_string()); let result = f(&mut p); assert!(result.is_ok()); @@ -76,18 +76,18 @@ where /// Maps a string to tts, using a made-up filename. pub(crate) fn string_to_stream(source_str: String) -> TokenStream { - let ps = sess(); + let psess = psess(); source_file_to_stream( - &ps, - ps.source_map().new_source_file(PathBuf::from("bogofile").into(), source_str), + &psess, + psess.source_map().new_source_file(PathBuf::from("bogofile").into(), source_str), None, ) } /// Parses a string, returns a crate. pub(crate) fn string_to_crate(source_str: String) -> ast::Crate { - let ps = sess(); - with_error_checking_parse(source_str, &ps, |p| p.parse_crate_mod()) + let psess = psess(); + with_error_checking_parse(source_str, &psess, |p| p.parse_crate_mod()) } /// Does the given string match the pattern? whitespace in the first string diff --git a/compiler/rustc_hir_analysis/src/check/errs.rs b/compiler/rustc_hir_analysis/src/check/errs.rs index c92320bc0fee8..3d32fdd89c867 100644 --- a/compiler/rustc_hir_analysis/src/check/errs.rs +++ b/compiler/rustc_hir_analysis/src/check/errs.rs @@ -70,7 +70,7 @@ fn handle_static_mut_ref( } else { (errors::StaticMutRefSugg::Shared { span, var }, "shared") }; - tcx.sess.parse_sess.dcx.emit_err(errors::StaticMutRef { span, sugg, shared }); + tcx.sess.psess.dcx.emit_err(errors::StaticMutRef { span, sugg, shared }); return; } diff --git a/compiler/rustc_hir_typeck/src/expr.rs b/compiler/rustc_hir_typeck/src/expr.rs index b8cceebe1036e..fcb490bcfecd5 100644 --- a/compiler/rustc_hir_typeck/src/expr.rs +++ b/compiler/rustc_hir_typeck/src/expr.rs @@ -390,7 +390,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ); let sp = tcx.sess.source_map().start_point(expr.span).with_parent(None); if let Some(sp) = - tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) + tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) { err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp)); } diff --git a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs index 809102557acaa..5a1c7b0561185 100644 --- a/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs +++ b/compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs @@ -1117,7 +1117,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { expr: &hir::Expr<'_>, ) -> bool { let sp = self.tcx.sess.source_map().start_point(expr.span).with_parent(None); - if let Some(sp) = self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) { + if let Some(sp) = self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) { // `{ 42 } &&x` (#61475) or `{ 42 } && if x { 1 } else { 0 }` err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp)); true diff --git a/compiler/rustc_hir_typeck/src/op.rs b/compiler/rustc_hir_typeck/src/op.rs index 9c9507d58522f..79f574aa7fdc4 100644 --- a/compiler/rustc_hir_typeck/src/op.rs +++ b/compiler/rustc_hir_typeck/src/op.rs @@ -818,7 +818,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let sp = self.tcx.sess.source_map().start_point(ex.span).with_parent(None); if let Some(sp) = - self.tcx.sess.parse_sess.ambiguous_block_expr_parse.borrow().get(&sp) + self.tcx.sess.psess.ambiguous_block_expr_parse.borrow().get(&sp) { // If the previous expression was a block expression, suggest parentheses // (turning this into a binary subtraction operation instead.) diff --git a/compiler/rustc_incremental/src/persist/dirty_clean.rs b/compiler/rustc_incremental/src/persist/dirty_clean.rs index 8311a7351333d..24512dea93999 100644 --- a/compiler/rustc_incremental/src/persist/dirty_clean.rs +++ b/compiler/rustc_incremental/src/persist/dirty_clean.rs @@ -395,7 +395,7 @@ impl<'tcx> DirtyCleanVisitor<'tcx> { /// a cfg flag called `foo`. fn check_config(tcx: TyCtxt<'_>, attr: &Attribute) -> bool { debug!("check_config(attr={:?})", attr); - let config = &tcx.sess.parse_sess.config; + let config = &tcx.sess.psess.config; debug!("check_config: config={:?}", config); let mut cfg = None; for item in attr.meta_item_list().unwrap_or_else(ThinVec::new) { diff --git a/compiler/rustc_interface/src/interface.rs b/compiler/rustc_interface/src/interface.rs index cd7957c3bce29..3a2bbed19beff 100644 --- a/compiler/rustc_interface/src/interface.rs +++ b/compiler/rustc_interface/src/interface.rs @@ -45,7 +45,7 @@ pub struct Compiler { pub(crate) fn parse_cfg(dcx: &DiagCtxt, cfgs: Vec) -> Cfg { cfgs.into_iter() .map(|s| { - let sess = ParseSess::with_silent_emitter(format!( + let psess = ParseSess::with_silent_emitter(format!( "this error occurred on the command line: `--cfg={s}`" )); let filename = FileName::cfg_spec_source_code(&s); @@ -61,7 +61,7 @@ pub(crate) fn parse_cfg(dcx: &DiagCtxt, cfgs: Vec) -> Cfg { }; } - match maybe_new_parser_from_source_str(&sess, filename, s.to_string()) { + match maybe_new_parser_from_source_str(&psess, filename, s.to_string()) { Ok(mut parser) => match parser.parse_meta_item() { Ok(meta_item) if parser.token == token::Eof => { if meta_item.path.segments.len() != 1 { @@ -107,7 +107,7 @@ pub(crate) fn parse_check_cfg(dcx: &DiagCtxt, specs: Vec) -> CheckCfg { let mut check_cfg = CheckCfg { exhaustive_names, exhaustive_values, ..CheckCfg::default() }; for s in specs { - let sess = ParseSess::with_silent_emitter(format!( + let psess = ParseSess::with_silent_emitter(format!( "this error occurred on the command line: `--check-cfg={s}`" )); let filename = FileName::cfg_spec_source_code(&s); @@ -127,7 +127,7 @@ pub(crate) fn parse_check_cfg(dcx: &DiagCtxt, specs: Vec) -> CheckCfg { error!("expected `cfg(name, values(\"value1\", \"value2\", ... \"valueN\"))`") }; - let mut parser = match maybe_new_parser_from_source_str(&sess, filename, s.to_string()) { + let mut parser = match maybe_new_parser_from_source_str(&psess, filename, s.to_string()) { Ok(parser) => parser, Err(errs) => { errs.into_iter().for_each(|err| err.cancel()); @@ -277,7 +277,7 @@ pub struct Config { pub lint_caps: FxHashMap, /// This is a callback from the driver that is called when [`ParseSess`] is created. - pub parse_sess_created: Option>, + pub psess_created: Option>, /// This is a callback to hash otherwise untracked state used by the caller, if the /// hash changes between runs the incremental cache will be cleared. @@ -393,14 +393,14 @@ pub fn run_compiler(config: Config, f: impl FnOnce(&Compiler) -> R + Se let cfg = parse_cfg(&sess.dcx(), config.crate_cfg); let mut cfg = config::build_configuration(&sess, cfg); util::add_configuration(&mut cfg, &mut sess, &*codegen_backend); - sess.parse_sess.config = cfg; + sess.psess.config = cfg; let mut check_cfg = parse_check_cfg(&sess.dcx(), config.crate_check_cfg); check_cfg.fill_well_known(&sess.target); - sess.parse_sess.check_config = check_cfg; + sess.psess.check_config = check_cfg; - if let Some(parse_sess_created) = config.parse_sess_created { - parse_sess_created(&mut sess.parse_sess); + if let Some(psess_created) = config.psess_created { + psess_created(&mut sess.psess); } if let Some(hash_untracked_state) = config.hash_untracked_state { @@ -422,7 +422,7 @@ pub fn run_compiler(config: Config, f: impl FnOnce(&Compiler) -> R + Se let compiler = Compiler { sess, codegen_backend, override_queries: config.override_queries }; - rustc_span::set_source_map(compiler.sess.parse_sess.clone_source_map(), move || { + rustc_span::set_source_map(compiler.sess.psess.clone_source_map(), move || { // There are two paths out of `f`. // - Normal exit. // - Panic, e.g. triggered by `abort_if_errors`. diff --git a/compiler/rustc_interface/src/passes.rs b/compiler/rustc_interface/src/passes.rs index 661401687593d..085e90260515b 100644 --- a/compiler/rustc_interface/src/passes.rs +++ b/compiler/rustc_interface/src/passes.rs @@ -44,9 +44,9 @@ use std::{env, fs, iter}; pub fn parse<'a>(sess: &'a Session) -> PResult<'a, ast::Crate> { let krate = sess.time("parse_crate", || match &sess.io.input { - Input::File(file) => parse_crate_from_file(file, &sess.parse_sess), + Input::File(file) => parse_crate_from_file(file, &sess.psess), Input::Str { input, name } => { - parse_crate_from_source_str(name.clone(), input.clone(), &sess.parse_sess) + parse_crate_from_source_str(name.clone(), input.clone(), &sess.psess) } })?; @@ -205,7 +205,7 @@ fn configure_and_expand( // The rest is error reporting - sess.parse_sess.buffered_lints.with_lock(|buffered_lints: &mut Vec| { + sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec| { buffered_lints.append(&mut ecx.buffered_early_lint); }); @@ -297,7 +297,7 @@ fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) { }); // Add all buffered lints from the `ParseSess` to the `Session`. - sess.parse_sess.buffered_lints.with_lock(|buffered_lints| { + sess.psess.buffered_lints.with_lock(|buffered_lints| { info!("{} parse sess buffered_lints", buffered_lints.len()); for early_lint in buffered_lints.drain(..) { lint_buffer.add_early_lint(early_lint); @@ -305,7 +305,7 @@ fn early_lint_checks(tcx: TyCtxt<'_>, (): ()) { }); // Gate identifiers containing invalid Unicode codepoints that were recovered during lexing. - sess.parse_sess.bad_unicode_identifiers.with_lock(|identifiers| { + sess.psess.bad_unicode_identifiers.with_lock(|identifiers| { for (ident, mut spans) in identifiers.drain(..) { spans.sort(); if ident == sym::ferris { @@ -422,7 +422,7 @@ fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[P // Account for explicitly marked-to-track files // (e.g. accessed in proc macros). - let file_depinfo = sess.parse_sess.file_depinfo.borrow(); + let file_depinfo = sess.psess.file_depinfo.borrow(); let normalize_path = |path: PathBuf| { let file = FileName::from(path); @@ -485,7 +485,7 @@ fn write_out_deps(tcx: TyCtxt<'_>, outputs: &OutputFilenames, out_filenames: &[P } // Emit special comments with information about accessed environment variables. - let env_depinfo = sess.parse_sess.env_depinfo.borrow(); + let env_depinfo = sess.psess.env_depinfo.borrow(); if !env_depinfo.is_empty() { // We will soon sort, so the initial order does not matter. #[allow(rustc::potential_query_instability)] @@ -956,7 +956,7 @@ fn get_recursion_limit(krate_attrs: &[ast::Attribute], sess: &Session) -> Limit // `check_builtin_attribute`), but by the time that runs the macro // is expanded, and it doesn't give an error. validate_attr::emit_fatal_malformed_builtin_attribute( - &sess.parse_sess, + &sess.psess, attr, sym::recursion_limit, ); diff --git a/compiler/rustc_interface/src/queries.rs b/compiler/rustc_interface/src/queries.rs index 86858bfe41d81..7cdf7cd25b1c1 100644 --- a/compiler/rustc_interface/src/queries.rs +++ b/compiler/rustc_interface/src/queries.rs @@ -120,7 +120,7 @@ impl<'tcx> Queries<'tcx> { rustc_builtin_macros::cmdline_attrs::inject( &mut krate, - &sess.parse_sess, + &sess.psess, &sess.opts.unstable_opts.crate_attr, ); diff --git a/compiler/rustc_interface/src/util.rs b/compiler/rustc_interface/src/util.rs index 823614e1f0619..7572805f66122 100644 --- a/compiler/rustc_interface/src/util.rs +++ b/compiler/rustc_interface/src/util.rs @@ -369,7 +369,7 @@ pub(crate) fn check_attr_crate_type( // by the time that runs the macro is expanded, and it doesn't // give an error. validate_attr::emit_fatal_malformed_builtin_attribute( - &sess.parse_sess, + &sess.psess, a, sym::crate_type, ); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 9f73d2e681251..8d61d29783945 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -1868,7 +1868,7 @@ impl KeywordIdents { }; // Don't lint `r#foo`. - if cx.sess().parse_sess.raw_identifier_spans.contains(ident.span) { + if cx.sess().psess.raw_identifier_spans.contains(ident.span) { return; } diff --git a/compiler/rustc_lint/src/context/diagnostics.rs b/compiler/rustc_lint/src/context/diagnostics.rs index 728996f07417c..ad1808b5f803d 100644 --- a/compiler/rustc_lint/src/context/diagnostics.rs +++ b/compiler/rustc_lint/src/context/diagnostics.rs @@ -186,12 +186,12 @@ pub(super) fn builtin(sess: &Session, diagnostic: BuiltinLintDiagnostics, diag: BuiltinLintDiagnostics::UnexpectedCfgName((name, name_span), value) => { #[allow(rustc::potential_query_instability)] let possibilities: Vec = - sess.parse_sess.check_config.expecteds.keys().copied().collect(); + sess.psess.check_config.expecteds.keys().copied().collect(); let mut names_possibilities: Vec<_> = if value.is_none() { // We later sort and display all the possibilities, so the order here does not matter. #[allow(rustc::potential_query_instability)] - sess.parse_sess + sess.psess .check_config .expecteds .iter() @@ -212,7 +212,7 @@ pub(super) fn builtin(sess: &Session, diagnostic: BuiltinLintDiagnostics, diag: // Suggest the most probable if we found one } else if let Some(best_match) = find_best_match_for_name(&possibilities, name, None) { if let Some(ExpectedValues::Some(best_match_values)) = - sess.parse_sess.check_config.expecteds.get(&best_match) + sess.psess.check_config.expecteds.get(&best_match) { // We will soon sort, so the initial order does not matter. #[allow(rustc::potential_query_instability)] @@ -322,8 +322,7 @@ pub(super) fn builtin(sess: &Session, diagnostic: BuiltinLintDiagnostics, diag: } } BuiltinLintDiagnostics::UnexpectedCfgValue((name, name_span), value) => { - let Some(ExpectedValues::Some(values)) = - &sess.parse_sess.check_config.expecteds.get(&name) + let Some(ExpectedValues::Some(values)) = &sess.psess.check_config.expecteds.get(&name) else { bug!( "it shouldn't be possible to have a diagnostic on a value whose name is not in values" @@ -398,8 +397,7 @@ pub(super) fn builtin(sess: &Session, diagnostic: BuiltinLintDiagnostics, diag: // We don't want to suggest adding values to well known names // since those are defined by rustc it-self. Users can still // do it if they want, but should not encourage them. - let is_cfg_a_well_know_name = - sess.parse_sess.check_config.well_known_names.contains(&name); + let is_cfg_a_well_know_name = sess.psess.check_config.well_known_names.contains(&name); let inst = if let Some((value, _value_span)) = value { let pre = if is_from_cargo { "\\" } else { "" }; diff --git a/compiler/rustc_lint/src/non_ascii_idents.rs b/compiler/rustc_lint/src/non_ascii_idents.rs index 5e66ade035774..79bc78ae55a8d 100644 --- a/compiler/rustc_lint/src/non_ascii_idents.rs +++ b/compiler/rustc_lint/src/non_ascii_idents.rs @@ -172,7 +172,7 @@ impl EarlyLintPass for NonAsciiIdents { } let mut has_non_ascii_idents = false; - let symbols = cx.sess().parse_sess.symbol_gallery.symbols.lock(); + let symbols = cx.sess().psess.symbol_gallery.symbols.lock(); // Sort by `Span` so that error messages make sense with respect to the // order of identifier locations in the code. diff --git a/compiler/rustc_lint/src/non_fmt_panic.rs b/compiler/rustc_lint/src/non_fmt_panic.rs index ebef77f687972..a2d07fff5067c 100644 --- a/compiler/rustc_lint/src/non_fmt_panic.rs +++ b/compiler/rustc_lint/src/non_fmt_panic.rs @@ -231,7 +231,7 @@ fn check_panic_str<'tcx>( let fmt_span = arg.span.source_callsite(); - let (snippet, style) = match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) { + let (snippet, style) = match cx.sess().psess.source_map().span_to_snippet(fmt_span) { Ok(snippet) => { // Count the number of `#`s between the `r` and `"`. let style = snippet.strip_prefix('r').and_then(|s| s.find('"')); @@ -282,7 +282,7 @@ fn check_panic_str<'tcx>( /// Given the span of `some_macro!(args);`, gives the span of `(` and `)`, /// and the type of (opening) delimiter used. fn find_delimiters(cx: &LateContext<'_>, span: Span) -> Option<(Span, Span, char)> { - let snippet = cx.sess().parse_sess.source_map().span_to_snippet(span).ok()?; + let snippet = cx.sess().psess.source_map().span_to_snippet(span).ok()?; let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?; let close = snippet.rfind(|c| ")]}".contains(c))?; Some(( diff --git a/compiler/rustc_metadata/src/creader.rs b/compiler/rustc_metadata/src/creader.rs index f65fe1a29c7cc..8b48570fbbadd 100644 --- a/compiler/rustc_metadata/src/creader.rs +++ b/compiler/rustc_metadata/src/creader.rs @@ -971,7 +971,7 @@ impl<'a, 'tcx> CrateLoader<'a, 'tcx> { continue; } - self.sess.parse_sess.buffer_lint( + self.sess.psess.buffer_lint( lint::builtin::UNUSED_CRATE_DEPENDENCIES, span, ast::CRATE_NODE_ID, diff --git a/compiler/rustc_metadata/src/rmeta/decoder.rs b/compiler/rustc_metadata/src/rmeta/decoder.rs index e7c80639a0d7c..09cb6b9fa0a8b 100644 --- a/compiler/rustc_metadata/src/rmeta/decoder.rs +++ b/compiler/rustc_metadata/src/rmeta/decoder.rs @@ -420,7 +420,7 @@ impl<'a, 'tcx> Decodable> for ExpnIndex { impl<'a, 'tcx> SpanDecoder for DecodeContext<'a, 'tcx> { fn decode_attr_id(&mut self) -> rustc_span::AttrId { let sess = self.sess.expect("can't decode AttrId without Session"); - sess.parse_sess.attr_id_generator.mk_attr_id() + sess.psess.attr_id_generator.mk_attr_id() } fn decode_crate_num(&mut self) -> CrateNum { diff --git a/compiler/rustc_metadata/src/rmeta/encoder.rs b/compiler/rustc_metadata/src/rmeta/encoder.rs index fdb2b4f202415..7d3f84060f64c 100644 --- a/compiler/rustc_metadata/src/rmeta/encoder.rs +++ b/compiler/rustc_metadata/src/rmeta/encoder.rs @@ -1789,7 +1789,7 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> { let stability = tcx.lookup_stability(CRATE_DEF_ID); let macros = self.lazy_array(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)); - for (i, span) in self.tcx.sess.parse_sess.proc_macro_quoted_spans() { + for (i, span) in self.tcx.sess.psess.proc_macro_quoted_spans() { let span = self.lazy(span); self.tables.proc_macro_quoted_spans.set_some(i, span); } diff --git a/compiler/rustc_middle/src/middle/stability.rs b/compiler/rustc_middle/src/middle/stability.rs index 31f986403ab9d..1b09f9fdc492a 100644 --- a/compiler/rustc_middle/src/middle/stability.rs +++ b/compiler/rustc_middle/src/middle/stability.rs @@ -269,7 +269,7 @@ fn suggestion_for_allocator_api( if feature == sym::allocator_api { if let Some(trait_) = tcx.opt_parent(def_id) { if tcx.is_diagnostic_item(sym::Vec, trait_) { - let sm = tcx.sess.parse_sess.source_map(); + let sm = tcx.sess.psess.source_map(); let inner_types = sm.span_extend_to_prev_char(span, '<', true); if let Ok(snippet) = sm.span_to_snippet(inner_types) { return Some(( diff --git a/compiler/rustc_parse/src/lexer/mod.rs b/compiler/rustc_parse/src/lexer/mod.rs index 4cfd061ebd921..ca998ccc356fc 100644 --- a/compiler/rustc_parse/src/lexer/mod.rs +++ b/compiler/rustc_parse/src/lexer/mod.rs @@ -42,12 +42,12 @@ pub struct UnmatchedDelim { pub candidate_span: Option, } -pub(crate) fn parse_token_trees<'sess, 'src>( - sess: &'sess ParseSess, +pub(crate) fn parse_token_trees<'psess, 'src>( + psess: &'psess ParseSess, mut src: &'src str, mut start_pos: BytePos, override_span: Option, -) -> Result>> { +) -> Result>> { // Skip `#!`, if present. if let Some(shebang_len) = rustc_lexer::strip_shebang(src) { src = &src[shebang_len..]; @@ -56,7 +56,7 @@ pub(crate) fn parse_token_trees<'sess, 'src>( let cursor = Cursor::new(src); let string_reader = StringReader { - sess, + psess, start_pos, pos: start_pos, src, @@ -75,7 +75,7 @@ pub(crate) fn parse_token_trees<'sess, 'src>( let mut buffer = Vec::with_capacity(1); for unmatched in unmatched_delims { - if let Some(err) = make_unclosed_delims_error(unmatched, sess) { + if let Some(err) = make_unclosed_delims_error(unmatched, psess) { buffer.push(err); } } @@ -90,8 +90,8 @@ pub(crate) fn parse_token_trees<'sess, 'src>( } } -struct StringReader<'sess, 'src> { - sess: &'sess ParseSess, +struct StringReader<'psess, 'src> { + psess: &'psess ParseSess, /// Initial position, read-only. start_pos: BytePos, /// The absolute offset within the source_map of the current character. @@ -107,9 +107,9 @@ struct StringReader<'sess, 'src> { nbsp_is_whitespace: bool, } -impl<'sess, 'src> StringReader<'sess, 'src> { - pub fn dcx(&self) -> &'sess DiagCtxt { - &self.sess.dcx +impl<'psess, 'src> StringReader<'psess, 'src> { + pub fn dcx(&self) -> &'psess DiagCtxt { + &self.psess.dcx } fn mk_sp(&self, lo: BytePos, hi: BytePos) -> Span { @@ -176,11 +176,11 @@ impl<'sess, 'src> StringReader<'sess, 'src> { rustc_lexer::TokenKind::RawIdent => { let sym = nfc_normalize(self.str_from(start + BytePos(2))); let span = self.mk_sp(start, self.pos); - self.sess.symbol_gallery.insert(sym, span); + self.psess.symbol_gallery.insert(sym, span); if !sym.can_be_raw() { self.dcx().emit_err(errors::CannotBeRawIdent { span, ident: sym }); } - self.sess.raw_identifier_spans.push(span); + self.psess.raw_identifier_spans.push(span); token::Ident(sym, IdentIsRaw::Yes) } rustc_lexer::TokenKind::UnknownPrefix => { @@ -199,7 +199,7 @@ impl<'sess, 'src> StringReader<'sess, 'src> { { let sym = nfc_normalize(self.str_from(start)); let span = self.mk_sp(start, self.pos); - self.sess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default() + self.psess.bad_unicode_identifiers.borrow_mut().entry(sym).or_default() .push(span); token::Ident(sym, IdentIsRaw::No) } @@ -230,7 +230,7 @@ impl<'sess, 'src> StringReader<'sess, 'src> { let suffix = if suffix_start < self.pos { let string = self.str_from(suffix_start); if string == "_" { - self.sess + self.psess .dcx .emit_err(errors::UnderscoreLiteralSuffix { span: self.mk_sp(suffix_start, self.pos) }); None @@ -338,7 +338,7 @@ impl<'sess, 'src> StringReader<'sess, 'src> { fn ident(&self, start: BytePos) -> TokenKind { let sym = nfc_normalize(self.str_from(start)); let span = self.mk_sp(start, self.pos); - self.sess.symbol_gallery.insert(sym, span); + self.psess.symbol_gallery.insert(sym, span); token::Ident(sym, IdentIsRaw::No) } @@ -350,7 +350,7 @@ impl<'sess, 'src> StringReader<'sess, 'src> { let content = self.str_from(content_start); if contains_text_flow_control_chars(content) { let span = self.mk_sp(start, self.pos); - self.sess.buffer_lint_with_diagnostic( + self.psess.buffer_lint_with_diagnostic( TEXT_DIRECTION_CODEPOINT_IN_COMMENT, span, ast::CRATE_NODE_ID, @@ -566,7 +566,7 @@ impl<'sess, 'src> StringReader<'sess, 'src> { } fn report_non_started_raw_string(&self, start: BytePos, bad_char: char) -> ! { - self.sess + self.psess .dcx .struct_span_fatal( self.mk_sp(start, self.pos), @@ -680,7 +680,7 @@ impl<'sess, 'src> StringReader<'sess, 'src> { self.dcx().emit_err(errors::UnknownPrefix { span: prefix_span, prefix, sugg }); } else { // Before Rust 2021, only emit a lint for migration. - self.sess.buffer_lint_with_diagnostic( + self.psess.buffer_lint_with_diagnostic( RUST_2021_PREFIXES_INCOMPATIBLE_SYNTAX, prefix_span, ast::CRATE_NODE_ID, diff --git a/compiler/rustc_parse/src/lexer/tokentrees.rs b/compiler/rustc_parse/src/lexer/tokentrees.rs index c9ff2d58e2c56..a506f98bf3a53 100644 --- a/compiler/rustc_parse/src/lexer/tokentrees.rs +++ b/compiler/rustc_parse/src/lexer/tokentrees.rs @@ -8,18 +8,18 @@ use rustc_ast_pretty::pprust::token_to_string; use rustc_errors::{Applicability, PErr}; use rustc_span::symbol::kw; -pub(super) struct TokenTreesReader<'sess, 'src> { - string_reader: StringReader<'sess, 'src>, +pub(super) struct TokenTreesReader<'psess, 'src> { + string_reader: StringReader<'psess, 'src>, /// The "next" token, which has been obtained from the `StringReader` but /// not yet handled by the `TokenTreesReader`. token: Token, diag_info: TokenTreeDiagInfo, } -impl<'sess, 'src> TokenTreesReader<'sess, 'src> { +impl<'psess, 'src> TokenTreesReader<'psess, 'src> { pub(super) fn parse_all_token_trees( - string_reader: StringReader<'sess, 'src>, - ) -> (TokenStream, Result<(), Vec>>, Vec) { + string_reader: StringReader<'psess, 'src>, + ) -> (TokenStream, Result<(), Vec>>, Vec) { let mut tt_reader = TokenTreesReader { string_reader, token: Token::dummy(), @@ -35,7 +35,7 @@ impl<'sess, 'src> TokenTreesReader<'sess, 'src> { fn parse_token_trees( &mut self, is_delimited: bool, - ) -> (Spacing, TokenStream, Result<(), Vec>>) { + ) -> (Spacing, TokenStream, Result<(), Vec>>) { // Move past the opening delimiter. let (_, open_spacing) = self.bump(false); @@ -71,9 +71,9 @@ impl<'sess, 'src> TokenTreesReader<'sess, 'src> { } } - fn eof_err(&mut self) -> PErr<'sess> { + fn eof_err(&mut self) -> PErr<'psess> { let msg = "this file contains an unclosed delimiter"; - let mut err = self.string_reader.sess.dcx.struct_span_err(self.token.span, msg); + let mut err = self.string_reader.psess.dcx.struct_span_err(self.token.span, msg); for &(_, sp) in &self.diag_info.open_braces { err.span_label(sp, "unclosed delimiter"); self.diag_info.unmatched_delims.push(UnmatchedDelim { @@ -89,7 +89,7 @@ impl<'sess, 'src> TokenTreesReader<'sess, 'src> { report_suspicious_mismatch_block( &mut err, &self.diag_info, - self.string_reader.sess.source_map(), + self.string_reader.psess.source_map(), *delim, ) } @@ -99,7 +99,7 @@ impl<'sess, 'src> TokenTreesReader<'sess, 'src> { fn parse_token_tree_open_delim( &mut self, open_delim: Delimiter, - ) -> Result>> { + ) -> Result>> { // The span for beginning of the delimited section let pre_span = self.token.span; @@ -115,7 +115,7 @@ impl<'sess, 'src> TokenTreesReader<'sess, 'src> { // Expand to cover the entire delimited token tree let delim_span = DelimSpan::from_pair(pre_span, self.token.span); - let sm = self.string_reader.sess.source_map(); + let sm = self.string_reader.psess.source_map(); let close_spacing = match self.token.kind { // Correct delimiter. @@ -232,11 +232,11 @@ impl<'sess, 'src> TokenTreesReader<'sess, 'src> { fn unclosed_delim_err( &mut self, tts: TokenStream, - mut errs: Vec>, - ) -> Vec> { + mut errs: Vec>, + ) -> Vec> { // If there are unclosed delims, see if there are diff markers and if so, point them // out instead of complaining about the unclosed delims. - let mut parser = crate::stream_to_parser(self.string_reader.sess, tts, None); + let mut parser = crate::stream_to_parser(self.string_reader.psess, tts, None); let mut diff_errs = vec![]; // Suggest removing a `{` we think appears in an `if`/`while` condition // We want to suggest removing a `{` only if we think we're in an `if`/`while` condition, but @@ -289,17 +289,17 @@ impl<'sess, 'src> TokenTreesReader<'sess, 'src> { return errs; } - fn close_delim_err(&mut self, delim: Delimiter) -> PErr<'sess> { + fn close_delim_err(&mut self, delim: Delimiter) -> PErr<'psess> { // An unexpected closing delimiter (i.e., there is no // matching opening delimiter). let token_str = token_to_string(&self.token); let msg = format!("unexpected closing delimiter: `{token_str}`"); - let mut err = self.string_reader.sess.dcx.struct_span_err(self.token.span, msg); + let mut err = self.string_reader.psess.dcx.struct_span_err(self.token.span, msg); report_suspicious_mismatch_block( &mut err, &self.diag_info, - self.string_reader.sess.source_map(), + self.string_reader.psess.source_map(), delim, ); err.span_label(self.token.span, "unexpected closing delimiter"); diff --git a/compiler/rustc_parse/src/lexer/unicode_chars.rs b/compiler/rustc_parse/src/lexer/unicode_chars.rs index 3b4e05332fac9..6b055fc844ae1 100644 --- a/compiler/rustc_parse/src/lexer/unicode_chars.rs +++ b/compiler/rustc_parse/src/lexer/unicode_chars.rs @@ -350,7 +350,7 @@ pub(super) fn check_for_substitution( let Some((_, ascii_name, token)) = ASCII_ARRAY.iter().find(|&&(s, _, _)| s == ascii_str) else { let msg = format!("substitution character not found for '{ch}'"); - reader.sess.dcx.span_bug(span, msg); + reader.psess.dcx.span_bug(span, msg); }; // special help suggestion for "directed" double quotes diff --git a/compiler/rustc_parse/src/lib.rs b/compiler/rustc_parse/src/lib.rs index 53bcb35101e2e..a46372d368f42 100644 --- a/compiler/rustc_parse/src/lib.rs +++ b/compiler/rustc_parse/src/lib.rs @@ -57,84 +57,84 @@ macro_rules! panictry_buffer { }}; } -pub fn parse_crate_from_file<'a>(input: &Path, sess: &'a ParseSess) -> PResult<'a, ast::Crate> { - let mut parser = new_parser_from_file(sess, input, None); +pub fn parse_crate_from_file<'a>(input: &Path, psess: &'a ParseSess) -> PResult<'a, ast::Crate> { + let mut parser = new_parser_from_file(psess, input, None); parser.parse_crate_mod() } pub fn parse_crate_attrs_from_file<'a>( input: &Path, - sess: &'a ParseSess, + psess: &'a ParseSess, ) -> PResult<'a, ast::AttrVec> { - let mut parser = new_parser_from_file(sess, input, None); + let mut parser = new_parser_from_file(psess, input, None); parser.parse_inner_attributes() } pub fn parse_crate_from_source_str( name: FileName, source: String, - sess: &ParseSess, + psess: &ParseSess, ) -> PResult<'_, ast::Crate> { - new_parser_from_source_str(sess, name, source).parse_crate_mod() + new_parser_from_source_str(psess, name, source).parse_crate_mod() } pub fn parse_crate_attrs_from_source_str( name: FileName, source: String, - sess: &ParseSess, + psess: &ParseSess, ) -> PResult<'_, ast::AttrVec> { - new_parser_from_source_str(sess, name, source).parse_inner_attributes() + new_parser_from_source_str(psess, name, source).parse_inner_attributes() } pub fn parse_stream_from_source_str( name: FileName, source: String, - sess: &ParseSess, + psess: &ParseSess, override_span: Option, ) -> TokenStream { - source_file_to_stream(sess, sess.source_map().new_source_file(name, source), override_span) + source_file_to_stream(psess, psess.source_map().new_source_file(name, source), override_span) } /// Creates a new parser from a source string. -pub fn new_parser_from_source_str(sess: &ParseSess, name: FileName, source: String) -> Parser<'_> { - panictry_buffer!(maybe_new_parser_from_source_str(sess, name, source)) +pub fn new_parser_from_source_str(psess: &ParseSess, name: FileName, source: String) -> Parser<'_> { + panictry_buffer!(maybe_new_parser_from_source_str(psess, name, source)) } /// Creates a new parser from a source string. Returns any buffered errors from lexing the initial /// token stream; these must be consumed via `emit`, `cancel`, etc., otherwise a panic will occur /// when they are dropped. pub fn maybe_new_parser_from_source_str( - sess: &ParseSess, + psess: &ParseSess, name: FileName, source: String, ) -> Result, Vec>> { - maybe_source_file_to_parser(sess, sess.source_map().new_source_file(name, source)) + maybe_source_file_to_parser(psess, psess.source_map().new_source_file(name, source)) } /// Creates a new parser, aborting if the file doesn't exist. If a span is given, that is used on /// an error as the source of the problem. -pub fn new_parser_from_file<'a>(sess: &'a ParseSess, path: &Path, sp: Option) -> Parser<'a> { - let source_file = sess.source_map().load_file(path).unwrap_or_else(|e| { +pub fn new_parser_from_file<'a>(psess: &'a ParseSess, path: &Path, sp: Option) -> Parser<'a> { + let source_file = psess.source_map().load_file(path).unwrap_or_else(|e| { let msg = format!("couldn't read {}: {}", path.display(), e); - let mut err = sess.dcx.struct_fatal(msg); + let mut err = psess.dcx.struct_fatal(msg); if let Some(sp) = sp { err.span(sp); } err.emit(); }); - panictry_buffer!(maybe_source_file_to_parser(sess, source_file)) + panictry_buffer!(maybe_source_file_to_parser(psess, source_file)) } /// Given a session and a `source_file`, return a parser. Returns any buffered errors from lexing /// the initial token stream. fn maybe_source_file_to_parser( - sess: &ParseSess, + psess: &ParseSess, source_file: Lrc, ) -> Result, Vec>> { let end_pos = source_file.end_position(); - let stream = maybe_file_to_stream(sess, source_file, None)?; - let mut parser = stream_to_parser(sess, stream, None); + let stream = maybe_file_to_stream(psess, source_file, None)?; + let mut parser = stream_to_parser(psess, stream, None); if parser.token == token::Eof { parser.token.span = Span::new(end_pos, end_pos, parser.token.span.ctxt(), None); } @@ -146,47 +146,47 @@ fn maybe_source_file_to_parser( /// Given a `source_file`, produces a sequence of token trees. pub fn source_file_to_stream( - sess: &ParseSess, + psess: &ParseSess, source_file: Lrc, override_span: Option, ) -> TokenStream { - panictry_buffer!(maybe_file_to_stream(sess, source_file, override_span)) + panictry_buffer!(maybe_file_to_stream(psess, source_file, override_span)) } /// Given a source file, produces a sequence of token trees. Returns any buffered errors from /// parsing the token stream. -fn maybe_file_to_stream<'sess>( - sess: &'sess ParseSess, +fn maybe_file_to_stream<'psess>( + psess: &'psess ParseSess, source_file: Lrc, override_span: Option, -) -> Result>> { +) -> Result>> { let src = source_file.src.as_ref().unwrap_or_else(|| { - sess.dcx.bug(format!( + psess.dcx.bug(format!( "cannot lex `source_file` without source: {}", - sess.source_map().filename_for_diagnostics(&source_file.name) + psess.source_map().filename_for_diagnostics(&source_file.name) )); }); - lexer::parse_token_trees(sess, src.as_str(), source_file.start_pos, override_span) + lexer::parse_token_trees(psess, src.as_str(), source_file.start_pos, override_span) } /// Given a stream and the `ParseSess`, produces a parser. pub fn stream_to_parser<'a>( - sess: &'a ParseSess, + psess: &'a ParseSess, stream: TokenStream, subparser_name: Option<&'static str>, ) -> Parser<'a> { - Parser::new(sess, stream, subparser_name) + Parser::new(psess, stream, subparser_name) } /// Runs the given subparser `f` on the tokens of the given `attr`'s item. pub fn parse_in<'a, T>( - sess: &'a ParseSess, + psess: &'a ParseSess, tts: TokenStream, name: &'static str, mut f: impl FnMut(&mut Parser<'a>) -> PResult<'a, T>, ) -> PResult<'a, T> { - let mut parser = Parser::new(sess, tts, Some(name)); + let mut parser = Parser::new(psess, tts, Some(name)); let result = f(&mut parser)?; if parser.token != token::Eof { parser.unexpected()?; @@ -194,28 +194,28 @@ pub fn parse_in<'a, T>( Ok(result) } -pub fn fake_token_stream_for_item(sess: &ParseSess, item: &ast::Item) -> TokenStream { +pub fn fake_token_stream_for_item(psess: &ParseSess, item: &ast::Item) -> TokenStream { let source = pprust::item_to_string(item); let filename = FileName::macro_expansion_source_code(&source); - parse_stream_from_source_str(filename, source, sess, Some(item.span)) + parse_stream_from_source_str(filename, source, psess, Some(item.span)) } -pub fn fake_token_stream_for_crate(sess: &ParseSess, krate: &ast::Crate) -> TokenStream { +pub fn fake_token_stream_for_crate(psess: &ParseSess, krate: &ast::Crate) -> TokenStream { let source = pprust::crate_to_string_for_macros(krate); let filename = FileName::macro_expansion_source_code(&source); - parse_stream_from_source_str(filename, source, sess, Some(krate.spans.inner_span)) + parse_stream_from_source_str(filename, source, psess, Some(krate.spans.inner_span)) } pub fn parse_cfg_attr( attr: &Attribute, - parse_sess: &ParseSess, + psess: &ParseSess, ) -> Option<(MetaItem, Vec<(AttrItem, Span)>)> { match attr.get_normal_item().args { ast::AttrArgs::Delimited(ast::DelimArgs { dspan, delim, ref tokens }) if !tokens.is_empty() => { - crate::validate_attr::check_cfg_attr_bad_delim(parse_sess, dspan, delim); - match parse_in(parse_sess, tokens.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) { + crate::validate_attr::check_cfg_attr_bad_delim(psess, dspan, delim); + match parse_in(psess, tokens.clone(), "`cfg_attr` input", |p| p.parse_cfg_attr()) { Ok(r) => return Some(r), Err(e) => { e.with_help(format!("the valid syntax is `{CFG_ATTR_GRAMMAR_HELP}`")) @@ -224,7 +224,7 @@ pub fn parse_cfg_attr( } } } - _ => error_malformed_cfg_attr_missing(attr.span, parse_sess), + _ => error_malformed_cfg_attr_missing(attr.span, psess), } None } @@ -234,6 +234,6 @@ const CFG_ATTR_NOTE_REF: &str = "for more information, visit \ "; -fn error_malformed_cfg_attr_missing(span: Span, parse_sess: &ParseSess) { - parse_sess.dcx.emit_err(errors::MalformedCfgAttr { span, sugg: CFG_ATTR_GRAMMAR_HELP }); +fn error_malformed_cfg_attr_missing(span: Span, psess: &ParseSess) { + psess.dcx.emit_err(errors::MalformedCfgAttr { span, sugg: CFG_ATTR_GRAMMAR_HELP }); } diff --git a/compiler/rustc_parse/src/parser/attr.rs b/compiler/rustc_parse/src/parser/attr.rs index 685af6546f5f5..eb9a10f4bdab1 100644 --- a/compiler/rustc_parse/src/parser/attr.rs +++ b/compiler/rustc_parse/src/parser/attr.rs @@ -85,7 +85,7 @@ impl<'a> Parser<'a> { // Always make an outer attribute - this allows us to recover from a misplaced // inner attribute. Some(attr::mk_doc_comment( - &self.sess.attr_id_generator, + &self.psess.attr_id_generator, comment_kind, ast::AttrStyle::Outer, data, @@ -135,7 +135,7 @@ impl<'a> Parser<'a> { this.error_on_forbidden_inner_attr(attr_sp, inner_parse_policy); } - Ok(attr::mk_attr_from_item(&self.sess.attr_id_generator, item, None, style, attr_sp)) + Ok(attr::mk_attr_from_item(&self.psess.attr_id_generator, item, None, style, attr_sp)) }) } @@ -288,7 +288,7 @@ impl<'a> Parser<'a> { if attr_style == ast::AttrStyle::Inner { self.bump(); Some(attr::mk_doc_comment( - &self.sess.attr_id_generator, + &self.psess.attr_id_generator, comment_kind, attr_style, data, diff --git a/compiler/rustc_parse/src/parser/attr_wrapper.rs b/compiler/rustc_parse/src/parser/attr_wrapper.rs index 2307f4cfffae6..a1dd7d6f67345 100644 --- a/compiler/rustc_parse/src/parser/attr_wrapper.rs +++ b/compiler/rustc_parse/src/parser/attr_wrapper.rs @@ -40,8 +40,8 @@ impl AttrWrapper { AttrWrapper { attrs: AttrVec::new(), start_pos: usize::MAX } } - pub(crate) fn take_for_recovery(self, sess: &ParseSess) -> AttrVec { - sess.dcx.span_delayed_bug( + pub(crate) fn take_for_recovery(self, psess: &ParseSess) -> AttrVec { + psess.dcx.span_delayed_bug( self.attrs.get(0).map(|attr| attr.span).unwrap_or(DUMMY_SP), "AttrVec is taken for recovery but no error is produced", ); diff --git a/compiler/rustc_parse/src/parser/diagnostics.rs b/compiler/rustc_parse/src/parser/diagnostics.rs index 2a8cb74337b53..2f7ac7d3a12e5 100644 --- a/compiler/rustc_parse/src/parser/diagnostics.rs +++ b/compiler/rustc_parse/src/parser/diagnostics.rs @@ -242,7 +242,7 @@ impl<'a> DerefMut for SnapshotParser<'a> { impl<'a> Parser<'a> { pub fn dcx(&self) -> &'a DiagCtxt { - &self.sess.dcx + &self.psess.dcx } /// Replace `self` with `snapshot.parser`. @@ -257,7 +257,7 @@ impl<'a> Parser<'a> { } pub(super) fn span_to_snippet(&self, span: Span) -> Result { - self.sess.source_map().span_to_snippet(span) + self.psess.source_map().span_to_snippet(span) } /// Emits an error with suggestions if an identifier was expected but not found. @@ -364,7 +364,7 @@ impl<'a> Parser<'a> { if !self.look_ahead(1, |t| *t == token::Lt) && let Ok(snippet) = - self.sess.source_map().span_to_snippet(generic.span) + self.psess.source_map().span_to_snippet(generic.span) { err.multipart_suggestion_verbose( format!("place the generic parameter name after the {ident_name} name"), @@ -489,7 +489,7 @@ impl<'a> Parser<'a> { expected.sort_by_cached_key(|x| x.to_string()); expected.dedup(); - let sm = self.sess.source_map(); + let sm = self.psess.source_map(); // Special-case "expected `;`" errors. if expected.contains(&TokenType::Token(token::Semi)) { @@ -822,7 +822,7 @@ impl<'a> Parser<'a> { // #[cfg(..)] // other_expr // So we suggest using `if cfg!(..) { expr } else if cfg!(..) { other_expr }`. - let margin = self.sess.source_map().span_to_margin(next_expr.span).unwrap_or(0); + let margin = self.psess.source_map().span_to_margin(next_expr.span).unwrap_or(0); let sugg = vec![ (attr.span.with_hi(segment.span().hi()), "if cfg!".to_string()), (args_span.shrink_to_hi().with_hi(attr.span.hi()), " {".to_string()), @@ -850,7 +850,7 @@ impl<'a> Parser<'a> { } fn check_too_many_raw_str_terminators(&mut self, err: &mut Diag<'_>) -> bool { - let sm = self.sess.source_map(); + let sm = self.psess.source_map(); match (&self.prev_token.kind, &self.token.kind) { ( TokenKind::Literal(Lit { @@ -935,7 +935,7 @@ impl<'a> Parser<'a> { // expand `before` so that we take care of module path such as: // `foo::Bar { ... } ` // we expect to suggest `(foo::Bar { ... })` instead of `foo::(Bar { ... })` - let sm = self.sess.source_map(); + let sm = self.psess.source_map(); let before = maybe_struct_name.span.shrink_to_lo(); if let Ok(extend_before) = sm.span_extend_prev_while(before, |t| { t.is_alphanumeric() || t == ':' || t == '_' @@ -1872,7 +1872,7 @@ impl<'a> Parser<'a> { ); let mut err = self.dcx().struct_span_err(sp, msg); let label_exp = format!("expected `{token_str}`"); - let sm = self.sess.source_map(); + let sm = self.psess.source_map(); if !sm.is_multiline(prev_sp.until(sp)) { // When the spans are in the same line, it means that the only content // between them is whitespace, point only at the found token. @@ -1893,7 +1893,7 @@ impl<'a> Parser<'a> { pub(super) fn recover_colon_as_semi(&mut self) -> bool { let line_idx = |span: Span| { - self.sess + self.psess .source_map() .span_to_lines(span) .ok() @@ -1906,7 +1906,7 @@ impl<'a> Parser<'a> { { self.dcx().emit_err(ColonAsSemi { span: self.token.span, - type_ascription: self.sess.unstable_features.is_nightly_build().then_some(()), + type_ascription: self.psess.unstable_features.is_nightly_build().then_some(()), }); self.bump(); return true; @@ -2357,8 +2357,8 @@ impl<'a> Parser<'a> { ), }; let mut err = self.dcx().struct_span_err(span, msg); - let sp = self.sess.source_map().start_point(self.token.span); - if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) { + let sp = self.psess.source_map().start_point(self.token.span); + if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) { err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp)); } err.span_label(span, "expected expression"); @@ -2539,7 +2539,7 @@ impl<'a> Parser<'a> { }; let ident = param.ident.to_string(); - let sugg = match (ty_generics, self.sess.source_map().span_to_snippet(param.span())) { + let sugg = match (ty_generics, self.psess.source_map().span_to_snippet(param.span())) { (Some(Generics { params, span: impl_generics, .. }), Ok(snippet)) => { Some(match ¶ms[..] { [] => UnexpectedConstParamDeclarationSugg::AddParam { diff --git a/compiler/rustc_parse/src/parser/expr.rs b/compiler/rustc_parse/src/parser/expr.rs index 54771cccd75a1..eb9a26596183d 100644 --- a/compiler/rustc_parse/src/parser/expr.rs +++ b/compiler/rustc_parse/src/parser/expr.rs @@ -403,8 +403,8 @@ impl<'a> Parser<'a> { // suggestions based on the assumption that double-refs are rarely intentional, // and closures are distinct enough that they don't get mixed up with their // return value. - let sp = self.sess.source_map().start_point(self.token.span); - self.sess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span); + let sp = self.psess.source_map().start_point(self.token.span); + self.psess.ambiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span); false } (true, Some(op)) if !op.can_continue_expr_unambiguously() => false, @@ -608,7 +608,7 @@ impl<'a> Parser<'a> { }; // a block on the LHS might have been intended to be an expression instead - if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) { + if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) { err.add_parentheses = Some(ExprParenthesesNeeded::surrounding(*sp)); } else { err.remove_plus = Some(lo); @@ -666,7 +666,7 @@ impl<'a> Parser<'a> { fn parse_expr_box(&mut self, box_kw: Span) -> PResult<'a, (Span, ExprKind)> { let (span, _) = self.parse_expr_prefix_common(box_kw)?; let inner_span = span.with_lo(box_kw.hi()); - let code = self.sess.source_map().span_to_snippet(inner_span).unwrap(); + let code = self.psess.source_map().span_to_snippet(inner_span).unwrap(); let guar = self.dcx().emit_err(errors::BoxSyntaxRemoved { span: span, code: code.trim() }); Ok((span, ExprKind::Err(guar))) } @@ -700,7 +700,7 @@ impl<'a> Parser<'a> { // Span the `not` plus trailing whitespace to avoid // trailing whitespace after the `!` in our suggestion sub: sub_diag( - self.sess.source_map().span_until_non_whitespace(lo.to(negated_token.span)), + self.psess.source_map().span_until_non_whitespace(lo.to(negated_token.span)), ), }); @@ -915,7 +915,7 @@ impl<'a> Parser<'a> { let found_raw = self.eat_keyword(kw::Raw); assert!(found_raw); let mutability = self.parse_const_or_mut().unwrap(); - self.sess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span)); + self.psess.gated_spans.gate(sym::raw_ref_op, lo.to(self.prev_token.span)); (ast::BorrowKind::Raw, mutability) } else { // `mut?` @@ -1013,7 +1013,7 @@ impl<'a> Parser<'a> { fn error_unexpected_after_dot(&self) { let actual = pprust::token_to_string(&self.token); let span = self.token.span; - let sm = self.sess.source_map(); + let sm = self.psess.source_map(); let (span, actual) = match (&self.token.kind, self.subparser_name) { (token::Eof, Some(_)) if let Ok(actual) = sm.span_to_snippet(sm.next_point(span)) => { (span.shrink_to_hi(), actual.into()) @@ -1434,7 +1434,7 @@ impl<'a> Parser<'a> { this.parse_expr_closure().map_err(|mut err| { // If the input is something like `if a { 1 } else { 2 } | if a { 3 } else { 4 }` // then suggest parens around the lhs. - if let Some(sp) = this.sess.ambiguous_block_expr_parse.borrow().get(&lo) { + if let Some(sp) = this.psess.ambiguous_block_expr_parse.borrow().get(&lo) { err.subdiagnostic(this.dcx(), ExprParenthesesNeeded::surrounding(*sp)); } err @@ -1634,7 +1634,7 @@ impl<'a> Parser<'a> { && let Some(expr) = self.maybe_parse_struct_expr(&qself, &path) { if qself.is_some() { - self.sess.gated_spans.gate(sym::more_qualified_paths, path.span); + self.psess.gated_spans.gate(sym::more_qualified_paths, path.span); } return expr; } else { @@ -1821,7 +1821,7 @@ impl<'a> Parser<'a> { let kind = ExprKind::Yeet(self.parse_expr_opt()?); let span = lo.to(self.prev_token.span); - self.sess.gated_spans.gate(sym::yeet_expr, span); + self.psess.gated_spans.gate(sym::yeet_expr, span); let expr = self.mk_expr(span, kind); self.maybe_recover_from_bad_qpath(expr) } @@ -1831,7 +1831,7 @@ impl<'a> Parser<'a> { let lo = self.prev_token.span; let kind = ExprKind::Become(self.parse_expr()?); let span = lo.to(self.prev_token.span); - self.sess.gated_spans.gate(sym::explicit_tail_calls, span); + self.psess.gated_spans.gate(sym::explicit_tail_calls, span); let expr = self.mk_expr(span, kind); self.maybe_recover_from_bad_qpath(expr) } @@ -1875,7 +1875,7 @@ impl<'a> Parser<'a> { | ExprKind::Block(_, None) ) { - self.sess.buffer_lint_with_diagnostic( + self.psess.buffer_lint_with_diagnostic( BREAK_WITH_LABEL_AND_LOOP, lo.to(expr.span), ast::CRATE_NODE_ID, @@ -1926,7 +1926,7 @@ impl<'a> Parser<'a> { let lo = self.prev_token.span; let kind = ExprKind::Yield(self.parse_expr_opt()?); let span = lo.to(self.prev_token.span); - self.sess.gated_spans.gate(sym::yield_expr, span); + self.psess.gated_spans.gate(sym::yield_expr, span); let expr = self.mk_expr(span, kind); self.maybe_recover_from_bad_qpath(expr) } @@ -1955,7 +1955,7 @@ impl<'a> Parser<'a> { let err = self.dcx().create_err(errors::ExpectedBuiltinIdent { span: self.token.span }); return Err(err); }; - self.sess.gated_spans.gate(sym::builtin_syntax, ident.span); + self.psess.gated_spans.gate(sym::builtin_syntax, ident.span); self.bump(); self.expect(&TokenKind::OpenDelim(Delimiter::Parenthesis))?; @@ -2143,7 +2143,7 @@ impl<'a> Parser<'a> { Err(err) => { let span = token.uninterpolated_span(); self.bump(); - let guar = report_lit_error(self.sess, err, lit, span); + let guar = report_lit_error(self.psess, err, lit, span); // Pack possible quotes and prefixes from the original literal into // the error literal's symbol so they can be pretty-printed faithfully. let suffixless_lit = token::Lit::new(lit.kind, lit.symbol, None); @@ -2236,7 +2236,7 @@ impl<'a> Parser<'a> { } if self.token.kind == token::Comma { - if !self.sess.source_map().is_multiline(prev_span.until(self.token.span)) { + if !self.psess.source_map().is_multiline(prev_span.until(self.token.span)) { return Ok(()); } let mut snapshot = self.create_snapshot_for_diagnostic(); @@ -2312,7 +2312,7 @@ impl<'a> Parser<'a> { let lifetime_defs = self.parse_late_bound_lifetime_defs()?; let span = lo.to(self.prev_token.span); - self.sess.gated_spans.gate(sym::closure_lifetime_binder, span); + self.psess.gated_spans.gate(sym::closure_lifetime_binder, span); ClosureBinder::For { span, generic_params: lifetime_defs } } else { @@ -2354,12 +2354,12 @@ impl<'a> Parser<'a> { match coroutine_kind { Some(CoroutineKind::Async { span, .. }) => { // Feature-gate `async ||` closures. - self.sess.gated_spans.gate(sym::async_closure, span); + self.psess.gated_spans.gate(sym::async_closure, span); } Some(CoroutineKind::Gen { span, .. }) | Some(CoroutineKind::AsyncGen { span, .. }) => { // Feature-gate `gen ||` and `async gen ||` closures. // FIXME(gen_blocks): This perhaps should be a different gate. - self.sess.gated_spans.gate(sym::gen_blocks, span); + self.psess.gated_spans.gate(sym::gen_blocks, span); } None => {} } @@ -2502,7 +2502,7 @@ impl<'a> Parser<'a> { ExprKind::Block(_, None) => { let guar = this.dcx().emit_err(errors::IfExpressionMissingCondition { if_span: lo.with_neighbor(cond.span).shrink_to_hi(), - block_span: self.sess.source_map().start_point(cond_span), + block_span: self.psess.source_map().start_point(cond_span), }); std::mem::replace(&mut cond, this.mk_expr_err(cond_span.shrink_to_hi(), guar)) } @@ -2594,7 +2594,7 @@ impl<'a> Parser<'a> { if let ExprKind::Let(_, _, _, None) = cond.kind { // Remove the last feature gating of a `let` expression since it's stable. - self.sess.gated_spans.ungate_last(sym::let_chains, cond.span); + self.psess.gated_spans.ungate_last(sym::let_chains, cond.span); } Ok(cond) @@ -2690,7 +2690,7 @@ impl<'a> Parser<'a> { attrs: AttrWrapper, ) { if !attrs.is_empty() - && let [x0 @ xn] | [x0, .., xn] = &*attrs.take_for_recovery(self.sess) + && let [x0 @ xn] | [x0, .., xn] = &*attrs.take_for_recovery(self.psess) { let attributes = x0.span.to(xn.span); let last = xn.span; @@ -2787,7 +2787,7 @@ impl<'a> Parser<'a> { self.token.uninterpolated_span().at_least_rust_2018() && self.eat_keyword(kw::Await); if is_await { - self.sess.gated_spans.gate(sym::async_for_loop, self.prev_token.span); + self.psess.gated_spans.gate(sym::async_for_loop, self.prev_token.span); } let kind = if is_await { ForLoopKind::ForAwait } else { ForLoopKind::For }; @@ -3048,7 +3048,7 @@ impl<'a> Parser<'a> { |x| { // Don't gate twice if !pat.contains_never_pattern() { - this.sess.gated_spans.gate(sym::never_patterns, pat.span); + this.psess.gated_spans.gate(sym::never_patterns, pat.span); } x }, @@ -3103,7 +3103,7 @@ impl<'a> Parser<'a> { this.expect_one_of(&[token::Comma], &[token::CloseDelim(Delimiter::Brace)]) .map_err(|mut err| { if this.token == token::FatArrow { - let sm = this.sess.source_map(); + let sm = this.psess.source_map(); if let Ok(expr_lines) = sm.span_to_lines(expr_span) && let Ok(arm_start_lines) = sm.span_to_lines(arm_start_span) && arm_start_lines.lines[0].end_col @@ -3227,10 +3227,10 @@ impl<'a> Parser<'a> { if has_let_expr { if does_not_have_bin_op { // Remove the last feature gating of a `let` expression since it's stable. - self.sess.gated_spans.ungate_last(sym::let_chains, cond.span); + self.psess.gated_spans.ungate_last(sym::let_chains, cond.span); } let span = if_span.to(cond.span); - self.sess.gated_spans.gate(sym::if_let_guard, span); + self.psess.gated_spans.gate(sym::if_let_guard, span); } Ok(Some(cond)) } @@ -3321,7 +3321,7 @@ impl<'a> Parser<'a> { Err(self.dcx().create_err(errors::CatchAfterTry { span: self.prev_token.span })) } else { let span = span_lo.to(body.span); - self.sess.gated_spans.gate(sym::try_blocks, span); + self.psess.gated_spans.gate(sym::try_blocks, span); Ok(self.mk_expr_with_attrs(span, ExprKind::TryBlock(body), attrs)) } } @@ -3359,7 +3359,7 @@ impl<'a> Parser<'a> { // `async` blocks are stable } GenBlockKind::Gen | GenBlockKind::AsyncGen => { - self.sess.gated_spans.gate(sym::gen_blocks, lo.to(self.prev_token.span)); + self.psess.gated_spans.gate(sym::gen_blocks, lo.to(self.prev_token.span)); } } let capture_clause = self.parse_capture_clause()?; @@ -3876,7 +3876,7 @@ impl MutVisitor for CondChecker<'_> { comparison: self.comparison, })); } else { - self.parser.sess.gated_spans.gate(sym::let_chains, span); + self.parser.psess.gated_spans.gate(sym::let_chains, span); } } ExprKind::Binary(Spanned { node: BinOpKind::And, .. }, _, _) => { diff --git a/compiler/rustc_parse/src/parser/generics.rs b/compiler/rustc_parse/src/parser/generics.rs index e059e7074910a..263b2a9064356 100644 --- a/compiler/rustc_parse/src/parser/generics.rs +++ b/compiler/rustc_parse/src/parser/generics.rs @@ -420,7 +420,7 @@ impl<'a> Parser<'a> { type_err.cancel(); let body_sp = pred_lo.to(snapshot.prev_token.span); - let map = self.sess.source_map(); + let map = self.psess.source_map(); self.dcx().emit_err(WhereClauseBeforeTupleStructBody { span: where_sp, diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index d8587f1340a1a..79492fe62ed97 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -563,7 +563,7 @@ impl<'a> Parser<'a> { let constness = self.parse_constness(Case::Sensitive); if let Const::Yes(span) = constness { - self.sess.gated_spans.gate(sym::const_trait_impl, span); + self.psess.gated_spans.gate(sym::const_trait_impl, span); } // Parse stray `impl async Trait` @@ -699,7 +699,7 @@ impl<'a> Parser<'a> { None }; let span = span.to(self.prev_token.span); - self.sess.gated_spans.gate(sym::fn_delegation, span); + self.psess.gated_spans.gate(sym::fn_delegation, span); let ident = path.segments.last().map(|seg| seg.ident).unwrap_or(Ident::empty()); Ok(( @@ -859,7 +859,7 @@ impl<'a> Parser<'a> { let unsafety = self.parse_unsafety(Case::Sensitive); // Parse optional `auto` prefix. let is_auto = if self.eat_keyword(kw::Auto) { - self.sess.gated_spans.gate(sym::auto_traits, self.prev_token.span); + self.psess.gated_spans.gate(sym::auto_traits, self.prev_token.span); IsAuto::Yes } else { IsAuto::No @@ -894,7 +894,7 @@ impl<'a> Parser<'a> { self.dcx().emit_err(errors::TraitAliasCannotBeUnsafe { span: whole_span }); } - self.sess.gated_spans.gate(sym::trait_alias, whole_span); + self.psess.gated_spans.gate(sym::trait_alias, whole_span); Ok((ident, ItemKind::TraitAlias(generics, bounds))) } else { @@ -1209,7 +1209,7 @@ impl<'a> Parser<'a> { fn error_bad_item_kind(&self, span: Span, kind: &ItemKind, ctx: &'static str) -> Option { // FIXME(#100717): needs variant for each `ItemKind` (instead of using `ItemKind::descr()`) - let span = self.sess.source_map().guess_head_span(span); + let span = self.psess.source_map().guess_head_span(span); let descr = kind.descr(); self.dcx().emit_err(errors::BadItemKind { span, descr, ctx }); None @@ -1332,7 +1332,7 @@ impl<'a> Parser<'a> { // Check the span for emptiness instead of the list of parameters in order to correctly // recognize and subsequently flag empty parameter lists (`<>`) as unstable. if !generics.span.is_empty() { - self.sess.gated_spans.gate(sym::generic_const_items, generics.span); + self.psess.gated_spans.gate(sym::generic_const_items, generics.span); } // Parse the type of a constant item. That is, the `":" $ty` fragment. @@ -1366,7 +1366,7 @@ impl<'a> Parser<'a> { name: ident.span, body: expr.span, sugg: if !after_where_clause.has_where_token { - self.sess.source_map().span_to_snippet(expr.span).ok().map(|body| { + self.psess.source_map().span_to_snippet(expr.span).ok().map(|body| { errors::WhereClauseBeforeConstBodySugg { left: before_where_clause.span.shrink_to_lo(), snippet: body, @@ -1401,7 +1401,7 @@ impl<'a> Parser<'a> { }; if where_clause.has_where_token { - self.sess.gated_spans.gate(sym::generic_const_items, where_clause.span); + self.psess.gated_spans.gate(sym::generic_const_items, where_clause.span); } generics.where_clause = where_clause; @@ -1898,7 +1898,7 @@ impl<'a> Parser<'a> { fn expect_field_ty_separator(&mut self) -> PResult<'a, ()> { if let Err(err) = self.expect(&token::Colon) { - let sm = self.sess.source_map(); + let sm = self.psess.source_map(); let eq_typo = self.token.kind == token::Eq && self.look_ahead(1, |t| t.is_path_start()); let semi_typo = self.token.kind == token::Semi && self.look_ahead(1, |t| { @@ -1970,7 +1970,7 @@ impl<'a> Parser<'a> { fn parse_field_ident(&mut self, adt_ty: &str, lo: Span) -> PResult<'a, Ident> { let (ident, is_raw) = self.ident_or_err(true)?; if ident.name == kw::Underscore { - self.sess.gated_spans.gate(sym::unnamed_fields, lo); + self.psess.gated_spans.gate(sym::unnamed_fields, lo); } else if matches!(is_raw, IdentIsRaw::No) && ident.is_reserved() { let snapshot = self.create_snapshot_for_diagnostic(); let err = if self.check_fn_front_matter(false, Case::Sensitive) { @@ -2080,7 +2080,7 @@ impl<'a> Parser<'a> { return self.unexpected(); }; - self.sess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span)); + self.psess.gated_spans.gate(sym::decl_macro, lo.to(self.prev_token.span)); Ok((ident, ItemKind::MacroDef(ast::MacroDef { body, macro_rules: false }))) } @@ -2460,7 +2460,7 @@ impl<'a> Parser<'a> { match coroutine_kind { Some(CoroutineKind::Gen { span, .. }) | Some(CoroutineKind::AsyncGen { span, .. }) => { - self.sess.gated_spans.gate(sym::gen_blocks, span); + self.psess.gated_spans.gate(sym::gen_blocks, span); } Some(CoroutineKind::Async { .. }) | None => {} } diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 8542ea6231038..12879dc429bc9 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -128,7 +128,7 @@ pub enum Recovery { #[derive(Clone)] pub struct Parser<'a> { - pub sess: &'a ParseSess, + pub psess: &'a ParseSess, /// The current token. pub token: Token, /// The spacing for the current token. @@ -414,12 +414,12 @@ pub(super) fn token_descr(token: &Token) -> String { impl<'a> Parser<'a> { pub fn new( - sess: &'a ParseSess, + psess: &'a ParseSess, stream: TokenStream, subparser_name: Option<&'static str>, ) -> Self { let mut parser = Parser { - sess, + psess, token: Token::dummy(), token_spacing: Spacing::Alone, prev_token: Token::dummy(), @@ -714,7 +714,7 @@ impl<'a> Parser<'a> { } match self.token.kind.break_two_token_op() { Some((first, second)) if first == expected => { - let first_span = self.sess.source_map().start_point(self.token.span); + let first_span = self.psess.source_map().start_point(self.token.span); let second_span = self.token.span.with_lo(first_span.hi()); self.token = Token::new(first, first_span); // Keep track of this token - if we end token capturing now, @@ -1213,7 +1213,7 @@ impl<'a> Parser<'a> { fn parse_closure_constness(&mut self) -> Const { let constness = self.parse_constness_(Case::Sensitive, true); if let Const::Yes(span) = constness { - self.sess.gated_spans.gate(sym::const_closures, span); + self.psess.gated_spans.gate(sym::const_closures, span); } constness } @@ -1234,9 +1234,9 @@ impl<'a> Parser<'a> { /// Parses inline const expressions. fn parse_const_block(&mut self, span: Span, pat: bool) -> PResult<'a, P> { if pat { - self.sess.gated_spans.gate(sym::inline_const_pat, span); + self.psess.gated_spans.gate(sym::inline_const_pat, span); } else { - self.sess.gated_spans.gate(sym::inline_const, span); + self.psess.gated_spans.gate(sym::inline_const, span); } self.eat_keyword(kw::Const); let (attrs, blk) = self.parse_inner_attrs_and_block()?; @@ -1521,7 +1521,7 @@ impl<'a> Parser<'a> { pub(crate) fn make_unclosed_delims_error( unmatched: UnmatchedDelim, - sess: &ParseSess, + psess: &ParseSess, ) -> Option> { // `None` here means an `Eof` was found. We already emit those errors elsewhere, we add them to // `unmatched_delims` only for error recovery in the `Parser`. @@ -1530,7 +1530,7 @@ pub(crate) fn make_unclosed_delims_error( if let Some(sp) = unmatched.unclosed_span { spans.push(sp); }; - let err = sess.dcx.create_err(MismatchedClosingDelimiter { + let err = psess.dcx.create_err(MismatchedClosingDelimiter { spans, delimiter: pprust::token_kind_to_string(&token::CloseDelim(found_delim)).to_string(), unmatched: unmatched.found_span, diff --git a/compiler/rustc_parse/src/parser/pat.rs b/compiler/rustc_parse/src/parser/pat.rs index 7aeab6488a5ea..88ae1b5420fe7 100644 --- a/compiler/rustc_parse/src/parser/pat.rs +++ b/compiler/rustc_parse/src/parser/pat.rs @@ -470,7 +470,7 @@ impl<'a> Parser<'a> { self.parse_pat_range_to(form)? // `..=X`, `...X`, or `..X`. } else if self.eat(&token::Not) { // Parse `!` - self.sess.gated_spans.gate(sym::never_patterns, self.prev_token.span); + self.psess.gated_spans.gate(sym::never_patterns, self.prev_token.span); PatKind::Never } else if self.eat_keyword(kw::Underscore) { // Parse `_` @@ -843,8 +843,8 @@ impl<'a> Parser<'a> { let mut err = self.dcx().struct_span_err(self.token.span, msg); err.span_label(self.token.span, format!("expected {expected}")); - let sp = self.sess.source_map().start_point(self.token.span); - if let Some(sp) = self.sess.ambiguous_block_expr_parse.borrow().get(&sp) { + let sp = self.psess.source_map().start_point(self.token.span); + if let Some(sp) = self.psess.ambiguous_block_expr_parse.borrow().get(&sp) { err.subdiagnostic(self.dcx(), ExprParenthesesNeeded::surrounding(*sp)); } @@ -1067,7 +1067,7 @@ impl<'a> Parser<'a> { fn parse_pat_struct(&mut self, qself: Option>, path: Path) -> PResult<'a, PatKind> { if qself.is_some() { // Feature gate the use of qualified paths in patterns - self.sess.gated_spans.gate(sym::more_qualified_paths, path.span); + self.psess.gated_spans.gate(sym::more_qualified_paths, path.span); } self.bump(); let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| { @@ -1096,7 +1096,7 @@ impl<'a> Parser<'a> { ) })?; if qself.is_some() { - self.sess.gated_spans.gate(sym::more_qualified_paths, path.span); + self.psess.gated_spans.gate(sym::more_qualified_paths, path.span); } Ok(PatKind::TupleStruct(qself, path, fields)) } @@ -1143,7 +1143,7 @@ impl<'a> Parser<'a> { Ok(PatKind::Ident(BindingAnnotation::NONE, Ident::new(kw::Box, box_span), sub)) } else { let pat = self.parse_pat_with_range_pat(false, None, None)?; - self.sess.gated_spans.gate(sym::box_patterns, box_span.to(self.prev_token.span)); + self.psess.gated_spans.gate(sym::box_patterns, box_span.to(self.prev_token.span)); Ok(PatKind::Box(pat)) } } @@ -1192,15 +1192,15 @@ impl<'a> Parser<'a> { .look_ahead(1, |t| if *t == token::Comma { Some(t.clone()) } else { None }) { let nw_span = self - .sess + .psess .source_map() .span_extend_to_line(comma_tok.span) .trim_start(comma_tok.span.shrink_to_lo()) - .map(|s| self.sess.source_map().span_until_non_whitespace(s)); + .map(|s| self.psess.source_map().span_until_non_whitespace(s)); first_etc_and_maybe_comma_span = nw_span.map(|s| etc_sp.to(s)); } else { first_etc_and_maybe_comma_span = - Some(self.sess.source_map().span_until_non_whitespace(etc_sp)); + Some(self.psess.source_map().span_until_non_whitespace(etc_sp)); } } @@ -1218,7 +1218,8 @@ impl<'a> Parser<'a> { let mut comma_sp = None; if self.token == token::Comma { // Issue #49257 - let nw_span = self.sess.source_map().span_until_non_whitespace(self.token.span); + let nw_span = + self.psess.source_map().span_until_non_whitespace(self.token.span); etc_sp = etc_sp.to(nw_span); err.span_label( etc_sp, diff --git a/compiler/rustc_parse/src/parser/path.rs b/compiler/rustc_parse/src/parser/path.rs index 6e7bbe7e06d42..545db5138a3ab 100644 --- a/compiler/rustc_parse/src/parser/path.rs +++ b/compiler/rustc_parse/src/parser/path.rs @@ -250,7 +250,7 @@ impl<'a> Parser<'a> { self.dcx().emit_err(PathSingleColon { span: self.prev_token.span, type_ascription: self - .sess + .psess .unstable_features .is_nightly_build() .then_some(()), @@ -322,7 +322,7 @@ impl<'a> Parser<'a> { err = self.dcx().create_err(PathSingleColon { span: self.token.span, type_ascription: self - .sess + .psess .unstable_features .is_nightly_build() .then_some(()), @@ -638,9 +638,9 @@ impl<'a> Parser<'a> { && args.inputs.is_empty() && matches!(args.output, ast::FnRetTy::Default(..)) { - self.sess.gated_spans.gate(sym::return_type_notation, span); + self.psess.gated_spans.gate(sym::return_type_notation, span); } else { - self.sess.gated_spans.gate(sym::associated_type_bounds, span); + self.psess.gated_spans.gate(sym::associated_type_bounds, span); } } let constraint = @@ -675,7 +675,7 @@ impl<'a> Parser<'a> { let term = match arg { Some(GenericArg::Type(ty)) => ty.into(), Some(GenericArg::Const(c)) => { - self.sess.gated_spans.gate(sym::associated_const_equality, span); + self.psess.gated_spans.gate(sym::associated_const_equality, span); c.into() } Some(GenericArg::Lifetime(lt)) => { @@ -691,7 +691,7 @@ impl<'a> Parser<'a> { .struct_span_err(after_eq.to(before_next), "missing type to the right of `=`"); if matches!(self.token.kind, token::Comma | token::Gt) { err.span_suggestion( - self.sess.source_map().next_point(eq).to(before_next), + self.psess.source_map().next_point(eq).to(before_next), "to constrain the associated type, add a type after `=`", " TheType", Applicability::HasPlaceholders, diff --git a/compiler/rustc_parse/src/parser/stmt.rs b/compiler/rustc_parse/src/parser/stmt.rs index 65c0f7d49c153..54854cd2da995 100644 --- a/compiler/rustc_parse/src/parser/stmt.rs +++ b/compiler/rustc_parse/src/parser/stmt.rs @@ -230,7 +230,7 @@ impl<'a> Parser<'a> { /// Also error if the previous token was a doc comment. fn error_outer_attrs(&self, attrs: AttrWrapper) { if !attrs.is_empty() - && let attrs @ [.., last] = &*attrs.take_for_recovery(self.sess) + && let attrs @ [.., last] = &*attrs.take_for_recovery(self.psess) { if last.is_doc_comment() { self.dcx().emit_err(errors::DocCommentDoesNotDocumentAnything { @@ -494,7 +494,7 @@ impl<'a> Parser<'a> { // Do not suggest `if foo println!("") {;}` (as would be seen in test for #46836). Ok(Some(Stmt { kind: StmtKind::Empty, .. })) => {} Ok(Some(stmt)) => { - let stmt_own_line = self.sess.source_map().is_line_before_span_empty(sp); + let stmt_own_line = self.psess.source_map().is_line_before_span_empty(sp); let stmt_span = if stmt_own_line && self.eat(&token::Semi) { // Expand the span to include the semicolon. stmt.span.with_hi(self.prev_token.span.hi()) @@ -613,7 +613,7 @@ impl<'a> Parser<'a> { Applicability::MaybeIncorrect, ); } - if self.sess.unstable_features.is_nightly_build() { + if self.psess.unstable_features.is_nightly_build() { // FIXME(Nilstrieb): Remove this again after a few months. err.note("type ascription syntax has been removed, see issue #101728 "); } diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index e3fe535bd5f8d..2385c18c0891c 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -397,7 +397,7 @@ impl<'a> Parser<'a> { let (fields, _recovered) = self.parse_record_struct_body(if is_union { "union" } else { "struct" }, lo, false)?; let span = lo.to(self.prev_token.span); - self.sess.gated_spans.gate(sym::unnamed_fields, span); + self.psess.gated_spans.gate(sym::unnamed_fields, span); let id = ast::DUMMY_NODE_ID; let kind = if is_union { TyKind::AnonUnion(id, fields) } else { TyKind::AnonStruct(id, fields) }; @@ -694,7 +694,7 @@ impl<'a> Parser<'a> { // parse dyn* types let syntax = if self.eat(&TokenKind::BinOp(token::Star)) { - self.sess.gated_spans.gate(sym::dyn_star, lo.to(self.prev_token.span)); + self.psess.gated_spans.gate(sym::dyn_star, lo.to(self.prev_token.span)); TraitObjectSyntax::DynStar } else { TraitObjectSyntax::Dyn @@ -874,10 +874,10 @@ impl<'a> Parser<'a> { let tilde = self.prev_token.span; self.expect_keyword(kw::Const)?; let span = tilde.to(self.prev_token.span); - self.sess.gated_spans.gate(sym::const_trait_impl, span); + self.psess.gated_spans.gate(sym::const_trait_impl, span); BoundConstness::Maybe(span) } else if self.eat_keyword(kw::Const) { - self.sess.gated_spans.gate(sym::const_trait_impl, self.prev_token.span); + self.psess.gated_spans.gate(sym::const_trait_impl, self.prev_token.span); BoundConstness::Always(self.prev_token.span) } else { BoundConstness::Never @@ -886,7 +886,7 @@ impl<'a> Parser<'a> { let asyncness = if self.token.uninterpolated_span().at_least_rust_2018() && self.eat_keyword(kw::Async) { - self.sess.gated_spans.gate(sym::async_closure, self.prev_token.span); + self.psess.gated_spans.gate(sym::async_closure, self.prev_token.span); BoundAsyncness::Async(self.prev_token.span) } else if self.may_recover() && self.token.uninterpolated_span().is_rust_2015() @@ -897,7 +897,7 @@ impl<'a> Parser<'a> { span: self.prev_token.span, help: HelpUseLatestEdition::new(), }); - self.sess.gated_spans.gate(sym::async_closure, self.prev_token.span); + self.psess.gated_spans.gate(sym::async_closure, self.prev_token.span); BoundAsyncness::Async(self.prev_token.span) } else { BoundAsyncness::Normal @@ -906,7 +906,7 @@ impl<'a> Parser<'a> { let polarity = if self.eat(&token::Question) { BoundPolarity::Maybe(self.prev_token.span) } else if self.eat(&token::Not) { - self.sess.gated_spans.gate(sym::negative_bounds, self.prev_token.span); + self.psess.gated_spans.gate(sym::negative_bounds, self.prev_token.span); BoundPolarity::Negative(self.prev_token.span) } else { BoundPolarity::Positive diff --git a/compiler/rustc_parse/src/validate_attr.rs b/compiler/rustc_parse/src/validate_attr.rs index 73c92708eb39c..f88edf29dcebe 100644 --- a/compiler/rustc_parse/src/validate_attr.rs +++ b/compiler/rustc_parse/src/validate_attr.rs @@ -13,7 +13,7 @@ use rustc_session::lint::builtin::ILL_FORMED_ATTRIBUTE_INPUT; use rustc_session::parse::ParseSess; use rustc_span::{sym, Span, Symbol}; -pub fn check_attr(sess: &ParseSess, attr: &Attribute) { +pub fn check_attr(psess: &ParseSess, attr: &Attribute) { if attr.is_doc_comment() { return; } @@ -24,11 +24,11 @@ pub fn check_attr(sess: &ParseSess, attr: &Attribute) { match attr_info { // `rustc_dummy` doesn't have any restrictions specific to built-in attributes. Some(BuiltinAttribute { name, template, .. }) if *name != sym::rustc_dummy => { - check_builtin_attribute(sess, attr, *name, *template) + check_builtin_attribute(psess, attr, *name, *template) } _ if let AttrArgs::Eq(..) = attr.get_normal_item().args => { // All key-value attributes are restricted to meta-item syntax. - parse_meta(sess, attr) + parse_meta(psess, attr) .map_err(|err| { err.emit(); }) @@ -38,7 +38,7 @@ pub fn check_attr(sess: &ParseSess, attr: &Attribute) { } } -pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> { +pub fn parse_meta<'a>(psess: &'a ParseSess, attr: &Attribute) -> PResult<'a, MetaItem> { let item = attr.get_normal_item(); Ok(MetaItem { span: attr.span, @@ -46,8 +46,9 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta kind: match &item.args { AttrArgs::Empty => MetaItemKind::Word, AttrArgs::Delimited(DelimArgs { dspan, delim, tokens }) => { - check_meta_bad_delim(sess, *dspan, *delim); - let nmis = parse_in(sess, tokens.clone(), "meta list", |p| p.parse_meta_seq_top())?; + check_meta_bad_delim(psess, *dspan, *delim); + let nmis = + parse_in(psess, tokens.clone(), "meta list", |p| p.parse_meta_seq_top())?; MetaItemKind::List(nmis) } AttrArgs::Eq(_, AttrArgsEq::Ast(expr)) => { @@ -56,7 +57,7 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta let res = match res { Ok(lit) => { if token_lit.suffix.is_some() { - let mut err = sess.dcx.struct_span_err( + let mut err = psess.dcx.struct_span_err( expr.span, "suffixed literals are not allowed in attributes", ); @@ -70,7 +71,7 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta } } Err(err) => { - let guar = report_lit_error(sess, err, token_lit, expr.span); + let guar = report_lit_error(psess, err, token_lit, expr.span); let lit = ast::MetaItemLit { symbol: token_lit.symbol, suffix: token_lit.suffix, @@ -89,7 +90,7 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta // the error because an earlier error will have already // been reported. let msg = "attribute value must be a literal"; - let mut err = sess.dcx.struct_span_err(expr.span, msg); + let mut err = psess.dcx.struct_span_err(expr.span, msg); if let ast::ExprKind::Err(_) = expr.kind { err.downgrade_to_delayed_bug(); } @@ -101,21 +102,21 @@ pub fn parse_meta<'a>(sess: &'a ParseSess, attr: &Attribute) -> PResult<'a, Meta }) } -pub fn check_meta_bad_delim(sess: &ParseSess, span: DelimSpan, delim: Delimiter) { +pub fn check_meta_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) { if let Delimiter::Parenthesis = delim { return; } - sess.dcx.emit_err(errors::MetaBadDelim { + psess.dcx.emit_err(errors::MetaBadDelim { span: span.entire(), sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close }, }); } -pub fn check_cfg_attr_bad_delim(sess: &ParseSess, span: DelimSpan, delim: Delimiter) { +pub fn check_cfg_attr_bad_delim(psess: &ParseSess, span: DelimSpan, delim: Delimiter) { if let Delimiter::Parenthesis = delim { return; } - sess.dcx.emit_err(errors::CfgAttrBadDelim { + psess.dcx.emit_err(errors::CfgAttrBadDelim { span: span.entire(), sugg: errors::MetaBadDelimSugg { open: span.open, close: span.close }, }); @@ -132,13 +133,13 @@ fn is_attr_template_compatible(template: &AttributeTemplate, meta: &ast::MetaIte } pub fn check_builtin_attribute( - sess: &ParseSess, + psess: &ParseSess, attr: &Attribute, name: Symbol, template: AttributeTemplate, ) { - match parse_meta(sess, attr) { - Ok(meta) => check_builtin_meta_item(sess, &meta, attr.style, name, template), + match parse_meta(psess, attr) { + Ok(meta) => check_builtin_meta_item(psess, &meta, attr.style, name, template), Err(err) => { err.emit(); } @@ -146,7 +147,7 @@ pub fn check_builtin_attribute( } pub fn check_builtin_meta_item( - sess: &ParseSess, + psess: &ParseSess, meta: &MetaItem, style: ast::AttrStyle, name: Symbol, @@ -157,12 +158,12 @@ pub fn check_builtin_meta_item( let should_skip = |name| name == sym::cfg; if !should_skip(name) && !is_attr_template_compatible(&template, &meta.kind) { - emit_malformed_attribute(sess, style, meta.span, name, template); + emit_malformed_attribute(psess, style, meta.span, name, template); } } fn emit_malformed_attribute( - sess: &ParseSess, + psess: &ParseSess, style: ast::AttrStyle, span: Span, name: Symbol, @@ -204,9 +205,10 @@ fn emit_malformed_attribute( } suggestions.sort(); if should_warn(name) { - sess.buffer_lint(ILL_FORMED_ATTRIBUTE_INPUT, span, ast::CRATE_NODE_ID, msg); + psess.buffer_lint(ILL_FORMED_ATTRIBUTE_INPUT, span, ast::CRATE_NODE_ID, msg); } else { - sess.dcx + psess + .dcx .struct_span_err(span, error_msg) .with_span_suggestions( span, @@ -223,12 +225,12 @@ fn emit_malformed_attribute( } pub fn emit_fatal_malformed_builtin_attribute( - sess: &ParseSess, + psess: &ParseSess, attr: &Attribute, name: Symbol, ) -> ! { let template = BUILTIN_ATTRIBUTE_MAP.get(&name).expect("builtin attr defined").template; - emit_malformed_attribute(sess, attr.style, attr.span, name, template); + emit_malformed_attribute(psess, attr.style, attr.span, name, template); // This is fatal, otherwise it will likely cause a cascade of other errors // (and an error here is expected to be very rare). FatalError.raise() diff --git a/compiler/rustc_resolve/src/macros.rs b/compiler/rustc_resolve/src/macros.rs index 3fccdec8aa0b6..4dbfb072154d5 100644 --- a/compiler/rustc_resolve/src/macros.rs +++ b/compiler/rustc_resolve/src/macros.rs @@ -590,7 +590,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { _ => unreachable!(), }; if soft_custom_inner_attributes_gate { - self.tcx.sess.parse_sess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg); + self.tcx.sess.psess.buffer_lint(SOFT_UNSTABLE, path.span, node_id, msg); } else { feature_err(&self.tcx.sess, sym::custom_inner_attributes, path.span, msg).emit(); } @@ -601,7 +601,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> { && path.segments[0].ident.name == sym::diagnostic && path.segments[1].ident.name != sym::on_unimplemented { - self.tcx.sess.parse_sess.buffer_lint( + self.tcx.sess.psess.buffer_lint( UNKNOWN_OR_MALFORMED_DIAGNOSTIC_ATTRIBUTES, path.segments[1].span(), node_id, diff --git a/compiler/rustc_session/src/errors.rs b/compiler/rustc_session/src/errors.rs index 903d429d3a518..1ea29227e4a52 100644 --- a/compiler/rustc_session/src/errors.rs +++ b/compiler/rustc_session/src/errors.rs @@ -346,7 +346,7 @@ pub(crate) struct BinaryFloatLiteralNotSupported { } pub fn report_lit_error( - sess: &ParseSess, + psess: &ParseSess, err: LitError, lit: token::Lit, span: Span, @@ -378,7 +378,7 @@ pub fn report_lit_error( valid.then(|| format!("0{}{}", base_char.to_ascii_lowercase(), &suffix[1..])) } - let dcx = &sess.dcx; + let dcx = &psess.dcx; match err { LitError::InvalidSuffix(suffix) => { dcx.emit_err(InvalidLiteralSuffix { span, kind: lit.kind.descr(), suffix }) diff --git a/compiler/rustc_session/src/parse.rs b/compiler/rustc_session/src/parse.rs index 656781353ea76..e30e8cd9f62a6 100644 --- a/compiler/rustc_session/src/parse.rs +++ b/compiler/rustc_session/src/parse.rs @@ -106,13 +106,12 @@ pub fn feature_err_issue( // Cancel an earlier warning for this same error, if it exists. if let Some(span) = span.primary_span() { - if let Some(err) = sess.parse_sess.dcx.steal_non_err(span, StashKey::EarlySyntaxWarning) { + if let Some(err) = sess.psess.dcx.steal_non_err(span, StashKey::EarlySyntaxWarning) { err.cancel() } } - let mut err = - sess.parse_sess.dcx.create_err(FeatureGateError { span, explain: explain.into() }); + let mut err = sess.psess.dcx.create_err(FeatureGateError { span, explain: explain.into() }); add_feature_diagnostics_for_issue(&mut err, sess, feature, issue, false); err } @@ -141,7 +140,7 @@ pub fn feature_warn_issue( issue: GateIssue, explain: &'static str, ) { - let mut err = sess.parse_sess.dcx.struct_span_warn(span, explain); + let mut err = sess.psess.dcx.struct_span_warn(span, explain); add_feature_diagnostics_for_issue(&mut err, sess, feature, issue, false); // Decorate this as a future-incompatibility lint as in rustc_middle::lint::lint_level @@ -181,7 +180,7 @@ pub fn add_feature_diagnostics_for_issue( } // #23973: do not suggest `#![feature(...)]` if we are in beta/stable - if sess.parse_sess.unstable_features.is_nightly_build() { + if sess.psess.unstable_features.is_nightly_build() { if feature_from_cli { err.subdiagnostic(sess.dcx(), CliFeatureDiagnosticHelp { feature }); } else { diff --git a/compiler/rustc_session/src/session.rs b/compiler/rustc_session/src/session.rs index 09fb6aa5d8f98..9c642b98b01a1 100644 --- a/compiler/rustc_session/src/session.rs +++ b/compiler/rustc_session/src/session.rs @@ -146,7 +146,7 @@ pub struct Session { pub opts: config::Options, pub host_tlib_path: Lrc, pub target_tlib_path: Lrc, - pub parse_sess: ParseSess, + pub psess: ParseSess, pub sysroot: PathBuf, /// Input, input file path and output file path to this compilation process. pub io: CompilerIO, @@ -336,12 +336,12 @@ impl Session { #[inline] pub fn dcx(&self) -> &DiagCtxt { - &self.parse_sess.dcx + &self.psess.dcx } #[inline] pub fn source_map(&self) -> &SourceMap { - self.parse_sess.source_map() + self.psess.source_map() } /// Returns `true` if internal lints should be added to the lint store - i.e. if @@ -1114,8 +1114,8 @@ pub fn build_session( None }; - let mut parse_sess = ParseSess::with_dcx(dcx, source_map); - parse_sess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release; + let mut psess = ParseSess::with_dcx(dcx, source_map); + psess.assume_incomplete_release = sopts.unstable_opts.assume_incomplete_release; let host_triple = config::host_triple(); let target_triple = sopts.target_triple.triple(); @@ -1154,7 +1154,7 @@ pub fn build_session( opts: sopts, host_tlib_path, target_tlib_path, - parse_sess, + psess, sysroot, io, incr_comp_session: RwLock::new(IncrCompSession::NotInitialized), diff --git a/src/librustdoc/clean/cfg.rs b/src/librustdoc/clean/cfg.rs index 0445daf0d4d72..277db90df9aaa 100644 --- a/src/librustdoc/clean/cfg.rs +++ b/src/librustdoc/clean/cfg.rs @@ -130,18 +130,18 @@ impl Cfg { /// /// Equivalent to `attr::cfg_matches`. // FIXME: Actually make use of `features`. - pub(crate) fn matches(&self, parse_sess: &ParseSess, features: Option<&Features>) -> bool { + pub(crate) fn matches(&self, psess: &ParseSess, features: Option<&Features>) -> bool { match *self { Cfg::False => false, Cfg::True => true, - Cfg::Not(ref child) => !child.matches(parse_sess, features), + Cfg::Not(ref child) => !child.matches(psess, features), Cfg::All(ref sub_cfgs) => { - sub_cfgs.iter().all(|sub_cfg| sub_cfg.matches(parse_sess, features)) + sub_cfgs.iter().all(|sub_cfg| sub_cfg.matches(psess, features)) } Cfg::Any(ref sub_cfgs) => { - sub_cfgs.iter().any(|sub_cfg| sub_cfg.matches(parse_sess, features)) + sub_cfgs.iter().any(|sub_cfg| sub_cfg.matches(psess, features)) } - Cfg::Cfg(name, value) => parse_sess.config.contains(&(name, value)), + Cfg::Cfg(name, value) => psess.config.contains(&(name, value)), } } diff --git a/src/librustdoc/clean/render_macro_matchers.rs b/src/librustdoc/clean/render_macro_matchers.rs index 97e094bb3fb3a..5ac1b742c386a 100644 --- a/src/librustdoc/clean/render_macro_matchers.rs +++ b/src/librustdoc/clean/render_macro_matchers.rs @@ -62,10 +62,10 @@ fn snippet_equal_to_token(tcx: TyCtxt<'_>, matcher: &TokenTree) -> Option parser, Err(errs) => { errs.into_iter().for_each(|err| err.cancel()); diff --git a/src/librustdoc/core.rs b/src/librustdoc/core.rs index 9ba79cf5d29f1..5a28f49538163 100644 --- a/src/librustdoc/core.rs +++ b/src/librustdoc/core.rs @@ -263,7 +263,7 @@ pub(crate) fn create_config( file_loader: None, locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES, lint_caps, - parse_sess_created: None, + psess_created: None, hash_untracked_state: None, register_lints: Some(Box::new(crate::lint::register_lints)), override_queries: Some(|_sess, providers| { diff --git a/src/librustdoc/doctest.rs b/src/librustdoc/doctest.rs index 3d92444364f68..d446b781bf139 100644 --- a/src/librustdoc/doctest.rs +++ b/src/librustdoc/doctest.rs @@ -102,7 +102,7 @@ pub(crate) fn run(options: RustdocOptions) -> Result<(), ErrorGuaranteed> { file_loader: None, locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES, lint_caps, - parse_sess_created: None, + psess_created: None, hash_untracked_state: None, register_lints: Some(Box::new(crate::lint::register_lints)), override_queries: None, @@ -131,7 +131,7 @@ pub(crate) fn run(options: RustdocOptions) -> Result<(), ErrorGuaranteed> { options, false, opts, - Some(compiler.sess.parse_sess.clone_source_map()), + Some(compiler.sess.psess.clone_source_map()), None, enable_per_target_ignores, ); @@ -585,13 +585,13 @@ pub(crate) fn make_test( // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser let dcx = DiagCtxt::new(Box::new(emitter)).disable_warnings(); - let sess = ParseSess::with_dcx(dcx, sm); + let psess = ParseSess::with_dcx(dcx, sm); let mut found_main = false; let mut found_extern_crate = crate_name.is_none(); let mut found_macro = false; - let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) { + let mut parser = match maybe_new_parser_from_source_str(&psess, filename, source) { Ok(p) => p, Err(errs) => { errs.into_iter().for_each(|err| err.cancel()); @@ -646,7 +646,7 @@ pub(crate) fn make_test( // dcx. Any errors in the tests will be reported when the test file is compiled, // Note that we still need to cancel the errors above otherwise `Diag` will panic on // drop. - sess.dcx.reset_err_count(); + psess.dcx.reset_err_count(); (found_main, found_extern_crate, found_macro) }) @@ -770,9 +770,9 @@ fn check_if_attr_is_complete(source: &str, edition: Edition) -> bool { let emitter = HumanEmitter::new(Box::new(io::sink()), fallback_bundle); let dcx = DiagCtxt::new(Box::new(emitter)).disable_warnings(); - let sess = ParseSess::with_dcx(dcx, sm); + let psess = ParseSess::with_dcx(dcx, sm); let mut parser = - match maybe_new_parser_from_source_str(&sess, filename, source.to_owned()) { + match maybe_new_parser_from_source_str(&psess, filename, source.to_owned()) { Ok(p) => p, Err(errs) => { errs.into_iter().for_each(|err| err.cancel()); @@ -1233,7 +1233,7 @@ impl<'a, 'hir, 'tcx> HirCollector<'a, 'hir, 'tcx> { ) { let ast_attrs = self.tcx.hir().attrs(self.tcx.local_def_id_to_hir_id(def_id)); if let Some(ref cfg) = ast_attrs.cfg(self.tcx, &FxHashSet::default()) { - if !cfg.matches(&self.sess.parse_sess, Some(self.tcx.features())) { + if !cfg.matches(&self.sess.psess, Some(self.tcx.features())) { return; } } diff --git a/src/librustdoc/passes/lint/check_code_block_syntax.rs b/src/librustdoc/passes/lint/check_code_block_syntax.rs index 5145d8babef9d..7b81b5e63be6f 100644 --- a/src/librustdoc/passes/lint/check_code_block_syntax.rs +++ b/src/librustdoc/passes/lint/check_code_block_syntax.rs @@ -44,7 +44,7 @@ fn check_rust_syntax( let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); let dcx = DiagCtxt::new(Box::new(emitter)).disable_warnings(); let source = dox[code_block.code].to_owned(); - let sess = ParseSess::with_dcx(dcx, sm); + let psess = ParseSess::with_dcx(dcx, sm); let edition = code_block.lang_string.edition.unwrap_or_else(|| cx.tcx.sess.edition()); let expn_data = @@ -56,7 +56,7 @@ fn check_rust_syntax( parse_stream_from_source_str( FileName::Custom(String::from("doctest")), source, - &sess, + &psess, Some(span), ) .is_empty() diff --git a/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs b/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs index d5205e65cef3a..0c1bb2da7e896 100644 --- a/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs +++ b/src/tools/clippy/clippy_lints/src/disallowed_script_idents.rs @@ -72,7 +72,7 @@ impl EarlyLintPass for DisallowedScriptIdents { return; } - let symbols = cx.sess().parse_sess.symbol_gallery.symbols.lock(); + let symbols = cx.sess().psess.symbol_gallery.symbols.lock(); // Sort by `Span` so that error messages make sense with respect to the // order of identifier locations in the code. let mut symbols: Vec<_> = symbols.iter().collect(); diff --git a/src/tools/clippy/clippy_lints/src/doc/needless_doctest_main.rs b/src/tools/clippy/clippy_lints/src/doc/needless_doctest_main.rs index fdb9ceb7179a5..e55a988321b34 100644 --- a/src/tools/clippy/clippy_lints/src/doc/needless_doctest_main.rs +++ b/src/tools/clippy/clippy_lints/src/doc/needless_doctest_main.rs @@ -48,9 +48,9 @@ pub fn check( let dcx = DiagCtxt::new(Box::new(emitter)).disable_warnings(); #[expect(clippy::arc_with_non_send_sync)] // `Lrc` is expected by with_dcx let sm = Lrc::new(SourceMap::new(FilePathMapping::empty())); - let sess = ParseSess::with_dcx(dcx, sm); + let psess = ParseSess::with_dcx(dcx, sm); - let mut parser = match maybe_new_parser_from_source_str(&sess, filename, code) { + let mut parser = match maybe_new_parser_from_source_str(&psess, filename, code) { Ok(p) => p, Err(errs) => { errs.into_iter().for_each(Diag::cancel); diff --git a/src/tools/clippy/src/driver.rs b/src/tools/clippy/src/driver.rs index b966fcf9b80f2..8fc66644632cd 100644 --- a/src/tools/clippy/src/driver.rs +++ b/src/tools/clippy/src/driver.rs @@ -68,8 +68,8 @@ fn test_arg_value() { assert_eq!(arg_value(args, "--foo", |_| true), None); } -fn track_clippy_args(parse_sess: &mut ParseSess, args_env_var: &Option) { - parse_sess.env_depinfo.get_mut().insert(( +fn track_clippy_args(psess: &mut ParseSess, args_env_var: &Option) { + psess.env_depinfo.get_mut().insert(( Symbol::intern("CLIPPY_ARGS"), args_env_var.as_deref().map(Symbol::intern), )); @@ -77,8 +77,8 @@ fn track_clippy_args(parse_sess: &mut ParseSess, args_env_var: &Option) /// Track files that may be accessed at runtime in `file_depinfo` so that cargo will re-run clippy /// when any of them are modified -fn track_files(parse_sess: &mut ParseSess) { - let file_depinfo = parse_sess.file_depinfo.get_mut(); +fn track_files(psess: &mut ParseSess) { + let file_depinfo = psess.file_depinfo.get_mut(); // Used by `clippy::cargo` lints and to determine the MSRV. `cargo clippy` executes `clippy-driver` // with the current directory set to `CARGO_MANIFEST_DIR` so a relative path is fine @@ -115,8 +115,8 @@ struct RustcCallbacks { impl rustc_driver::Callbacks for RustcCallbacks { fn config(&mut self, config: &mut interface::Config) { let clippy_args_var = self.clippy_args_var.take(); - config.parse_sess_created = Some(Box::new(move |parse_sess| { - track_clippy_args(parse_sess, &clippy_args_var); + config.psess_created = Some(Box::new(move |psess| { + track_clippy_args(psess, &clippy_args_var); })); } } @@ -132,13 +132,13 @@ impl rustc_driver::Callbacks for ClippyCallbacks { let conf_path = clippy_config::lookup_conf_file(); let previous = config.register_lints.take(); let clippy_args_var = self.clippy_args_var.take(); - config.parse_sess_created = Some(Box::new(move |parse_sess| { - track_clippy_args(parse_sess, &clippy_args_var); - track_files(parse_sess); + config.psess_created = Some(Box::new(move |psess| { + track_clippy_args(psess, &clippy_args_var); + track_files(psess); // Trigger a rebuild if CLIPPY_CONF_DIR changes. The value must be a valid string so // changes between dirs that are invalid UTF-8 will not trigger rebuilds - parse_sess.env_depinfo.get_mut().insert(( + psess.env_depinfo.get_mut().insert(( Symbol::intern("CLIPPY_CONF_DIR"), env::var("CLIPPY_CONF_DIR").ok().map(|dir| Symbol::intern(&dir)), )); diff --git a/src/tools/rustfmt/src/comment.rs b/src/tools/rustfmt/src/comment.rs index f7cd7cefb3d69..7d1b0384431be 100644 --- a/src/tools/rustfmt/src/comment.rs +++ b/src/tools/rustfmt/src/comment.rs @@ -1721,10 +1721,10 @@ pub(crate) fn recover_comment_removed( // We missed some comments. Warn and keep the original text. if context.config.error_on_unformatted() { context.report.append( - context.parse_sess.span_to_filename(span), + context.psess.span_to_filename(span), vec![FormattingError::from_span( span, - context.parse_sess, + context.psess, ErrorKind::LostComment, )], ); diff --git a/src/tools/rustfmt/src/formatting.rs b/src/tools/rustfmt/src/formatting.rs index 1c64921b1a68d..3bcb4d15184a1 100644 --- a/src/tools/rustfmt/src/formatting.rs +++ b/src/tools/rustfmt/src/formatting.rs @@ -79,7 +79,7 @@ fn should_skip_module( // FIXME(calebcartwright) - we need to determine how we'll handle the // `format_generated_files` option with stdin based input. if !input_is_stdin && !config.format_generated_files() { - let source_file = context.parse_session.span_to_file_contents(module.span); + let source_file = context.psess.span_to_file_contents(module.span); let src = source_file.src.as_ref().expect("SourceFile without src"); if is_generated_file(src) { @@ -109,8 +109,8 @@ fn format_project( let main_file = input.file_name(); let input_is_stdin = main_file == FileName::Stdin; - let parse_session = ParseSess::new(config)?; - if config.skip_children() && parse_session.ignore_file(&main_file) { + let psess = ParseSess::new(config)?; + if config.skip_children() && psess.ignore_file(&main_file) { return Ok(FormatReport::new()); } @@ -118,7 +118,7 @@ fn format_project( let mut report = FormatReport::new(); let directory_ownership = input.to_directory_ownership(); - let krate = match Parser::parse_crate(input, &parse_session) { + let krate = match Parser::parse_crate(input, &psess) { Ok(krate) => krate, // Surface parse error via Session (errors are merged there from report) Err(e) => { @@ -131,9 +131,9 @@ fn format_project( } }; - let mut context = FormatContext::new(&krate, report, parse_session, config, handler); + let mut context = FormatContext::new(&krate, report, psess, config, handler); let files = modules::ModResolver::new( - &context.parse_session, + &context.psess, directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock), !input_is_stdin && !config.skip_children(), ) @@ -148,16 +148,11 @@ fn format_project( timer = timer.done_parsing(); // Suppress error output if we have to do any further parsing. - context.parse_session.set_silent_emitter(); + context.psess.set_silent_emitter(); for (path, module) in files { if input_is_stdin && contains_skip(module.attrs()) { - return echo_back_stdin( - context - .parse_session - .snippet_provider(module.span) - .entire_snippet(), - ); + return echo_back_stdin(context.psess.snippet_provider(module.span).entire_snippet()); } should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path)); context.format_file(path, &module, is_macro_def)?; @@ -179,7 +174,7 @@ fn format_project( struct FormatContext<'a, T: FormatHandler> { krate: &'a ast::Crate, report: FormatReport, - parse_session: ParseSess, + psess: ParseSess, config: &'a Config, handler: &'a mut T, } @@ -188,21 +183,21 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> { fn new( krate: &'a ast::Crate, report: FormatReport, - parse_session: ParseSess, + psess: ParseSess, config: &'a Config, handler: &'a mut T, ) -> Self { FormatContext { krate, report, - parse_session, + psess, config, handler, } } fn ignore_file(&self, path: &FileName) -> bool { - self.parse_session.ignore_file(path) + self.psess.ignore_file(path) } // Formats a single file/module. @@ -212,9 +207,9 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> { module: &Module<'_>, is_macro_def: bool, ) -> Result<(), ErrorKind> { - let snippet_provider = self.parse_session.snippet_provider(module.span); - let mut visitor = FmtVisitor::from_parse_sess( - &self.parse_session, + let snippet_provider = self.psess.snippet_provider(module.span); + let mut visitor = FmtVisitor::from_psess( + &self.psess, self.config, &snippet_provider, self.report.clone(), @@ -257,7 +252,7 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> { .add_non_formatted_ranges(visitor.skipped_range.borrow().clone()); self.handler.handle_formatted_file( - &self.parse_session, + &self.psess, path, visitor.buffer.to_owned(), &mut self.report, @@ -269,7 +264,7 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> { trait FormatHandler { fn handle_formatted_file( &mut self, - parse_session: &ParseSess, + psess: &ParseSess, path: FileName, result: String, report: &mut FormatReport, @@ -280,14 +275,14 @@ impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> { // Called for each formatted file. fn handle_formatted_file( &mut self, - parse_session: &ParseSess, + psess: &ParseSess, path: FileName, result: String, report: &mut FormatReport, ) -> Result<(), ErrorKind> { if let Some(ref mut out) = self.out { match source_file::write_file( - Some(parse_session), + Some(psess), &path, &result, out, @@ -318,17 +313,13 @@ pub(crate) struct FormattingError { } impl FormattingError { - pub(crate) fn from_span( - span: Span, - parse_sess: &ParseSess, - kind: ErrorKind, - ) -> FormattingError { + pub(crate) fn from_span(span: Span, psess: &ParseSess, kind: ErrorKind) -> FormattingError { FormattingError { - line: parse_sess.line_of_byte_pos(span.lo()), + line: psess.line_of_byte_pos(span.lo()), is_comment: kind.is_comment(), kind, is_string: false, - line_buffer: parse_sess.span_to_first_line_string(span), + line_buffer: psess.span_to_first_line_string(span), } } diff --git a/src/tools/rustfmt/src/macros.rs b/src/tools/rustfmt/src/macros.rs index b4c58d2fefb10..8d77d2b32542d 100644 --- a/src/tools/rustfmt/src/macros.rs +++ b/src/tools/rustfmt/src/macros.rs @@ -136,8 +136,8 @@ fn return_macro_parse_failure_fallback( } context.skipped_range.borrow_mut().push(( - context.parse_sess.line_of_byte_pos(span.lo()), - context.parse_sess.line_of_byte_pos(span.hi()), + context.psess.line_of_byte_pos(span.lo()), + context.psess.line_of_byte_pos(span.hi()), )); // Return the snippet unmodified if the macro is not block-like diff --git a/src/tools/rustfmt/src/missed_spans.rs b/src/tools/rustfmt/src/missed_spans.rs index 28edcb784b40e..b1a7769c21bf4 100644 --- a/src/tools/rustfmt/src/missed_spans.rs +++ b/src/tools/rustfmt/src/missed_spans.rs @@ -91,7 +91,7 @@ impl<'a> FmtVisitor<'a> { assert!( start < end, "Request to format inverted span: {}", - self.parse_sess.span_to_debug_info(mk_sp(start, end)), + self.psess.span_to_debug_info(mk_sp(start, end)), ); self.last_pos = end; @@ -166,8 +166,8 @@ impl<'a> FmtVisitor<'a> { // Trim whitespace from the right hand side of each line. // Annoyingly, the library functions for splitting by lines etc. are not // quite right, so we must do it ourselves. - let line = self.parse_sess.line_of_byte_pos(span.lo()); - let file_name = &self.parse_sess.span_to_filename(span); + let line = self.psess.line_of_byte_pos(span.lo()); + let file_name = &self.psess.span_to_filename(span); let mut status = SnippetStatus::new(line); let snippet = &*transform_missing_snippet(self.config, old_snippet); diff --git a/src/tools/rustfmt/src/modules.rs b/src/tools/rustfmt/src/modules.rs index af9a154a6aea6..0590f28ee0521 100644 --- a/src/tools/rustfmt/src/modules.rs +++ b/src/tools/rustfmt/src/modules.rs @@ -57,8 +57,8 @@ impl<'a> Module<'a> { } /// Maps each module to the corresponding file. -pub(crate) struct ModResolver<'ast, 'sess> { - parse_sess: &'sess ParseSess, +pub(crate) struct ModResolver<'ast, 'psess> { + psess: &'psess ParseSess, directory: Directory, file_map: FileModMap<'ast>, recursive: bool, @@ -99,10 +99,10 @@ enum SubModKind<'a, 'ast> { Internal(&'a ast::Item), } -impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { +impl<'ast, 'psess, 'c> ModResolver<'ast, 'psess> { /// Creates a new `ModResolver`. pub(crate) fn new( - parse_sess: &'sess ParseSess, + psess: &'psess ParseSess, directory_ownership: DirectoryOwnership, recursive: bool, ) -> Self { @@ -112,7 +112,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { ownership: directory_ownership, }, file_map: BTreeMap::new(), - parse_sess, + psess, recursive, } } @@ -122,7 +122,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { mut self, krate: &'ast ast::Crate, ) -> Result, ModuleResolutionError> { - let root_filename = self.parse_sess.span_to_filename(krate.spans.inner_span); + let root_filename = self.psess.span_to_filename(krate.spans.inner_span); self.directory.path = match root_filename { FileName::Real(ref p) => p.parent().unwrap_or(Path::new("")).to_path_buf(), _ => PathBuf::new(), @@ -133,7 +133,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { self.visit_mod_from_ast(&krate.items)?; } - let snippet_provider = self.parse_sess.snippet_provider(krate.spans.inner_span); + let snippet_provider = self.psess.snippet_provider(krate.spans.inner_span); self.file_map.insert( root_filename, @@ -149,7 +149,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { /// Visit `cfg_if` macro and look for module declarations. fn visit_cfg_if(&mut self, item: Cow<'ast, ast::Item>) -> Result<(), ModuleResolutionError> { - let mut visitor = visitor::CfgIfVisitor::new(self.parse_sess); + let mut visitor = visitor::CfgIfVisitor::new(self.psess); visitor.visit_item(&item); for module_item in visitor.mods() { if let ast::ItemKind::Mod(_, ref sub_mod_kind) = module_item.item.kind { @@ -338,10 +338,10 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { DirectoryOwnership::UnownedViaBlock => None, }; if let Some(path) = Parser::submod_path_from_attr(attrs, &self.directory.path) { - if self.parse_sess.is_file_parsed(&path) { + if self.psess.is_file_parsed(&path) { return Ok(None); } - return match Parser::parse_file_as_module(self.parse_sess, &path, sub_mod.span) { + return match Parser::parse_file_as_module(self.psess, &path, sub_mod.span) { Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None), Ok((attrs, items, span)) => Ok(Some(SubModKind::External( path, @@ -368,7 +368,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { let mut mods_outside_ast = self.find_mods_outside_of_ast(attrs, sub_mod); match self - .parse_sess + .psess .default_submod_path(mod_name, relative, &self.directory.path) { Ok(ModulePathSuccess { @@ -380,7 +380,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { let should_insert = !mods_outside_ast .iter() .any(|(outside_path, _, _)| outside_path == &file_path); - if self.parse_sess.is_file_parsed(&file_path) { + if self.psess.is_file_parsed(&file_path) { if outside_mods_empty { return Ok(None); } else { @@ -390,7 +390,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { return Ok(Some(SubModKind::MultiExternal(mods_outside_ast))); } } - match Parser::parse_file_as_module(self.parse_sess, &file_path, sub_mod.span) { + match Parser::parse_file_as_module(self.psess, &file_path, sub_mod.span) { Ok((ref attrs, _, _)) if contains_skip(attrs) => Ok(None), Ok((attrs, items, span)) if outside_mods_empty => { Ok(Some(SubModKind::External( @@ -517,7 +517,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { if !actual_path.exists() { continue; } - if self.parse_sess.is_file_parsed(&actual_path) { + if self.psess.is_file_parsed(&actual_path) { // If the specified file is already parsed, then we just use that. result.push(( actual_path, @@ -527,7 +527,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { continue; } let (attrs, items, span) = - match Parser::parse_file_as_module(self.parse_sess, &actual_path, sub_mod.span) { + match Parser::parse_file_as_module(self.psess, &actual_path, sub_mod.span) { Ok((ref attrs, _, _)) if contains_skip(attrs) => continue, Ok(m) => m, Err(..) => continue, diff --git a/src/tools/rustfmt/src/modules/visitor.rs b/src/tools/rustfmt/src/modules/visitor.rs index 48431693332a6..3e05b6d0c5d49 100644 --- a/src/tools/rustfmt/src/modules/visitor.rs +++ b/src/tools/rustfmt/src/modules/visitor.rs @@ -12,15 +12,15 @@ pub(crate) struct ModItem { /// Traverse `cfg_if!` macro and fetch modules. pub(crate) struct CfgIfVisitor<'a> { - parse_sess: &'a ParseSess, + psess: &'a ParseSess, mods: Vec, } impl<'a> CfgIfVisitor<'a> { - pub(crate) fn new(parse_sess: &'a ParseSess) -> CfgIfVisitor<'a> { + pub(crate) fn new(psess: &'a ParseSess) -> CfgIfVisitor<'a> { CfgIfVisitor { mods: vec![], - parse_sess, + psess, } } @@ -62,7 +62,7 @@ impl<'a, 'ast: 'a> CfgIfVisitor<'a> { } }; - let items = parse_cfg_if(self.parse_sess, mac)?; + let items = parse_cfg_if(self.psess, mac)?; self.mods .append(&mut items.into_iter().map(|item| ModItem { item }).collect()); diff --git a/src/tools/rustfmt/src/parse/macros/cfg_if.rs b/src/tools/rustfmt/src/parse/macros/cfg_if.rs index bafef7b0f4620..5fc988e431935 100644 --- a/src/tools/rustfmt/src/parse/macros/cfg_if.rs +++ b/src/tools/rustfmt/src/parse/macros/cfg_if.rs @@ -9,10 +9,10 @@ use crate::parse::macros::build_stream_parser; use crate::parse::session::ParseSess; pub(crate) fn parse_cfg_if<'a>( - sess: &'a ParseSess, + psess: &'a ParseSess, mac: &'a ast::MacCall, ) -> Result, &'static str> { - match catch_unwind(AssertUnwindSafe(|| parse_cfg_if_inner(sess, mac))) { + match catch_unwind(AssertUnwindSafe(|| parse_cfg_if_inner(psess, mac))) { Ok(Ok(items)) => Ok(items), Ok(err @ Err(_)) => err, Err(..) => Err("failed to parse cfg_if!"), @@ -20,11 +20,11 @@ pub(crate) fn parse_cfg_if<'a>( } fn parse_cfg_if_inner<'a>( - sess: &'a ParseSess, + psess: &'a ParseSess, mac: &'a ast::MacCall, ) -> Result, &'static str> { let ts = mac.args.tokens.clone(); - let mut parser = build_stream_parser(sess.inner(), ts); + let mut parser = build_stream_parser(psess.inner(), ts); let mut items = vec![]; let mut process_if_cfg = true; @@ -67,7 +67,7 @@ fn parse_cfg_if_inner<'a>( Ok(None) => continue, Err(err) => { err.cancel(); - parser.sess.dcx.reset_err_count(); + parser.psess.dcx.reset_err_count(); return Err( "Expected item inside cfg_if block, but failed to parse it as an item", ); diff --git a/src/tools/rustfmt/src/parse/macros/lazy_static.rs b/src/tools/rustfmt/src/parse/macros/lazy_static.rs index 8b1dc6694d6f5..badd956995007 100644 --- a/src/tools/rustfmt/src/parse/macros/lazy_static.rs +++ b/src/tools/rustfmt/src/parse/macros/lazy_static.rs @@ -16,8 +16,8 @@ pub(crate) fn parse_lazy_static( ($method:ident $(,)* $($arg:expr),* $(,)*) => { match parser.$method($($arg,)*) { Ok(val) => { - if parser.sess.dcx.has_errors().is_some() { - parser.sess.dcx.reset_err_count(); + if parser.psess.dcx.has_errors().is_some() { + parser.psess.dcx.reset_err_count(); return None; } else { val @@ -25,7 +25,7 @@ pub(crate) fn parse_lazy_static( } Err(err) => { err.cancel(); - parser.sess.dcx.reset_err_count(); + parser.psess.dcx.reset_err_count(); return None; } } diff --git a/src/tools/rustfmt/src/parse/macros/mod.rs b/src/tools/rustfmt/src/parse/macros/mod.rs index a9f9ea1826ae5..3cf133c647cc4 100644 --- a/src/tools/rustfmt/src/parse/macros/mod.rs +++ b/src/tools/rustfmt/src/parse/macros/mod.rs @@ -14,12 +14,12 @@ pub(crate) mod asm; pub(crate) mod cfg_if; pub(crate) mod lazy_static; -fn build_stream_parser<'a>(sess: &'a ParseSess, tokens: TokenStream) -> Parser<'a> { - stream_to_parser(sess, tokens, MACRO_ARGUMENTS).recovery(Recovery::Forbidden) +fn build_stream_parser<'a>(psess: &'a ParseSess, tokens: TokenStream) -> Parser<'a> { + stream_to_parser(psess, tokens, MACRO_ARGUMENTS).recovery(Recovery::Forbidden) } fn build_parser<'a>(context: &RewriteContext<'a>, tokens: TokenStream) -> Parser<'a> { - build_stream_parser(context.parse_sess.inner(), tokens) + build_stream_parser(context.psess.inner(), tokens) } fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option { @@ -29,8 +29,8 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option { if Parser::nonterminal_may_begin_with($nt_kind, &cloned_parser.token) { match $try_parse(&mut cloned_parser) { Ok(x) => { - if parser.sess.dcx.has_errors().is_some() { - parser.sess.dcx.reset_err_count(); + if parser.psess.dcx.has_errors().is_some() { + parser.psess.dcx.reset_err_count(); } else { // Parsing succeeded. *parser = cloned_parser; @@ -39,7 +39,7 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option { } Err(e) => { e.cancel(); - parser.sess.dcx.reset_err_count(); + parser.psess.dcx.reset_err_count(); } } } diff --git a/src/tools/rustfmt/src/parse/parser.rs b/src/tools/rustfmt/src/parse/parser.rs index 19b0dada08f33..5dcdca1d9538d 100644 --- a/src/tools/rustfmt/src/parse/parser.rs +++ b/src/tools/rustfmt/src/parse/parser.rs @@ -29,7 +29,7 @@ pub(crate) struct Parser<'a> { /// A builder for the `Parser`. #[derive(Default)] pub(crate) struct ParserBuilder<'a> { - sess: Option<&'a ParseSess>, + psess: Option<&'a ParseSess>, input: Option, } @@ -39,20 +39,20 @@ impl<'a> ParserBuilder<'a> { self } - pub(crate) fn sess(mut self, sess: &'a ParseSess) -> ParserBuilder<'a> { - self.sess = Some(sess); + pub(crate) fn psess(mut self, psess: &'a ParseSess) -> ParserBuilder<'a> { + self.psess = Some(psess); self } pub(crate) fn build(self) -> Result, ParserError> { - let sess = self.sess.ok_or(ParserError::NoParseSess)?; + let psess = self.psess.ok_or(ParserError::NoParseSess)?; let input = self.input.ok_or(ParserError::NoInput)?; - let parser = match Self::parser(sess.inner(), input) { + let parser = match Self::parser(psess.inner(), input) { Ok(p) => p, Err(db) => { if let Some(diagnostics) = db { - sess.emit_diagnostics(diagnostics); + psess.emit_diagnostics(diagnostics); return Err(ParserError::ParserCreationError); } return Err(ParserError::ParsePanicError); @@ -63,16 +63,16 @@ impl<'a> ParserBuilder<'a> { } fn parser( - sess: &'a rustc_session::parse::ParseSess, + psess: &'a rustc_session::parse::ParseSess, input: Input, ) -> Result, Option>>> { match input { Input::File(ref file) => catch_unwind(AssertUnwindSafe(move || { - new_parser_from_file(sess, file, None) + new_parser_from_file(psess, file, None) })) .map_err(|_| None), Input::Text(text) => rustc_parse::maybe_new_parser_from_source_str( - sess, + psess, rustc_span::FileName::Custom("stdin".to_owned()), text, ) @@ -106,27 +106,27 @@ impl<'a> Parser<'a> { } pub(crate) fn parse_file_as_module( - sess: &'a ParseSess, + psess: &'a ParseSess, path: &Path, span: Span, ) -> Result<(ast::AttrVec, ThinVec>, Span), ParserError> { let result = catch_unwind(AssertUnwindSafe(|| { - let mut parser = new_parser_from_file(sess.inner(), path, Some(span)); + let mut parser = new_parser_from_file(psess.inner(), path, Some(span)); match parser.parse_mod(&TokenKind::Eof) { Ok((a, i, spans)) => Some((a, i, spans.inner_span)), Err(e) => { e.emit(); - if sess.can_reset_errors() { - sess.reset_errors(); + if psess.can_reset_errors() { + psess.reset_errors(); } None } } })); match result { - Ok(Some(m)) if !sess.has_errors() => Ok(m), - Ok(Some(m)) if sess.can_reset_errors() => { - sess.reset_errors(); + Ok(Some(m)) if !psess.has_errors() => Ok(m), + Ok(Some(m)) if psess.can_reset_errors() => { + psess.reset_errors(); Ok(m) } Ok(_) => Err(ParserError::ParseError), @@ -137,25 +137,25 @@ impl<'a> Parser<'a> { pub(crate) fn parse_crate( input: Input, - sess: &'a ParseSess, + psess: &'a ParseSess, ) -> Result { - let krate = Parser::parse_crate_inner(input, sess)?; - if !sess.has_errors() { + let krate = Parser::parse_crate_inner(input, psess)?; + if !psess.has_errors() { return Ok(krate); } - if sess.can_reset_errors() { - sess.reset_errors(); + if psess.can_reset_errors() { + psess.reset_errors(); return Ok(krate); } Err(ParserError::ParseError) } - fn parse_crate_inner(input: Input, sess: &'a ParseSess) -> Result { + fn parse_crate_inner(input: Input, psess: &'a ParseSess) -> Result { ParserBuilder::default() .input(input) - .sess(sess) + .psess(psess) .build()? .parse_crate_mod() } diff --git a/src/tools/rustfmt/src/parse/session.rs b/src/tools/rustfmt/src/parse/session.rs index d6386a9504db7..356410f559624 100644 --- a/src/tools/rustfmt/src/parse/session.rs +++ b/src/tools/rustfmt/src/parse/session.rs @@ -23,7 +23,7 @@ use crate::{Config, ErrorKind, FileName}; /// ParseSess holds structs necessary for constructing a parser. pub(crate) struct ParseSess { - parse_sess: RawParseSess, + raw_psess: RawParseSess, ignore_path_set: Lrc, can_reset_errors: Lrc, } @@ -180,10 +180,10 @@ impl ParseSess { config.hide_parse_errors(), config.color(), ); - let parse_sess = RawParseSess::with_dcx(dcx, source_map); + let raw_psess = RawParseSess::with_dcx(dcx, source_map); Ok(ParseSess { - parse_sess, + raw_psess, ignore_path_set, can_reset_errors, }) @@ -202,14 +202,14 @@ impl ParseSess { relative: Option, dir_path: &Path, ) -> Result> { - rustc_expand::module::default_submod_path(&self.parse_sess, id, relative, dir_path).or_else( + rustc_expand::module::default_submod_path(&self.raw_psess, id, relative, dir_path).or_else( |e| { // If resloving a module relative to {dir_path}/{symbol} fails because a file // could not be found, then try to resolve the module relative to {dir_path}. // If we still can't find the module after searching for it in {dir_path}, // surface the original error. if matches!(e, ModError::FileNotFound(..)) && relative.is_some() { - rustc_expand::module::default_submod_path(&self.parse_sess, id, None, dir_path) + rustc_expand::module::default_submod_path(&self.raw_psess, id, None, dir_path) .map_err(|_| e) } else { Err(e) @@ -219,7 +219,7 @@ impl ParseSess { } pub(crate) fn is_file_parsed(&self, path: &Path) -> bool { - self.parse_sess + self.raw_psess .source_map() .get_source_file(&rustc_span::FileName::Real( rustc_span::RealFileName::LocalPath(path.to_path_buf()), @@ -232,21 +232,21 @@ impl ParseSess { } pub(crate) fn set_silent_emitter(&mut self) { - self.parse_sess.dcx = DiagCtxt::new(silent_emitter()); + self.raw_psess.dcx = DiagCtxt::new(silent_emitter()); } pub(crate) fn span_to_filename(&self, span: Span) -> FileName { - self.parse_sess.source_map().span_to_filename(span).into() + self.raw_psess.source_map().span_to_filename(span).into() } pub(crate) fn span_to_file_contents(&self, span: Span) -> Lrc { - self.parse_sess + self.raw_psess .source_map() .lookup_source_file(span.data().lo) } pub(crate) fn span_to_first_line_string(&self, span: Span) -> String { - let file_lines = self.parse_sess.source_map().span_to_lines(span).ok(); + let file_lines = self.raw_psess.source_map().span_to_lines(span).ok(); match file_lines { Some(fl) => fl @@ -258,7 +258,7 @@ impl ParseSess { } pub(crate) fn line_of_byte_pos(&self, pos: BytePos) -> usize { - self.parse_sess.source_map().lookup_char_pos(pos).line + self.raw_psess.source_map().lookup_char_pos(pos).line } // TODO(calebcartwright): Preemptive, currently unused addition @@ -271,15 +271,15 @@ impl ParseSess { } pub(crate) fn span_to_debug_info(&self, span: Span) -> String { - self.parse_sess.source_map().span_to_diagnostic_string(span) + self.raw_psess.source_map().span_to_diagnostic_string(span) } pub(crate) fn inner(&self) -> &RawParseSess { - &self.parse_sess + &self.raw_psess } pub(crate) fn snippet_provider(&self, span: Span) -> SnippetProvider { - let source_file = self.parse_sess.source_map().lookup_char_pos(span.lo()).file; + let source_file = self.raw_psess.source_map().lookup_char_pos(span.lo()).file; SnippetProvider::new( source_file.start_pos, source_file.end_position(), @@ -288,7 +288,7 @@ impl ParseSess { } pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option> { - self.parse_sess + self.raw_psess .source_map() .get_source_file(&file_name.into()) .and_then(|source_file| source_file.src.clone()) @@ -308,23 +308,23 @@ impl ParseSess { } pub(super) fn has_errors(&self) -> bool { - self.parse_sess.dcx.has_errors().is_some() + self.raw_psess.dcx.has_errors().is_some() } pub(super) fn reset_errors(&self) { - self.parse_sess.dcx.reset_err_count(); + self.raw_psess.dcx.reset_err_count(); } } impl LineRangeUtils for ParseSess { fn lookup_line_range(&self, span: Span) -> LineRange { let snippet = self - .parse_sess + .raw_psess .source_map() .span_to_snippet(span) .unwrap_or_default(); - let lo = self.parse_sess.source_map().lookup_line(span.lo()).unwrap(); - let hi = self.parse_sess.source_map().lookup_line(span.hi()).unwrap(); + let lo = self.raw_psess.source_map().lookup_line(span.lo()).unwrap(); + let hi = self.raw_psess.source_map().lookup_line(span.hi()).unwrap(); debug_assert_eq!( lo.sf.name, hi.sf.name, diff --git a/src/tools/rustfmt/src/reorder.rs b/src/tools/rustfmt/src/reorder.rs index 3e14f9f1272f4..fdbed939af542 100644 --- a/src/tools/rustfmt/src/reorder.rs +++ b/src/tools/rustfmt/src/reorder.rs @@ -263,13 +263,13 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { item_kind: ReorderableItemKind, in_group: bool, ) -> usize { - let mut last = self.parse_sess.lookup_line_range(items[0].span()); + let mut last = self.psess.lookup_line_range(items[0].span()); let item_length = items .iter() .take_while(|ppi| { item_kind.is_same_item_kind(&***ppi) && (!in_group || { - let current = self.parse_sess.lookup_line_range(ppi.span()); + let current = self.psess.lookup_line_range(ppi.span()); let in_same_group = current.lo < last.hi + 2; last = current; in_same_group diff --git a/src/tools/rustfmt/src/rewrite.rs b/src/tools/rustfmt/src/rewrite.rs index 4a3bd129d16f5..e2498a3500a0f 100644 --- a/src/tools/rustfmt/src/rewrite.rs +++ b/src/tools/rustfmt/src/rewrite.rs @@ -26,7 +26,7 @@ impl Rewrite for ptr::P { #[derive(Clone)] pub(crate) struct RewriteContext<'a> { - pub(crate) parse_sess: &'a ParseSess, + pub(crate) psess: &'a ParseSess, pub(crate) config: &'a Config, pub(crate) inside_macro: Rc>, // Force block indent style even if we are using visual indent style. diff --git a/src/tools/rustfmt/src/source_file.rs b/src/tools/rustfmt/src/source_file.rs index 512a8593c27cd..6376bc49b69f3 100644 --- a/src/tools/rustfmt/src/source_file.rs +++ b/src/tools/rustfmt/src/source_file.rs @@ -49,7 +49,7 @@ where } pub(crate) fn write_file( - parse_sess: Option<&ParseSess>, + psess: Option<&ParseSess>, filename: &FileName, formatted_text: &str, out: &mut T, @@ -90,7 +90,7 @@ where let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin { Lrc::new(fs::read_to_string(ensure_real_path(filename))?) } else { - match parse_sess.and_then(|sess| sess.get_original_snippet(filename)) { + match psess.and_then(|psess| psess.get_original_snippet(filename)) { Some(ori) => ori, None => Lrc::new(fs::read_to_string(ensure_real_path(filename))?), } diff --git a/src/tools/rustfmt/src/utils.rs b/src/tools/rustfmt/src/utils.rs index d4218cff75aaa..b91d9b47cb63b 100644 --- a/src/tools/rustfmt/src/utils.rs +++ b/src/tools/rustfmt/src/utils.rs @@ -362,7 +362,7 @@ macro_rules! out_of_file_lines_range { && !$self .config .file_lines() - .intersects(&$self.parse_sess.lookup_line_range($span)) + .intersects(&$self.psess.lookup_line_range($span)) }; } diff --git a/src/tools/rustfmt/src/visitor.rs b/src/tools/rustfmt/src/visitor.rs index bc5accefd92b8..47f772b485daf 100644 --- a/src/tools/rustfmt/src/visitor.rs +++ b/src/tools/rustfmt/src/visitor.rs @@ -71,7 +71,7 @@ impl SnippetProvider { pub(crate) struct FmtVisitor<'a> { parent_context: Option<&'a RewriteContext<'a>>, - pub(crate) parse_sess: &'a ParseSess, + pub(crate) psess: &'a ParseSess, pub(crate) buffer: String, pub(crate) last_pos: BytePos, // FIXME: use an RAII util or closure for indenting @@ -113,10 +113,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } fn visit_stmt(&mut self, stmt: &Stmt<'_>, include_empty_semi: bool) { - debug!( - "visit_stmt: {}", - self.parse_sess.span_to_debug_info(stmt.span()) - ); + debug!("visit_stmt: {}", self.psess.span_to_debug_info(stmt.span())); if stmt.is_empty() { // If the statement is empty, just skip over it. Before that, make sure any comment @@ -217,10 +214,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { inner_attrs: Option<&[ast::Attribute]>, has_braces: bool, ) { - debug!( - "visit_block: {}", - self.parse_sess.span_to_debug_info(b.span), - ); + debug!("visit_block: {}", self.psess.span_to_debug_info(b.span)); // Check if this block has braces. let brace_compensation = BytePos(if has_braces { 1 } else { 0 }); @@ -744,10 +738,10 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { // do not take into account the lines with attributes as part of the skipped range let attrs_end = attrs .iter() - .map(|attr| self.parse_sess.line_of_byte_pos(attr.span.hi())) + .map(|attr| self.psess.line_of_byte_pos(attr.span.hi())) .max() .unwrap_or(1); - let first_line = self.parse_sess.line_of_byte_pos(main_span.lo()); + let first_line = self.psess.line_of_byte_pos(main_span.lo()); // Statement can start after some newlines and/or spaces // or it can be on the same line as the last attribute. // So here we need to take a minimum between the two. @@ -758,8 +752,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { } pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> { - let mut visitor = FmtVisitor::from_parse_sess( - ctx.parse_sess, + let mut visitor = FmtVisitor::from_psess( + ctx.psess, ctx.config, ctx.snippet_provider, ctx.report.clone(), @@ -769,8 +763,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { visitor } - pub(crate) fn from_parse_sess( - parse_session: &'a ParseSess, + pub(crate) fn from_psess( + psess: &'a ParseSess, config: &'a Config, snippet_provider: &'a SnippetProvider, report: FormatReport, @@ -786,7 +780,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { skip_context.macros.extend(macro_names); FmtVisitor { parent_context: None, - parse_sess: parse_session, + psess, buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2), last_pos: BytePos(0), block_indent: Indent::empty(), @@ -814,12 +808,12 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool { for attr in attrs { if attr.has_name(depr_skip_annotation()) { - let file_name = self.parse_sess.span_to_filename(attr.span); + let file_name = self.psess.span_to_filename(attr.span); self.report.append( file_name, vec![FormattingError::from_span( attr.span, - self.parse_sess, + self.psess, ErrorKind::DeprecatedAttr, )], ); @@ -828,12 +822,12 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { ast::AttrKind::Normal(ref normal) if self.is_unknown_rustfmt_attr(&normal.item.path.segments) => { - let file_name = self.parse_sess.span_to_filename(attr.span); + let file_name = self.psess.span_to_filename(attr.span); self.report.append( file_name, vec![FormattingError::from_span( attr.span, - self.parse_sess, + self.psess, ErrorKind::BadAttr, )], ); @@ -1007,7 +1001,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> { pub(crate) fn get_context(&self) -> RewriteContext<'_> { RewriteContext { - parse_sess: self.parse_sess, + psess: self.psess, config: self.config, inside_macro: Rc::new(Cell::new(false)), use_block: Cell::new(false), diff --git a/tests/run-make-fulldeps/issue-19371/foo.rs b/tests/run-make-fulldeps/issue-19371/foo.rs index a0bbe3851e82f..327c99a02c6fe 100644 --- a/tests/run-make-fulldeps/issue-19371/foo.rs +++ b/tests/run-make-fulldeps/issue-19371/foo.rs @@ -56,7 +56,7 @@ fn compile(code: String, output: PathBuf, sysroot: PathBuf) { file_loader: None, locale_resources: &[], lint_caps: Default::default(), - parse_sess_created: None, + psess_created: None, hash_untracked_state: None, register_lints: None, override_queries: None, diff --git a/tests/ui-fulldeps/mod_dir_path_canonicalized.rs b/tests/ui-fulldeps/mod_dir_path_canonicalized.rs index 4527a34e14f02..ef70e64ed7e91 100644 --- a/tests/ui-fulldeps/mod_dir_path_canonicalized.rs +++ b/tests/ui-fulldeps/mod_dir_path_canonicalized.rs @@ -30,10 +30,10 @@ pub fn main() { } fn parse() { - let parse_session = ParseSess::new(vec![rustc_parse::DEFAULT_LOCALE_RESOURCE]); + let psess = ParseSess::new(vec![rustc_parse::DEFAULT_LOCALE_RESOURCE]); let path = Path::new(file!()); let path = path.canonicalize().unwrap(); - let mut parser = new_parser_from_file(&parse_session, &path, None); + let mut parser = new_parser_from_file(&psess, &path, None); let _ = parser.parse_crate_mod(); } diff --git a/tests/ui-fulldeps/pprust-expr-roundtrip.rs b/tests/ui-fulldeps/pprust-expr-roundtrip.rs index 86719bb23acb8..475a69f4ad098 100644 --- a/tests/ui-fulldeps/pprust-expr-roundtrip.rs +++ b/tests/ui-fulldeps/pprust-expr-roundtrip.rs @@ -43,11 +43,11 @@ use rustc_span::symbol::Ident; use rustc_span::{FileName, DUMMY_SP}; use thin_vec::{thin_vec, ThinVec}; -fn parse_expr(ps: &ParseSess, src: &str) -> Option> { +fn parse_expr(psess: &ParseSess, src: &str) -> Option> { let src_as_string = src.to_string(); let mut p = - new_parser_from_source_str(ps, FileName::Custom(src_as_string.clone()), src_as_string); + new_parser_from_source_str(psess, FileName::Custom(src_as_string.clone()), src_as_string); p.parse_expr().map_err(|e| e.cancel()).ok() } @@ -225,7 +225,7 @@ fn main() { } fn run() { - let ps = ParseSess::new(vec![rustc_parse::DEFAULT_LOCALE_RESOURCE]); + let psess = ParseSess::new(vec![rustc_parse::DEFAULT_LOCALE_RESOURCE]); iter_exprs(2, &mut |mut e| { // If the pretty printer is correct, then `parse(print(e))` should be identical to `e`, @@ -234,7 +234,7 @@ fn run() { println!("printed: {}", printed); // Ignore expressions with chained comparisons that fail to parse - if let Some(mut parsed) = parse_expr(&ps, &printed) { + if let Some(mut parsed) = parse_expr(&psess, &printed) { // We want to know if `parsed` is structurally identical to `e`, ignoring trivial // differences like placement of `Paren`s or the exact ranges of node spans. // Unfortunately, there is no easy way to make this comparison. Instead, we add `Paren`s