Auto merge of #136471 - safinaskar:parallel, r=SparrowLii

tree-wide: parallel: Fully removed all `Lrc`, replaced with `Arc`

tree-wide: parallel: Fully removed all `Lrc`, replaced with `Arc`

This is continuation of https://github.com/rust-lang/rust/pull/132282 .

I'm pretty sure I did everything right. In particular, I searched all occurrences of `Lrc` in submodules and made sure that they don't need replacement.

There are other possibilities, through.

We can define `enum Lrc<T> { Rc(Rc<T>), Arc(Arc<T>) }`. Or we can make `Lrc` a union and on every clone we can read from special thread-local variable. Or we can add a generic parameter to `Lrc` and, yes, this parameter will be everywhere across all codebase.

So, if you think we should take some alternative approach, then don't merge this PR. But if it is decided to stick with `Arc`, then, please, merge.

cc "Parallel Rustc Front-end" ( https://github.com/rust-lang/rust/issues/113349 )

r? SparrowLii

`@rustbot` label WG-compiler-parallel
This commit is contained in:
bors 2025-02-06 10:50:05 +00:00
commit 2f92f050e8
77 changed files with 405 additions and 395 deletions

View file

@ -15,9 +15,9 @@ extern crate rustc_span;
use std::io;
use std::path::Path;
use std::sync::Arc;
use rustc_ast_pretty::pprust::item_to_string;
use rustc_data_structures::sync::Lrc;
use rustc_driver::{Compilation, run_compiler};
use rustc_interface::interface::{Compiler, Config};
use rustc_middle::ty::TyCtxt;
@ -43,7 +43,7 @@ fn main() {
}
}
fn read_binary_file(&self, _path: &Path) -> io::Result<Lrc<[u8]>> {
fn read_binary_file(&self, _path: &Path) -> io::Result<Arc<[u8]>> {
Err(io::Error::other("oops"))
}
}

View file

@ -15,9 +15,9 @@ extern crate rustc_span;
use std::io;
use std::path::Path;
use std::sync::Arc;
use rustc_ast_pretty::pprust::item_to_string;
use rustc_data_structures::sync::Lrc;
use rustc_driver::{Compilation, run_compiler};
use rustc_interface::interface::{Compiler, Config};
use rustc_middle::ty::TyCtxt;
@ -43,7 +43,7 @@ fn main() {
}
}
fn read_binary_file(&self, _path: &Path) -> io::Result<Lrc<[u8]>> {
fn read_binary_file(&self, _path: &Path) -> io::Result<Arc<[u8]>> {
Err(io::Error::other("oops"))
}
}

View file

@ -54,7 +54,7 @@ Lints are registered via the [`LintStore::register_lint`] function. This should
happen just once for any lint, or an ICE will occur.
Once the registration is complete, we "freeze" the lint store by placing it in
an `Lrc`.
an `Arc`.
Lint passes are registered separately into one of the categories
(pre-expansion, early, late, late module). Passes are registered as a closure

View file

@ -46,7 +46,6 @@ are implemented differently depending on whether `parallel-compiler` is true.
| data structure | parallel | non-parallel |
| -------------------------------- | --------------------------------------------------- | ------------ |
| Lrc | std::sync::Arc | std::rc::Rc |
| Weak | std::sync::Weak | std::rc::Weak |
| Atomic{Bool}/{Usize}/{U32}/{U64} | std::sync::atomic::Atomic{Bool}/{Usize}/{U32}/{U64} | (std::cell::Cell<bool/usize/u32/u64>) |
| OnceCell | std::sync::OnceLock | std::cell::OnceCell |

View file

@ -1,8 +1,7 @@
use std::sync::LazyLock;
use std::sync::{Arc, LazyLock};
use std::{io, mem};
use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxIndexMap};
use rustc_data_structures::sync::Lrc;
use rustc_data_structures::unord::UnordSet;
use rustc_driver::USING_INTERNAL_FEATURES;
use rustc_errors::TerminalUrl;
@ -145,7 +144,7 @@ impl<'tcx> DocContext<'tcx> {
/// will be created for the `DiagCtxt`.
pub(crate) fn new_dcx(
error_format: ErrorOutputType,
source_map: Option<Lrc<source_map::SourceMap>>,
source_map: Option<Arc<source_map::SourceMap>>,
diagnostic_width: Option<usize>,
unstable_opts: &UnstableOptions,
) -> rustc_errors::DiagCtxt {
@ -173,7 +172,7 @@ pub(crate) fn new_dcx(
}
ErrorOutputType::Json { pretty, json_rendered, color_config } => {
let source_map = source_map.unwrap_or_else(|| {
Lrc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
Arc::new(source_map::SourceMap::new(source_map::FilePathMapping::empty()))
});
Box::new(
JsonEmitter::new(

View file

@ -2,9 +2,9 @@
//! runnable, e.g. by adding a `main` function if it doesn't already exist.
use std::io;
use std::sync::Arc;
use rustc_ast as ast;
use rustc_data_structures::sync::Lrc;
use rustc_errors::emitter::stderr_destination;
use rustc_errors::{ColorConfig, FatalError};
use rustc_parse::new_parser_from_source_str;
@ -280,7 +280,7 @@ fn parse_source(
// Any errors in parsing should also appear when the doctest is compiled for real, so just
// send all the errors that librustc_ast emits directly into a `Sink` instead of stderr.
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sm = Arc::new(SourceMap::new(FilePathMapping::empty()));
let fallback_bundle = rustc_errors::fallback_fluent_bundle(
rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
false,
@ -474,7 +474,7 @@ fn check_if_attr_is_complete(source: &str, edition: Edition) -> Option<AttrKind>
let filename = FileName::anon_source_code(source);
// Any errors in parsing should also appear when the doctest is compiled for real, so just
// send all the errors that librustc_ast emits directly into a `Sink` instead of stderr.
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sm = Arc::new(SourceMap::new(FilePathMapping::empty()));
let fallback_bundle = rustc_errors::fallback_fluent_bundle(
rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
false,

View file

@ -1,9 +1,9 @@
//! Doctest functionality used only for doctests in `.rs` source files.
use std::env;
use std::sync::Arc;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::Lrc;
use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
use rustc_hir::{self as hir, CRATE_HIR_ID, intravisit};
use rustc_middle::hir::nested_filter;
@ -17,7 +17,7 @@ use crate::clean::{Attributes, extract_cfg_from_attrs};
use crate::html::markdown::{self, ErrorCodes, LangString, MdRelLine};
struct RustCollector {
source_map: Lrc<SourceMap>,
source_map: Arc<SourceMap>,
tests: Vec<ScrapedDocTest>,
cur_path: Vec<String>,
position: Span,

View file

@ -1,6 +1,8 @@
//! Validates syntax inside Rust code blocks (\`\`\`rust).
use rustc_data_structures::sync::{Lock, Lrc};
use std::sync::Arc;
use rustc_data_structures::sync::Lock;
use rustc_errors::emitter::Emitter;
use rustc_errors::registry::Registry;
use rustc_errors::translation::{Translate, to_fluent_args};
@ -32,14 +34,14 @@ fn check_rust_syntax(
dox: &str,
code_block: RustCodeBlock,
) {
let buffer = Lrc::new(Lock::new(Buffer::default()));
let buffer = Arc::new(Lock::new(Buffer::default()));
let fallback_bundle = rustc_errors::fallback_fluent_bundle(
rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
false,
);
let emitter = BufferEmitter { buffer: Lrc::clone(&buffer), fallback_bundle };
let emitter = BufferEmitter { buffer: Arc::clone(&buffer), fallback_bundle };
let sm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let sm = Arc::new(SourceMap::new(FilePathMapping::empty()));
let dcx = DiagCtxt::new(Box::new(emitter)).disable_warnings();
let source = dox[code_block.code].to_owned();
let psess = ParseSess::with_dcx(dcx, sm);
@ -141,7 +143,7 @@ struct Buffer {
}
struct BufferEmitter {
buffer: Lrc<Lock<Buffer>>,
buffer: Arc<Lock<Buffer>>,
fallback_bundle: LazyFallbackBundle,
}

View file

@ -1,8 +1,8 @@
use std::sync::Arc;
use super::MIXED_ATTRIBUTES_STYLE;
use clippy_utils::diagnostics::span_lint;
use rustc_ast::{AttrKind, AttrStyle, Attribute};
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::Lrc;
use rustc_lint::{EarlyContext, LintContext};
use rustc_span::source_map::SourceMap;
use rustc_span::{SourceFile, Span, Symbol};
@ -79,7 +79,7 @@ fn lint_mixed_attrs(cx: &EarlyContext<'_>, attrs: &[Attribute]) {
);
}
fn attr_in_same_src_as_item(source_map: &SourceMap, item_src: &Lrc<SourceFile>, attr_span: Span) -> bool {
fn attr_in_same_src_as_item(source_map: &SourceMap, item_src: &Arc<SourceFile>, attr_span: Span) -> bool {
let attr_src = source_map.lookup_source_file(attr_span.lo());
Lrc::ptr_eq(item_src, &attr_src)
Arc::ptr_eq(item_src, &attr_src)
}

View file

@ -1,10 +1,10 @@
use std::ops::Range;
use std::{io, thread};
use std::sync::Arc;
use crate::doc::{NEEDLESS_DOCTEST_MAIN, TEST_ATTR_IN_DOCTEST};
use clippy_utils::diagnostics::span_lint;
use rustc_ast::{CoroutineKind, Fn, FnRetTy, Item, ItemKind};
use rustc_data_structures::sync::Lrc;
use rustc_errors::emitter::HumanEmitter;
use rustc_errors::{Diag, DiagCtxt};
use rustc_lint::LateContext;
@ -46,8 +46,8 @@ pub fn check(
rustc_errors::fallback_fluent_bundle(rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(), false);
let emitter = HumanEmitter::new(Box::new(io::sink()), fallback_bundle);
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()));
#[expect(clippy::arc_with_non_send_sync)] // `Arc` is expected by with_dcx
let sm = Arc::new(SourceMap::new(FilePathMapping::empty()));
let psess = ParseSess::with_dcx(dcx, sm);
let mut parser = match new_parser_from_source_str(&psess, filename, code) {

View file

@ -1,3 +1,4 @@
use std::sync::Arc;
use std::ops::ControlFlow;
use clippy_config::Conf;
@ -6,7 +7,6 @@ use clippy_utils::is_lint_allowed;
use clippy_utils::source::walk_span_to_context;
use clippy_utils::visitors::{Descend, for_each_expr};
use hir::HirId;
use rustc_data_structures::sync::Lrc;
use rustc_hir as hir;
use rustc_hir::{Block, BlockCheckMode, ItemKind, Node, UnsafeSource};
use rustc_lexer::{TokenKind, tokenize};
@ -480,7 +480,7 @@ fn item_has_safety_comment(cx: &LateContext<'_>, item: &hir::Item<'_>) -> HasSaf
if let Some(comment_start) = comment_start
&& let Ok(unsafe_line) = source_map.lookup_line(item.span.lo())
&& let Ok(comment_start_line) = source_map.lookup_line(comment_start)
&& Lrc::ptr_eq(&unsafe_line.sf, &comment_start_line.sf)
&& Arc::ptr_eq(&unsafe_line.sf, &comment_start_line.sf)
&& let Some(src) = unsafe_line.sf.src.as_deref()
{
return if comment_start_line.line >= unsafe_line.line {
@ -520,7 +520,7 @@ fn stmt_has_safety_comment(cx: &LateContext<'_>, span: Span, hir_id: HirId) -> H
if let Some(comment_start) = comment_start
&& let Ok(unsafe_line) = source_map.lookup_line(span.lo())
&& let Ok(comment_start_line) = source_map.lookup_line(comment_start)
&& Lrc::ptr_eq(&unsafe_line.sf, &comment_start_line.sf)
&& Arc::ptr_eq(&unsafe_line.sf, &comment_start_line.sf)
&& let Some(src) = unsafe_line.sf.src.as_deref()
{
return if comment_start_line.line >= unsafe_line.line {
@ -580,7 +580,7 @@ fn span_from_macro_expansion_has_safety_comment(cx: &LateContext<'_>, span: Span
// ^--------------------------------------------^
if let Ok(unsafe_line) = source_map.lookup_line(span.lo())
&& let Ok(macro_line) = source_map.lookup_line(ctxt.outer_expn_data().def_site.lo())
&& Lrc::ptr_eq(&unsafe_line.sf, &macro_line.sf)
&& Arc::ptr_eq(&unsafe_line.sf, &macro_line.sf)
&& let Some(src) = unsafe_line.sf.src.as_deref()
{
if macro_line.line < unsafe_line.line {
@ -641,7 +641,7 @@ fn span_has_safety_comment(cx: &LateContext<'_>, span: Span) -> bool {
if let Ok(unsafe_line) = source_map.lookup_line(span.lo())
&& let Some(body_span) = walk_span_to_context(search_span, SyntaxContext::root())
&& let Ok(body_line) = source_map.lookup_line(body_span.lo())
&& Lrc::ptr_eq(&unsafe_line.sf, &body_line.sf)
&& Arc::ptr_eq(&unsafe_line.sf, &body_line.sf)
&& let Some(src) = unsafe_line.sf.src.as_deref()
{
// Get the text from the start of function body to the unsafe block.

View file

@ -1,14 +1,13 @@
use std::mem;
use std::sync::OnceLock;
use std::sync::{Arc, OnceLock};
use rustc_ast::{Attribute, Crate};
use rustc_data_structures::sync::Lrc;
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_session::impl_lint_pass;
use rustc_span::Span;
#[derive(Clone, Default)]
pub struct AttrStorage(pub Lrc<OnceLock<Vec<Span>>>);
pub struct AttrStorage(pub Arc<OnceLock<Vec<Span>>>);
pub struct AttrCollector {
storage: AttrStorage,

View file

@ -4,13 +4,14 @@
//! executable MIR bodies, so we have to do this instead.
#![allow(clippy::float_cmp)]
use std::sync::Arc;
use crate::source::{SpanRangeExt, walk_span_to_context};
use crate::{clip, is_direct_expn_of, sext, unsext};
use rustc_apfloat::Float;
use rustc_apfloat::ieee::{Half, Quad};
use rustc_ast::ast::{self, LitFloatType, LitKind};
use rustc_data_structures::sync::Lrc;
use rustc_hir::def::{DefKind, Res};
use rustc_hir::{
BinOp, BinOpKind, Block, ConstBlock, Expr, ExprKind, HirId, Item, ItemKind, Node, PatExpr, PatExprKind, QPath, UnOp,
@ -37,7 +38,7 @@ pub enum Constant<'tcx> {
/// A `String` (e.g., "abc").
Str(String),
/// A binary string (e.g., `b"abc"`).
Binary(Lrc<[u8]>),
Binary(Arc<[u8]>),
/// A single `char` (e.g., `'a'`).
Char(char),
/// An integer's bit representation.
@ -305,7 +306,7 @@ pub fn lit_to_mir_constant<'tcx>(lit: &LitKind, ty: Option<Ty<'tcx>>) -> Constan
match *lit {
LitKind::Str(ref is, _) => Constant::Str(is.to_string()),
LitKind::Byte(b) => Constant::Int(u128::from(b)),
LitKind::ByteStr(ref s, _) | LitKind::CStr(ref s, _) => Constant::Binary(Lrc::clone(s)),
LitKind::ByteStr(ref s, _) | LitKind::CStr(ref s, _) => Constant::Binary(Arc::clone(s)),
LitKind::Char(c) => Constant::Char(c),
LitKind::Int(n, _) => Constant::Int(n.get()),
LitKind::Float(ref is, LitFloatType::Suffixed(fty)) => match fty {

View file

@ -1,12 +1,14 @@
#![allow(clippy::similar_names)] // `expr` and `expn`
use std::sync::Arc;
use crate::get_unique_attr;
use crate::visitors::{Descend, for_each_expr_without_closures};
use arrayvec::ArrayVec;
use rustc_ast::{FormatArgs, FormatArgument, FormatPlaceholder};
use rustc_data_structures::fx::FxHashMap;
use rustc_data_structures::sync::{Lrc, OnceLock};
use rustc_data_structures::sync::OnceLock;
use rustc_hir::{self as hir, Expr, ExprKind, HirId, Node, QPath};
use rustc_lint::{LateContext, LintContext};
use rustc_span::def_id::DefId;
@ -393,7 +395,7 @@ fn is_assert_arg(cx: &LateContext<'_>, expr: &Expr<'_>, assert_expn: ExpnId) ->
/// Stores AST [`FormatArgs`] nodes for use in late lint passes, as they are in a desugared form in
/// the HIR
#[derive(Default, Clone)]
pub struct FormatArgsStorage(Lrc<OnceLock<FxHashMap<Span, FormatArgs>>>);
pub struct FormatArgsStorage(Arc<OnceLock<FxHashMap<Span, FormatArgs>>>);
impl FormatArgsStorage {
/// Returns an AST [`FormatArgs`] node if a `format_args` expansion is found as a descendant of

View file

@ -2,8 +2,9 @@
#![allow(clippy::module_name_repetitions)]
use std::sync::Arc;
use rustc_ast::{LitKind, StrStyle};
use rustc_data_structures::sync::Lrc;
use rustc_errors::Applicability;
use rustc_hir::{BlockCheckMode, Expr, ExprKind, UnsafeSource};
use rustc_lint::{EarlyContext, LateContext};
@ -204,7 +205,7 @@ impl fmt::Display for SourceText {
fn get_source_range(sm: &SourceMap, sp: Range<BytePos>) -> Option<SourceFileRange> {
let start = sm.lookup_byte_offset(sp.start);
let end = sm.lookup_byte_offset(sp.end);
if !Lrc::ptr_eq(&start.sf, &end.sf) || start.pos > end.pos {
if !Arc::ptr_eq(&start.sf, &end.sf) || start.pos > end.pos {
return None;
}
sm.ensure_source_file_source_present(&start.sf);
@ -277,7 +278,7 @@ fn trim_start(sm: &SourceMap, sp: Range<BytePos>) -> Range<BytePos> {
}
pub struct SourceFileRange {
pub sf: Lrc<SourceFile>,
pub sf: Arc<SourceFile>,
pub range: Range<usize>,
}
impl SourceFileRange {

View file

@ -29,7 +29,7 @@ use std::num::NonZero;
use std::ops::Range;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Once;
use std::sync::{Arc, Once};
use std::sync::atomic::{AtomicI32, AtomicU32, Ordering};
use miri::{
@ -38,7 +38,6 @@ use miri::{
};
use rustc_abi::ExternAbi;
use rustc_data_structures::sync;
use rustc_data_structures::sync::Lrc;
use rustc_driver::Compilation;
use rustc_hir::def_id::LOCAL_CRATE;
use rustc_hir::{self as hir, Node};
@ -134,7 +133,7 @@ impl rustc_driver::Callbacks for MiriCompilerCalls {
// HACK: rustc will emit "crate ... required to be available in rlib format, but
// was not found in this form" errors once we use `tcx.dependency_formats()` if
// there's no rlib provided, so setting a dummy path here to workaround those errors.
Lrc::make_mut(&mut crate_source).rlib = Some((PathBuf::new(), PathKind::All));
Arc::make_mut(&mut crate_source).rlib = Some((PathBuf::new(), PathKind::All));
crate_source
};
});

View file

@ -3,9 +3,9 @@
use itertools::Itertools;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::{cmp, fmt, iter, str};
use rustc_data_structures::sync::Lrc;
use rustc_span::SourceFile;
use serde::{Deserialize, Deserializer, Serialize, Serializer, ser};
use serde_json as json;
@ -13,7 +13,7 @@ use thiserror::Error;
/// A range of lines in a file, inclusive of both ends.
pub struct LineRange {
pub(crate) file: Lrc<SourceFile>,
pub(crate) file: Arc<SourceFile>,
pub(crate) lo: usize,
pub(crate) hi: usize,
}

View file

@ -1,7 +1,8 @@
use std::path::Path;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use rustc_data_structures::sync::{IntoDynSyncSend, Lrc};
use rustc_data_structures::sync::IntoDynSyncSend;
use rustc_errors::emitter::{DynEmitter, Emitter, HumanEmitter, SilentEmitter, stderr_destination};
use rustc_errors::registry::Registry;
use rustc_errors::translation::Translate;
@ -25,17 +26,17 @@ use crate::{Config, ErrorKind, FileName};
/// ParseSess holds structs necessary for constructing a parser.
pub(crate) struct ParseSess {
raw_psess: RawParseSess,
ignore_path_set: Lrc<IgnorePathSet>,
can_reset_errors: Lrc<AtomicBool>,
ignore_path_set: Arc<IgnorePathSet>,
can_reset_errors: Arc<AtomicBool>,
}
/// Emit errors against every files expect ones specified in the `ignore_path_set`.
struct SilentOnIgnoredFilesEmitter {
ignore_path_set: IntoDynSyncSend<Lrc<IgnorePathSet>>,
source_map: Lrc<SourceMap>,
ignore_path_set: IntoDynSyncSend<Arc<IgnorePathSet>>,
source_map: Arc<SourceMap>,
emitter: Box<DynEmitter>,
has_non_ignorable_parser_errors: bool,
can_reset: Lrc<AtomicBool>,
can_reset: Arc<AtomicBool>,
}
impl SilentOnIgnoredFilesEmitter {
@ -96,9 +97,9 @@ impl From<Color> for ColorConfig {
}
fn default_dcx(
source_map: Lrc<SourceMap>,
ignore_path_set: Lrc<IgnorePathSet>,
can_reset: Lrc<AtomicBool>,
source_map: Arc<SourceMap>,
ignore_path_set: Arc<IgnorePathSet>,
can_reset: Arc<AtomicBool>,
show_parse_errors: bool,
color: Color,
) -> DiagCtxt {
@ -139,16 +140,16 @@ fn default_dcx(
impl ParseSess {
pub(crate) fn new(config: &Config) -> Result<ParseSess, ErrorKind> {
let ignore_path_set = match IgnorePathSet::from_ignore_list(&config.ignore()) {
Ok(ignore_path_set) => Lrc::new(ignore_path_set),
Ok(ignore_path_set) => Arc::new(ignore_path_set),
Err(e) => return Err(ErrorKind::InvalidGlobPattern(e)),
};
let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let can_reset_errors = Lrc::new(AtomicBool::new(false));
let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
let can_reset_errors = Arc::new(AtomicBool::new(false));
let dcx = default_dcx(
Lrc::clone(&source_map),
Lrc::clone(&ignore_path_set),
Lrc::clone(&can_reset_errors),
Arc::clone(&source_map),
Arc::clone(&ignore_path_set),
Arc::clone(&can_reset_errors),
config.show_parse_errors(),
config.color(),
);
@ -211,7 +212,7 @@ impl ParseSess {
self.raw_psess.source_map().span_to_filename(span).into()
}
pub(crate) fn span_to_file_contents(&self, span: Span) -> Lrc<rustc_span::SourceFile> {
pub(crate) fn span_to_file_contents(&self, span: Span) -> Arc<rustc_span::SourceFile> {
self.raw_psess
.source_map()
.lookup_source_file(span.data().lo)
@ -255,11 +256,11 @@ impl ParseSess {
SnippetProvider::new(
source_file.start_pos,
source_file.end_position(),
Lrc::clone(source_file.src.as_ref().unwrap()),
Arc::clone(source_file.src.as_ref().unwrap()),
)
}
pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option<Lrc<String>> {
pub(crate) fn get_original_snippet(&self, file_name: &FileName) -> Option<Arc<String>> {
self.raw_psess
.source_map()
.get_source_file(&file_name.into())
@ -331,7 +332,7 @@ mod tests {
use std::sync::atomic::AtomicU32;
struct TestEmitter {
num_emitted_errors: Lrc<AtomicU32>,
num_emitted_errors: Arc<AtomicU32>,
}
impl Translate for TestEmitter {
@ -365,15 +366,15 @@ mod tests {
}
fn build_emitter(
num_emitted_errors: Lrc<AtomicU32>,
can_reset: Lrc<AtomicBool>,
source_map: Option<Lrc<SourceMap>>,
num_emitted_errors: Arc<AtomicU32>,
can_reset: Arc<AtomicBool>,
source_map: Option<Arc<SourceMap>>,
ignore_list: Option<IgnoreList>,
) -> SilentOnIgnoredFilesEmitter {
let emitter_writer = TestEmitter { num_emitted_errors };
let source_map =
source_map.unwrap_or_else(|| Lrc::new(SourceMap::new(FilePathMapping::empty())));
let ignore_path_set = Lrc::new(
source_map.unwrap_or_else(|| Arc::new(SourceMap::new(FilePathMapping::empty())));
let ignore_path_set = Arc::new(
IgnorePathSet::from_ignore_list(&ignore_list.unwrap_or_default()).unwrap(),
);
SilentOnIgnoredFilesEmitter {
@ -393,10 +394,10 @@ mod tests {
#[test]
fn handles_fatal_parse_error_in_ignored_file() {
let num_emitted_errors = Lrc::new(AtomicU32::new(0));
let can_reset_errors = Lrc::new(AtomicBool::new(false));
let num_emitted_errors = Arc::new(AtomicU32::new(0));
let can_reset_errors = Arc::new(AtomicBool::new(false));
let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
let source =
String::from(r#"extern "system" fn jni_symbol!( funcName ) ( ... ) -> {} "#);
source_map.new_source_file(
@ -405,9 +406,9 @@ mod tests {
);
let registry = Registry::new(&[]);
let mut emitter = build_emitter(
Lrc::clone(&num_emitted_errors),
Lrc::clone(&can_reset_errors),
Some(Lrc::clone(&source_map)),
Arc::clone(&num_emitted_errors),
Arc::clone(&can_reset_errors),
Some(Arc::clone(&source_map)),
Some(ignore_list),
);
let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
@ -420,10 +421,10 @@ mod tests {
#[nightly_only_test]
#[test]
fn handles_recoverable_parse_error_in_ignored_file() {
let num_emitted_errors = Lrc::new(AtomicU32::new(0));
let can_reset_errors = Lrc::new(AtomicBool::new(false));
let num_emitted_errors = Arc::new(AtomicU32::new(0));
let can_reset_errors = Arc::new(AtomicBool::new(false));
let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
let source = String::from(r#"pub fn bar() { 1x; }"#);
source_map.new_source_file(
SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
@ -431,9 +432,9 @@ mod tests {
);
let registry = Registry::new(&[]);
let mut emitter = build_emitter(
Lrc::clone(&num_emitted_errors),
Lrc::clone(&can_reset_errors),
Some(Lrc::clone(&source_map)),
Arc::clone(&num_emitted_errors),
Arc::clone(&can_reset_errors),
Some(Arc::clone(&source_map)),
Some(ignore_list),
);
let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
@ -446,9 +447,9 @@ mod tests {
#[nightly_only_test]
#[test]
fn handles_recoverable_parse_error_in_non_ignored_file() {
let num_emitted_errors = Lrc::new(AtomicU32::new(0));
let can_reset_errors = Lrc::new(AtomicBool::new(false));
let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let num_emitted_errors = Arc::new(AtomicU32::new(0));
let can_reset_errors = Arc::new(AtomicBool::new(false));
let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
let source = String::from(r#"pub fn bar() { 1x; }"#);
source_map.new_source_file(
SourceMapFileName::Real(RealFileName::LocalPath(PathBuf::from("foo.rs"))),
@ -456,9 +457,9 @@ mod tests {
);
let registry = Registry::new(&[]);
let mut emitter = build_emitter(
Lrc::clone(&num_emitted_errors),
Lrc::clone(&can_reset_errors),
Some(Lrc::clone(&source_map)),
Arc::clone(&num_emitted_errors),
Arc::clone(&can_reset_errors),
Some(Arc::clone(&source_map)),
None,
);
let span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));
@ -471,9 +472,9 @@ mod tests {
#[nightly_only_test]
#[test]
fn handles_mix_of_recoverable_parse_error() {
let num_emitted_errors = Lrc::new(AtomicU32::new(0));
let can_reset_errors = Lrc::new(AtomicBool::new(false));
let source_map = Lrc::new(SourceMap::new(FilePathMapping::empty()));
let num_emitted_errors = Arc::new(AtomicU32::new(0));
let can_reset_errors = Arc::new(AtomicBool::new(false));
let source_map = Arc::new(SourceMap::new(FilePathMapping::empty()));
let ignore_list = get_ignore_list(r#"ignore = ["foo.rs"]"#);
let bar_source = String::from(r#"pub fn bar() { 1x; }"#);
let foo_source = String::from(r#"pub fn foo() { 1x; }"#);
@ -493,9 +494,9 @@ mod tests {
);
let registry = Registry::new(&[]);
let mut emitter = build_emitter(
Lrc::clone(&num_emitted_errors),
Lrc::clone(&can_reset_errors),
Some(Lrc::clone(&source_map)),
Arc::clone(&num_emitted_errors),
Arc::clone(&can_reset_errors),
Some(Arc::clone(&source_map)),
Some(ignore_list),
);
let bar_span = MultiSpan::from_span(mk_sp(BytePos(0), BytePos(1)));

View file

@ -1,6 +1,7 @@
use std::fs;
use std::io::{self, Write};
use std::path::Path;
use std::sync::Arc;
use crate::NewlineStyle;
use crate::config::FileName;
@ -14,8 +15,6 @@ use crate::create_emitter;
#[cfg(test)]
use crate::formatting::FileRecord;
use rustc_data_structures::sync::Lrc;
// Append a newline to the end of each file.
pub(crate) fn append_newline(s: &mut String) {
s.push('\n');
@ -88,11 +87,11 @@ where
// source map instead of hitting the file system. This also supports getting
// original text for `FileName::Stdin`.
let original_text = if newline_style != NewlineStyle::Auto && *filename != FileName::Stdin {
Lrc::new(fs::read_to_string(ensure_real_path(filename))?)
Arc::new(fs::read_to_string(ensure_real_path(filename))?)
} else {
match psess.and_then(|psess| psess.get_original_snippet(filename)) {
Some(ori) => ori,
None => Lrc::new(fs::read_to_string(ensure_real_path(filename))?),
None => Arc::new(fs::read_to_string(ensure_real_path(filename))?),
}
};

View file

@ -1,8 +1,8 @@
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use rustc_ast::{ast, token::Delimiter, visit};
use rustc_data_structures::sync::Lrc;
use rustc_span::{BytePos, Pos, Span, symbol};
use tracing::debug;
@ -32,7 +32,7 @@ use crate::{ErrorKind, FormatReport, FormattingError};
/// Creates a string slice corresponding to the specified span.
pub(crate) struct SnippetProvider {
/// A pointer to the content of the file we are formatting.
big_snippet: Lrc<String>,
big_snippet: Arc<String>,
/// A position of the start of `big_snippet`, used as an offset.
start_pos: usize,
/// An end position of the file that this snippet lives.
@ -46,7 +46,7 @@ impl SnippetProvider {
Some(&self.big_snippet[start_index..end_index])
}
pub(crate) fn new(start_pos: BytePos, end_pos: BytePos, big_snippet: Lrc<String>) -> Self {
pub(crate) fn new(start_pos: BytePos, end_pos: BytePos, big_snippet: Arc<String>) -> Self {
let start_pos = start_pos.to_usize();
let end_pos = end_pos.to_usize();
SnippetProvider {