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`.
This commit is contained in:
Nicholas Nethercote 2024-03-04 16:31:49 +11:00
parent 0b56261cef
commit 78c99ebfea
16 changed files with 126 additions and 141 deletions

@ -1721,10 +1721,10 @@ pub(crate) fn recover_comment_removed(
// We missed some comments. Warn and keep the original text. // We missed some comments. Warn and keep the original text.
if context.config.error_on_unformatted() { if context.config.error_on_unformatted() {
context.report.append( context.report.append(
context.parse_sess.span_to_filename(span), context.psess.span_to_filename(span),
vec![FormattingError::from_span( vec![FormattingError::from_span(
span, span,
context.parse_sess, context.psess,
ErrorKind::LostComment, ErrorKind::LostComment,
)], )],
); );

@ -79,7 +79,7 @@ fn should_skip_module<T: FormatHandler>(
// FIXME(calebcartwright) - we need to determine how we'll handle the // FIXME(calebcartwright) - we need to determine how we'll handle the
// `format_generated_files` option with stdin based input. // `format_generated_files` option with stdin based input.
if !input_is_stdin && !config.format_generated_files() { 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"); let src = source_file.src.as_ref().expect("SourceFile without src");
if is_generated_file(src) { if is_generated_file(src) {
@ -109,8 +109,8 @@ fn format_project<T: FormatHandler>(
let main_file = input.file_name(); let main_file = input.file_name();
let input_is_stdin = main_file == FileName::Stdin; let input_is_stdin = main_file == FileName::Stdin;
let parse_session = ParseSess::new(config)?; let psess = ParseSess::new(config)?;
if config.skip_children() && parse_session.ignore_file(&main_file) { if config.skip_children() && psess.ignore_file(&main_file) {
return Ok(FormatReport::new()); return Ok(FormatReport::new());
} }
@ -118,7 +118,7 @@ fn format_project<T: FormatHandler>(
let mut report = FormatReport::new(); let mut report = FormatReport::new();
let directory_ownership = input.to_directory_ownership(); 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, Ok(krate) => krate,
// Surface parse error via Session (errors are merged there from report) // Surface parse error via Session (errors are merged there from report)
Err(e) => { Err(e) => {
@ -131,9 +131,9 @@ fn format_project<T: FormatHandler>(
} }
}; };
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( let files = modules::ModResolver::new(
&context.parse_session, &context.psess,
directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock), directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
!input_is_stdin && !config.skip_children(), !input_is_stdin && !config.skip_children(),
) )
@ -148,16 +148,11 @@ fn format_project<T: FormatHandler>(
timer = timer.done_parsing(); timer = timer.done_parsing();
// Suppress error output if we have to do any further 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 { for (path, module) in files {
if input_is_stdin && contains_skip(module.attrs()) { if input_is_stdin && contains_skip(module.attrs()) {
return echo_back_stdin( return echo_back_stdin(context.psess.snippet_provider(module.span).entire_snippet());
context
.parse_session
.snippet_provider(module.span)
.entire_snippet(),
);
} }
should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path)); should_emit_verbose(input_is_stdin, config, || println!("Formatting {}", path));
context.format_file(path, &module, is_macro_def)?; context.format_file(path, &module, is_macro_def)?;
@ -179,7 +174,7 @@ fn format_project<T: FormatHandler>(
struct FormatContext<'a, T: FormatHandler> { struct FormatContext<'a, T: FormatHandler> {
krate: &'a ast::Crate, krate: &'a ast::Crate,
report: FormatReport, report: FormatReport,
parse_session: ParseSess, psess: ParseSess,
config: &'a Config, config: &'a Config,
handler: &'a mut T, handler: &'a mut T,
} }
@ -188,21 +183,21 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
fn new( fn new(
krate: &'a ast::Crate, krate: &'a ast::Crate,
report: FormatReport, report: FormatReport,
parse_session: ParseSess, psess: ParseSess,
config: &'a Config, config: &'a Config,
handler: &'a mut T, handler: &'a mut T,
) -> Self { ) -> Self {
FormatContext { FormatContext {
krate, krate,
report, report,
parse_session, psess,
config, config,
handler, handler,
} }
} }
fn ignore_file(&self, path: &FileName) -> bool { fn ignore_file(&self, path: &FileName) -> bool {
self.parse_session.ignore_file(path) self.psess.ignore_file(path)
} }
// Formats a single file/module. // Formats a single file/module.
@ -212,9 +207,9 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
module: &Module<'_>, module: &Module<'_>,
is_macro_def: bool, is_macro_def: bool,
) -> Result<(), ErrorKind> { ) -> Result<(), ErrorKind> {
let snippet_provider = self.parse_session.snippet_provider(module.span); let snippet_provider = self.psess.snippet_provider(module.span);
let mut visitor = FmtVisitor::from_parse_sess( let mut visitor = FmtVisitor::from_psess(
&self.parse_session, &self.psess,
self.config, self.config,
&snippet_provider, &snippet_provider,
self.report.clone(), self.report.clone(),
@ -257,7 +252,7 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
.add_non_formatted_ranges(visitor.skipped_range.borrow().clone()); .add_non_formatted_ranges(visitor.skipped_range.borrow().clone());
self.handler.handle_formatted_file( self.handler.handle_formatted_file(
&self.parse_session, &self.psess,
path, path,
visitor.buffer.to_owned(), visitor.buffer.to_owned(),
&mut self.report, &mut self.report,
@ -269,7 +264,7 @@ impl<'a, T: FormatHandler + 'a> FormatContext<'a, T> {
trait FormatHandler { trait FormatHandler {
fn handle_formatted_file( fn handle_formatted_file(
&mut self, &mut self,
parse_session: &ParseSess, psess: &ParseSess,
path: FileName, path: FileName,
result: String, result: String,
report: &mut FormatReport, report: &mut FormatReport,
@ -280,14 +275,14 @@ impl<'b, T: Write + 'b> FormatHandler for Session<'b, T> {
// Called for each formatted file. // Called for each formatted file.
fn handle_formatted_file( fn handle_formatted_file(
&mut self, &mut self,
parse_session: &ParseSess, psess: &ParseSess,
path: FileName, path: FileName,
result: String, result: String,
report: &mut FormatReport, report: &mut FormatReport,
) -> Result<(), ErrorKind> { ) -> Result<(), ErrorKind> {
if let Some(ref mut out) = self.out { if let Some(ref mut out) = self.out {
match source_file::write_file( match source_file::write_file(
Some(parse_session), Some(psess),
&path, &path,
&result, &result,
out, out,
@ -318,17 +313,13 @@ pub(crate) struct FormattingError {
} }
impl FormattingError { impl FormattingError {
pub(crate) fn from_span( pub(crate) fn from_span(span: Span, psess: &ParseSess, kind: ErrorKind) -> FormattingError {
span: Span,
parse_sess: &ParseSess,
kind: ErrorKind,
) -> FormattingError {
FormattingError { FormattingError {
line: parse_sess.line_of_byte_pos(span.lo()), line: psess.line_of_byte_pos(span.lo()),
is_comment: kind.is_comment(), is_comment: kind.is_comment(),
kind, kind,
is_string: false, is_string: false,
line_buffer: parse_sess.span_to_first_line_string(span), line_buffer: psess.span_to_first_line_string(span),
} }
} }

@ -136,8 +136,8 @@ fn return_macro_parse_failure_fallback(
} }
context.skipped_range.borrow_mut().push(( context.skipped_range.borrow_mut().push((
context.parse_sess.line_of_byte_pos(span.lo()), context.psess.line_of_byte_pos(span.lo()),
context.parse_sess.line_of_byte_pos(span.hi()), context.psess.line_of_byte_pos(span.hi()),
)); ));
// Return the snippet unmodified if the macro is not block-like // Return the snippet unmodified if the macro is not block-like

@ -91,7 +91,7 @@ impl<'a> FmtVisitor<'a> {
assert!( assert!(
start < end, start < end,
"Request to format inverted span: {}", "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; self.last_pos = end;
@ -166,8 +166,8 @@ impl<'a> FmtVisitor<'a> {
// Trim whitespace from the right hand side of each line. // Trim whitespace from the right hand side of each line.
// Annoyingly, the library functions for splitting by lines etc. are not // Annoyingly, the library functions for splitting by lines etc. are not
// quite right, so we must do it ourselves. // quite right, so we must do it ourselves.
let line = self.parse_sess.line_of_byte_pos(span.lo()); let line = self.psess.line_of_byte_pos(span.lo());
let file_name = &self.parse_sess.span_to_filename(span); let file_name = &self.psess.span_to_filename(span);
let mut status = SnippetStatus::new(line); let mut status = SnippetStatus::new(line);
let snippet = &*transform_missing_snippet(self.config, old_snippet); let snippet = &*transform_missing_snippet(self.config, old_snippet);

@ -57,8 +57,8 @@ impl<'a> Module<'a> {
} }
/// Maps each module to the corresponding file. /// Maps each module to the corresponding file.
pub(crate) struct ModResolver<'ast, 'sess> { pub(crate) struct ModResolver<'ast, 'psess> {
parse_sess: &'sess ParseSess, psess: &'psess ParseSess,
directory: Directory, directory: Directory,
file_map: FileModMap<'ast>, file_map: FileModMap<'ast>,
recursive: bool, recursive: bool,
@ -99,10 +99,10 @@ enum SubModKind<'a, 'ast> {
Internal(&'a ast::Item), Internal(&'a ast::Item),
} }
impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> { impl<'ast, 'psess, 'c> ModResolver<'ast, 'psess> {
/// Creates a new `ModResolver`. /// Creates a new `ModResolver`.
pub(crate) fn new( pub(crate) fn new(
parse_sess: &'sess ParseSess, psess: &'psess ParseSess,
directory_ownership: DirectoryOwnership, directory_ownership: DirectoryOwnership,
recursive: bool, recursive: bool,
) -> Self { ) -> Self {
@ -112,7 +112,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
ownership: directory_ownership, ownership: directory_ownership,
}, },
file_map: BTreeMap::new(), file_map: BTreeMap::new(),
parse_sess, psess,
recursive, recursive,
} }
} }
@ -122,7 +122,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
mut self, mut self,
krate: &'ast ast::Crate, krate: &'ast ast::Crate,
) -> Result<FileModMap<'ast>, ModuleResolutionError> { ) -> Result<FileModMap<'ast>, 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 { self.directory.path = match root_filename {
FileName::Real(ref p) => p.parent().unwrap_or(Path::new("")).to_path_buf(), FileName::Real(ref p) => p.parent().unwrap_or(Path::new("")).to_path_buf(),
_ => PathBuf::new(), _ => PathBuf::new(),
@ -133,7 +133,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
self.visit_mod_from_ast(&krate.items)?; 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( self.file_map.insert(
root_filename, root_filename,
@ -149,7 +149,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
/// Visit `cfg_if` macro and look for module declarations. /// Visit `cfg_if` macro and look for module declarations.
fn visit_cfg_if(&mut self, item: Cow<'ast, ast::Item>) -> Result<(), ModuleResolutionError> { 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); visitor.visit_item(&item);
for module_item in visitor.mods() { for module_item in visitor.mods() {
if let ast::ItemKind::Mod(_, ref sub_mod_kind) = module_item.item.kind { 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, DirectoryOwnership::UnownedViaBlock => None,
}; };
if let Some(path) = Parser::submod_path_from_attr(attrs, &self.directory.path) { 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 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((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
Ok((attrs, items, span)) => Ok(Some(SubModKind::External( Ok((attrs, items, span)) => Ok(Some(SubModKind::External(
path, 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); let mut mods_outside_ast = self.find_mods_outside_of_ast(attrs, sub_mod);
match self match self
.parse_sess .psess
.default_submod_path(mod_name, relative, &self.directory.path) .default_submod_path(mod_name, relative, &self.directory.path)
{ {
Ok(ModulePathSuccess { Ok(ModulePathSuccess {
@ -380,7 +380,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
let should_insert = !mods_outside_ast let should_insert = !mods_outside_ast
.iter() .iter()
.any(|(outside_path, _, _)| outside_path == &file_path); .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 { if outside_mods_empty {
return Ok(None); return Ok(None);
} else { } else {
@ -390,7 +390,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
return Ok(Some(SubModKind::MultiExternal(mods_outside_ast))); 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((ref attrs, _, _)) if contains_skip(attrs) => Ok(None),
Ok((attrs, items, span)) if outside_mods_empty => { Ok((attrs, items, span)) if outside_mods_empty => {
Ok(Some(SubModKind::External( Ok(Some(SubModKind::External(
@ -517,7 +517,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
if !actual_path.exists() { if !actual_path.exists() {
continue; 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. // If the specified file is already parsed, then we just use that.
result.push(( result.push((
actual_path, actual_path,
@ -527,7 +527,7 @@ impl<'ast, 'sess, 'c> ModResolver<'ast, 'sess> {
continue; continue;
} }
let (attrs, items, span) = 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((ref attrs, _, _)) if contains_skip(attrs) => continue,
Ok(m) => m, Ok(m) => m,
Err(..) => continue, Err(..) => continue,

@ -12,15 +12,15 @@ pub(crate) struct ModItem {
/// Traverse `cfg_if!` macro and fetch modules. /// Traverse `cfg_if!` macro and fetch modules.
pub(crate) struct CfgIfVisitor<'a> { pub(crate) struct CfgIfVisitor<'a> {
parse_sess: &'a ParseSess, psess: &'a ParseSess,
mods: Vec<ModItem>, mods: Vec<ModItem>,
} }
impl<'a> CfgIfVisitor<'a> { impl<'a> CfgIfVisitor<'a> {
pub(crate) fn new(parse_sess: &'a ParseSess) -> CfgIfVisitor<'a> { pub(crate) fn new(psess: &'a ParseSess) -> CfgIfVisitor<'a> {
CfgIfVisitor { CfgIfVisitor {
mods: vec![], 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 self.mods
.append(&mut items.into_iter().map(|item| ModItem { item }).collect()); .append(&mut items.into_iter().map(|item| ModItem { item }).collect());

@ -9,10 +9,10 @@ use crate::parse::macros::build_stream_parser;
use crate::parse::session::ParseSess; use crate::parse::session::ParseSess;
pub(crate) fn parse_cfg_if<'a>( pub(crate) fn parse_cfg_if<'a>(
sess: &'a ParseSess, psess: &'a ParseSess,
mac: &'a ast::MacCall, mac: &'a ast::MacCall,
) -> Result<Vec<ast::Item>, &'static str> { ) -> Result<Vec<ast::Item>, &'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(Ok(items)) => Ok(items),
Ok(err @ Err(_)) => err, Ok(err @ Err(_)) => err,
Err(..) => Err("failed to parse cfg_if!"), Err(..) => Err("failed to parse cfg_if!"),
@ -20,11 +20,11 @@ pub(crate) fn parse_cfg_if<'a>(
} }
fn parse_cfg_if_inner<'a>( fn parse_cfg_if_inner<'a>(
sess: &'a ParseSess, psess: &'a ParseSess,
mac: &'a ast::MacCall, mac: &'a ast::MacCall,
) -> Result<Vec<ast::Item>, &'static str> { ) -> Result<Vec<ast::Item>, &'static str> {
let ts = mac.args.tokens.clone(); 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 items = vec![];
let mut process_if_cfg = true; let mut process_if_cfg = true;
@ -67,7 +67,7 @@ fn parse_cfg_if_inner<'a>(
Ok(None) => continue, Ok(None) => continue,
Err(err) => { Err(err) => {
err.cancel(); err.cancel();
parser.sess.dcx.reset_err_count(); parser.psess.dcx.reset_err_count();
return Err( return Err(
"Expected item inside cfg_if block, but failed to parse it as an item", "Expected item inside cfg_if block, but failed to parse it as an item",
); );

@ -16,8 +16,8 @@ pub(crate) fn parse_lazy_static(
($method:ident $(,)* $($arg:expr),* $(,)*) => { ($method:ident $(,)* $($arg:expr),* $(,)*) => {
match parser.$method($($arg,)*) { match parser.$method($($arg,)*) {
Ok(val) => { Ok(val) => {
if parser.sess.dcx.has_errors().is_some() { if parser.psess.dcx.has_errors().is_some() {
parser.sess.dcx.reset_err_count(); parser.psess.dcx.reset_err_count();
return None; return None;
} else { } else {
val val
@ -25,7 +25,7 @@ pub(crate) fn parse_lazy_static(
} }
Err(err) => { Err(err) => {
err.cancel(); err.cancel();
parser.sess.dcx.reset_err_count(); parser.psess.dcx.reset_err_count();
return None; return None;
} }
} }

@ -14,12 +14,12 @@ pub(crate) mod asm;
pub(crate) mod cfg_if; pub(crate) mod cfg_if;
pub(crate) mod lazy_static; pub(crate) mod lazy_static;
fn build_stream_parser<'a>(sess: &'a ParseSess, tokens: TokenStream) -> Parser<'a> { fn build_stream_parser<'a>(psess: &'a ParseSess, tokens: TokenStream) -> Parser<'a> {
stream_to_parser(sess, tokens, MACRO_ARGUMENTS).recovery(Recovery::Forbidden) stream_to_parser(psess, tokens, MACRO_ARGUMENTS).recovery(Recovery::Forbidden)
} }
fn build_parser<'a>(context: &RewriteContext<'a>, tokens: TokenStream) -> Parser<'a> { 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<MacroArg> { fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
@ -29,8 +29,8 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
if Parser::nonterminal_may_begin_with($nt_kind, &cloned_parser.token) { if Parser::nonterminal_may_begin_with($nt_kind, &cloned_parser.token) {
match $try_parse(&mut cloned_parser) { match $try_parse(&mut cloned_parser) {
Ok(x) => { Ok(x) => {
if parser.sess.dcx.has_errors().is_some() { if parser.psess.dcx.has_errors().is_some() {
parser.sess.dcx.reset_err_count(); parser.psess.dcx.reset_err_count();
} else { } else {
// Parsing succeeded. // Parsing succeeded.
*parser = cloned_parser; *parser = cloned_parser;
@ -39,7 +39,7 @@ fn parse_macro_arg<'a, 'b: 'a>(parser: &'a mut Parser<'b>) -> Option<MacroArg> {
} }
Err(e) => { Err(e) => {
e.cancel(); e.cancel();
parser.sess.dcx.reset_err_count(); parser.psess.dcx.reset_err_count();
} }
} }
} }

@ -29,7 +29,7 @@ pub(crate) struct Parser<'a> {
/// A builder for the `Parser`. /// A builder for the `Parser`.
#[derive(Default)] #[derive(Default)]
pub(crate) struct ParserBuilder<'a> { pub(crate) struct ParserBuilder<'a> {
sess: Option<&'a ParseSess>, psess: Option<&'a ParseSess>,
input: Option<Input>, input: Option<Input>,
} }
@ -39,20 +39,20 @@ impl<'a> ParserBuilder<'a> {
self self
} }
pub(crate) fn sess(mut self, sess: &'a ParseSess) -> ParserBuilder<'a> { pub(crate) fn psess(mut self, psess: &'a ParseSess) -> ParserBuilder<'a> {
self.sess = Some(sess); self.psess = Some(psess);
self self
} }
pub(crate) fn build(self) -> Result<Parser<'a>, ParserError> { pub(crate) fn build(self) -> Result<Parser<'a>, 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 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, Ok(p) => p,
Err(db) => { Err(db) => {
if let Some(diagnostics) = db { if let Some(diagnostics) = db {
sess.emit_diagnostics(diagnostics); psess.emit_diagnostics(diagnostics);
return Err(ParserError::ParserCreationError); return Err(ParserError::ParserCreationError);
} }
return Err(ParserError::ParsePanicError); return Err(ParserError::ParsePanicError);
@ -63,16 +63,16 @@ impl<'a> ParserBuilder<'a> {
} }
fn parser( fn parser(
sess: &'a rustc_session::parse::ParseSess, psess: &'a rustc_session::parse::ParseSess,
input: Input, input: Input,
) -> Result<rustc_parse::parser::Parser<'a>, Option<Vec<Diag<'a>>>> { ) -> Result<rustc_parse::parser::Parser<'a>, Option<Vec<Diag<'a>>>> {
match input { match input {
Input::File(ref file) => catch_unwind(AssertUnwindSafe(move || { 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), .map_err(|_| None),
Input::Text(text) => rustc_parse::maybe_new_parser_from_source_str( Input::Text(text) => rustc_parse::maybe_new_parser_from_source_str(
sess, psess,
rustc_span::FileName::Custom("stdin".to_owned()), rustc_span::FileName::Custom("stdin".to_owned()),
text, text,
) )
@ -106,27 +106,27 @@ impl<'a> Parser<'a> {
} }
pub(crate) fn parse_file_as_module( pub(crate) fn parse_file_as_module(
sess: &'a ParseSess, psess: &'a ParseSess,
path: &Path, path: &Path,
span: Span, span: Span,
) -> Result<(ast::AttrVec, ThinVec<ptr::P<ast::Item>>, Span), ParserError> { ) -> Result<(ast::AttrVec, ThinVec<ptr::P<ast::Item>>, Span), ParserError> {
let result = catch_unwind(AssertUnwindSafe(|| { 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) { match parser.parse_mod(&TokenKind::Eof) {
Ok((a, i, spans)) => Some((a, i, spans.inner_span)), Ok((a, i, spans)) => Some((a, i, spans.inner_span)),
Err(e) => { Err(e) => {
e.emit(); e.emit();
if sess.can_reset_errors() { if psess.can_reset_errors() {
sess.reset_errors(); psess.reset_errors();
} }
None None
} }
} }
})); }));
match result { match result {
Ok(Some(m)) if !sess.has_errors() => Ok(m), Ok(Some(m)) if !psess.has_errors() => Ok(m),
Ok(Some(m)) if sess.can_reset_errors() => { Ok(Some(m)) if psess.can_reset_errors() => {
sess.reset_errors(); psess.reset_errors();
Ok(m) Ok(m)
} }
Ok(_) => Err(ParserError::ParseError), Ok(_) => Err(ParserError::ParseError),
@ -137,25 +137,25 @@ impl<'a> Parser<'a> {
pub(crate) fn parse_crate( pub(crate) fn parse_crate(
input: Input, input: Input,
sess: &'a ParseSess, psess: &'a ParseSess,
) -> Result<ast::Crate, ParserError> { ) -> Result<ast::Crate, ParserError> {
let krate = Parser::parse_crate_inner(input, sess)?; let krate = Parser::parse_crate_inner(input, psess)?;
if !sess.has_errors() { if !psess.has_errors() {
return Ok(krate); return Ok(krate);
} }
if sess.can_reset_errors() { if psess.can_reset_errors() {
sess.reset_errors(); psess.reset_errors();
return Ok(krate); return Ok(krate);
} }
Err(ParserError::ParseError) Err(ParserError::ParseError)
} }
fn parse_crate_inner(input: Input, sess: &'a ParseSess) -> Result<ast::Crate, ParserError> { fn parse_crate_inner(input: Input, psess: &'a ParseSess) -> Result<ast::Crate, ParserError> {
ParserBuilder::default() ParserBuilder::default()
.input(input) .input(input)
.sess(sess) .psess(psess)
.build()? .build()?
.parse_crate_mod() .parse_crate_mod()
} }

@ -23,7 +23,7 @@ use crate::{Config, ErrorKind, FileName};
/// ParseSess holds structs necessary for constructing a parser. /// ParseSess holds structs necessary for constructing a parser.
pub(crate) struct ParseSess { pub(crate) struct ParseSess {
parse_sess: RawParseSess, raw_psess: RawParseSess,
ignore_path_set: Lrc<IgnorePathSet>, ignore_path_set: Lrc<IgnorePathSet>,
can_reset_errors: Lrc<AtomicBool>, can_reset_errors: Lrc<AtomicBool>,
} }
@ -180,10 +180,10 @@ impl ParseSess {
config.hide_parse_errors(), config.hide_parse_errors(),
config.color(), config.color(),
); );
let parse_sess = RawParseSess::with_dcx(dcx, source_map); let raw_psess = RawParseSess::with_dcx(dcx, source_map);
Ok(ParseSess { Ok(ParseSess {
parse_sess, raw_psess,
ignore_path_set, ignore_path_set,
can_reset_errors, can_reset_errors,
}) })
@ -202,14 +202,14 @@ impl ParseSess {
relative: Option<symbol::Ident>, relative: Option<symbol::Ident>,
dir_path: &Path, dir_path: &Path,
) -> Result<ModulePathSuccess, ModError<'_>> { ) -> Result<ModulePathSuccess, ModError<'_>> {
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| { |e| {
// If resloving a module relative to {dir_path}/{symbol} fails because a file // 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}. // 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}, // If we still can't find the module after searching for it in {dir_path},
// surface the original error. // surface the original error.
if matches!(e, ModError::FileNotFound(..)) && relative.is_some() { 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) .map_err(|_| e)
} else { } else {
Err(e) Err(e)
@ -219,7 +219,7 @@ impl ParseSess {
} }
pub(crate) fn is_file_parsed(&self, path: &Path) -> bool { pub(crate) fn is_file_parsed(&self, path: &Path) -> bool {
self.parse_sess self.raw_psess
.source_map() .source_map()
.get_source_file(&rustc_span::FileName::Real( .get_source_file(&rustc_span::FileName::Real(
rustc_span::RealFileName::LocalPath(path.to_path_buf()), rustc_span::RealFileName::LocalPath(path.to_path_buf()),
@ -232,21 +232,21 @@ impl ParseSess {
} }
pub(crate) fn set_silent_emitter(&mut self) { 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 { 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<rustc_span::SourceFile> { pub(crate) fn span_to_file_contents(&self, span: Span) -> Lrc<rustc_span::SourceFile> {
self.parse_sess self.raw_psess
.source_map() .source_map()
.lookup_source_file(span.data().lo) .lookup_source_file(span.data().lo)
} }
pub(crate) fn span_to_first_line_string(&self, span: Span) -> String { 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 { match file_lines {
Some(fl) => fl Some(fl) => fl
@ -258,7 +258,7 @@ impl ParseSess {
} }
pub(crate) fn line_of_byte_pos(&self, pos: BytePos) -> usize { 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 // TODO(calebcartwright): Preemptive, currently unused addition
@ -271,15 +271,15 @@ impl ParseSess {
} }
pub(crate) fn span_to_debug_info(&self, span: Span) -> String { 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 { pub(crate) fn inner(&self) -> &RawParseSess {
&self.parse_sess &self.raw_psess
} }
pub(crate) fn snippet_provider(&self, span: Span) -> SnippetProvider { 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( SnippetProvider::new(
source_file.start_pos, source_file.start_pos,
source_file.end_position(), source_file.end_position(),
@ -288,7 +288,7 @@ impl ParseSess {
} }
pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option<Lrc<String>> { pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option<Lrc<String>> {
self.parse_sess self.raw_psess
.source_map() .source_map()
.get_source_file(&file_name.into()) .get_source_file(&file_name.into())
.and_then(|source_file| source_file.src.clone()) .and_then(|source_file| source_file.src.clone())
@ -308,23 +308,23 @@ impl ParseSess {
} }
pub(super) fn has_errors(&self) -> bool { 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) { pub(super) fn reset_errors(&self) {
self.parse_sess.dcx.reset_err_count(); self.raw_psess.dcx.reset_err_count();
} }
} }
impl LineRangeUtils for ParseSess { impl LineRangeUtils for ParseSess {
fn lookup_line_range(&self, span: Span) -> LineRange { fn lookup_line_range(&self, span: Span) -> LineRange {
let snippet = self let snippet = self
.parse_sess .raw_psess
.source_map() .source_map()
.span_to_snippet(span) .span_to_snippet(span)
.unwrap_or_default(); .unwrap_or_default();
let lo = self.parse_sess.source_map().lookup_line(span.lo()).unwrap(); let lo = self.raw_psess.source_map().lookup_line(span.lo()).unwrap();
let hi = self.parse_sess.source_map().lookup_line(span.hi()).unwrap(); let hi = self.raw_psess.source_map().lookup_line(span.hi()).unwrap();
debug_assert_eq!( debug_assert_eq!(
lo.sf.name, hi.sf.name, lo.sf.name, hi.sf.name,

@ -263,13 +263,13 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
item_kind: ReorderableItemKind, item_kind: ReorderableItemKind,
in_group: bool, in_group: bool,
) -> usize { ) -> 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 let item_length = items
.iter() .iter()
.take_while(|ppi| { .take_while(|ppi| {
item_kind.is_same_item_kind(&***ppi) item_kind.is_same_item_kind(&***ppi)
&& (!in_group || { && (!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; let in_same_group = current.lo < last.hi + 2;
last = current; last = current;
in_same_group in_same_group

@ -26,7 +26,7 @@ impl<T: Rewrite> Rewrite for ptr::P<T> {
#[derive(Clone)] #[derive(Clone)]
pub(crate) struct RewriteContext<'a> { pub(crate) struct RewriteContext<'a> {
pub(crate) parse_sess: &'a ParseSess, pub(crate) psess: &'a ParseSess,
pub(crate) config: &'a Config, pub(crate) config: &'a Config,
pub(crate) inside_macro: Rc<Cell<bool>>, pub(crate) inside_macro: Rc<Cell<bool>>,
// Force block indent style even if we are using visual indent style. // Force block indent style even if we are using visual indent style.

@ -49,7 +49,7 @@ where
} }
pub(crate) fn write_file<T>( pub(crate) fn write_file<T>(
parse_sess: Option<&ParseSess>, psess: Option<&ParseSess>,
filename: &FileName, filename: &FileName,
formatted_text: &str, formatted_text: &str,
out: &mut T, out: &mut T,
@ -90,7 +90,7 @@ where
let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin { let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin {
Lrc::new(fs::read_to_string(ensure_real_path(filename))?) Lrc::new(fs::read_to_string(ensure_real_path(filename))?)
} else { } 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, Some(ori) => ori,
None => Lrc::new(fs::read_to_string(ensure_real_path(filename))?), None => Lrc::new(fs::read_to_string(ensure_real_path(filename))?),
} }

@ -362,7 +362,7 @@ macro_rules! out_of_file_lines_range {
&& !$self && !$self
.config .config
.file_lines() .file_lines()
.intersects(&$self.parse_sess.lookup_line_range($span)) .intersects(&$self.psess.lookup_line_range($span))
}; };
} }

@ -71,7 +71,7 @@ impl SnippetProvider {
pub(crate) struct FmtVisitor<'a> { pub(crate) struct FmtVisitor<'a> {
parent_context: Option<&'a RewriteContext<'a>>, parent_context: Option<&'a RewriteContext<'a>>,
pub(crate) parse_sess: &'a ParseSess, pub(crate) psess: &'a ParseSess,
pub(crate) buffer: String, pub(crate) buffer: String,
pub(crate) last_pos: BytePos, pub(crate) last_pos: BytePos,
// FIXME: use an RAII util or closure for indenting // 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) { fn visit_stmt(&mut self, stmt: &Stmt<'_>, include_empty_semi: bool) {
debug!( debug!("visit_stmt: {}", self.psess.span_to_debug_info(stmt.span()));
"visit_stmt: {}",
self.parse_sess.span_to_debug_info(stmt.span())
);
if stmt.is_empty() { if stmt.is_empty() {
// If the statement is empty, just skip over it. Before that, make sure any comment // 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]>, inner_attrs: Option<&[ast::Attribute]>,
has_braces: bool, has_braces: bool,
) { ) {
debug!( debug!("visit_block: {}", self.psess.span_to_debug_info(b.span));
"visit_block: {}",
self.parse_sess.span_to_debug_info(b.span),
);
// Check if this block has braces. // Check if this block has braces.
let brace_compensation = BytePos(if has_braces { 1 } else { 0 }); 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 // do not take into account the lines with attributes as part of the skipped range
let attrs_end = attrs let attrs_end = attrs
.iter() .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() .max()
.unwrap_or(1); .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 // Statement can start after some newlines and/or spaces
// or it can be on the same line as the last attribute. // or it can be on the same line as the last attribute.
// So here we need to take a minimum between the two. // 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> { pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> {
let mut visitor = FmtVisitor::from_parse_sess( let mut visitor = FmtVisitor::from_psess(
ctx.parse_sess, ctx.psess,
ctx.config, ctx.config,
ctx.snippet_provider, ctx.snippet_provider,
ctx.report.clone(), ctx.report.clone(),
@ -769,8 +763,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
visitor visitor
} }
pub(crate) fn from_parse_sess( pub(crate) fn from_psess(
parse_session: &'a ParseSess, psess: &'a ParseSess,
config: &'a Config, config: &'a Config,
snippet_provider: &'a SnippetProvider, snippet_provider: &'a SnippetProvider,
report: FormatReport, report: FormatReport,
@ -786,7 +780,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
skip_context.macros.extend(macro_names); skip_context.macros.extend(macro_names);
FmtVisitor { FmtVisitor {
parent_context: None, parent_context: None,
parse_sess: parse_session, psess,
buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2), buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
last_pos: BytePos(0), last_pos: BytePos(0),
block_indent: Indent::empty(), 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 { pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
for attr in attrs { for attr in attrs {
if attr.has_name(depr_skip_annotation()) { 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( self.report.append(
file_name, file_name,
vec![FormattingError::from_span( vec![FormattingError::from_span(
attr.span, attr.span,
self.parse_sess, self.psess,
ErrorKind::DeprecatedAttr, ErrorKind::DeprecatedAttr,
)], )],
); );
@ -828,12 +822,12 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
ast::AttrKind::Normal(ref normal) ast::AttrKind::Normal(ref normal)
if self.is_unknown_rustfmt_attr(&normal.item.path.segments) => 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( self.report.append(
file_name, file_name,
vec![FormattingError::from_span( vec![FormattingError::from_span(
attr.span, attr.span,
self.parse_sess, self.psess,
ErrorKind::BadAttr, ErrorKind::BadAttr,
)], )],
); );
@ -1007,7 +1001,7 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
pub(crate) fn get_context(&self) -> RewriteContext<'_> { pub(crate) fn get_context(&self) -> RewriteContext<'_> {
RewriteContext { RewriteContext {
parse_sess: self.parse_sess, psess: self.psess,
config: self.config, config: self.config,
inside_macro: Rc::new(Cell::new(false)), inside_macro: Rc::new(Cell::new(false)),
use_block: Cell::new(false), use_block: Cell::new(false),