Replace all Prehashed with LazyHash (#4127)

This commit is contained in:
Laurenz 2024-05-13 19:54:34 +02:00 committed by GitHub
parent 95cd6adf24
commit 2d32ac73b6
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 54 additions and 56 deletions

2
Cargo.lock generated
View File

@ -2759,10 +2759,10 @@ dependencies = [
name = "typst-syntax" name = "typst-syntax"
version = "0.11.0" version = "0.11.0"
dependencies = [ dependencies = [
"comemo",
"ecow", "ecow",
"once_cell", "once_cell",
"serde", "serde",
"typst-utils",
"unicode-ident", "unicode-ident",
"unicode-math-class", "unicode-math-class",
"unicode-script", "unicode-script",

View File

@ -5,7 +5,6 @@ use std::sync::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 comemo::Prehashed;
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
@ -13,6 +12,7 @@ use typst::diag::{FileError, FileResult};
use typst::foundations::{Bytes, Datetime, Dict, IntoValue}; use typst::foundations::{Bytes, Datetime, Dict, IntoValue};
use typst::syntax::{FileId, Source, VirtualPath}; use typst::syntax::{FileId, Source, VirtualPath};
use typst::text::{Font, FontBook}; use typst::text::{Font, FontBook};
use typst::utils::LazyHash;
use typst::{Library, World}; use typst::{Library, World};
use typst_timing::{timed, TimingScope}; use typst_timing::{timed, TimingScope};
@ -34,9 +34,9 @@ pub struct SystemWorld {
/// The input path. /// The input path.
main: FileId, main: FileId,
/// Typst's standard library. /// Typst's standard library.
library: Prehashed<Library>, library: LazyHash<Library>,
/// Metadata about discovered fonts. /// Metadata about discovered fonts.
book: Prehashed<FontBook>, book: LazyHash<FontBook>,
/// Locations of and storage for lazily loaded fonts. /// Locations of and storage for lazily loaded fonts.
fonts: Vec<FontSlot>, fonts: Vec<FontSlot>,
/// Maps file ids to source files and buffers. /// Maps file ids to source files and buffers.
@ -114,8 +114,8 @@ impl SystemWorld {
workdir: std::env::current_dir().ok(), workdir: std::env::current_dir().ok(),
root, root,
main, main,
library: Prehashed::new(library), library: LazyHash::new(library),
book: Prehashed::new(searcher.book), book: LazyHash::new(searcher.book),
fonts: searcher.fonts, fonts: searcher.fonts,
slots: Mutex::new(HashMap::new()), slots: Mutex::new(HashMap::new()),
now, now,
@ -170,11 +170,11 @@ impl SystemWorld {
} }
impl World for SystemWorld { impl World for SystemWorld {
fn library(&self) -> &Prehashed<Library> { fn library(&self) -> &LazyHash<Library> {
&self.library &self.library
} }
fn book(&self) -> &Prehashed<FontBook> { fn book(&self) -> &LazyHash<FontBook> {
&self.book &self.book
} }

View File

@ -93,12 +93,12 @@ fn summarize_font_family<'a>(variants: impl Iterator<Item = &'a FontInfo>) -> Ec
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use comemo::Prehashed;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use typst::diag::{FileError, FileResult}; use typst::diag::{FileError, FileResult};
use typst::foundations::{Bytes, Datetime}; use typst::foundations::{Bytes, Datetime};
use typst::syntax::{FileId, Source}; use typst::syntax::{FileId, Source};
use typst::text::{Font, FontBook}; use typst::text::{Font, FontBook};
use typst::utils::LazyHash;
use typst::{Library, World}; use typst::{Library, World};
/// A world for IDE testing. /// A world for IDE testing.
@ -120,11 +120,11 @@ mod tests {
} }
impl World for TestWorld { impl World for TestWorld {
fn library(&self) -> &Prehashed<Library> { fn library(&self) -> &LazyHash<Library> {
&self.base.library &self.base.library
} }
fn book(&self) -> &Prehashed<FontBook> { fn book(&self) -> &LazyHash<FontBook> {
&self.base.book &self.base.book
} }
@ -155,8 +155,8 @@ mod tests {
/// Shared foundation of all test worlds. /// Shared foundation of all test worlds.
struct TestBase { struct TestBase {
library: Prehashed<Library>, library: LazyHash<Library>,
book: Prehashed<FontBook>, book: LazyHash<FontBook>,
fonts: Vec<Font>, fonts: Vec<Font>,
} }
@ -168,8 +168,8 @@ mod tests {
.collect(); .collect();
Self { Self {
library: Prehashed::new(Library::default()), library: LazyHash::new(Library::default()),
book: Prehashed::new(FontBook::from_fonts(&fonts)), book: LazyHash::new(FontBook::from_fonts(&fonts)),
fonts, fonts,
} }
} }

View File

@ -13,7 +13,7 @@ keywords = { workspace = true }
readme = { workspace = true } readme = { workspace = true }
[dependencies] [dependencies]
comemo = { workspace = true } typst-utils = { workspace = true }
ecow = { workspace = true } ecow = { workspace = true }
once_cell = { workspace = true } once_cell = { workspace = true }
serde = { workspace = true } serde = { workspace = true }

View File

@ -6,7 +6,7 @@ use std::iter::zip;
use std::ops::Range; use std::ops::Range;
use std::sync::Arc; use std::sync::Arc;
use comemo::Prehashed; use typst_utils::LazyHash;
use crate::reparser::reparse; use crate::reparser::reparse;
use crate::{is_newline, parse, FileId, LinkedNode, Span, SyntaxNode, VirtualPath}; use crate::{is_newline, parse, FileId, LinkedNode, Span, SyntaxNode, VirtualPath};
@ -24,8 +24,8 @@ pub struct Source(Arc<Repr>);
#[derive(Clone)] #[derive(Clone)]
struct Repr { struct Repr {
id: FileId, id: FileId,
text: Prehashed<String>, text: LazyHash<String>,
root: Prehashed<SyntaxNode>, root: LazyHash<SyntaxNode>,
lines: Vec<Line>, lines: Vec<Line>,
} }
@ -37,8 +37,8 @@ impl Source {
Self(Arc::new(Repr { Self(Arc::new(Repr {
id, id,
lines: lines(&text), lines: lines(&text),
text: Prehashed::new(text), text: LazyHash::new(text),
root: Prehashed::new(root), root: LazyHash::new(root),
})) }))
} }
@ -117,7 +117,7 @@ impl Source {
let inner = Arc::make_mut(&mut self.0); let inner = Arc::make_mut(&mut self.0);
// Update the text itself. // Update the text itself.
inner.text.update(|text| text.replace_range(replace.clone(), with)); inner.text.replace_range(replace.clone(), with);
// Remove invalidated line starts. // Remove invalidated line starts.
inner.lines.truncate(line + 1); inner.lines.truncate(line + 1);
@ -135,9 +135,7 @@ impl Source {
)); ));
// Incrementally reparse the replaced range. // Incrementally reparse the replaced range.
inner reparse(&mut inner.root, &inner.text, replace, with.len())
.root
.update(|root| reparse(root, &inner.text, replace, with.len()))
} }
/// Get the length of the file in UTF-8 encoded bytes. /// Get the length of the file in UTF-8 encoded bytes.

View File

@ -59,7 +59,7 @@ pub use typst_utils as utils;
use std::collections::HashSet; use std::collections::HashSet;
use std::ops::{Deref, Range}; use std::ops::{Deref, Range};
use comemo::{Prehashed, Track, Tracked, Validate}; use comemo::{Track, Tracked, Validate};
use ecow::{EcoString, EcoVec}; use ecow::{EcoString, EcoVec};
use typst_timing::{timed, TimingScope}; use typst_timing::{timed, TimingScope};
@ -75,6 +75,7 @@ use crate::model::Document;
use crate::syntax::package::PackageSpec; use crate::syntax::package::PackageSpec;
use crate::syntax::{FileId, Source, Span}; use crate::syntax::{FileId, Source, Span};
use crate::text::{Font, FontBook}; use crate::text::{Font, FontBook};
use crate::utils::LazyHash;
use crate::visualize::Color; use crate::visualize::Color;
/// Compile a source file into a fully layouted document. /// Compile a source file into a fully layouted document.
@ -194,10 +195,10 @@ pub trait World {
/// The standard library. /// The standard library.
/// ///
/// Can be created through `Library::build()`. /// Can be created through `Library::build()`.
fn library(&self) -> &Prehashed<Library>; fn library(&self) -> &LazyHash<Library>;
/// Metadata about all known fonts. /// Metadata about all known fonts.
fn book(&self) -> &Prehashed<FontBook>; fn book(&self) -> &LazyHash<FontBook>;
/// Access the main source file. /// Access the main source file.
fn main(&self) -> Source; fn main(&self) -> Source;
@ -234,11 +235,11 @@ pub trait World {
macro_rules! delegate_for_ptr { macro_rules! delegate_for_ptr {
($W:ident for $ptr:ty) => { ($W:ident for $ptr:ty) => {
impl<$W: World> World for $ptr { impl<$W: World> World for $ptr {
fn library(&self) -> &Prehashed<Library> { fn library(&self) -> &LazyHash<Library> {
self.deref().library() self.deref().library()
} }
fn book(&self) -> &Prehashed<FontBook> { fn book(&self) -> &LazyHash<FontBook> {
self.deref().book() self.deref().book()
} }

View File

@ -1,7 +1,6 @@
use std::hash::Hash; use std::hash::Hash;
use std::sync::Arc; use std::sync::Arc;
use comemo::Prehashed;
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use crate::diag::{bail, SourceResult}; use crate::diag::{bail, SourceResult};
@ -9,7 +8,7 @@ use crate::engine::Engine;
use crate::foundations::{func, repr, scope, ty, Content, Smart, StyleChain}; use crate::foundations::{func, repr, scope, ty, Content, Smart, StyleChain};
use crate::layout::{Abs, Axes, Frame, LayoutMultiple, Length, Regions, Size}; use crate::layout::{Abs, Axes, Frame, LayoutMultiple, Length, Regions, Size};
use crate::syntax::{Span, Spanned}; use crate::syntax::{Span, Spanned};
use crate::utils::Numeric; use crate::utils::{LazyHash, Numeric};
use crate::visualize::RelativeTo; use crate::visualize::RelativeTo;
use crate::World; use crate::World;
@ -102,7 +101,7 @@ pub struct Pattern(Arc<Repr>);
#[derive(Debug, Clone, Eq, PartialEq, Hash)] #[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct Repr { struct Repr {
/// The pattern's rendered content. /// The pattern's rendered content.
frame: Prehashed<Frame>, frame: LazyHash<Frame>,
/// The pattern's tile size. /// The pattern's tile size.
size: Size, size: Size,
/// The pattern's tile spacing. /// The pattern's tile spacing.
@ -209,7 +208,7 @@ impl Pattern {
Ok(Self(Arc::new(Repr { Ok(Self(Arc::new(Repr {
size: frame.size(), size: frame.size(),
frame: Prehashed::new(frame), frame: LazyHash::new(frame),
spacing: spacing.v.map(|l| l.abs), spacing: spacing.v.map(|l| l.abs),
relative, relative,
}))) })))

View File

@ -1,7 +1,6 @@
use std::fmt::{self, Debug, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::ops::Range; use std::ops::Range;
use comemo::Prehashed;
use ecow::EcoString; use ecow::EcoString;
use heck::{ToKebabCase, ToTitleCase}; use heck::{ToKebabCase, ToTitleCase};
use pulldown_cmark as md; use pulldown_cmark as md;
@ -13,6 +12,7 @@ use typst::foundations::{Bytes, Datetime};
use typst::layout::{Abs, Point, Size}; use typst::layout::{Abs, Point, Size};
use typst::syntax::{FileId, Source, VirtualPath}; use typst::syntax::{FileId, Source, VirtualPath};
use typst::text::{Font, FontBook}; use typst::text::{Font, FontBook};
use typst::utils::LazyHash;
use typst::{Library, World}; use typst::{Library, World};
use unscanny::Scanner; use unscanny::Scanner;
use yaml_front_matter::YamlFrontMatter; use yaml_front_matter::YamlFrontMatter;
@ -457,11 +457,11 @@ fn nest_heading(level: &mut md::HeadingLevel, nesting: usize) {
struct DocWorld(Source); struct DocWorld(Source);
impl World for DocWorld { impl World for DocWorld {
fn library(&self) -> &Prehashed<Library> { fn library(&self) -> &LazyHash<Library> {
&LIBRARY &LIBRARY
} }
fn book(&self) -> &Prehashed<FontBook> { fn book(&self) -> &LazyHash<FontBook> {
&FONTS.0 &FONTS.0
} }

View File

@ -9,7 +9,6 @@ pub use self::contribs::*;
pub use self::html::*; pub use self::html::*;
pub use self::model::*; pub use self::model::*;
use comemo::Prehashed;
use ecow::{eco_format, EcoString}; use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use serde::Deserialize; use serde::Deserialize;
@ -28,6 +27,7 @@ use typst::model::Document;
use typst::model::MODEL; use typst::model::MODEL;
use typst::symbols::SYMBOLS; use typst::symbols::SYMBOLS;
use typst::text::{Font, FontBook, TEXT}; use typst::text::{Font, FontBook, TEXT};
use typst::utils::LazyHash;
use typst::visualize::VISUALIZE; use typst::visualize::VISUALIZE;
use typst::Library; use typst::Library;
@ -54,7 +54,7 @@ static GROUPS: Lazy<Vec<GroupData>> = Lazy::new(|| {
groups groups
}); });
static LIBRARY: Lazy<Prehashed<Library>> = Lazy::new(|| { static LIBRARY: Lazy<LazyHash<Library>> = Lazy::new(|| {
let mut lib = Library::default(); let mut lib = Library::default();
lib.styles lib.styles
.set(PageElem::set_width(Smart::Custom(Abs::pt(240.0).into()))); .set(PageElem::set_width(Smart::Custom(Abs::pt(240.0).into())));
@ -62,16 +62,16 @@ static LIBRARY: Lazy<Prehashed<Library>> = Lazy::new(|| {
lib.styles.set(PageElem::set_margin(Margin::splat(Some(Smart::Custom( lib.styles.set(PageElem::set_margin(Margin::splat(Some(Smart::Custom(
Abs::pt(15.0).into(), Abs::pt(15.0).into(),
))))); )))));
Prehashed::new(lib) LazyHash::new(lib)
}); });
static FONTS: Lazy<(Prehashed<FontBook>, Vec<Font>)> = Lazy::new(|| { static FONTS: Lazy<(LazyHash<FontBook>, Vec<Font>)> = Lazy::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)))
.collect(); .collect();
let book = FontBook::from_fonts(&fonts); let book = FontBook::from_fonts(&fonts);
(Prehashed::new(book), fonts) (LazyHash::new(book), fonts)
}); });
/// Build documentation pages. /// Build documentation pages.

View File

@ -1,18 +1,18 @@
#![no_main] #![no_main]
use comemo::Prehashed;
use libfuzzer_sys::fuzz_target; use libfuzzer_sys::fuzz_target;
use typst::diag::{FileError, FileResult}; use typst::diag::{FileError, FileResult};
use typst::eval::Tracer; use typst::eval::Tracer;
use typst::foundations::{Bytes, Datetime}; use typst::foundations::{Bytes, Datetime};
use typst::syntax::{FileId, Source}; use typst::syntax::{FileId, Source};
use typst::text::{Font, FontBook}; use typst::text::{Font, FontBook};
use typst::utils::LazyHash;
use typst::visualize::Color; use typst::visualize::Color;
use typst::{Library, World}; use typst::{Library, World};
struct FuzzWorld { struct FuzzWorld {
library: Prehashed<Library>, library: LazyHash<Library>,
book: Prehashed<FontBook>, book: LazyHash<FontBook>,
font: Font, font: Font,
source: Source, source: Source,
} }
@ -23,8 +23,8 @@ impl FuzzWorld {
let font = Font::new(Bytes::from_static(data), 0).unwrap(); let font = Font::new(Bytes::from_static(data), 0).unwrap();
let book = FontBook::from_fonts([&font]); let book = FontBook::from_fonts([&font]);
Self { Self {
library: Prehashed::new(Library::default()), library: LazyHash::new(Library::default()),
book: Prehashed::new(book), book: LazyHash::new(book),
font, font,
source: Source::detached(text), source: Source::detached(text),
} }
@ -32,11 +32,11 @@ impl FuzzWorld {
} }
impl World for FuzzWorld { impl World for FuzzWorld {
fn library(&self) -> &Prehashed<Library> { fn library(&self) -> &LazyHash<Library> {
&self.library &self.library
} }
fn book(&self) -> &Prehashed<FontBook> { fn book(&self) -> &LazyHash<FontBook> {
&self.book &self.book
} }

View File

@ -5,7 +5,6 @@ use std::io::Write;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::OnceLock; use std::sync::OnceLock;
use comemo::Prehashed;
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use parking_lot::Mutex; use parking_lot::Mutex;
use typst::diag::{bail, FileError, FileResult, StrResult}; use typst::diag::{bail, FileError, FileResult, StrResult};
@ -13,6 +12,7 @@ use typst::foundations::{func, Bytes, Datetime, NoneValue, Repr, Smart, Value};
use typst::layout::{Abs, Margin, PageElem}; use typst::layout::{Abs, Margin, PageElem};
use typst::syntax::{FileId, Source}; use typst::syntax::{FileId, Source};
use typst::text::{Font, FontBook, TextElem, TextSize}; use typst::text::{Font, FontBook, TextElem, TextSize};
use typst::utils::LazyHash;
use typst::visualize::Color; use typst::visualize::Color;
use typst::{Library, World}; use typst::{Library, World};
@ -35,11 +35,11 @@ impl TestWorld {
} }
impl World for TestWorld { impl World for TestWorld {
fn library(&self) -> &Prehashed<Library> { fn library(&self) -> &LazyHash<Library> {
&self.base.library &self.base.library
} }
fn book(&self) -> &Prehashed<FontBook> { fn book(&self) -> &LazyHash<FontBook> {
&self.base.book &self.base.book
} }
@ -81,8 +81,8 @@ impl TestWorld {
/// Shared foundation of all test worlds. /// Shared foundation of all test worlds.
struct TestBase { struct TestBase {
library: Prehashed<Library>, library: LazyHash<Library>,
book: Prehashed<FontBook>, book: LazyHash<FontBook>,
fonts: Vec<Font>, fonts: Vec<Font>,
slots: Mutex<HashMap<FileId, FileSlot>>, slots: Mutex<HashMap<FileId, FileSlot>>,
} }
@ -95,8 +95,8 @@ impl Default for TestBase {
.collect(); .collect();
Self { Self {
library: Prehashed::new(library()), library: LazyHash::new(library()),
book: Prehashed::new(FontBook::from_fonts(&fonts)), book: LazyHash::new(FontBook::from_fonts(&fonts)),
fonts, fonts,
slots: Mutex::new(HashMap::new()), slots: Mutex::new(HashMap::new()),
} }