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 4260f7ec67
commit 80d2bdb619
98 changed files with 653 additions and 687 deletions

View File

@ -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,

View File

@ -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) {

View File

@ -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) {

View File

@ -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

View File

@ -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,

View File

@ -46,7 +46,7 @@ impl MultiItemModifier for Expander {
) -> ExpandResult<Vec<Annotatable>, 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,

View File

@ -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,

View File

@ -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,

View File

@ -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),
}

View File

@ -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),
}
}

View File

@ -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,

View File

@ -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,

View File

@ -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 {

View File

@ -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<ExpandResult<'a>>) -> Option<P<ast::Expr>> {
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,

View File

@ -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) {

View File

@ -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,

View File

@ -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,

View File

@ -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) {

View File

@ -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<geto
fn parse_crate_attrs<'a>(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)
}
}
}

View File

@ -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,
)
})
}

View File

@ -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<PathBuf>,
span: Span,
) -> PResult<'_, PathBuf> {
pub fn resolve_path(sess: &Session, path: impl Into<PathBuf>, 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,

View File

@ -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)
}
}

View File

@ -241,14 +241,14 @@ impl<'a> StripUnconfigured<'a> {
/// the attribute is incorrect.
pub(crate) fn expand_cfg_attr(&self, attr: &Attribute, recursive: bool) -> Vec<Attribute> {
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<MetaItem>) {
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();

View File

@ -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<Span> = 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,

View File

@ -24,12 +24,12 @@ pub(super) fn failed_to_match_macro<'cx>(
arg: TokenStream,
lhses: &[Vec<MatcherLoc>],
) -> Box<dyn MacResult + 'cx> {
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",

View File

@ -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<DiagnosticMessage>,
) {
// 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);
}
}

View File

@ -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<MatcherLoc>],
rhses: &[mbe::TokenTree],
) -> Box<dyn MacResult + 'cx> {
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<MatcherLoc>],
@ -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)
}

View File

@ -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",
))

View File

@ -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

View File

@ -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<Ident>,
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 {

View File

@ -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<P<ast::Item>>> {
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<ast::Expr> {
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<P<ast::Item>> {
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::<Vec<_>>();
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<ast::Expr>> {
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();

View File

@ -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 {

View File

@ -354,7 +354,7 @@ impl ToInternal<SmallVec<[tokenstream::TokenTree; 2]>>
)]
}
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<Literal<Self::Span, Self::Symbol>, ()> {
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<Self::Span>) {
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<Self::Span> {
@ -692,7 +692,7 @@ impl server::Span for Rustc<'_, '_> {
}
fn byte_range(&mut self, span: Self::Span) -> Range<usize> {
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<Self::Span> {
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<String> {
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 {

View File

@ -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<SourceMap>, Arc<Mutex<Vec<u8>>>) {
@ -44,13 +44,13 @@ fn create_test_handler() -> (DiagCtxt, Lrc<SourceMap>, Arc<Mutex<Vec<u8>>>) {
/// 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

View File

@ -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;
}

View File

@ -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));
}

View File

@ -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

View File

@ -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.)

View File

@ -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) {

View File

@ -45,7 +45,7 @@ pub struct Compiler {
pub(crate) fn parse_cfg(dcx: &DiagCtxt, cfgs: Vec<String>) -> 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<String>) -> 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<String>) -> 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<String>) -> 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<lint::LintId, lint::Level>,
/// This is a callback from the driver that is called when [`ParseSess`] is created.
pub parse_sess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
pub psess_created: Option<Box<dyn FnOnce(&mut ParseSess) + Send>>,
/// 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<R: Send>(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<R: Send>(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`.

View File

@ -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<BufferedEarlyLint>| {
sess.psess.buffered_lints.with_lock(|buffered_lints: &mut Vec<BufferedEarlyLint>| {
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,
);

View File

@ -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,
);

View File

@ -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,
);

View File

@ -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;
}

View File

@ -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<Symbol> =
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 { "" };

View File

@ -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.

View File

@ -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((

View File

@ -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,

View File

@ -420,7 +420,7 @@ impl<'a, 'tcx> Decodable<DecodeContext<'a, 'tcx>> 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 {

View File

@ -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);
}

View File

@ -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((

View File

@ -42,12 +42,12 @@ pub struct UnmatchedDelim {
pub candidate_span: Option<Span>,
}
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<Span>,
) -> Result<TokenStream, Vec<Diag<'sess>>> {
) -> Result<TokenStream, Vec<Diag<'psess>>> {
// 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,

View File

@ -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<PErr<'sess>>>, Vec<UnmatchedDelim>) {
string_reader: StringReader<'psess, 'src>,
) -> (TokenStream, Result<(), Vec<PErr<'psess>>>, Vec<UnmatchedDelim>) {
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<PErr<'sess>>>) {
) -> (Spacing, TokenStream, Result<(), Vec<PErr<'psess>>>) {
// 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<TokenTree, Vec<PErr<'sess>>> {
) -> Result<TokenTree, Vec<PErr<'psess>>> {
// 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<PErr<'sess>>,
) -> Vec<PErr<'sess>> {
mut errs: Vec<PErr<'psess>>,
) -> Vec<PErr<'psess>> {
// 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");

View File

@ -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

View File

@ -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<Span>,
) -> 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<Parser<'_>, Vec<Diag<'_>>> {
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<Span>) -> 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<Span>) -> 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<SourceFile>,
) -> Result<Parser<'_>, Vec<Diag<'_>>> {
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<SourceFile>,
override_span: Option<Span>,
) -> 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<SourceFile>,
override_span: Option<Span>,
) -> Result<TokenStream, Vec<Diag<'sess>>> {
) -> Result<TokenStream, Vec<Diag<'psess>>> {
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 \
<https://doc.rust-lang.org/reference/conditional-compilation.html\
#the-cfg_attr-attribute>";
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 });
}

View File

@ -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,

View File

@ -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",
);

View File

@ -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<String, SpanSnippetError> {
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 &params[..] {
[] => UnexpectedConstParamDeclarationSugg::AddParam {

View File

@ -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, .. }, _, _) => {

View File

@ -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,

View File

@ -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<T>(&self, span: Span, kind: &ItemKind, ctx: &'static str) -> Option<T> {
// 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 => {}
}

View File

@ -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<Expr>> {
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<Diag<'_>> {
// `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,

View File

@ -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<P<QSelf>>, 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,

View File

@ -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,

View File

@ -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 <https://github.com/rust-lang/rust/issues/101728>");
}

View File

@ -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

View File

@ -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()

View File

@ -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,

View File

@ -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 })

View File

@ -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<G: EmissionGuarantee>(
}
// #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 {

View File

@ -146,7 +146,7 @@ pub struct Session {
pub opts: config::Options,
pub host_tlib_path: Lrc<SearchPath>,
pub target_tlib_path: Lrc<SearchPath>,
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),

View File

@ -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)),
}
}

View File

@ -62,10 +62,10 @@ fn snippet_equal_to_token(tcx: TyCtxt<'_>, matcher: &TokenTree) -> Option<String
let snippet = source_map.span_to_snippet(span).ok()?;
// Create a Parser.
let sess = ParseSess::new(rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec());
let psess = ParseSess::new(rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec());
let file_name = source_map.span_to_filename(span);
let mut parser =
match rustc_parse::maybe_new_parser_from_source_str(&sess, file_name, snippet.clone()) {
match rustc_parse::maybe_new_parser_from_source_str(&psess, file_name, snippet.clone()) {
Ok(parser) => parser,
Err(errs) => {
errs.into_iter().for_each(|err| err.cancel());

View File

@ -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| {

View File

@ -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;
}
}

View File

@ -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()

View File

@ -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();

View File

@ -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);

View File

@ -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<String>) {
parse_sess.env_depinfo.get_mut().insert((
fn track_clippy_args(psess: &mut ParseSess, args_env_var: &Option<String>) {
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<String>)
/// 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)),
));

View File

@ -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,
)],
);

View File

@ -79,7 +79,7 @@ fn should_skip_module<T: FormatHandler>(
// 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<T: FormatHandler>(
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<T: FormatHandler>(
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<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(
&context.parse_session,
&context.psess,
directory_ownership.unwrap_or(DirectoryOwnership::UnownedViaBlock),
!input_is_stdin && !config.skip_children(),
)
@ -148,16 +148,11 @@ fn format_project<T: FormatHandler>(
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<T: FormatHandler>(
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),
}
}

View File

@ -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

View File

@ -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);

View File

@ -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<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 {
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,

View File

@ -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<ModItem>,
}
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());

View File

@ -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<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(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<Vec<ast::Item>, &'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",
);

View File

@ -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;
}
}

View File

@ -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<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) {
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<MacroArg> {
}
Err(e) => {
e.cancel();
parser.sess.dcx.reset_err_count();
parser.psess.dcx.reset_err_count();
}
}
}

View File

@ -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<Input>,
}
@ -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<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 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<rustc_parse::parser::Parser<'a>, Option<Vec<Diag<'a>>>> {
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<ptr::P<ast::Item>>, 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<ast::Crate, ParserError> {
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<ast::Crate, ParserError> {
fn parse_crate_inner(input: Input, psess: &'a ParseSess) -> Result<ast::Crate, ParserError> {
ParserBuilder::default()
.input(input)
.sess(sess)
.psess(psess)
.build()?
.parse_crate_mod()
}

View File

@ -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<IgnorePathSet>,
can_reset_errors: Lrc<AtomicBool>,
}
@ -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<symbol::Ident>,
dir_path: &Path,
) -> 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| {
// 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<rustc_span::SourceFile> {
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<Lrc<String>> {
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,

View File

@ -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

View File

@ -26,7 +26,7 @@ impl<T: Rewrite> Rewrite for ptr::P<T> {
#[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<Cell<bool>>,
// Force block indent style even if we are using visual indent style.

View File

@ -49,7 +49,7 @@ where
}
pub(crate) fn write_file<T>(
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))?),
}

View File

@ -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))
};
}

View File

@ -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),

View File

@ -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,

View File

@ -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();
}

View File

@ -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<P<Expr>> {
fn parse_expr(psess: &ParseSess, src: &str) -> Option<P<Expr>> {
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