Auto merge of #121998 - matthiaskrgr:rollup-l7lzwpb, r=matthiaskrgr

Rollup of 10 pull requests

Successful merges:

 - #120976 (constify a couple thread_local statics)
 - #121683 (Fix LVI tests after frame pointers are enabled by default)
 - #121703 (Add a way to add constructors for `rustc_type_ir` types)
 - #121732 (Improve assert_matches! documentation)
 - #121928 (Extract an arguments struct for `Builder::then_else_break`)
 - #121939 (Small enhancement to description of From trait)
 - #121968 (Don't run test_get_os_named_thread on win7)
 - #121969 (`ParseSess` cleanups)
 - #121977 (Doc: Fix incorrect reference to integer in Atomic{Ptr,Bool}::as_ptr.)
 - #121994 (Update platform-support.md with supported musl version)

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2024-03-04 21:56:57 +00:00
commit 50e77f133f
122 changed files with 900 additions and 889 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

@ -10,7 +10,6 @@ use rustc_index::bit_set::GrowableBitSet;
use rustc_parse::parser::Parser;
use rustc_parse_format as parse;
use rustc_session::lint;
use rustc_session::parse::ParseSess;
use rustc_span::symbol::Ident;
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::{ErrorGuaranteed, InnerSpan, Span};
@ -36,19 +35,17 @@ fn parse_args<'a>(
is_global_asm: bool,
) -> PResult<'a, AsmArgs> {
let mut p = ecx.new_parser_from_tts(tts);
let sess = &ecx.sess.parse_sess;
parse_asm_args(&mut p, sess, sp, is_global_asm)
parse_asm_args(&mut p, sp, is_global_asm)
}
// Primarily public for rustfmt consumption.
// Internal consumers should continue to leverage `expand_asm`/`expand__global_asm`
pub fn parse_asm_args<'a>(
p: &mut Parser<'a>,
sess: &'a ParseSess,
sp: Span,
is_global_asm: bool,
) -> PResult<'a, AsmArgs> {
let dcx = &sess.dcx;
let dcx = &p.psess.dcx;
if p.token == token::Eof {
return Err(dcx.create_err(errors::AsmRequiresTemplate { span: sp }));
@ -299,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`.
@ -371,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();
@ -382,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);
}
@ -498,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,
@ -506,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

@ -42,7 +42,7 @@ pub struct Registry(Arc<RegistryData>);
thread_local! {
/// The registry associated with the thread.
/// This allows the `WorkerLocal` type to clone the registry in its constructor.
static REGISTRY: OnceCell<Registry> = OnceCell::new();
static REGISTRY: OnceCell<Registry> = const { OnceCell::new() };
}
struct ThreadData {

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

@ -9,9 +9,9 @@ const DEFAULT_COLUMN_WIDTH: usize = 140;
thread_local! {
/// Track the position of viewable characters in our buffer
static CURSOR: Cell<usize> = Cell::new(0);
static CURSOR: Cell<usize> = const { Cell::new(0) };
/// Width of the terminal
static WIDTH: Cell<usize> = Cell::new(DEFAULT_COLUMN_WIDTH);
static WIDTH: Cell<usize> = const { Cell::new(DEFAULT_COLUMN_WIDTH) };
}
/// Print to terminal output to a buffer

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,26 +1216,22 @@ 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(
parse_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
// after macro expansion (that is, they are unhygienic).
if !path.is_absolute() {
let callsite = span.source_callsite();
let mut result = match parse_sess.source_map().span_to_filename(callsite) {
let mut result = match sess.source_map().span_to_filename(callsite) {
FileName::Real(name) => name
.into_local_path()
.expect("attempting to resolve a file path in an external file"),
FileName::DocTest(path, _) => path,
other => {
return Err(parse_sess.dcx().create_err(errors::ResolveRelativePath {
return Err(sess.dcx().create_err(errors::ResolveRelativePath {
span,
path: parse_sess.source_map().filename_for_diagnostics(&other).to_string(),
path: sess.source_map().filename_for_diagnostics(&other).to_string(),
}));
}
};
@ -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,6 @@
use crate::tests::{
matches_codepattern, string_to_stream, with_error_checking_parse, with_expected_parse_error,
matches_codepattern, psess, string_to_stream, with_error_checking_parse,
with_expected_parse_error,
};
use ast::token::IdentIsRaw;
@ -14,19 +15,10 @@ use rustc_parse::new_parser_from_source_str;
use rustc_parse::parser::ForceCollect;
use rustc_session::parse::ParseSess;
use rustc_span::create_default_session_globals_then;
use rustc_span::source_map::FilePathMapping;
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_span::{BytePos, FileName, Pos, Span};
use std::path::PathBuf;
fn sess() -> ParseSess {
ParseSess::new(
vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE],
FilePathMapping::empty(),
)
}
/// Parses an item.
///
/// Returns `Ok(Some(item))` when successful, `Ok(None)` when no item was found, and `Err`
@ -34,9 +26,9 @@ fn sess() -> ParseSess {
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`.
@ -46,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]
@ -287,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 ");
});
@ -315,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"),
}
@ -348,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,9 +18,13 @@ use std::path::{Path, PathBuf};
use std::str;
use std::sync::{Arc, Mutex};
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>>>) {
@ -40,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
}
@ -57,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());
@ -72,24 +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 = ParseSess::new(
vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE],
FilePathMapping::empty(),
);
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 = ParseSess::new(
vec![crate::DEFAULT_LOCALE_RESOURCE, rustc_parse::DEFAULT_LOCALE_RESOURCE],
FilePathMapping::empty(),
);
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

@ -175,7 +175,20 @@ impl<'tcx> Const<'tcx> {
let reported = tcx.dcx().span_delayed_bug(span, msg);
Const::new_error(tcx, reported, ty)
}
}
impl<'tcx> rustc_type_ir::new::Const<TyCtxt<'tcx>> for Const<'tcx> {
fn new_anon_bound(
tcx: TyCtxt<'tcx>,
debruijn: ty::DebruijnIndex,
var: ty::BoundVar,
ty: Ty<'tcx>,
) -> Self {
Const::new_bound(tcx, debruijn, var, ty)
}
}
impl<'tcx> Const<'tcx> {
/// Literals and const generic parameters are eagerly converted to a constant, everything else
/// becomes `Unevaluated`.
#[instrument(skip(tcx), level = "debug")]

View File

@ -130,27 +130,6 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
fn mk_canonical_var_infos(self, infos: &[ty::CanonicalVarInfo<Self>]) -> Self::CanonicalVars {
self.mk_canonical_var_infos(infos)
}
fn mk_bound_ty(self, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self::Ty {
Ty::new_bound(self, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
}
fn mk_bound_region(self, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self::Region {
Region::new_bound(
self,
debruijn,
ty::BoundRegion { var, kind: ty::BoundRegionKind::BrAnon },
)
}
fn mk_bound_const(
self,
debruijn: ty::DebruijnIndex,
var: ty::BoundVar,
ty: Self::Ty,
) -> Self::Const {
Const::new_bound(self, debruijn, var, ty)
}
}
type InternedSet<'tcx, T> = ShardedHashMap<InternedInSet<'tcx, T>, ()>;

View File

@ -136,6 +136,12 @@ impl<'tcx> Region<'tcx> {
}
}
impl<'tcx> rustc_type_ir::new::Region<TyCtxt<'tcx>> for Region<'tcx> {
fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
Region::new_bound(tcx, debruijn, ty::BoundRegion { var, kind: ty::BoundRegionKind::BrAnon })
}
}
/// Region utilities
impl<'tcx> Region<'tcx> {
pub fn kind(self) -> RegionKind<'tcx> {

View File

@ -1426,7 +1426,8 @@ impl From<BoundVar> for BoundTy {
/// Constructors for `Ty`
impl<'tcx> Ty<'tcx> {
// Avoid this in favour of more specific `new_*` methods, where possible.
/// Avoid using this in favour of more specific `new_*` methods, where possible.
/// The more specific methods will often optimize their creation.
#[allow(rustc::usage_of_ty_tykind)]
#[inline]
pub fn new(tcx: TyCtxt<'tcx>, st: TyKind<'tcx>) -> Ty<'tcx> {
@ -1813,6 +1814,12 @@ impl<'tcx> Ty<'tcx> {
}
}
impl<'tcx> rustc_type_ir::new::Ty<TyCtxt<'tcx>> for Ty<'tcx> {
fn new_anon_bound(tcx: TyCtxt<'tcx>, debruijn: ty::DebruijnIndex, var: ty::BoundVar) -> Self {
Ty::new_bound(tcx, debruijn, ty::BoundTy { var, kind: ty::BoundTyKind::Anon })
}
}
/// Type utilities
impl<'tcx> Ty<'tcx> {
#[inline(always)]

View File

@ -81,10 +81,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let then_blk = unpack!(this.then_else_break(
block,
cond,
Some(condition_scope),
Some(condition_scope), // Temp scope
condition_scope,
source_info,
true,
true, // Declare `let` bindings normally
));
this.expr_into_dest(destination, then_blk, then)
@ -146,9 +146,11 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
this.then_else_break(
block,
lhs,
Some(condition_scope),
Some(condition_scope), // Temp scope
condition_scope,
source_info,
// This flag controls how inner `let` expressions are lowered,
// but either way there shouldn't be any of those in here.
true,
)
});

View File

@ -30,21 +30,55 @@ mod util;
use std::borrow::Borrow;
use std::mem;
/// Arguments to [`Builder::then_else_break_inner`] that are usually forwarded
/// to recursive invocations.
#[derive(Clone, Copy)]
struct ThenElseArgs {
/// Used as the temp scope for lowering `expr`. If absent (for match guards),
/// `self.local_scope()` is used.
temp_scope_override: Option<region::Scope>,
/// Scope to pass to [`Builder::break_for_else`]. Must match the scope used
/// by the enclosing call to [`Builder::in_if_then_scope`].
break_scope: region::Scope,
variable_source_info: SourceInfo,
/// Forwarded to [`Builder::lower_let_expr`] when lowering [`ExprKind::Let`].
/// When false (for match guards), `let` bindings won't be declared.
declare_let_bindings: bool,
}
impl<'a, 'tcx> Builder<'a, 'tcx> {
/// Lowers a condition in a way that ensures that variables bound in any let
/// expressions are definitely initialized in the if body.
///
/// If `declare_bindings` is false then variables created in `let`
/// If `declare_let_bindings` is false then variables created in `let`
/// expressions will not be declared. This is for if let guards on arms with
/// an or pattern, where the guard is lowered multiple times.
pub(crate) fn then_else_break(
&mut self,
mut block: BasicBlock,
block: BasicBlock,
expr_id: ExprId,
temp_scope_override: Option<region::Scope>,
break_scope: region::Scope,
variable_source_info: SourceInfo,
declare_bindings: bool,
declare_let_bindings: bool,
) -> BlockAnd<()> {
self.then_else_break_inner(
block,
expr_id,
ThenElseArgs {
temp_scope_override,
break_scope,
variable_source_info,
declare_let_bindings,
},
)
}
fn then_else_break_inner(
&mut self,
block: BasicBlock, // Block that the condition and branch will be lowered into
expr_id: ExprId, // Condition expression to lower
args: ThenElseArgs,
) -> BlockAnd<()> {
let this = self;
let expr = &this.thir[expr_id];
@ -52,54 +86,36 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
match expr.kind {
ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
let lhs_then_block = unpack!(this.then_else_break(
block,
lhs,
temp_scope_override,
break_scope,
variable_source_info,
declare_bindings,
));
let rhs_then_block = unpack!(this.then_else_break(
lhs_then_block,
rhs,
temp_scope_override,
break_scope,
variable_source_info,
declare_bindings,
));
let lhs_then_block = unpack!(this.then_else_break_inner(block, lhs, args));
let rhs_then_block = unpack!(this.then_else_break_inner(lhs_then_block, rhs, args));
rhs_then_block.unit()
}
ExprKind::LogicalOp { op: LogicalOp::Or, lhs, rhs } => {
let local_scope = this.local_scope();
let (lhs_success_block, failure_block) =
this.in_if_then_scope(local_scope, expr_span, |this| {
this.then_else_break(
this.then_else_break_inner(
block,
lhs,
temp_scope_override,
local_scope,
variable_source_info,
true,
ThenElseArgs {
break_scope: local_scope,
declare_let_bindings: true,
..args
},
)
});
let rhs_success_block = unpack!(this.then_else_break(
let rhs_success_block = unpack!(this.then_else_break_inner(
failure_block,
rhs,
temp_scope_override,
break_scope,
variable_source_info,
true,
ThenElseArgs { declare_let_bindings: true, ..args },
));
// Make the LHS and RHS success arms converge to a common block.
// (We can't just make LHS goto RHS, because `rhs_success_block`
// might contain statements that we don't want on the LHS path.)
let success_block = this.cfg.start_new_block();
this.cfg.goto(lhs_success_block, variable_source_info, success_block);
this.cfg.goto(rhs_success_block, variable_source_info, success_block);
this.cfg.goto(lhs_success_block, args.variable_source_info, success_block);
this.cfg.goto(rhs_success_block, args.variable_source_info, success_block);
success_block.unit()
}
ExprKind::Unary { op: UnOp::Not, arg } => {
@ -111,50 +127,38 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
if this.tcx.sess.instrument_coverage() {
this.cfg.push_coverage_span_marker(block, this.source_info(expr_span));
}
this.then_else_break(
this.then_else_break_inner(
block,
arg,
temp_scope_override,
local_scope,
variable_source_info,
true,
ThenElseArgs {
break_scope: local_scope,
declare_let_bindings: true,
..args
},
)
});
this.break_for_else(success_block, break_scope, variable_source_info);
this.break_for_else(success_block, args.break_scope, args.variable_source_info);
failure_block.unit()
}
ExprKind::Scope { region_scope, lint_level, value } => {
let region_scope = (region_scope, this.source_info(expr_span));
this.in_scope(region_scope, lint_level, |this| {
this.then_else_break(
block,
value,
temp_scope_override,
break_scope,
variable_source_info,
declare_bindings,
)
this.then_else_break_inner(block, value, args)
})
}
ExprKind::Use { source } => this.then_else_break(
block,
source,
temp_scope_override,
break_scope,
variable_source_info,
declare_bindings,
),
ExprKind::Use { source } => this.then_else_break_inner(block, source, args),
ExprKind::Let { expr, ref pat } => this.lower_let_expr(
block,
expr,
pat,
break_scope,
Some(variable_source_info.scope),
variable_source_info.span,
declare_bindings,
args.break_scope,
Some(args.variable_source_info.scope),
args.variable_source_info.span,
args.declare_let_bindings,
),
_ => {
let temp_scope = temp_scope_override.unwrap_or_else(|| this.local_scope());
let mut block = block;
let temp_scope = args.temp_scope_override.unwrap_or_else(|| this.local_scope());
let mutability = Mutability::Mut;
let place =
unpack!(block = this.as_temp(block, Some(temp_scope), expr_id, mutability));
@ -166,7 +170,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
let source_info = this.source_info(expr_span);
this.cfg.terminate(block, source_info, term);
this.break_for_else(else_block, break_scope, source_info);
this.break_for_else(else_block, args.break_scope, source_info);
then_block.unit()
}
@ -2105,10 +2109,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
this.then_else_break(
block,
guard,
None,
None, // Use `self.local_scope()` as the temp scope
match_scope,
this.source_info(arm.span),
false,
false, // For guards, `let` bindings are declared separately
)
});

View File

@ -1,6 +1,7 @@
use std::cmp::Ordering;
use rustc_type_ir::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
use rustc_type_ir::new::{Const, Region, Ty};
use rustc_type_ir::visit::TypeVisitableExt;
use rustc_type_ir::{
self as ty, Canonical, CanonicalTyVarKind, CanonicalVarInfo, CanonicalVarKind, ConstTy,
@ -293,7 +294,7 @@ impl<Infcx: InferCtxtLike<Interner = I>, I: Interner> TypeFolder<I>
var
});
self.interner().mk_bound_region(self.binder_index, var)
Region::new_anon_bound(self.interner(), self.binder_index, var)
}
fn fold_ty(&mut self, t: I::Ty) -> I::Ty
@ -375,7 +376,7 @@ impl<Infcx: InferCtxtLike<Interner = I>, I: Interner> TypeFolder<I>
}),
);
self.interner().mk_bound_ty(self.binder_index, var)
Ty::new_anon_bound(self.interner(), self.binder_index, var)
}
fn fold_const(&mut self, c: I::Const) -> I::Const
@ -435,6 +436,6 @@ impl<Infcx: InferCtxtLike<Interner = I>, I: Interner> TypeFolder<I>
}),
);
self.interner().mk_bound_const(self.binder_index, var, c.ty())
Const::new_anon_bound(self.interner(), self.binder_index, var, c.ty())
}
}

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 {
@ -233,9 +232,9 @@ pub struct ParseSess {
impl ParseSess {
/// Used for testing.
pub fn new(locale_resources: Vec<&'static str>, file_path_mapping: FilePathMapping) -> Self {
pub fn new(locale_resources: Vec<&'static str>) -> Self {
let fallback_bundle = fallback_fluent_bundle(locale_resources, false);
let sm = Lrc::new(SourceMap::new(file_path_mapping));
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let emitter = Box::new(
HumanEmitter::new(stderr_destination(ColorConfig::Auto), fallback_bundle)
.sm(Some(sm.clone())),

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

@ -4,8 +4,8 @@ use std::hash::Hash;
use crate::visit::{Flags, TypeSuperVisitable, TypeVisitable};
use crate::{
BoundVar, BoundVars, CanonicalVarInfo, ConstKind, DebruijnIndex, DebugWithInfcx, RegionKind,
TyKind, UniverseIndex,
new, BoundVar, BoundVars, CanonicalVarInfo, ConstKind, DebugWithInfcx, RegionKind, TyKind,
UniverseIndex,
};
pub trait Interner: Sized {
@ -34,7 +34,8 @@ pub trait Interner: Sized {
+ Into<Self::GenericArg>
+ IntoKind<Kind = TyKind<Self>>
+ TypeSuperVisitable<Self>
+ Flags;
+ Flags
+ new::Ty<Self>;
type Tys: Copy + Debug + Hash + Ord + IntoIterator<Item = Self::Ty>;
type AliasTy: Copy + DebugWithInfcx<Self> + Hash + Ord;
type ParamTy: Copy + Debug + Hash + Ord;
@ -56,7 +57,8 @@ pub trait Interner: Sized {
+ IntoKind<Kind = ConstKind<Self>>
+ ConstTy<Self>
+ TypeSuperVisitable<Self>
+ Flags;
+ Flags
+ new::Const<Self>;
type AliasConst: Copy + DebugWithInfcx<Self> + Hash + Ord;
type PlaceholderConst: Copy + Debug + Hash + Ord + PlaceholderLike;
type ParamConst: Copy + Debug + Hash + Ord;
@ -71,7 +73,8 @@ pub trait Interner: Sized {
+ Ord
+ Into<Self::GenericArg>
+ IntoKind<Kind = RegionKind<Self>>
+ Flags;
+ Flags
+ new::Region<Self>;
type EarlyParamRegion: Copy + Debug + Hash + Ord;
type LateParamRegion: Copy + Debug + Hash + Ord;
type BoundRegion: Copy + Debug + Hash + Ord;
@ -90,11 +93,6 @@ pub trait Interner: Sized {
type ClosureKind: Copy + Debug + Hash + Eq;
fn mk_canonical_var_infos(self, infos: &[CanonicalVarInfo<Self>]) -> Self::CanonicalVars;
// FIXME: We should not have all these constructors on `Interner`, but as functions on some trait.
fn mk_bound_ty(self, debruijn: DebruijnIndex, var: BoundVar) -> Self::Ty;
fn mk_bound_region(self, debruijn: DebruijnIndex, var: BoundVar) -> Self::Region;
fn mk_bound_const(self, debruijn: DebruijnIndex, var: BoundVar, ty: Self::Ty) -> Self::Const;
}
/// Common capabilities of placeholder kinds

View File

@ -24,6 +24,7 @@ use std::sync::Arc as Lrc;
#[cfg(feature = "nightly")]
pub mod codec;
pub mod fold;
pub mod new;
pub mod ty_info;
pub mod ty_kind;
pub mod visit;

View File

@ -0,0 +1,13 @@
use crate::{BoundVar, DebruijnIndex, Interner};
pub trait Ty<I: Interner<Ty = Self>> {
fn new_anon_bound(interner: I, debruijn: DebruijnIndex, var: BoundVar) -> Self;
}
pub trait Region<I: Interner<Region = Self>> {
fn new_anon_bound(interner: I, debruijn: DebruijnIndex, var: BoundVar) -> Self;
}
pub trait Const<I: Interner<Const = Self>> {
fn new_anon_bound(interner: I, debruijn: DebruijnIndex, var: BoundVar, ty: I::Ty) -> Self;
}

View File

@ -466,10 +466,10 @@ pub trait Into<T>: Sized {
/// Prefer using [`Into`] over using `From` when specifying trait bounds on a generic function.
/// This way, types that directly implement [`Into`] can be used as arguments as well.
///
/// The `From` is also very useful when performing error handling. When constructing a function
/// The `From` trait is also very useful when performing error handling. When constructing a function
/// that is capable of failing, the return type will generally be of the form `Result<T, E>`.
/// The `From` trait simplifies error handling by allowing a function to return a single error type
/// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more
/// `From` simplifies error handling by allowing a function to return a single error type
/// that encapsulates multiple error types. See the "Examples" section and [the book][book] for more
/// details.
///
/// **Note: This trait must not fail**. The `From` trait is intended for perfect conversions.

View File

@ -112,16 +112,19 @@ macro_rules! assert_ne {
};
}
/// Asserts that an expression matches any of the given patterns.
/// Asserts that an expression matches the provided pattern.
///
/// Like in a `match` expression, the pattern can be optionally followed by `if`
/// and a guard expression that has access to names bound by the pattern.
/// This macro is generally preferable to `assert!(matches!(value, pattern))`, because it can print
/// the debug representation of the actual value shape that did not meet expectations. In contrast,
/// using [`assert!`] will only print that expectations were not met, but not why.
///
/// On panic, this macro will print the value of the expression with its
/// debug representation.
/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The
/// optional if guard can be used to add additional checks that must be true for the matched value,
/// otherwise this macro will panic.
///
/// Like [`assert!`], this macro has a second form, where a custom
/// panic message can be provided.
/// On panic, this macro will print the value of the expression with its debug representation.
///
/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided.
///
/// # Examples
///
@ -130,13 +133,20 @@ macro_rules! assert_ne {
///
/// use std::assert_matches::assert_matches;
///
/// let a = 1u32.checked_add(2);
/// let b = 1u32.checked_sub(2);
/// let a = Some(345);
/// let b = Some(56);
/// assert_matches!(a, Some(_));
/// assert_matches!(b, None);
/// assert_matches!(b, Some(_));
///
/// let c = Ok("abc".to_string());
/// assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
/// assert_matches!(a, Some(345));
/// assert_matches!(a, Some(345) | None);
///
/// // assert_matches!(a, None); // panics
/// // assert_matches!(b, Some(345)); // panics
/// // assert_matches!(b, Some(345) | None); // panics
///
/// assert_matches!(a, Some(x) if x > 100);
/// // assert_matches!(a, Some(x) if x < 100); // panics
/// ```
#[unstable(feature = "assert_matches", issue = "82775")]
#[allow_internal_unstable(panic_internals)]
@ -369,21 +379,25 @@ macro_rules! debug_assert_ne {
};
}
/// Asserts that an expression matches any of the given patterns.
/// Asserts that an expression matches the provided pattern.
///
/// Like in a `match` expression, the pattern can be optionally followed by `if`
/// and a guard expression that has access to names bound by the pattern.
/// This macro is generally preferable to `debug_assert!(matches!(value, pattern))`, because it can
/// print the debug representation of the actual value shape that did not meet expectations. In
/// contrast, using [`debug_assert!`] will only print that expectations were not met, but not why.
///
/// On panic, this macro will print the value of the expression with its
/// debug representation.
/// The pattern syntax is exactly the same as found in a match arm and the `matches!` macro. The
/// optional if guard can be used to add additional checks that must be true for the matched value,
/// otherwise this macro will panic.
///
/// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only
/// enabled in non optimized builds by default. An optimized build will not
/// execute `debug_assert_matches!` statements unless `-C debug-assertions` is
/// passed to the compiler. This makes `debug_assert_matches!` useful for
/// checks that are too expensive to be present in a release build but may be
/// helpful during development. The result of expanding `debug_assert_matches!`
/// is always type checked.
/// On panic, this macro will print the value of the expression with its debug representation.
///
/// Like [`assert!`], this macro has a second form, where a custom panic message can be provided.
///
/// Unlike [`assert_matches!`], `debug_assert_matches!` statements are only enabled in non optimized
/// builds by default. An optimized build will not execute `debug_assert_matches!` statements unless
/// `-C debug-assertions` is passed to the compiler. This makes `debug_assert_matches!` useful for
/// checks that are too expensive to be present in a release build but may be helpful during
/// development. The result of expanding `debug_assert_matches!` is always type checked.
///
/// # Examples
///
@ -392,13 +406,20 @@ macro_rules! debug_assert_ne {
///
/// use std::assert_matches::debug_assert_matches;
///
/// let a = 1u32.checked_add(2);
/// let b = 1u32.checked_sub(2);
/// let a = Some(345);
/// let b = Some(56);
/// debug_assert_matches!(a, Some(_));
/// debug_assert_matches!(b, None);
/// debug_assert_matches!(b, Some(_));
///
/// let c = Ok("abc".to_string());
/// debug_assert_matches!(c, Ok(x) | Err(x) if x.len() < 100);
/// debug_assert_matches!(a, Some(345));
/// debug_assert_matches!(a, Some(345) | None);
///
/// // debug_assert_matches!(a, None); // panics
/// // debug_assert_matches!(b, Some(345)); // panics
/// // debug_assert_matches!(b, Some(345) | None); // panics
///
/// debug_assert_matches!(a, Some(x) if x > 100);
/// // debug_assert_matches!(a, Some(x) if x < 100); // panics
/// ```
#[unstable(feature = "assert_matches", issue = "82775")]
#[allow_internal_unstable(assert_matches)]
@ -409,10 +430,15 @@ pub macro debug_assert_matches($($arg:tt)*) {
}
}
/// Returns whether the given expression matches any of the given patterns.
/// Returns whether the given expression matches the provided pattern.
///
/// Like in a `match` expression, the pattern can be optionally followed by `if`
/// and a guard expression that has access to names bound by the pattern.
/// The pattern syntax is exactly the same as found in a match arm. The optional if guard can be
/// used to add additional checks that must be true for the matched value, otherwise this macro will
/// return `false`.
///
/// When testing that a value matches a pattern, it's generally preferable to use
/// [`assert_matches!`] as it will print the debug representation of the value if the assertion
/// fails.
///
/// # Examples
///

View File

@ -1092,7 +1092,7 @@ impl AtomicBool {
/// Returns a mutable pointer to the underlying [`bool`].
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// Doing non-atomic reads and writes on the resulting boolean can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
/// `*mut bool` instead of `&AtomicBool`.
///
@ -2031,7 +2031,7 @@ impl<T> AtomicPtr<T> {
/// Returns a mutable pointer to the underlying pointer.
///
/// Doing non-atomic reads and writes on the resulting integer can be a data race.
/// Doing non-atomic reads and writes on the resulting pointer can be a data race.
/// This method is mostly useful for FFI, where the function signature may use
/// `*mut *mut T` instead of `&AtomicPtr<T>`.
///

View File

@ -209,7 +209,7 @@ impl<'a> scoped_cell::ApplyL<'a> for BridgeStateL {
thread_local! {
static BRIDGE_STATE: scoped_cell::ScopedCell<BridgeStateL> =
scoped_cell::ScopedCell::new(BridgeState::NotConnected);
const { scoped_cell::ScopedCell::new(BridgeState::NotConnected) };
}
impl BridgeState<'_> {

View File

@ -223,7 +223,7 @@ thread_local! {
/// This is required as the thread-local state in the proc_macro client does
/// not handle being re-entered, and will invalidate all `Symbol`s when
/// entering a nested macro.
static ALREADY_RUNNING_SAME_THREAD: Cell<bool> = Cell::new(false);
static ALREADY_RUNNING_SAME_THREAD: Cell<bool> = const { Cell::new(false) };
}
/// Keep `ALREADY_RUNNING_SAME_THREAD` (see also its documentation)

View File

@ -70,7 +70,7 @@ fn test_named_thread_truncation() {
}
#[cfg(any(
target_os = "windows",
all(target_os = "windows", not(target_vendor = "win7")),
target_os = "linux",
target_os = "macos",
target_os = "ios",

View File

@ -94,7 +94,7 @@ target | notes
-------|-------
`aarch64-apple-darwin` | ARM64 macOS (11.0+, Big Sur+)
`aarch64-pc-windows-msvc` | ARM64 Windows MSVC
`aarch64-unknown-linux-musl` | ARM64 Linux with MUSL
`aarch64-unknown-linux-musl` | ARM64 Linux with musl 1.2.3
`arm-unknown-linux-gnueabi` | ARMv6 Linux (kernel 3.2, glibc 2.17)
`arm-unknown-linux-gnueabihf` | ARMv6 Linux, hardfloat (kernel 3.2, glibc 2.17)
`armv7-unknown-linux-gnueabihf` | ARMv7-A Linux, hardfloat (kernel 3.2, glibc 2.17)
@ -106,7 +106,7 @@ target | notes
`s390x-unknown-linux-gnu` | S390x Linux (kernel 3.2, glibc 2.17)
`x86_64-unknown-freebsd` | 64-bit FreeBSD
`x86_64-unknown-illumos` | illumos
`x86_64-unknown-linux-musl` | 64-bit Linux with MUSL
`x86_64-unknown-linux-musl` | 64-bit Linux with musl 1.2.3
[`x86_64-unknown-netbsd`](platform-support/netbsd.md) | NetBSD/amd64
## Tier 2 without Host Tools
@ -148,26 +148,26 @@ target | std | notes
`aarch64-unknown-none` | * | Bare ARM64, hardfloat
[`aarch64-unknown-uefi`](platform-support/unknown-uefi.md) | * | ARM64 UEFI
[`arm-linux-androideabi`](platform-support/android.md) | ✓ | ARMv6 Android
`arm-unknown-linux-musleabi` | ✓ | ARMv6 Linux with MUSL
`arm-unknown-linux-musleabihf` | ✓ | ARMv6 Linux with MUSL, hardfloat
`arm-unknown-linux-musleabi` | ✓ | ARMv6 Linux with musl 1.2.3
`arm-unknown-linux-musleabihf` | ✓ | ARMv6 Linux with musl 1.2.3, hardfloat
[`armebv7r-none-eabi`](platform-support/armv7r-none-eabi.md) | * | Bare ARMv7-R, Big Endian
[`armebv7r-none-eabihf`](platform-support/armv7r-none-eabi.md) | * | Bare ARMv7-R, Big Endian, hardfloat
`armv5te-unknown-linux-gnueabi` | ✓ | ARMv5TE Linux (kernel 4.4, glibc 2.23)
`armv5te-unknown-linux-musleabi` | ✓ | ARMv5TE Linux with MUSL
`armv5te-unknown-linux-musleabi` | ✓ | ARMv5TE Linux with musl 1.2.3
[`armv7-linux-androideabi`](platform-support/android.md) | ✓ | ARMv7-A Android
`armv7-unknown-linux-gnueabi` | ✓ | ARMv7-A Linux (kernel 4.15, glibc 2.27)
`armv7-unknown-linux-musleabi` | ✓ | ARMv7-A Linux with MUSL
`armv7-unknown-linux-musleabihf` | ✓ | ARMv7-A Linux with MUSL, hardfloat
`armv7-unknown-linux-musleabi` | ✓ | ARMv7-A Linux with musl 1.2.3
`armv7-unknown-linux-musleabihf` | ✓ | ARMv7-A Linux with musl 1.2.3, hardfloat
[`armv7-unknown-linux-ohos`](platform-support/openharmony.md) | ✓ | ARMv7-A OpenHarmony
[`armv7a-none-eabi`](platform-support/arm-none-eabi.md) | * | Bare ARMv7-A
[`armv7r-none-eabi`](platform-support/armv7r-none-eabi.md) | * | Bare ARMv7-R
[`armv7r-none-eabihf`](platform-support/armv7r-none-eabi.md) | * | Bare ARMv7-R, hardfloat
`i586-pc-windows-msvc` | * | 32-bit Windows w/o SSE [^x86_32-floats-x87]
`i586-unknown-linux-gnu` | ✓ | 32-bit Linux w/o SSE (kernel 3.2, glibc 2.17) [^x86_32-floats-x87]
`i586-unknown-linux-musl` | ✓ | 32-bit Linux w/o SSE, MUSL [^x86_32-floats-x87]
`i586-unknown-linux-musl` | ✓ | 32-bit Linux w/o SSE, musl 1.2.3 [^x86_32-floats-x87]
[`i686-linux-android`](platform-support/android.md) | ✓ | 32-bit x86 Android [^x86_32-floats-return-ABI]
`i686-unknown-freebsd` | ✓ | 32-bit FreeBSD [^x86_32-floats-return-ABI]
`i686-unknown-linux-musl` | ✓ | 32-bit Linux with MUSL [^x86_32-floats-return-ABI]
`i686-unknown-linux-musl` | ✓ | 32-bit Linux with musl 1.2.3 [^x86_32-floats-return-ABI]
[`i686-unknown-uefi`](platform-support/unknown-uefi.md) | * | 32-bit UEFI
[`loongarch64-unknown-none`](platform-support/loongarch-none.md) | * | | LoongArch64 Bare-metal (LP64D ABI)
[`loongarch64-unknown-none-softfloat`](platform-support/loongarch-none.md) | * | | LoongArch64 Bare-metal (LP64S ABI)
@ -290,7 +290,7 @@ target | std | host | notes
`csky-unknown-linux-gnuabiv2` | ✓ | | C-SKY abiv2 Linux (little endian)
`csky-unknown-linux-gnuabiv2hf` | ✓ | | C-SKY abiv2 Linux, hardfloat (little endian)
[`hexagon-unknown-none-elf`](platform-support/hexagon-unknown-none-elf.md)| * | | Bare Hexagon (v60+, HVX)
[`hexagon-unknown-linux-musl`](platform-support/hexagon-unknown-linux-musl.md) | ✓ | | Hexagon Linux
[`hexagon-unknown-linux-musl`](platform-support/hexagon-unknown-linux-musl.md) | ✓ | | Hexagon Linux with musl 1.2.3
`i386-apple-ios` | ✓ | | 32-bit x86 iOS [^x86_32-floats-return-ABI]
[`i586-pc-nto-qnx700`](platform-support/nto-qnx.md) | * | | 32-bit x86 QNX Neutrino 7.0 RTOS [^x86_32-floats-return-ABI]
[`i586-unknown-netbsd`](platform-support/netbsd.md) | ✓ | | 32-bit x86, restricted to Pentium
@ -307,15 +307,15 @@ target | std | host | notes
`i686-wrs-vxworks` | ? | | [^x86_32-floats-return-ABI]
[`m68k-unknown-linux-gnu`](platform-support/m68k-unknown-linux-gnu.md) | ? | | Motorola 680x0 Linux
`mips-unknown-linux-gnu` | ✓ | ✓ | MIPS Linux (kernel 4.4, glibc 2.23)
`mips-unknown-linux-musl` | ✓ | | MIPS Linux with musl libc
`mips-unknown-linux-musl` | ✓ | | MIPS Linux with musl 1.2.3
`mips-unknown-linux-uclibc` | ✓ | | MIPS Linux with uClibc
[`mips64-openwrt-linux-musl`](platform-support/mips64-openwrt-linux-musl.md) | ? | | MIPS64 for OpenWrt Linux MUSL
[`mips64-openwrt-linux-musl`](platform-support/mips64-openwrt-linux-musl.md) | ? | | MIPS64 for OpenWrt Linux musl 1.2.3
`mips64-unknown-linux-gnuabi64` | ✓ | ✓ | MIPS64 Linux, N64 ABI (kernel 4.4, glibc 2.23)
`mips64-unknown-linux-muslabi64` | ✓ | | MIPS64 Linux, N64 ABI, musl libc
`mips64-unknown-linux-muslabi64` | ✓ | | MIPS64 Linux, N64 ABI, musl 1.2.3
`mips64el-unknown-linux-gnuabi64` | ✓ | ✓ | MIPS64 (little endian) Linux, N64 ABI (kernel 4.4, glibc 2.23)
`mips64el-unknown-linux-muslabi64` | ✓ | | MIPS64 (little endian) Linux, N64 ABI, musl libc
`mips64el-unknown-linux-muslabi64` | ✓ | | MIPS64 (little endian) Linux, N64 ABI, musl 1.2.3
`mipsel-unknown-linux-gnu` | ✓ | ✓ | MIPS (little endian) Linux (kernel 4.4, glibc 2.23)
`mipsel-unknown-linux-musl` | ✓ | | MIPS (little endian) Linux with musl libc
`mipsel-unknown-linux-musl` | ✓ | | MIPS (little endian) Linux with musl 1.2.3
[`mipsel-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | 32-bit MIPS (LE), requires mips32 cpu support
`mipsel-sony-psp` | * | | MIPS (LE) Sony PlayStation Portable (PSP)
[`mipsel-sony-psx`](platform-support/mipsel-sony-psx.md) | * | | MIPS (LE) Sony PlayStation 1 (PSX)
@ -327,7 +327,7 @@ target | std | host | notes
[`mipsisa64r6el-unknown-linux-gnuabi64`](platform-support/mips-release-6.md) | ✓ | ✓ | 64-bit MIPS Release 6 Little Endian
`msp430-none-elf` | * | | 16-bit MSP430 microcontrollers
`powerpc-unknown-linux-gnuspe` | ✓ | | PowerPC SPE Linux
`powerpc-unknown-linux-musl` | ? | |
`powerpc-unknown-linux-musl` | ? | | PowerPC Linux with musl 1.2.3
[`powerpc-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD 32-bit powerpc systems
`powerpc-unknown-openbsd` | ? | |
`powerpc-wrs-vxworks-spe` | ? | |
@ -335,13 +335,13 @@ target | std | host | notes
`powerpc64-unknown-freebsd` | ✓ | ✓ | PPC64 FreeBSD (ELFv1 and ELFv2)
`powerpc64le-unknown-freebsd` | | | PPC64LE FreeBSD
`powerpc-unknown-freebsd` | | | PowerPC FreeBSD
`powerpc64-unknown-linux-musl` | ? | |
`powerpc64-unknown-linux-musl` | ? | | 64-bit PowerPC Linux with musl 1.2.3
`powerpc64-wrs-vxworks` | ? | |
`powerpc64le-unknown-linux-musl` | ? | |
`powerpc64le-unknown-linux-musl` | ? | | 64-bit PowerPC Linux with musl 1.2.3, Little Endian
[`powerpc64-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | OpenBSD/powerpc64
[`powerpc64-ibm-aix`](platform-support/aix.md) | ? | | 64-bit AIX (7.2 and newer)
`riscv32gc-unknown-linux-gnu` | | | RISC-V Linux (kernel 5.4, glibc 2.33)
`riscv32gc-unknown-linux-musl` | | | RISC-V Linux (kernel 5.4, musl + RISCV32 support patches)
`riscv32gc-unknown-linux-musl` | | | RISC-V Linux (kernel 5.4, musl 1.2.3 + RISCV32 support patches)
[`riscv32im-risc0-zkvm-elf`](platform-support/riscv32im-risc0-zkvm-elf.md) | ? | | RISC Zero's zero-knowledge Virtual Machine (RV32IM ISA)
[`riscv32imac-unknown-xous-elf`](platform-support/riscv32imac-unknown-xous-elf.md) | ? | | RISC-V Xous (RV32IMAC ISA)
[`riscv32imc-esp-espidf`](platform-support/esp-idf.md) | ✓ | | RISC-V ESP-IDF
@ -350,11 +350,11 @@ target | std | host | notes
[`riscv64gc-unknown-hermit`](platform-support/hermit.md) | ✓ | | RISC-V Hermit
`riscv64gc-unknown-freebsd` | | | RISC-V FreeBSD
`riscv64gc-unknown-fuchsia` | | | RISC-V Fuchsia
`riscv64gc-unknown-linux-musl` | | | RISC-V Linux (kernel 4.20, musl 1.2.0)
`riscv64gc-unknown-linux-musl` | | | RISC-V Linux (kernel 4.20, musl 1.2.3)
[`riscv64gc-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | RISC-V NetBSD
[`riscv64gc-unknown-openbsd`](platform-support/openbsd.md) | ✓ | ✓ | OpenBSD/riscv64
[`riscv64-linux-android`](platform-support/android.md) | | | RISC-V 64-bit Android
`s390x-unknown-linux-musl` | | | S390x Linux (kernel 3.2, MUSL)
`s390x-unknown-linux-musl` | | | S390x Linux (kernel 3.2, musl 1.2.3)
`sparc-unknown-linux-gnu` | ✓ | | 32-bit SPARC Linux
[`sparc-unknown-none-elf`](./platform-support/sparc-unknown-none-elf.md) | * | | Bare 32-bit SPARC V7+
[`sparc64-unknown-netbsd`](platform-support/netbsd.md) | ✓ | ✓ | NetBSD/sparc64
@ -363,7 +363,7 @@ target | std | host | notes
[`thumbv5te-none-eabi`](platform-support/armv5te-none-eabi.md) | * | | Thumb-mode Bare ARMv5TE
`thumbv7a-pc-windows-msvc` | ? | |
`thumbv7a-uwp-windows-msvc` | ✓ | |
`thumbv7neon-unknown-linux-musleabihf` | ? | | Thumb2-mode ARMv7-A Linux with NEON, MUSL
`thumbv7neon-unknown-linux-musleabihf` | ? | | Thumb2-mode ARMv7-A Linux with NEON, musl 1.2.3
[`wasm32-wasip2`](platform-support/wasm32-wasip2.md) | ✓ | | WebAssembly
[`wasm64-unknown-unknown`](platform-support/wasm64-unknown-unknown.md) | ? | | WebAssembly
`x86_64-apple-ios-macabi` | ✓ | | Apple Catalyst on x86_64
@ -372,7 +372,7 @@ target | std | host | notes
[`x86_64-pc-nto-qnx710`](platform-support/nto-qnx.md) | ✓ | | x86 64-bit QNX Neutrino 7.1 RTOS |
[`x86_64-pc-windows-gnullvm`](platform-support/pc-windows-gnullvm.md) | ✓ | ✓ |
`x86_64-pc-windows-msvc` | * | | 64-bit Windows XP support
[`x86_64-unikraft-linux-musl`](platform-support/unikraft-linux-musl.md) | ✓ | | 64-bit Unikraft with musl
[`x86_64-unikraft-linux-musl`](platform-support/unikraft-linux-musl.md) | ✓ | | 64-bit Unikraft with musl 1.2.3
`x86_64-unknown-dragonfly` | ✓ | ✓ | 64-bit DragonFlyBSD
`x86_64-unknown-haiku` | ✓ | ✓ | 64-bit Haiku
[`x86_64-unknown-hermit`](platform-support/hermit.md) | ✓ | | x86_64 Hermit

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

@ -4,7 +4,6 @@ use rustc_ast_pretty::pprust::state::State as Printer;
use rustc_ast_pretty::pprust::PrintState;
use rustc_middle::ty::TyCtxt;
use rustc_session::parse::ParseSess;
use rustc_span::source_map::FilePathMapping;
use rustc_span::symbol::{kw, Ident, Symbol};
use rustc_span::Span;
@ -63,11 +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(), FilePathMapping::empty());
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),
}
}

Some files were not shown because too many files have changed in this diff Show More