Auto merge of #17907 - ChayimFriedman2:no-once_cell, r=Veykril

internal: Replace once_cell with std's recently stabilized OnceCell/Lock and LazyCell/Lock

This doesn't get rid of the once_cell dependency, unfortunately, since we have dependencies that use it, but it's a nice to do cleanup. And when our deps will eventually get rid of once_cell we will get rid of it for free.
This commit is contained in:
bors 2024-08-16 07:05:59 +00:00
commit fc36e0ca16
19 changed files with 49 additions and 54 deletions

7
Cargo.lock generated
View file

@ -495,7 +495,6 @@ dependencies = [
"hir-ty",
"intern",
"itertools",
"once_cell",
"rustc-hash",
"smallvec",
"span",
@ -528,7 +527,6 @@ dependencies = [
"la-arena 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
"limit",
"mbe",
"once_cell",
"ra-ap-rustc_abi",
"ra-ap-rustc_parse_format",
"rustc-hash",
@ -595,7 +593,6 @@ dependencies = [
"la-arena 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
"limit",
"nohash-hasher",
"once_cell",
"oorandom",
"project-model",
"ra-ap-rustc_abi",
@ -691,7 +688,6 @@ dependencies = [
"hir",
"ide-db",
"itertools",
"once_cell",
"smallvec",
"stdx",
"syntax",
@ -720,7 +716,6 @@ dependencies = [
"line-index 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"memchr",
"nohash-hasher",
"once_cell",
"parser",
"profile",
"rayon",
@ -746,7 +741,6 @@ dependencies = [
"hir",
"ide-db",
"itertools",
"once_cell",
"paths",
"serde_json",
"stdx",
@ -1933,7 +1927,6 @@ dependencies = [
"expect-test",
"indexmap",
"itertools",
"once_cell",
"parser",
"ra-ap-rustc_lexer",
"rayon",

View file

@ -23,7 +23,6 @@ fst = { version = "0.4.7", default-features = false }
indexmap.workspace = true
itertools.workspace = true
la-arena.workspace = true
once_cell = "1.17.0"
rustc-hash.workspace = true
tracing.workspace = true
smallvec.workspace = true

View file

@ -12,7 +12,6 @@ use hir_expand::{
};
use intern::Interned;
use la_arena::{Arena, RawIdx};
use once_cell::unsync::Lazy;
use stdx::impl_from;
use syntax::ast::{self, HasGenericParams, HasName, HasTypeBounds};
use triomphe::Arc;
@ -394,11 +393,16 @@ impl GenericParams {
// Don't create an `Expander` if not needed since this
// could cause a reparse after the `ItemTree` has been created due to the spanmap.
let mut expander = Lazy::new(|| {
(module.def_map(db), Expander::new(db, loc.id.file_id(), module))
});
let mut expander = None;
for param in func_data.params.iter() {
generic_params.fill_implicit_impl_trait_args(db, &mut expander, param);
generic_params.fill_implicit_impl_trait_args(
db,
&mut expander,
&mut || {
(module.def_map(db), Expander::new(db, loc.id.file_id(), module))
},
param,
);
}
Interned::new(generic_params.finish())
}
@ -597,7 +601,9 @@ impl GenericParamsCollector {
fn fill_implicit_impl_trait_args(
&mut self,
db: &dyn DefDatabase,
exp: &mut Lazy<(Arc<DefMap>, Expander), impl FnOnce() -> (Arc<DefMap>, Expander)>,
// FIXME: Change this back to `LazyCell` if https://github.com/rust-lang/libs-team/issues/429 is accepted.
exp: &mut Option<(Arc<DefMap>, Expander)>,
exp_fill: &mut dyn FnMut() -> (Arc<DefMap>, Expander),
type_ref: &TypeRef,
) {
type_ref.walk(&mut |type_ref| {
@ -617,7 +623,7 @@ impl GenericParamsCollector {
}
if let TypeRef::Macro(mc) = type_ref {
let macro_call = mc.to_node(db.upcast());
let (def_map, expander) = &mut **exp;
let (def_map, expander) = exp.get_or_insert_with(&mut *exp_fill);
let module = expander.module.local_id;
let resolver = |path: &_| {
@ -637,8 +643,8 @@ impl GenericParamsCollector {
{
let ctx = expander.ctx(db);
let type_ref = TypeRef::from_ast(&ctx, expanded.tree());
self.fill_implicit_impl_trait_args(db, &mut *exp, &type_ref);
exp.1.exit(mark);
self.fill_implicit_impl_trait_args(db, &mut *exp, exp_fill, &type_ref);
exp.get_or_insert_with(&mut *exp_fill).1.exit(mark);
}
}
});

View file

@ -1,12 +1,13 @@
//! Describes items defined or visible (ie, imported) in a certain scope.
//! This is shared between modules and blocks.
use std::sync::LazyLock;
use base_db::CrateId;
use hir_expand::{attrs::AttrId, db::ExpandDatabase, name::Name, AstId, MacroCallId};
use indexmap::map::Entry;
use itertools::Itertools;
use la_arena::Idx;
use once_cell::sync::Lazy;
use rustc_hash::{FxHashMap, FxHashSet};
use smallvec::{smallvec, SmallVec};
use stdx::format_to;
@ -129,7 +130,7 @@ struct DeriveMacroInvocation {
derive_call_ids: SmallVec<[Option<MacroCallId>; 1]>,
}
pub(crate) static BUILTIN_SCOPE: Lazy<FxIndexMap<Name, PerNs>> = Lazy::new(|| {
pub(crate) static BUILTIN_SCOPE: LazyLock<FxIndexMap<Name, PerNs>> = LazyLock::new(|| {
BuiltinType::all_builtin_types()
.iter()
.map(|(name, ty)| (name.clone(), PerNs::types((*ty).into(), Visibility::Public, None)))

View file

@ -40,6 +40,7 @@ use std::{
fmt::{self, Debug},
hash::{Hash, Hasher},
ops::{Index, Range},
sync::OnceLock,
};
use ast::{AstNode, StructKind};
@ -48,7 +49,6 @@ use either::Either;
use hir_expand::{attrs::RawAttrs, name::Name, ExpandTo, HirFileId, InFile};
use intern::{Interned, Symbol};
use la_arena::{Arena, Idx, RawIdx};
use once_cell::sync::OnceCell;
use rustc_hash::FxHashMap;
use smallvec::SmallVec;
use span::{AstIdNode, FileAstId, SyntaxContextId};
@ -101,7 +101,7 @@ pub struct ItemTree {
impl ItemTree {
pub(crate) fn file_item_tree_query(db: &dyn DefDatabase, file_id: HirFileId) -> Arc<ItemTree> {
let _p = tracing::info_span!("file_item_tree_query", ?file_id).entered();
static EMPTY: OnceCell<Arc<ItemTree>> = OnceCell::new();
static EMPTY: OnceLock<Arc<ItemTree>> = OnceLock::new();
let syntax = db.parse_or_expand(file_id);
@ -152,7 +152,7 @@ impl ItemTree {
pub(crate) fn block_item_tree_query(db: &dyn DefDatabase, block: BlockId) -> Arc<ItemTree> {
let _p = tracing::info_span!("block_item_tree_query", ?block).entered();
static EMPTY: OnceCell<Arc<ItemTree>> = OnceCell::new();
static EMPTY: OnceLock<Arc<ItemTree>> = OnceLock::new();
let loc = block.lookup(db);
let block = loc.ast_id.to_node(db.upcast());
@ -626,9 +626,9 @@ impl Index<RawVisibilityId> for ItemTree {
type Output = RawVisibility;
fn index(&self, index: RawVisibilityId) -> &Self::Output {
static VIS_PUB: RawVisibility = RawVisibility::Public;
static VIS_PRIV_IMPLICIT: OnceCell<RawVisibility> = OnceCell::new();
static VIS_PRIV_EXPLICIT: OnceCell<RawVisibility> = OnceCell::new();
static VIS_PUB_CRATE: OnceCell<RawVisibility> = OnceCell::new();
static VIS_PRIV_IMPLICIT: OnceLock<RawVisibility> = OnceLock::new();
static VIS_PRIV_EXPLICIT: OnceLock<RawVisibility> = OnceLock::new();
static VIS_PUB_CRATE: OnceLock<RawVisibility> = OnceLock::new();
match index {
RawVisibilityId::PRIV_IMPLICIT => VIS_PRIV_IMPLICIT.get_or_init(|| {

View file

@ -29,7 +29,6 @@ chalk-ir.workspace = true
chalk-recursive.workspace = true
chalk-derive.workspace = true
la-arena.workspace = true
once_cell = "1.17.0"
triomphe.workspace = true
nohash-hasher.workspace = true
typed-arena = "2.0.1"

View file

@ -1,10 +1,10 @@
//! Interface with `rustc_pattern_analysis`.
use std::cell::LazyCell;
use std::fmt;
use hir_def::{DefWithBodyId, EnumId, EnumVariantId, HasModule, LocalFieldId, ModuleId, VariantId};
use intern::sym;
use once_cell::unsync::Lazy;
use rustc_pattern_analysis::{
constructor::{Constructor, ConstructorSet, VariantVisibility},
usefulness::{compute_match_usefulness, PlaceValidity, UsefulnessReport},
@ -384,8 +384,9 @@ impl<'db> PatCx for MatchCheckCtx<'db> {
let variant = Self::variant_id_for_adt(self.db, ctor, adt).unwrap();
// Whether we must not match the fields of this variant exhaustively.
let is_non_exhaustive = Lazy::new(|| self.is_foreign_non_exhaustive(adt));
let visibilities = Lazy::new(|| self.db.field_visibilities(variant));
let is_non_exhaustive =
LazyCell::new(|| self.is_foreign_non_exhaustive(adt));
let visibilities = LazyCell::new(|| self.db.field_visibilities(variant));
self.list_variant_fields(ty, variant)
.map(move |(fid, ty)| {

View file

@ -22,7 +22,7 @@ mod pat;
mod path;
pub(crate) mod unify;
use std::{convert::identity, iter, ops::Index};
use std::{cell::OnceCell, convert::identity, iter, ops::Index};
use chalk_ir::{
cast::Cast,
@ -49,7 +49,6 @@ use hir_expand::name::Name;
use indexmap::IndexSet;
use intern::sym;
use la_arena::{ArenaMap, Entry};
use once_cell::unsync::OnceCell;
use rustc_hash::{FxHashMap, FxHashSet};
use stdx::{always, never};
use triomphe::Arc;

View file

@ -6,7 +6,7 @@
//!
//! This usually involves resolving names, collecting generic arguments etc.
use std::{
cell::{Cell, RefCell, RefMut},
cell::{Cell, OnceCell, RefCell, RefMut},
iter,
ops::{self, Not as _},
};
@ -43,7 +43,6 @@ use hir_def::{
use hir_expand::{name::Name, ExpandResult};
use intern::Interned;
use la_arena::{Arena, ArenaMap};
use once_cell::unsync::OnceCell;
use rustc_hash::FxHashSet;
use rustc_pattern_analysis::Captures;
use smallvec::SmallVec;

View file

@ -12,6 +12,7 @@ mod traits;
mod type_alias_impl_traits;
use std::env;
use std::sync::LazyLock;
use base_db::SourceDatabaseFileInputExt as _;
use expect_test::Expect;
@ -25,7 +26,6 @@ use hir_def::{
AssocItemId, DefWithBodyId, HasModule, LocalModuleId, Lookup, ModuleDefId,
};
use hir_expand::{db::ExpandDatabase, FileRange, InFile};
use once_cell::race::OnceBool;
use rustc_hash::FxHashMap;
use stdx::format_to;
use syntax::{
@ -50,8 +50,8 @@ use crate::{
// `env UPDATE_EXPECT=1 cargo test -p hir_ty` to update the snapshots.
fn setup_tracing() -> Option<tracing::subscriber::DefaultGuard> {
static ENABLE: OnceBool = OnceBool::new();
if !ENABLE.get_or_init(|| env::var("CHALK_DEBUG").is_ok()) {
static ENABLE: LazyLock<bool> = LazyLock::new(|| env::var("CHALK_DEBUG").is_ok());
if !*ENABLE {
return None;
}

View file

@ -20,7 +20,6 @@ itertools.workspace = true
smallvec.workspace = true
tracing.workspace = true
triomphe.workspace = true
once_cell = "1.17.1"
# local deps
base-db.workspace = true

View file

@ -17,7 +17,6 @@ cov-mark = "2.0.0-pre.1"
itertools.workspace = true
tracing.workspace = true
once_cell = "1.17.0"
smallvec.workspace = true

View file

@ -2,6 +2,8 @@
//!
//! This module uses a bit of static metadata to provide completions for builtin-in attributes and lints.
use std::sync::LazyLock;
use ide_db::{
generated::lints::{
Lint, CLIPPY_LINTS, CLIPPY_LINT_GROUPS, DEFAULT_LINTS, FEATURES, RUSTDOC_LINTS,
@ -10,7 +12,6 @@ use ide_db::{
FxHashMap, SymbolKind,
};
use itertools::Itertools;
use once_cell::sync::Lazy;
use syntax::{
ast::{self, AttrKind},
AstNode, SyntaxKind, T,
@ -215,7 +216,7 @@ macro_rules! attrs {
}
#[rustfmt::skip]
static KIND_TO_ATTRIBUTES: Lazy<FxHashMap<SyntaxKind, &[&str]>> = Lazy::new(|| {
static KIND_TO_ATTRIBUTES: LazyLock<FxHashMap<SyntaxKind, &[&str]>> = LazyLock::new(|| {
use SyntaxKind::*;
[
(

View file

@ -19,7 +19,6 @@ tracing.workspace = true
rayon.workspace = true
fst = { version = "0.4.7", default-features = false }
rustc-hash.workspace = true
once_cell = "1.17.0"
either.workspace = true
itertools.workspace = true
arrayvec.workspace = true

View file

@ -4,6 +4,7 @@
//! get a super-set of matches. Then, we confirm each match using precise
//! name resolution.
use std::cell::LazyCell;
use std::mem;
use base_db::{salsa::Database, SourceDatabase, SourceRootDatabase};
@ -12,7 +13,6 @@ use hir::{
InFile, InRealFile, ModuleSource, PathResolution, Semantics, Visibility,
};
use memchr::memmem::Finder;
use once_cell::unsync::Lazy;
use parser::SyntaxKind;
use rustc_hash::FxHashMap;
use span::EditionedFileId;
@ -543,7 +543,7 @@ impl<'a> FindUsages<'a> {
for (text, file_id, search_range) in scope_files(sema, &search_scope) {
self.sema.db.unwind_if_cancelled();
let tree = Lazy::new(move || sema.parse(file_id).syntax().clone());
let tree = LazyCell::new(move || sema.parse(file_id).syntax().clone());
// Search for occurrences of the items name
for offset in match_indices(&text, finder, search_range) {
@ -589,7 +589,7 @@ impl<'a> FindUsages<'a> {
for (text, file_id, search_range) in scope_files(sema, &scope) {
self.sema.db.unwind_if_cancelled();
let tree = Lazy::new(move || sema.parse(file_id).syntax().clone());
let tree = LazyCell::new(move || sema.parse(file_id).syntax().clone());
for offset in match_indices(&text, finder, search_range) {
for name_ref in
@ -641,7 +641,7 @@ impl<'a> FindUsages<'a> {
let search_range =
search_range.unwrap_or_else(|| TextRange::up_to(TextSize::of(&*text)));
let tree = Lazy::new(|| sema.parse(file_id).syntax().clone());
let tree = LazyCell::new(|| sema.parse(file_id).syntax().clone());
let finder = &Finder::new("self");
for offset in match_indices(&text, finder, search_range) {

View file

@ -18,7 +18,6 @@ either.workspace = true
itertools.workspace = true
serde_json.workspace = true
tracing.workspace = true
once_cell = "1.17.0"
# local deps
stdx.workspace = true

View file

@ -75,6 +75,8 @@ mod handlers {
#[cfg(test)]
mod tests;
use std::sync::LazyLock;
use hir::{diagnostics::AnyDiagnostic, InFile, Semantics};
use ide_db::{
assists::{Assist, AssistId, AssistKind, AssistResolveStrategy},
@ -86,7 +88,6 @@ use ide_db::{
syntax_helpers::node_ext::parse_tt_as_comma_sep_paths,
EditionedFileId, FileId, FileRange, FxHashMap, FxHashSet, RootDatabase, SnippetCap,
};
use once_cell::sync::Lazy;
use stdx::never;
use syntax::{
ast::{self, AstNode},
@ -512,11 +513,11 @@ pub fn full_diagnostics(
// `__RA_EVERY_LINT` is a fake lint group to allow every lint in proc macros
static RUSTC_LINT_GROUPS_DICT: Lazy<FxHashMap<&str, Vec<&str>>> =
Lazy::new(|| build_group_dict(DEFAULT_LINT_GROUPS, &["warnings", "__RA_EVERY_LINT"], ""));
static RUSTC_LINT_GROUPS_DICT: LazyLock<FxHashMap<&str, Vec<&str>>> =
LazyLock::new(|| build_group_dict(DEFAULT_LINT_GROUPS, &["warnings", "__RA_EVERY_LINT"], ""));
static CLIPPY_LINT_GROUPS_DICT: Lazy<FxHashMap<&str, Vec<&str>>> =
Lazy::new(|| build_group_dict(CLIPPY_LINT_GROUPS, &["__RA_EVERY_LINT"], "clippy::"));
static CLIPPY_LINT_GROUPS_DICT: LazyLock<FxHashMap<&str, Vec<&str>>> =
LazyLock::new(|| build_group_dict(CLIPPY_LINT_GROUPS, &["__RA_EVERY_LINT"], "clippy::"));
fn build_group_dict(
lint_group: &'static [LintGroup],

View file

@ -18,7 +18,6 @@ either.workspace = true
itertools.workspace = true
rowan = "0.15.15"
rustc-hash.workspace = true
once_cell = "1.17.0"
indexmap.workspace = true
smol_str.workspace = true
triomphe.workspace = true

View file

@ -1152,12 +1152,13 @@ pub fn token(kind: SyntaxKind) -> SyntaxToken {
}
pub mod tokens {
use once_cell::sync::Lazy;
use std::sync::LazyLock;
use parser::Edition;
use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
pub(super) static SOURCE_FILE: LazyLock<Parse<SourceFile>> = LazyLock::new(|| {
SourceFile::parse(
"const C: <()>::Item = ( true && true , true || true , 1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p, &p , &mut p, { let _ @ [] })\n;\n\nimpl A for B where: {}", Edition::CURRENT,
)