Replace once_cell's Lazy as much as possible (#4617)

Co-authored-by: Laurenz <laurmaedje@gmail.com>
This commit is contained in:
Abdul-Rahman Sibahi 2024-10-31 14:52:11 +03:00 committed by GitHub
parent 644ed252dd
commit b969c01b28
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
35 changed files with 87 additions and 107 deletions

8
Cargo.lock generated
View File

@ -2690,7 +2690,6 @@ dependencies = [
"fs_extra", "fs_extra",
"native-tls", "native-tls",
"notify", "notify",
"once_cell",
"open", "open",
"parking_lot", "parking_lot",
"pathdiff", "pathdiff",
@ -2730,7 +2729,6 @@ dependencies = [
"clap", "clap",
"ecow", "ecow",
"heck", "heck",
"once_cell",
"pulldown-cmark", "pulldown-cmark",
"serde", "serde",
"serde_json", "serde_json",
@ -2828,7 +2826,6 @@ dependencies = [
"icu_provider_blob", "icu_provider_blob",
"icu_segmenter", "icu_segmenter",
"kurbo", "kurbo",
"once_cell",
"rustybuzz", "rustybuzz",
"smallvec", "smallvec",
"ttf-parser", "ttf-parser",
@ -2867,7 +2864,6 @@ dependencies = [
"kamadak-exif", "kamadak-exif",
"kurbo", "kurbo",
"lipsum", "lipsum",
"once_cell",
"palette", "palette",
"phf", "phf",
"png", "png",
@ -2924,7 +2920,6 @@ dependencies = [
"image", "image",
"indexmap 2.6.0", "indexmap 2.6.0",
"miniz_oxide", "miniz_oxide",
"once_cell",
"pdf-writer", "pdf-writer",
"serde", "serde",
"subsetter", "subsetter",
@ -2947,7 +2942,6 @@ dependencies = [
"bumpalo", "bumpalo",
"comemo", "comemo",
"ecow", "ecow",
"once_cell",
"regex", "regex",
"typst-library", "typst-library",
"typst-macros", "typst-macros",
@ -2994,7 +2988,6 @@ name = "typst-syntax"
version = "0.12.0" version = "0.12.0"
dependencies = [ dependencies = [
"ecow", "ecow",
"once_cell",
"serde", "serde",
"toml", "toml",
"typst-timing", "typst-timing",
@ -3013,7 +3006,6 @@ dependencies = [
"clap", "clap",
"comemo", "comemo",
"ecow", "ecow",
"once_cell",
"oxipng", "oxipng",
"parking_lot", "parking_lot",
"rayon", "rayon",

View File

@ -36,7 +36,6 @@ ecow = { workspace = true }
fs_extra = { workspace = true } fs_extra = { workspace = true }
native-tls = { workspace = true } native-tls = { workspace = true }
notify = { workspace = true } notify = { workspace = true }
once_cell = { workspace = true }
open = { workspace = true } open = { workspace = true }
parking_lot = { workspace = true } parking_lot = { workspace = true }
pathdiff = { workspace = true } pathdiff = { workspace = true }

View File

@ -16,12 +16,12 @@ mod world;
use std::cell::Cell; use std::cell::Cell;
use std::io::{self, Write}; use std::io::{self, Write};
use std::process::ExitCode; use std::process::ExitCode;
use std::sync::LazyLock;
use clap::error::ErrorKind; use clap::error::ErrorKind;
use clap::Parser; use clap::Parser;
use codespan_reporting::term; use codespan_reporting::term;
use codespan_reporting::term::termcolor::WriteColor; use codespan_reporting::term::termcolor::WriteColor;
use once_cell::sync::Lazy;
use typst::diag::HintedStrResult; use typst::diag::HintedStrResult;
use crate::args::{CliArguments, Command}; use crate::args::{CliArguments, Command};
@ -33,7 +33,7 @@ thread_local! {
} }
/// The parsed command line arguments. /// The parsed command line arguments.
static ARGS: Lazy<CliArguments> = Lazy::new(|| { static ARGS: LazyLock<CliArguments> = LazyLock::new(|| {
CliArguments::try_parse().unwrap_or_else(|error| { CliArguments::try_parse().unwrap_or_else(|error| {
if error.kind() == ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand { if error.kind() == ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand {
crate::greet::greet(); crate::greet::greet();

View File

@ -1,12 +1,11 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::io::Read; use std::io::Read;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::OnceLock; use std::sync::{LazyLock, OnceLock};
use std::{fmt, fs, io, mem}; use std::{fmt, fs, io, mem};
use chrono::{DateTime, Datelike, FixedOffset, Local, Utc}; use chrono::{DateTime, Datelike, FixedOffset, Local, Utc};
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use typst::diag::{FileError, FileResult}; use typst::diag::{FileError, FileResult};
use typst::foundations::{Bytes, Datetime, Dict, IntoValue}; use typst::foundations::{Bytes, Datetime, Dict, IntoValue};
@ -25,8 +24,8 @@ use crate::package;
/// Static `FileId` allocated for stdin. /// Static `FileId` allocated for stdin.
/// This is to ensure that a file is read in the correct way. /// This is to ensure that a file is read in the correct way.
static STDIN_ID: Lazy<FileId> = static STDIN_ID: LazyLock<FileId> =
Lazy::new(|| FileId::new_fake(VirtualPath::new("<stdin>"))); LazyLock::new(|| FileId::new_fake(VirtualPath::new("<stdin>")));
/// A world that provides access to the operating system. /// A world that provides access to the operating system.
pub struct SystemWorld { pub struct SystemWorld {

View File

@ -30,7 +30,6 @@ icu_provider_adapters = { workspace = true }
icu_provider_blob = { workspace = true } icu_provider_blob = { workspace = true }
icu_segmenter = { workspace = true } icu_segmenter = { workspace = true }
kurbo = { workspace = true } kurbo = { workspace = true }
once_cell = { workspace = true }
rustybuzz = { workspace = true } rustybuzz = { workspace = true }
smallvec = { workspace = true } smallvec = { workspace = true }
ttf-parser = { workspace = true } ttf-parser = { workspace = true }

View File

@ -1,4 +1,5 @@
use once_cell::unsync::Lazy; use std::cell::LazyCell;
use smallvec::SmallVec; use smallvec::SmallVec;
use typst_library::diag::SourceResult; use typst_library::diag::SourceResult;
use typst_library::engine::Engine; use typst_library::engine::Engine;
@ -79,8 +80,8 @@ pub fn layout_single_block(
.map(|s| s.map(Stroke::unwrap_or_default)); .map(|s| s.map(Stroke::unwrap_or_default));
// Only fetch these if necessary (for clipping or filling/stroking). // Only fetch these if necessary (for clipping or filling/stroking).
let outset = Lazy::new(|| elem.outset(styles).unwrap_or_default()); let outset = LazyCell::new(|| elem.outset(styles).unwrap_or_default());
let radius = Lazy::new(|| elem.radius(styles).unwrap_or_default()); let radius = LazyCell::new(|| elem.radius(styles).unwrap_or_default());
// Clip the contents, if requested. // Clip the contents, if requested.
if elem.clip(styles) { if elem.clip(styles) {
@ -194,8 +195,8 @@ pub fn layout_multi_block(
.map(|s| s.map(Stroke::unwrap_or_default)); .map(|s| s.map(Stroke::unwrap_or_default));
// Only fetch these if necessary (for clipping or filling/stroking). // Only fetch these if necessary (for clipping or filling/stroking).
let outset = Lazy::new(|| elem.outset(styles).unwrap_or_default()); let outset = LazyCell::new(|| elem.outset(styles).unwrap_or_default());
let radius = Lazy::new(|| elem.radius(styles).unwrap_or_default()); let radius = LazyCell::new(|| elem.radius(styles).unwrap_or_default());
// Fetch/compute these outside of the loop. // Fetch/compute these outside of the loop.
let clip = elem.clip(styles); let clip = elem.clip(styles);

View File

@ -1,11 +1,10 @@
use std::cell::RefCell; use std::cell::{LazyCell, RefCell};
use std::fmt::{self, Debug, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::hash::Hash; use std::hash::Hash;
use bumpalo::boxed::Box as BumpBox; use bumpalo::boxed::Box as BumpBox;
use bumpalo::Bump; use bumpalo::Bump;
use comemo::{Track, Tracked, TrackedMut}; use comemo::{Track, Tracked, TrackedMut};
use once_cell::unsync::Lazy;
use typst_library::diag::{bail, SourceResult}; use typst_library::diag::{bail, SourceResult};
use typst_library::engine::{Engine, Route, Sink, Traced}; use typst_library::engine::{Engine, Route, Sink, Traced};
use typst_library::foundations::{Packed, Resolve, Smart, StyleChain}; use typst_library::foundations::{Packed, Resolve, Smart, StyleChain};
@ -182,7 +181,7 @@ impl<'a> Collector<'a, '_, '_> {
_ => None, _ => None,
}; };
let fallback = Lazy::new(|| ParElem::spacing_in(styles)); let fallback = LazyCell::new(|| ParElem::spacing_in(styles));
let spacing = |amount| match amount { let spacing = |amount| match amount {
Smart::Auto => Child::Rel((*fallback).into(), 4), Smart::Auto => Child::Rel((*fallback).into(), 4),
Smart::Custom(Spacing::Rel(rel)) => Child::Rel(rel.resolve(styles), 3), Smart::Custom(Spacing::Rel(rel)) => Child::Rel(rel.resolve(styles), 3),

View File

@ -1,4 +1,5 @@
use once_cell::unsync::Lazy; use std::cell::LazyCell;
use typst_library::diag::SourceResult; use typst_library::diag::SourceResult;
use typst_library::engine::Engine; use typst_library::engine::Engine;
use typst_library::foundations::{Packed, StyleChain}; use typst_library::foundations::{Packed, StyleChain};
@ -56,8 +57,8 @@ pub fn layout_box(
.map(|s| s.map(Stroke::unwrap_or_default)); .map(|s| s.map(Stroke::unwrap_or_default));
// Only fetch these if necessary (for clipping or filling/stroking). // Only fetch these if necessary (for clipping or filling/stroking).
let outset = Lazy::new(|| elem.outset(styles).unwrap_or_default()); let outset = LazyCell::new(|| elem.outset(styles).unwrap_or_default());
let radius = Lazy::new(|| elem.radius(styles).unwrap_or_default()); let radius = LazyCell::new(|| elem.radius(styles).unwrap_or_default());
// Clip the contents, if requested. // Clip the contents, if requested.
if elem.clip(styles) { if elem.clip(styles) {

View File

@ -1,4 +1,5 @@
use std::ops::{Add, Sub}; use std::ops::{Add, Sub};
use std::sync::LazyLock;
use az::SaturatingAs; use az::SaturatingAs;
use icu_properties::maps::{CodePointMapData, CodePointMapDataBorrowed}; use icu_properties::maps::{CodePointMapData, CodePointMapDataBorrowed};
@ -7,7 +8,6 @@ use icu_provider::AsDeserializingBufferProvider;
use icu_provider_adapters::fork::ForkByKeyProvider; use icu_provider_adapters::fork::ForkByKeyProvider;
use icu_provider_blob::BlobDataProvider; use icu_provider_blob::BlobDataProvider;
use icu_segmenter::LineSegmenter; use icu_segmenter::LineSegmenter;
use once_cell::sync::Lazy;
use typst_library::engine::Engine; use typst_library::engine::Engine;
use typst_library::layout::{Abs, Em}; use typst_library::layout::{Abs, Em};
use typst_library::model::Linebreaks; use typst_library::model::Linebreaks;
@ -40,11 +40,11 @@ fn blob() -> BlobDataProvider {
} }
/// The general line break segmenter. /// The general line break segmenter.
static SEGMENTER: Lazy<LineSegmenter> = static SEGMENTER: LazyLock<LineSegmenter> =
Lazy::new(|| LineSegmenter::try_new_lstm_with_buffer_provider(&blob()).unwrap()); LazyLock::new(|| LineSegmenter::try_new_lstm_with_buffer_provider(&blob()).unwrap());
/// The line break segmenter for Chinese/Japanese text. /// The line break segmenter for Chinese/Japanese text.
static CJ_SEGMENTER: Lazy<LineSegmenter> = Lazy::new(|| { static CJ_SEGMENTER: LazyLock<LineSegmenter> = LazyLock::new(|| {
let cj_blob = let cj_blob =
BlobDataProvider::try_new_from_static_blob(typst_assets::icu::ICU_CJ_SEGMENT) BlobDataProvider::try_new_from_static_blob(typst_assets::icu::ICU_CJ_SEGMENT)
.unwrap(); .unwrap();
@ -53,7 +53,7 @@ static CJ_SEGMENTER: Lazy<LineSegmenter> = Lazy::new(|| {
}); });
/// The Unicode line break properties for each code point. /// The Unicode line break properties for each code point.
static LINEBREAK_DATA: Lazy<CodePointMapData<LineBreak>> = Lazy::new(|| { static LINEBREAK_DATA: LazyLock<CodePointMapData<LineBreak>> = LazyLock::new(|| {
icu_properties::maps::load_line_break(&blob().as_deserializing()).unwrap() icu_properties::maps::load_line_break(&blob().as_deserializing()).unwrap()
}); });

View File

@ -1,4 +1,5 @@
use once_cell::unsync::Lazy; use std::cell::LazyCell;
use typst_library::diag::{bail, SourceResult}; use typst_library::diag::{bail, SourceResult};
use typst_library::engine::Engine; use typst_library::engine::Engine;
use typst_library::foundations::{Content, Packed, Resolve, Smart, StyleChain}; use typst_library::foundations::{Content, Packed, Resolve, Smart, StyleChain};
@ -113,7 +114,7 @@ fn resolve_scale(
}) })
} }
let size = Lazy::new(|| { let size = LazyCell::new(|| {
let pod = Region::new(container, Axes::splat(false)); let pod = Region::new(container, Axes::splat(false));
let frame = crate::layout_frame(engine, &elem.body, locator, styles, pod)?; let frame = crate::layout_frame(engine, &elem.body, locator, styles, pod)?;
SourceResult::Ok(frame.size()) SourceResult::Ok(frame.size())

View File

@ -37,7 +37,6 @@ indexmap = { workspace = true }
kamadak-exif = { workspace = true } kamadak-exif = { workspace = true }
kurbo = { workspace = true } kurbo = { workspace = true }
lipsum = { workspace = true } lipsum = { workspace = true }
once_cell = { workspace = true }
palette = { workspace = true } palette = { workspace = true }
phf = { workspace = true } phf = { workspace = true }
png = { workspace = true } png = { workspace = true }

View File

@ -3,9 +3,9 @@ use std::cmp::Ordering;
use std::fmt::{self, Debug}; use std::fmt::{self, Debug};
use std::hash::Hash; use std::hash::Hash;
use std::ptr::NonNull; use std::ptr::NonNull;
use std::sync::LazyLock;
use ecow::EcoString; use ecow::EcoString;
use once_cell::sync::Lazy;
use smallvec::SmallVec; use smallvec::SmallVec;
#[doc(inline)] #[doc(inline)]
pub use typst_macros::elem; pub use typst_macros::elem;
@ -292,9 +292,9 @@ pub struct NativeElementData {
pub field_from_styles: fn(u8, StyleChain) -> Result<Value, FieldAccessError>, pub field_from_styles: fn(u8, StyleChain) -> Result<Value, FieldAccessError>,
/// Gets the localized name for this element (see [`LocalName`][crate::text::LocalName]). /// Gets the localized name for this element (see [`LocalName`][crate::text::LocalName]).
pub local_name: Option<fn(Lang, Option<Region>) -> &'static str>, pub local_name: Option<fn(Lang, Option<Region>) -> &'static str>,
pub scope: Lazy<Scope>, pub scope: LazyLock<Scope>,
/// A list of parameter information for each field. /// A list of parameter information for each field.
pub params: Lazy<Vec<ParamInfo>>, pub params: LazyLock<Vec<ParamInfo>>,
} }
impl From<&'static NativeElementData> for Element { impl From<&'static NativeElementData> for Element {

View File

@ -2,11 +2,10 @@
pub use typst_macros::func; pub use typst_macros::func;
use std::fmt::{self, Debug, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::sync::Arc; use std::sync::{Arc, LazyLock};
use comemo::{Tracked, TrackedMut}; use comemo::{Tracked, TrackedMut};
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy;
use typst_syntax::{ast, Span, SyntaxNode}; use typst_syntax::{ast, Span, SyntaxNode};
use typst_utils::{singleton, LazyHash, Static}; use typst_utils::{singleton, LazyHash, Static};
@ -463,11 +462,11 @@ pub struct NativeFuncData {
pub keywords: &'static [&'static str], pub keywords: &'static [&'static str],
/// Whether this function makes use of context. /// Whether this function makes use of context.
pub contextual: bool, pub contextual: bool,
pub scope: Lazy<Scope>, pub scope: LazyLock<Scope>,
/// A list of parameter information for each parameter. /// A list of parameter information for each parameter.
pub params: Lazy<Vec<ParamInfo>>, pub params: LazyLock<Vec<ParamInfo>>,
/// Information about the return value of this function. /// Information about the return value of this function.
pub returns: Lazy<CastInfo>, pub returns: LazyLock<CastInfo>,
} }
impl From<&'static NativeFuncData> for Func { impl From<&'static NativeFuncData> for Func {

View File

@ -71,7 +71,6 @@ pub use typst_macros::{scope, ty};
pub use { pub use {
ecow::{eco_format, eco_vec}, ecow::{eco_format, eco_vec},
indexmap::IndexMap, indexmap::IndexMap,
once_cell::sync::Lazy,
}; };
use ecow::EcoString; use ecow::EcoString;

View File

@ -3,9 +3,9 @@ pub use typst_macros::{scope, ty};
use std::cmp::Ordering; use std::cmp::Ordering;
use std::fmt::{self, Debug, Display, Formatter}; use std::fmt::{self, Debug, Display, Formatter};
use std::sync::LazyLock;
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy;
use typst_utils::Static; use typst_utils::Static;
use crate::diag::StrResult; use crate::diag::StrResult;
@ -207,8 +207,8 @@ pub struct NativeTypeData {
/// A list of alternate search terms for this type. /// A list of alternate search terms for this type.
pub keywords: &'static [&'static str], pub keywords: &'static [&'static str],
/// The constructor for this type. /// The constructor for this type.
pub constructor: Lazy<Option<&'static NativeFuncData>>, pub constructor: LazyLock<Option<&'static NativeFuncData>>,
pub scope: Lazy<Scope>, pub scope: LazyLock<Scope>,
} }
impl From<&'static NativeTypeData> for Type { impl From<&'static NativeTypeData> for Type {

View File

@ -4,7 +4,7 @@ use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::num::NonZeroUsize; use std::num::NonZeroUsize;
use std::path::Path; use std::path::Path;
use std::sync::Arc; use std::sync::{Arc, LazyLock};
use comemo::Tracked; use comemo::Tracked;
use ecow::{eco_format, EcoString, EcoVec}; use ecow::{eco_format, EcoString, EcoVec};
@ -15,7 +15,6 @@ use hayagriva::{
SpecificLocator, SpecificLocator,
}; };
use indexmap::IndexMap; use indexmap::IndexMap;
use once_cell::sync::Lazy;
use smallvec::{smallvec, SmallVec}; use smallvec::{smallvec, SmallVec};
use typed_arena::Arena; use typed_arena::Arena;
use typst_syntax::{Span, Spanned}; use typst_syntax::{Span, Spanned};
@ -633,8 +632,8 @@ impl<'a> Generator<'a> {
/// Drives hayagriva's citation driver. /// Drives hayagriva's citation driver.
fn drive(&mut self) -> hayagriva::Rendered { fn drive(&mut self) -> hayagriva::Rendered {
static LOCALES: Lazy<Vec<citationberg::Locale>> = static LOCALES: LazyLock<Vec<citationberg::Locale>> =
Lazy::new(hayagriva::archive::locales); LazyLock::new(hayagriva::archive::locales);
let database = self.bibliography.bibliography(); let database = self.bibliography.bibliography();
let bibliography_style = self.bibliography.style(StyleChain::default()); let bibliography_style = self.bibliography.style(StyleChain::default());

View File

@ -29,12 +29,12 @@ pub use self::smartquote::*;
pub use self::space::*; pub use self::space::*;
use std::fmt::{self, Debug, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::sync::LazyLock;
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use icu_properties::sets::CodePointSetData; use icu_properties::sets::CodePointSetData;
use icu_provider::AsDeserializingBufferProvider; use icu_provider::AsDeserializingBufferProvider;
use icu_provider_blob::BlobDataProvider; use icu_provider_blob::BlobDataProvider;
use once_cell::sync::Lazy;
use rustybuzz::Feature; use rustybuzz::Feature;
use smallvec::SmallVec; use smallvec::SmallVec;
use ttf_parser::Tag; use ttf_parser::Tag;
@ -1275,7 +1275,7 @@ cast! {
/// Whether a codepoint is Unicode `Default_Ignorable`. /// Whether a codepoint is Unicode `Default_Ignorable`.
pub fn is_default_ignorable(c: char) -> bool { pub fn is_default_ignorable(c: char) -> bool {
/// The set of Unicode default ignorables. /// The set of Unicode default ignorables.
static DEFAULT_IGNORABLE_DATA: Lazy<CodePointSetData> = Lazy::new(|| { static DEFAULT_IGNORABLE_DATA: LazyLock<CodePointSetData> = LazyLock::new(|| {
icu_properties::sets::load_default_ignorable_code_point( icu_properties::sets::load_default_ignorable_code_point(
&BlobDataProvider::try_new_from_static_blob(typst_assets::icu::ICU) &BlobDataProvider::try_new_from_static_blob(typst_assets::icu::ICU)
.unwrap() .unwrap()

View File

@ -1,10 +1,9 @@
use std::cell::LazyCell;
use std::hash::Hash; use std::hash::Hash;
use std::ops::Range; use std::ops::Range;
use std::sync::Arc; use std::sync::{Arc, LazyLock};
use ecow::{eco_format, EcoString, EcoVec}; use ecow::{eco_format, EcoString, EcoVec};
use once_cell::sync::Lazy;
use once_cell::unsync::Lazy as UnsyncLazy;
use syntect::highlighting::{self as synt, Theme}; use syntect::highlighting::{self as synt, Theme};
use syntect::parsing::{SyntaxDefinition, SyntaxSet, SyntaxSetBuilder}; use syntect::parsing::{SyntaxDefinition, SyntaxSet, SyntaxSetBuilder};
use typst_syntax::{split_newlines, LinkedNode, Span, Spanned}; use typst_syntax::{split_newlines, LinkedNode, Span, Spanned};
@ -325,7 +324,7 @@ impl Packed<RawElem> {
.map(|s| s.to_lowercase()) .map(|s| s.to_lowercase())
.or(Some("txt".into())); .or(Some("txt".into()));
let extra_syntaxes = UnsyncLazy::new(|| { let extra_syntaxes = LazyCell::new(|| {
load_syntaxes(&elem.syntaxes(styles), &elem.syntaxes_data(styles)).unwrap() load_syntaxes(&elem.syntaxes(styles), &elem.syntaxes_data(styles)).unwrap()
}); });
let non_highlighted_result = |lines: EcoVec<(EcoString, Span)>| { let non_highlighted_result = |lines: EcoVec<(EcoString, Span)>| {
@ -838,11 +837,11 @@ fn parse_theme(
/// ///
/// Syntax set is generated from the syntaxes from the `bat` project /// Syntax set is generated from the syntaxes from the `bat` project
/// <https://github.com/sharkdp/bat/tree/master/assets/syntaxes> /// <https://github.com/sharkdp/bat/tree/master/assets/syntaxes>
pub static RAW_SYNTAXES: Lazy<syntect::parsing::SyntaxSet> = pub static RAW_SYNTAXES: LazyLock<syntect::parsing::SyntaxSet> =
Lazy::new(two_face::syntax::extra_no_newlines); LazyLock::new(two_face::syntax::extra_no_newlines);
/// The default theme used for syntax highlighting. /// The default theme used for syntax highlighting.
pub static RAW_THEME: Lazy<synt::Theme> = Lazy::new(|| synt::Theme { pub static RAW_THEME: LazyLock<synt::Theme> = LazyLock::new(|| synt::Theme {
name: Some("Typst Light".into()), name: Some("Typst Light".into()),
author: Some("The Typst Project Developers".into()), author: Some("The Typst Project Developers".into()),
settings: synt::ThemeSettings::default(), settings: synt::ThemeSettings::default(),

View File

@ -1,9 +1,9 @@
use std::fmt::{self, Debug, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
use std::str::FromStr; use std::str::FromStr;
use std::sync::LazyLock;
use ecow::{eco_format, EcoString, EcoVec}; use ecow::{eco_format, EcoString, EcoVec};
use once_cell::sync::Lazy;
use palette::encoding::{self, Linear}; use palette::encoding::{self, Linear};
use palette::{ use palette::{
Alpha, Darken, Desaturate, FromColor, Lighten, OklabHue, RgbHue, Saturate, ShiftHue, Alpha, Darken, Desaturate, FromColor, Lighten, OklabHue, RgbHue, Saturate, ShiftHue,
@ -33,17 +33,18 @@ pub type Luma = palette::luma::Lumaa<encoding::Srgb, f32>;
/// to convert from CMYK to RGB. It is based on the CGATS TR 001-1995 /// to convert from CMYK to RGB. It is based on the CGATS TR 001-1995
/// specification. See /// specification. See
/// <https://github.com/saucecontrol/Compact-ICC-Profiles#cmyk>. /// <https://github.com/saucecontrol/Compact-ICC-Profiles#cmyk>.
static CMYK_TO_XYZ: Lazy<Box<Profile>> = static CMYK_TO_XYZ: LazyLock<Box<Profile>> = LazyLock::new(|| {
Lazy::new(|| Profile::new_from_slice(typst_assets::icc::CMYK_TO_XYZ, false).unwrap()); Profile::new_from_slice(typst_assets::icc::CMYK_TO_XYZ, false).unwrap()
});
/// The target sRGB profile. /// The target sRGB profile.
static SRGB_PROFILE: Lazy<Box<Profile>> = Lazy::new(|| { static SRGB_PROFILE: LazyLock<Box<Profile>> = LazyLock::new(|| {
let mut out = Profile::new_sRGB(); let mut out = Profile::new_sRGB();
out.precache_output_transform(); out.precache_output_transform();
out out
}); });
static TO_SRGB: Lazy<qcms::Transform> = Lazy::new(|| { static TO_SRGB: LazyLock<qcms::Transform> = LazyLock::new(|| {
qcms::Transform::new_to( qcms::Transform::new_to(
&CMYK_TO_XYZ, &CMYK_TO_XYZ,
&SRGB_PROFILE, &SRGB_PROFILE,

View File

@ -432,8 +432,8 @@ fn create_default_static(field: &Field) -> TokenStream {
}; };
quote! { quote! {
static #const_ident: ::once_cell::sync::Lazy<#ty> = static #const_ident: ::std::sync::LazyLock<#ty> =
::once_cell::sync::Lazy::new(#init); ::std::sync::LazyLock::new(#init);
} }
} }
@ -660,8 +660,8 @@ fn create_native_elem_impl(element: &Elem) -> TokenStream {
field_name: |id| id.try_into().ok().map(Fields::to_str), field_name: |id| id.try_into().ok().map(Fields::to_str),
field_from_styles: <#ident as #foundations::Fields>::field_from_styles, field_from_styles: <#ident as #foundations::Fields>::field_from_styles,
local_name: #local_name, local_name: #local_name,
scope: #foundations::Lazy::new(|| #scope), scope: ::std::sync::LazyLock::new(|| #scope),
params: #foundations::Lazy::new(|| ::std::vec![#(#params),*]) params: ::std::sync::LazyLock::new(|| ::std::vec![#(#params),*])
} }
}; };

View File

@ -321,9 +321,9 @@ fn create_func_data(func: &Func) -> TokenStream {
docs: #docs, docs: #docs,
keywords: &[#(#keywords),*], keywords: &[#(#keywords),*],
contextual: #contextual, contextual: #contextual,
scope: #foundations::Lazy::new(|| #scope), scope: ::std::sync::LazyLock::new(|| #scope),
params: #foundations::Lazy::new(|| ::std::vec![#(#params),*]), params: ::std::sync::LazyLock::new(|| ::std::vec![#(#params),*]),
returns: #foundations::Lazy::new(|| <#returns as #foundations::Reflect>::output()), returns: ::std::sync::LazyLock::new(|| <#returns as #foundations::Reflect>::output()),
} }
} }
} }

View File

@ -102,8 +102,8 @@ fn create(ty: &Type, item: Option<&syn::Item>) -> TokenStream {
title: #title, title: #title,
docs: #docs, docs: #docs,
keywords: &[#(#keywords),*], keywords: &[#(#keywords),*],
constructor: #foundations::Lazy::new(|| #constructor), constructor: ::std::sync::LazyLock::new(|| #constructor),
scope: #foundations::Lazy::new(|| #scope), scope: ::std::sync::LazyLock::new(|| #scope),
} }
}; };

View File

@ -27,7 +27,6 @@ ecow = { workspace = true }
image = { workspace = true } image = { workspace = true }
indexmap = { workspace = true } indexmap = { workspace = true }
miniz_oxide = { workspace = true } miniz_oxide = { workspace = true }
once_cell = { workspace = true }
pdf-writer = { workspace = true } pdf-writer = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
subsetter = { workspace = true } subsetter = { workspace = true }

View File

@ -1,5 +1,6 @@
use std::sync::LazyLock;
use arrayvec::ArrayVec; use arrayvec::ArrayVec;
use once_cell::sync::Lazy;
use pdf_writer::{writers, Chunk, Dict, Filter, Name, Ref}; use pdf_writer::{writers, Chunk, Dict, Filter, Name, Ref};
use typst_library::diag::{bail, SourceResult}; use typst_library::diag::{bail, SourceResult};
use typst_library::visualize::{Color, ColorSpace, Paint}; use typst_library::visualize::{Color, ColorSpace, Paint};
@ -13,10 +14,10 @@ pub const D65_GRAY: Name<'static> = Name(b"d65gray");
pub const LINEAR_SRGB: Name<'static> = Name(b"linearrgb"); pub const LINEAR_SRGB: Name<'static> = Name(b"linearrgb");
// The ICC profiles. // The ICC profiles.
static SRGB_ICC_DEFLATED: Lazy<Vec<u8>> = static SRGB_ICC_DEFLATED: LazyLock<Vec<u8>> =
Lazy::new(|| deflate(typst_assets::icc::S_RGB_V4)); LazyLock::new(|| deflate(typst_assets::icc::S_RGB_V4));
static GRAY_ICC_DEFLATED: Lazy<Vec<u8>> = static GRAY_ICC_DEFLATED: LazyLock<Vec<u8>> =
Lazy::new(|| deflate(typst_assets::icc::S_GREY_V4)); LazyLock::new(|| deflate(typst_assets::icc::S_GREY_V4));
/// The color spaces present in the PDF document /// The color spaces present in the PDF document
#[derive(Default)] #[derive(Default)]

View File

@ -22,7 +22,6 @@ arrayvec = { workspace = true }
bumpalo = { workspace = true } bumpalo = { workspace = true }
comemo = { workspace = true } comemo = { workspace = true }
ecow = { workspace = true } ecow = { workspace = true }
once_cell = { workspace = true }
regex = { workspace = true } regex = { workspace = true }
[lints] [lints]

View File

@ -5,12 +5,12 @@
//! further. //! further.
use std::borrow::Cow; use std::borrow::Cow;
use std::cell::LazyCell;
use arrayvec::ArrayVec; use arrayvec::ArrayVec;
use bumpalo::collections::{String as BumpString, Vec as BumpVec}; use bumpalo::collections::{String as BumpString, Vec as BumpVec};
use comemo::Track; use comemo::Track;
use ecow::EcoString; use ecow::EcoString;
use once_cell::unsync::Lazy;
use typst_library::diag::{bail, At, SourceResult}; use typst_library::diag::{bail, At, SourceResult};
use typst_library::engine::Engine; use typst_library::engine::Engine;
use typst_library::foundations::{ use typst_library::foundations::{
@ -420,7 +420,7 @@ fn verdict<'a>(
// it to determine whether a particular show rule was already applied to the // it to determine whether a particular show rule was already applied to the
// `target` previously. For this purpose, show rules are indexed from the // `target` previously. For this purpose, show rules are indexed from the
// top of the chain as the chain might grow to the bottom. // top of the chain as the chain might grow to the bottom.
let depth = Lazy::new(|| styles.recipes().count()); let depth = LazyCell::new(|| styles.recipes().count());
for (r, recipe) in styles.recipes().enumerate() { for (r, recipe) in styles.recipes().enumerate() {
// We're not interested in recipes that don't match. // We're not interested in recipes that don't match.
@ -1032,7 +1032,7 @@ fn find_regex_match_in_str<'a>(
let mut revoked = SmallBitSet::new(); let mut revoked = SmallBitSet::new();
let mut leftmost: Option<(regex::Match, RecipeIndex, &Recipe)> = None; let mut leftmost: Option<(regex::Match, RecipeIndex, &Recipe)> = None;
let depth = Lazy::new(|| styles.recipes().count()); let depth = LazyCell::new(|| styles.recipes().count());
for entry in styles.entries() { for entry in styles.entries() {
let recipe = match &**entry { let recipe = match &**entry {

View File

@ -16,7 +16,6 @@ readme = { workspace = true }
typst-timing = { workspace = true } typst-timing = { workspace = true }
typst-utils = { workspace = true } typst-utils = { workspace = true }
ecow = { workspace = true } ecow = { workspace = true }
once_cell = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
toml = { workspace = true } toml = { workspace = true }
unicode-ident = { workspace = true } unicode-ident = { workspace = true }

View File

@ -2,16 +2,15 @@
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::sync::RwLock; use std::sync::{LazyLock, RwLock};
use once_cell::sync::Lazy;
use crate::package::PackageSpec; use crate::package::PackageSpec;
use crate::VirtualPath; use crate::VirtualPath;
/// The global package-path interner. /// The global package-path interner.
static INTERNER: Lazy<RwLock<Interner>> = static INTERNER: LazyLock<RwLock<Interner>> = LazyLock::new(|| {
Lazy::new(|| RwLock::new(Interner { to_id: HashMap::new(), from_id: Vec::new() })); RwLock::new(Interner { to_id: HashMap::new(), from_id: Vec::new() })
});
/// A package-path interner. /// A package-path interner.
struct Interner { struct Interner {

View File

@ -2,8 +2,7 @@
#[macro_export] #[macro_export]
macro_rules! singleton { macro_rules! singleton {
($ty:ty, $value:expr) => {{ ($ty:ty, $value:expr) => {{
static VALUE: $crate::once_cell::sync::Lazy<$ty> = static VALUE: ::std::sync::LazyLock<$ty> = ::std::sync::LazyLock::new(|| $value);
$crate::once_cell::sync::Lazy::new(|| $value);
&*VALUE &*VALUE
}}; }};
} }

View File

@ -1,13 +1,12 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::{self, Debug, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::sync::RwLock; use std::sync::{LazyLock, RwLock};
use once_cell::sync::Lazy;
/// The global string interner. /// The global string interner.
static INTERNER: Lazy<RwLock<Interner>> = static INTERNER: LazyLock<RwLock<Interner>> = LazyLock::new(|| {
Lazy::new(|| RwLock::new(Interner { to_id: HashMap::new(), from_id: Vec::new() })); RwLock::new(Interner { to_id: HashMap::new(), from_id: Vec::new() })
});
/// A string interner. /// A string interner.
struct Interner { struct Interner {

View File

@ -22,7 +22,6 @@ typst-dev-assets = { workspace = true }
clap = { workspace = true, optional = true } clap = { workspace = true, optional = true }
ecow = { workspace = true } ecow = { workspace = true }
heck = { workspace = true } heck = { workspace = true }
once_cell = { workspace = true }
pulldown-cmark = { workspace = true } pulldown-cmark = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
serde_json = { workspace = true, optional = true } serde_json = { workspace = true, optional = true }

View File

@ -12,9 +12,9 @@ pub use self::model::*;
use std::collections::HashSet; use std::collections::HashSet;
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy;
use serde::Deserialize; use serde::Deserialize;
use serde_yaml as yaml; use serde_yaml as yaml;
use std::sync::LazyLock;
use typst::diag::{bail, StrResult}; use typst::diag::{bail, StrResult};
use typst::foundations::{ use typst::foundations::{
AutoValue, Bytes, CastInfo, Category, Func, Module, NoneValue, ParamInfo, Repr, AutoValue, Bytes, CastInfo, Category, Func, Module, NoneValue, ParamInfo, Repr,
@ -37,7 +37,7 @@ macro_rules! load {
}; };
} }
static GROUPS: Lazy<Vec<GroupData>> = Lazy::new(|| { static GROUPS: LazyLock<Vec<GroupData>> = LazyLock::new(|| {
let mut groups: Vec<GroupData> = let mut groups: Vec<GroupData> =
yaml::from_str(load!("reference/groups.yml")).unwrap(); yaml::from_str(load!("reference/groups.yml")).unwrap();
for group in &mut groups { for group in &mut groups {
@ -54,7 +54,7 @@ static GROUPS: Lazy<Vec<GroupData>> = Lazy::new(|| {
groups groups
}); });
static LIBRARY: Lazy<LazyHash<Library>> = Lazy::new(|| { static LIBRARY: LazyLock<LazyHash<Library>> = LazyLock::new(|| {
let mut lib = Library::default(); let mut lib = Library::default();
let scope = lib.global.scope_mut(); let scope = lib.global.scope_mut();
@ -74,7 +74,7 @@ static LIBRARY: Lazy<LazyHash<Library>> = Lazy::new(|| {
LazyHash::new(lib) LazyHash::new(lib)
}); });
static FONTS: Lazy<(LazyHash<FontBook>, Vec<Font>)> = Lazy::new(|| { static FONTS: LazyLock<(LazyHash<FontBook>, Vec<Font>)> = LazyLock::new(|| {
let fonts: Vec<_> = typst_assets::fonts() let fonts: Vec<_> = typst_assets::fonts()
.chain(typst_dev_assets::fonts()) .chain(typst_dev_assets::fonts())
.flat_map(|data| Font::iter(Bytes::from_static(data))) .flat_map(|data| Font::iter(Bytes::from_static(data)))

View File

@ -22,7 +22,6 @@ typst-svg = { workspace = true }
clap = { workspace = true } clap = { workspace = true }
comemo = { workspace = true } comemo = { workspace = true }
ecow = { workspace = true } ecow = { workspace = true }
once_cell = { workspace = true }
oxipng = { workspace = true } oxipng = { workspace = true }
parking_lot = { workspace = true } parking_lot = { workspace = true }
rayon = { workspace = true } rayon = { workspace = true }

View File

@ -3,9 +3,9 @@ use std::fmt::{self, Display, Formatter};
use std::ops::Range; use std::ops::Range;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::str::FromStr; use std::str::FromStr;
use std::sync::LazyLock;
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy;
use typst::syntax::package::PackageVersion; use typst::syntax::package::PackageVersion;
use typst::syntax::{is_id_continue, is_ident, is_newline, FileId, Source, VirtualPath}; use typst::syntax::{is_id_continue, is_ident, is_newline, FileId, Source, VirtualPath};
use unscanny::Scanner; use unscanny::Scanner;
@ -390,7 +390,7 @@ impl<'a> Parser<'a> {
/// Whether a test is within the selected set to run. /// Whether a test is within the selected set to run.
fn selected(name: &str, abs: PathBuf) -> bool { fn selected(name: &str, abs: PathBuf) -> bool {
static SKIPPED: Lazy<HashSet<&'static str>> = Lazy::new(|| { static SKIPPED: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
String::leak(std::fs::read_to_string(crate::SKIP_PATH).unwrap()) String::leak(std::fs::read_to_string(crate::SKIP_PATH).unwrap())
.lines() .lines()
.map(|line| line.trim()) .map(|line| line.trim())

View File

@ -8,10 +8,10 @@ mod run;
mod world; mod world;
use std::path::Path; use std::path::Path;
use std::sync::LazyLock;
use std::time::Duration; use std::time::Duration;
use clap::Parser; use clap::Parser;
use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use rayon::iter::{ParallelBridge, ParallelIterator}; use rayon::iter::{ParallelBridge, ParallelIterator};
@ -19,7 +19,7 @@ use crate::args::{CliArguments, Command};
use crate::logger::Logger; use crate::logger::Logger;
/// The parsed command line arguments. /// The parsed command line arguments.
static ARGS: Lazy<CliArguments> = Lazy::new(CliArguments::parse); static ARGS: LazyLock<CliArguments> = LazyLock::new(CliArguments::parse);
/// The directory where the test suite is located. /// The directory where the test suite is located.
const SUITE_PATH: &str = "tests/suite"; const SUITE_PATH: &str = "tests/suite";