From 955e6098677d465627519c75c7af757851d39d6c Mon Sep 17 00:00:00 2001 From: Chayim Refael Friedman Date: Fri, 16 Aug 2024 09:53:37 +0300 Subject: [PATCH] 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. --- Cargo.lock | 7 ------ crates/hir-def/Cargo.toml | 1 - crates/hir-def/src/generics.rs | 24 ++++++++++++------- crates/hir-def/src/item_scope.rs | 5 ++-- crates/hir-def/src/item_tree.rs | 12 +++++----- crates/hir-ty/Cargo.toml | 1 - .../diagnostics/match_check/pat_analysis.rs | 7 +++--- crates/hir-ty/src/infer.rs | 3 +-- crates/hir-ty/src/lower.rs | 3 +-- crates/hir-ty/src/tests.rs | 6 ++--- crates/hir/Cargo.toml | 1 - crates/ide-completion/Cargo.toml | 1 - .../src/completions/attribute.rs | 5 ++-- crates/ide-db/Cargo.toml | 1 - crates/ide-db/src/search.rs | 8 +++---- crates/ide-diagnostics/Cargo.toml | 1 - crates/ide-diagnostics/src/lib.rs | 11 +++++---- crates/syntax/Cargo.toml | 1 - crates/syntax/src/ast/make.rs | 5 ++-- 19 files changed, 49 insertions(+), 54 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index b6bf516af1..693e49c70f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", @@ -1938,7 +1932,6 @@ dependencies = [ "expect-test", "indexmap", "itertools", - "once_cell", "parser", "ra-ap-rustc_lexer", "rayon", diff --git a/crates/hir-def/Cargo.toml b/crates/hir-def/Cargo.toml index 5b9d227e31..c8ba5da449 100644 --- a/crates/hir-def/Cargo.toml +++ b/crates/hir-def/Cargo.toml @@ -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 diff --git a/crates/hir-def/src/generics.rs b/crates/hir-def/src/generics.rs index ebaaef66db..6c34ee086a 100644 --- a/crates/hir-def/src/generics.rs +++ b/crates/hir-def/src/generics.rs @@ -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, Expander), impl FnOnce() -> (Arc, Expander)>, + // FIXME: Change this back to `LazyCell` if https://github.com/rust-lang/libs-team/issues/429 is accepted. + exp: &mut Option<(Arc, Expander)>, + exp_fill: &mut dyn FnMut() -> (Arc, 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); } } }); diff --git a/crates/hir-def/src/item_scope.rs b/crates/hir-def/src/item_scope.rs index df6b1f55c1..485f434072 100644 --- a/crates/hir-def/src/item_scope.rs +++ b/crates/hir-def/src/item_scope.rs @@ -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; 1]>, } -pub(crate) static BUILTIN_SCOPE: Lazy> = Lazy::new(|| { +pub(crate) static BUILTIN_SCOPE: LazyLock> = LazyLock::new(|| { BuiltinType::all_builtin_types() .iter() .map(|(name, ty)| (name.clone(), PerNs::types((*ty).into(), Visibility::Public, None))) diff --git a/crates/hir-def/src/item_tree.rs b/crates/hir-def/src/item_tree.rs index 28eebb286e..10e6de3144 100644 --- a/crates/hir-def/src/item_tree.rs +++ b/crates/hir-def/src/item_tree.rs @@ -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 { let _p = tracing::info_span!("file_item_tree_query", ?file_id).entered(); - static EMPTY: OnceCell> = OnceCell::new(); + static EMPTY: OnceLock> = 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 { let _p = tracing::info_span!("block_item_tree_query", ?block).entered(); - static EMPTY: OnceCell> = OnceCell::new(); + static EMPTY: OnceLock> = OnceLock::new(); let loc = block.lookup(db); let block = loc.ast_id.to_node(db.upcast()); @@ -626,9 +626,9 @@ impl Index for ItemTree { type Output = RawVisibility; fn index(&self, index: RawVisibilityId) -> &Self::Output { static VIS_PUB: RawVisibility = RawVisibility::Public; - static VIS_PRIV_IMPLICIT: OnceCell = OnceCell::new(); - static VIS_PRIV_EXPLICIT: OnceCell = OnceCell::new(); - static VIS_PUB_CRATE: OnceCell = OnceCell::new(); + static VIS_PRIV_IMPLICIT: OnceLock = OnceLock::new(); + static VIS_PRIV_EXPLICIT: OnceLock = OnceLock::new(); + static VIS_PUB_CRATE: OnceLock = OnceLock::new(); match index { RawVisibilityId::PRIV_IMPLICIT => VIS_PRIV_IMPLICIT.get_or_init(|| { diff --git a/crates/hir-ty/Cargo.toml b/crates/hir-ty/Cargo.toml index b079b5675b..989f0955e1 100644 --- a/crates/hir-ty/Cargo.toml +++ b/crates/hir-ty/Cargo.toml @@ -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" diff --git a/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs b/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs index a12e201cf3..dbc69f02c4 100644 --- a/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs +++ b/crates/hir-ty/src/diagnostics/match_check/pat_analysis.rs @@ -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}, @@ -388,8 +388,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)| { diff --git a/crates/hir-ty/src/infer.rs b/crates/hir-ty/src/infer.rs index 804bc53905..bb604f599c 100644 --- a/crates/hir-ty/src/infer.rs +++ b/crates/hir-ty/src/infer.rs @@ -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, @@ -50,7 +50,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; diff --git a/crates/hir-ty/src/lower.rs b/crates/hir-ty/src/lower.rs index 444628ff52..06c975a113 100644 --- a/crates/hir-ty/src/lower.rs +++ b/crates/hir-ty/src/lower.rs @@ -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; diff --git a/crates/hir-ty/src/tests.rs b/crates/hir-ty/src/tests.rs index 19619008e3..4e4734e554 100644 --- a/crates/hir-ty/src/tests.rs +++ b/crates/hir-ty/src/tests.rs @@ -11,6 +11,7 @@ mod simple; mod traits; use std::env; +use std::sync::LazyLock; use base_db::SourceDatabaseFileInputExt as _; use expect_test::Expect; @@ -24,7 +25,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::{ @@ -49,8 +49,8 @@ use crate::{ // `env UPDATE_EXPECT=1 cargo test -p hir_ty` to update the snapshots. fn setup_tracing() -> Option { - static ENABLE: OnceBool = OnceBool::new(); - if !ENABLE.get_or_init(|| env::var("CHALK_DEBUG").is_ok()) { + static ENABLE: LazyLock = LazyLock::new(|| env::var("CHALK_DEBUG").is_ok()); + if !*ENABLE { return None; } diff --git a/crates/hir/Cargo.toml b/crates/hir/Cargo.toml index 324fa1c6a8..26666d6feb 100644 --- a/crates/hir/Cargo.toml +++ b/crates/hir/Cargo.toml @@ -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 diff --git a/crates/ide-completion/Cargo.toml b/crates/ide-completion/Cargo.toml index 035b2fc0db..614465b4d0 100644 --- a/crates/ide-completion/Cargo.toml +++ b/crates/ide-completion/Cargo.toml @@ -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 diff --git a/crates/ide-completion/src/completions/attribute.rs b/crates/ide-completion/src/completions/attribute.rs index a7a6cdebd3..697dfe7e57 100644 --- a/crates/ide-completion/src/completions/attribute.rs +++ b/crates/ide-completion/src/completions/attribute.rs @@ -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> = Lazy::new(|| { +static KIND_TO_ATTRIBUTES: LazyLock> = LazyLock::new(|| { use SyntaxKind::*; [ ( diff --git a/crates/ide-db/Cargo.toml b/crates/ide-db/Cargo.toml index 6714a99f80..3bf958e796 100644 --- a/crates/ide-db/Cargo.toml +++ b/crates/ide-db/Cargo.toml @@ -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 diff --git a/crates/ide-db/src/search.rs b/crates/ide-db/src/search.rs index 9e01a6d440..d9ffb173a0 100644 --- a/crates/ide-db/src/search.rs +++ b/crates/ide-db/src/search.rs @@ -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) { diff --git a/crates/ide-diagnostics/Cargo.toml b/crates/ide-diagnostics/Cargo.toml index 9c3a279a94..bf54f4ab32 100644 --- a/crates/ide-diagnostics/Cargo.toml +++ b/crates/ide-diagnostics/Cargo.toml @@ -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 diff --git a/crates/ide-diagnostics/src/lib.rs b/crates/ide-diagnostics/src/lib.rs index a61c5f0cd4..3e8ff12875 100644 --- a/crates/ide-diagnostics/src/lib.rs +++ b/crates/ide-diagnostics/src/lib.rs @@ -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>> = - Lazy::new(|| build_group_dict(DEFAULT_LINT_GROUPS, &["warnings", "__RA_EVERY_LINT"], "")); +static RUSTC_LINT_GROUPS_DICT: LazyLock>> = + LazyLock::new(|| build_group_dict(DEFAULT_LINT_GROUPS, &["warnings", "__RA_EVERY_LINT"], "")); -static CLIPPY_LINT_GROUPS_DICT: Lazy>> = - Lazy::new(|| build_group_dict(CLIPPY_LINT_GROUPS, &["__RA_EVERY_LINT"], "clippy::")); +static CLIPPY_LINT_GROUPS_DICT: LazyLock>> = + LazyLock::new(|| build_group_dict(CLIPPY_LINT_GROUPS, &["__RA_EVERY_LINT"], "clippy::")); fn build_group_dict( lint_group: &'static [LintGroup], diff --git a/crates/syntax/Cargo.toml b/crates/syntax/Cargo.toml index 994c21469f..d945fa59c9 100644 --- a/crates/syntax/Cargo.toml +++ b/crates/syntax/Cargo.toml @@ -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 diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs index 0228d9dd71..0b1561663c 100644 --- a/crates/syntax/src/ast/make.rs +++ b/crates/syntax/src/ast/make.rs @@ -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> = Lazy::new(|| { + pub(super) static SOURCE_FILE: LazyLock> = 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, )