Streamline imports

This commit is contained in:
Laurenz 2023-11-19 16:34:38 +01:00
parent ea987ef4a3
commit 2da619e17c
85 changed files with 218 additions and 246 deletions

View File

@ -8,7 +8,7 @@ use termcolor::WriteColor;
use typst::diag::{PackageError, PackageResult};
use typst::syntax::PackageSpec;
use super::color_stream;
use crate::color_stream;
use crate::download::download_with_progress;
/// Make a package available in the on-disk cache.

View File

@ -16,7 +16,7 @@ use typst::World;
use unscanny::Scanner;
use yaml_front_matter::YamlFrontMatter;
use super::{contributors, OutlineItem, Resolver, FILE_DIR, FONTS, LIBRARY};
use crate::{contributors, OutlineItem, Resolver, FILE_DIR, FONTS, LIBRARY};
/// HTML documentation.
#[derive(Serialize)]

View File

@ -1,7 +1,7 @@
use typst::diag::{bail, StrResult};
use typst::eval::Func;
use super::{get_module, GROUPS, LIBRARY};
use crate::{get_module, GROUPS, LIBRARY};
/// Resolve an intra-doc link.
pub fn resolve(link: &str) -> StrResult<String> {

View File

@ -5,9 +5,9 @@ use ecow::{eco_format, EcoString};
use if_chain::if_chain;
use serde::{Deserialize, Serialize};
use typst::doc::Frame;
use typst::eval::repr::separated_list;
use typst::eval::{
format_str, AutoValue, CastInfo, Func, Library, NoneValue, Repr, Scope, Type, Value,
format_str, repr, AutoValue, CastInfo, Func, Library, NoneValue, Repr, Scope, Type,
Value,
};
use typst::geom::Color;
use typst::model::Label;
@ -17,8 +17,8 @@ use typst::syntax::{
use typst::World;
use unscanny::Scanner;
use super::analyze::analyze_labels;
use super::{analyze_expr, analyze_import, plain_docs_sentence, summarize_font_family};
use crate::analyze::analyze_labels;
use crate::{analyze_expr, analyze_import, plain_docs_sentence, summarize_font_family};
/// Autocomplete a cursor position in a source file.
///
@ -1089,7 +1089,7 @@ impl<'a> CompletionContext<'a> {
kind: CompletionKind::Constant,
label: name.into(),
apply: Some(tags[0].into()),
detail: Some(separated_list(&tags, " or ").into()),
detail: Some(repr::separated_list(&tags, " or ").into()),
});
}
}

View File

@ -3,15 +3,14 @@ use std::fmt::Write;
use ecow::{eco_format, EcoString};
use if_chain::if_chain;
use typst::doc::Frame;
use typst::eval::repr::{pretty_comma_list, separated_list};
use typst::eval::{CapturesVisitor, CastInfo, Repr, Tracer, Value};
use typst::eval::{repr, CapturesVisitor, CastInfo, Repr, Tracer, Value};
use typst::geom::{round_2, Length, Numeric};
use typst::syntax::ast;
use typst::syntax::{LinkedNode, Source, SyntaxKind};
use typst::World;
use super::analyze::analyze_labels;
use super::{analyze_expr, plain_docs_sentence, summarize_font_family};
use crate::analyze::analyze_labels;
use crate::{analyze_expr, plain_docs_sentence, summarize_font_family};
/// Describe the item under the cursor.
pub fn tooltip(
@ -97,7 +96,7 @@ fn expr_tooltip(world: &dyn World, leaf: &LinkedNode) -> Option<Tooltip> {
pieces.push("...".into());
}
let tooltip = pretty_comma_list(&pieces, false);
let tooltip = repr::pretty_comma_list(&pieces, false);
(!tooltip.is_empty()).then(|| Tooltip::Code(tooltip.into()))
}
@ -128,7 +127,7 @@ fn closure_tooltip(leaf: &LinkedNode) -> Option<Tooltip> {
names.sort();
let tooltip = separated_list(&names, "and");
let tooltip = repr::separated_list(&names, "and");
Some(Tooltip::Text(eco_format!("This closure captures {tooltip}.")))
}

View File

@ -1,7 +1,6 @@
use typst::eval::AutoValue;
use super::VElem;
use crate::layout::Spacing;
use crate::layout::{Spacing, VElem};
use crate::prelude::*;
/// An inline-level container that sizes content.

View File

@ -1,12 +1,10 @@
use std::str::FromStr;
use crate::layout::{BlockElem, ParElem, Sizing, Spacing};
use crate::layout::{BlockElem, GridLayouter, ParElem, Sizing, Spacing};
use crate::meta::{Numbering, NumberingPattern};
use crate::prelude::*;
use crate::text::TextElem;
use super::GridLayouter;
/// A numbered list.
///
/// Displays a sequence of items vertically and numbers them consecutively.

View File

@ -2,7 +2,7 @@ use std::mem;
use comemo::Prehashed;
use super::{
use crate::layout::{
AlignElem, BlockElem, ColbreakElem, ColumnsElem, ParElem, PlaceElem, Spacing, VElem,
};
use crate::meta::{FootnoteElem, FootnoteEntry};

View File

@ -1,10 +1,9 @@
use smallvec::{smallvec, SmallVec};
use crate::layout::Sizing;
use crate::prelude::*;
use crate::text::TextElem;
use super::Sizing;
/// Arranges content in a grid.
///
/// The grid element allows you to arrange content in a grid. You can define the

View File

@ -1,9 +1,8 @@
use crate::layout::GridLayouter;
use crate::layout::{BlockElem, ParElem, Sizing, Spacing};
use crate::prelude::*;
use crate::text::TextElem;
use super::GridLayouter;
/// A bullet list.
///
/// Displays a sequence of items vertically, with each item introduced by a

View File

@ -4,7 +4,7 @@ use std::str::FromStr;
use typst::eval::AutoValue;
use super::{AlignElem, ColumnsElem};
use crate::layout::{AlignElem, ColumnsElem};
use crate::meta::{Counter, CounterKey, ManualPageCounter, Numbering};
use crate::prelude::*;
use crate::text::TextElem;

View File

@ -4,8 +4,7 @@ use typst::model::DelayedErrors;
use unicode_bidi::{BidiInfo, Level as BidiLevel};
use unicode_script::{Script, UnicodeScript};
use super::{BoxElem, HElem, Sizing, Spacing};
use crate::layout::AlignElem;
use crate::layout::{AlignElem, BoxElem, HElem, Sizing, Spacing};
use crate::math::EquationElem;
use crate::prelude::*;
use crate::text::{

View File

@ -1,7 +1,6 @@
use crate::layout::AlignElem;
use crate::prelude::*;
use super::AlignElem;
/// Repeats content to the available space.
///
/// This can be useful when implementing a custom index, reference, or outline.

View File

@ -1,4 +1,4 @@
use super::{AlignElem, Spacing};
use crate::layout::{AlignElem, Spacing};
use crate::prelude::*;
/// Arranges content and spacing horizontally or vertically.

View File

@ -1,5 +1,4 @@
use super::{HElem, VElem};
use crate::layout::{BlockElem, ParElem, Spacing};
use crate::layout::{BlockElem, HElem, ParElem, Spacing, VElem};
use crate::prelude::*;
/// A list of terms and their descriptions.

View File

@ -1,4 +1,4 @@
use super::*;
use crate::math::*;
/// How much the accent can be shorter than the base.
const ACCENT_SHORT_FALL: Em = Em::new(0.5);

View File

@ -1,4 +1,4 @@
use super::*;
use crate::math::*;
/// A math alignment point: `&`, `&&`.
#[elem(title = "Alignment Point", LayoutMath)]

View File

@ -1,5 +1,3 @@
use typst::model::Resolve;
use super::*;
const DEFAULT_ROW_GAP: Em = Em::new(0.5);

View File

@ -1,5 +1,3 @@
use typst::eval::Scope;
use super::*;
/// A text operator in an equation.

View File

@ -21,11 +21,12 @@ use typst::eval::{eval_string, Bytes, CastInfo, EvalMode, Reflect};
use typst::font::FontStyle;
use typst::util::{option_eq, PicoStr};
use super::{CitationForm, CiteGroup, LinkElem, LocalName};
use crate::layout::{
BlockElem, GridElem, HElem, PadElem, ParElem, Sizing, TrackSizings, VElem,
};
use crate::meta::{FootnoteElem, HeadingElem, LocalNameIn};
use crate::meta::{
CitationForm, CiteGroup, FootnoteElem, HeadingElem, LinkElem, LocalName, LocalNameIn,
};
use crate::prelude::*;
use crate::text::{Delta, SubElem, SuperElem, TextElem};

View File

@ -1,5 +1,5 @@
use super::bibliography::Works;
use super::CslStyle;
use crate::meta::bibliography::Works;
use crate::meta::CslStyle;
use crate::prelude::*;
use crate::text::TextElem;

View File

@ -5,9 +5,9 @@ use smallvec::{smallvec, SmallVec};
use typst::eval::{Repr, Tracer};
use typst::model::DelayedErrors;
use super::{FigureElem, HeadingElem, Numbering, NumberingPattern};
use crate::layout::PageElem;
use crate::math::EquationElem;
use crate::meta::{FigureElem, HeadingElem, Numbering, NumberingPattern};
use crate::prelude::*;
/// Counts through pages, elements, and more.

View File

@ -1,9 +1,11 @@
use std::borrow::Cow;
use std::str::FromStr;
use super::{Count, Counter, CounterKey, CounterUpdate, Numbering, NumberingPattern};
use crate::layout::{BlockElem, PlaceElem, VElem};
use crate::meta::{Outlinable, Refable, Supplement};
use crate::meta::{
Count, Counter, CounterKey, CounterUpdate, Numbering, NumberingPattern, Outlinable,
Refable, Supplement,
};
use crate::prelude::*;
use crate::text::TextElem;
use crate::visualize::ImageElem;

View File

@ -1,9 +1,8 @@
use comemo::Prehashed;
use std::str::FromStr;
use super::{Counter, Numbering, NumberingPattern};
use crate::layout::{HElem, ParElem};
use crate::meta::{Count, CounterUpdate};
use crate::meta::{Count, Counter, CounterUpdate, Numbering, NumberingPattern};
use crate::prelude::*;
use crate::text::{SuperElem, TextElem, TextSize};
use crate::visualize::LineElem;

View File

@ -2,11 +2,11 @@ use std::str::FromStr;
use typst::util::option_eq;
use super::{
Counter, CounterKey, HeadingElem, LocalName, Numbering, NumberingPattern, Refable,
};
use crate::layout::{BoxElem, HElem, HideElem, ParbreakElem, RepeatElem, Spacing};
use crate::meta::LocalNameIn;
use crate::meta::{
Counter, CounterKey, HeadingElem, LocalName, LocalNameIn, Numbering,
NumberingPattern, Refable,
};
use crate::prelude::*;
use crate::text::{LinebreakElem, SpaceElem, TextElem};

View File

@ -1,8 +1,8 @@
use kurbo::{BezPath, Line, ParamCurve};
use ttf_parser::{GlyphId, OutlineBuilder};
use super::{BottomEdge, BottomEdgeMetric, TextElem, TopEdge, TopEdgeMetric};
use crate::prelude::*;
use crate::text::{BottomEdge, BottomEdgeMetric, TextElem, TopEdge, TopEdgeMetric};
/// Underlines text.
///

View File

@ -7,8 +7,8 @@ use once_cell::sync::Lazy;
use typst::doc::Lang;
use typst::syntax::link_prefix;
use super::TextElem;
use crate::layout::Preparation;
use crate::text::TextElem;
/// Generated by the following command:
///

View File

@ -1,5 +1,5 @@
use super::TextElem;
use crate::prelude::*;
use crate::text::TextElem;
/// A text space.
#[elem(Behave, Unlabellable, PlainText, Repr)]

View File

@ -1,7 +1,7 @@
use super::{SmartquoteElem, SpaceElem, TextElem};
use crate::layout::{BlockElem, HElem, PadElem, Spacing, VElem};
use crate::meta::{CitationForm, CiteElem};
use crate::prelude::*;
use crate::text::{SmartquoteElem, SpaceElem, TextElem};
/// Displays a quote alongside an optional attribution.
///

View File

@ -13,12 +13,12 @@ use typst::syntax::{self, split_newlines, LinkedNode};
use typst::util::option_eq;
use unicode_segmentation::UnicodeSegmentation;
use super::{
FontFamily, FontList, Hyphenate, LinebreakElem, SmartquoteElem, TextElem, TextSize,
};
use crate::layout::BlockElem;
use crate::meta::Figurable;
use crate::prelude::*;
use crate::text::{
FontFamily, FontList, Hyphenate, LinebreakElem, SmartquoteElem, TextElem, TextSize,
};
// Shorthand for highlighter closures.
type StyleFn<'a> = &'a mut dyn FnMut(&LinkedNode, Range<usize>, synt::Style) -> Content;

View File

@ -8,9 +8,9 @@ use typst::font::{Font, FontStyle, FontVariant};
use typst::util::SliceExt;
use unicode_script::{Script, UnicodeScript};
use super::{decorate, NumberType, NumberWidth, TextElem};
use crate::layout::SpanMapper;
use crate::prelude::*;
use crate::text::{decorate, NumberType, NumberWidth, TextElem};
/// The result of shaping text.
///

View File

@ -1,5 +1,5 @@
use super::{variant, SpaceElem, TextElem, TextSize};
use crate::prelude::*;
use crate::text::{variant, SpaceElem, TextElem, TextSize};
/// Renders text in subscript.
///

View File

@ -1,5 +1,3 @@
use heck::ToKebabCase;
use super::*;
/// Expand the `#[derive(Cast)]` macro.

View File

@ -1,5 +1,3 @@
use heck::{ToKebabCase, ToShoutySnakeCase, ToUpperCamelCase};
use super::*;
/// Expand the `#[elem]` macro.

View File

@ -1,7 +1,5 @@
use super::*;
use heck::ToKebabCase;
/// Expand the `#[func]` macro.
pub fn func(stream: TokenStream, item: &syn::ItemFn) -> Result<TokenStream> {
let func = parse(stream, item)?;

View File

@ -11,6 +11,7 @@ mod scope;
mod symbols;
mod ty;
use heck::*;
use proc_macro::TokenStream as BoundaryStream;
use proc_macro2::TokenStream;
use quote::quote;

View File

@ -1,4 +1,3 @@
use heck::{ToKebabCase, ToTitleCase};
use quote::ToTokens;
use syn::token::Token;
use syn::Attribute;

View File

@ -1,4 +1,4 @@
use super::PdfContext;
use crate::PdfContext;
/// A PDF external graphics state.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]

View File

@ -8,7 +8,7 @@ use std::ops::Deref;
use ecow::EcoString;
use unscanny::Scanner;
use super::{
use crate::{
is_id_continue, is_id_start, is_newline, split_newlines, Span, SyntaxKind, SyntaxNode,
};

View File

@ -10,7 +10,7 @@ use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::is_ident;
use crate::is_ident;
/// The global package-path interner.
static INTERNER: Lazy<RwLock<Interner>> =

View File

@ -404,9 +404,8 @@ fn highlight_html_impl(html: &mut String, node: &LinkedNode) {
#[cfg(test)]
mod tests {
use std::ops::Range;
use super::*;
use std::ops::Range;
#[test]
fn test_highlighting() {

View File

@ -4,7 +4,7 @@ use unicode_script::{Script, UnicodeScript};
use unicode_segmentation::UnicodeSegmentation;
use unscanny::Scanner;
use super::SyntaxKind;
use crate::SyntaxKind;
/// Splits up a string of source code into tokens.
#[derive(Clone)]

View File

@ -5,8 +5,8 @@ use std::sync::Arc;
use ecow::{eco_vec, EcoString, EcoVec};
use super::ast::AstNode;
use super::{FileId, Span, SyntaxKind};
use crate::ast::AstNode;
use crate::{FileId, Span, SyntaxKind};
/// A node in the untyped syntax tree.
#[derive(Clone, Eq, PartialEq, Hash)]

View File

@ -4,7 +4,7 @@ use std::ops::Range;
use ecow::{eco_format, EcoString};
use unicode_math_class::MathClass;
use super::{ast, is_newline, LexMode, Lexer, SyntaxKind, SyntaxNode};
use crate::{ast, is_newline, LexMode, Lexer, SyntaxKind, SyntaxNode};
/// Parse a source file.
#[tracing::instrument(skip_all)]

View File

@ -1,6 +1,6 @@
use std::ops::Range;
use super::{
use crate::{
is_newline, parse, reparse_block, reparse_markup, Span, SyntaxKind, SyntaxNode,
};
@ -246,7 +246,7 @@ fn next_nesting(node: &SyntaxNode, nesting: &mut usize) {
mod tests {
use std::ops::Range;
use super::super::{parse, Source, Span};
use crate::{parse, Source, Span};
#[track_caller]
fn test(prev: &str, range: Range<usize>, with: &str, incremental: bool) {

View File

@ -7,9 +7,9 @@ use std::sync::Arc;
use comemo::Prehashed;
use super::reparser::reparse;
use super::{is_newline, parse, FileId, LinkedNode, Span, SyntaxNode};
use crate::reparser::reparse;
use crate::VirtualPath;
use crate::{is_newline, parse, FileId, LinkedNode, Span, SyntaxNode};
/// A source file.
///

View File

@ -2,7 +2,7 @@ use std::fmt::{self, Debug, Formatter};
use std::num::NonZeroU64;
use std::ops::Range;
use super::FileId;
use crate::FileId;
/// A unique identifier for a syntax node.
///
@ -119,7 +119,7 @@ impl<T: Debug> Debug for Spanned<T> {
#[cfg(test)]
mod tests {
use super::{FileId, Span};
use crate::{FileId, Span};
#[test]
fn test_span_encoding() {

View File

@ -2,9 +2,10 @@ use std::fmt::{self, Debug, Formatter};
use ecow::{eco_format, eco_vec, EcoString, EcoVec};
use super::repr::pretty_array_like;
use super::{func, scope, ty, Array, Dict, FromValue, IntoValue, Repr, Str, Value};
use crate::diag::{bail, At, SourceDiagnostic, SourceResult};
use crate::eval::{
func, repr, scope, ty, Array, Dict, FromValue, IntoValue, Repr, Str, Value,
};
use crate::syntax::{Span, Spanned};
/// Captured arguments to a function.
@ -288,7 +289,7 @@ impl Debug for Args {
impl Repr for Args {
fn repr(&self) -> EcoString {
let pieces = self.items.iter().map(Arg::repr).collect::<Vec<_>>();
pretty_array_like(&pieces, false).into()
repr::pretty_array_like(&pieces, false).into()
}
}

View File

@ -7,13 +7,11 @@ use ecow::{eco_format, EcoString, EcoVec};
use serde::{Deserialize, Serialize};
use smallvec::SmallVec;
use super::repr::pretty_array_like;
use super::{
cast, func, ops, scope, ty, Args, Bytes, CastInfo, FromValue, Func, IntoValue,
use crate::diag::{At, SourceResult, StrResult};
use crate::eval::{
cast, func, ops, repr, scope, ty, Args, Bytes, CastInfo, FromValue, Func, IntoValue,
Reflect, Repr, Value, Version, Vm,
};
use crate::diag::{At, SourceResult, StrResult};
use crate::eval::ops::{add, mul};
use crate::syntax::Span;
/// Create a new [`Array`] from values.
@ -553,7 +551,7 @@ impl Array {
.or(default)
.ok_or("cannot calculate sum of empty array with no default")?;
for item in iter {
acc = add(acc, item)?;
acc = ops::add(acc, item)?;
}
Ok(acc)
}
@ -574,7 +572,7 @@ impl Array {
.or(default)
.ok_or("cannot calculate product of empty array with no default")?;
for item in iter {
acc = mul(acc, item)?;
acc = ops::mul(acc, item)?;
}
Ok(acc)
}
@ -831,7 +829,7 @@ impl Repr for Array {
if self.len() > max {
pieces.push(eco_format!(".. ({} items omitted)", self.len() - max));
}
pretty_array_like(&pieces, self.len() == 1).into()
repr::pretty_array_like(&pieces, self.len() == 1).into()
}
}

View File

@ -1,8 +1,8 @@
use ecow::EcoString;
use std::fmt::Debug;
use super::{ty, CastInfo, FromValue, IntoValue, Reflect, Repr, Type, Value};
use crate::diag::StrResult;
use crate::eval::{ty, CastInfo, FromValue, IntoValue, Reflect, Repr, Type, Value};
use crate::model::{Fold, Resolve, StyleChain};
/// A value that indicates a smart default.

View File

@ -7,8 +7,8 @@ use comemo::Prehashed;
use ecow::{eco_format, EcoString};
use serde::{Serialize, Serializer};
use super::{cast, func, scope, ty, Array, Reflect, Repr, Str, Value};
use crate::diag::{bail, StrResult};
use crate::eval::{cast, func, scope, ty, Array, Reflect, Repr, Str, Value};
/// A sequence of bytes.
///

View File

@ -10,9 +10,8 @@ use ecow::{eco_format, EcoString};
use smallvec::SmallVec;
use unicode_math_class::MathClass;
use super::repr::separated_list;
use super::{Repr, Type, Value};
use crate::diag::{At, SourceResult, StrResult};
use crate::eval::{repr, Repr, Type, Value};
use crate::syntax::{Span, Spanned};
/// Determine details of a type.
@ -288,7 +287,7 @@ impl CastInfo {
msg.push_str(" nothing");
}
msg.push_str(&separated_list(&parts, "or"));
msg.push_str(&repr::separated_list(&parts, "or"));
if !matching_type {
msg.push_str(", found ");

View File

@ -9,9 +9,10 @@ use time::error::{Format, InvalidFormatDescription};
use time::macros::format_description;
use time::{format_description, Month, PrimitiveDateTime};
use super::repr::pretty_array_like;
use super::{cast, func, scope, ty, Dict, Duration, Repr, Smart, Str, Value, Vm};
use crate::diag::{bail, StrResult};
use crate::eval::{
cast, func, repr, scope, ty, Dict, Duration, Repr, Smart, Str, Value, Vm,
};
use crate::World;
/// Represents a date, a time, or a combination of both.
@ -438,7 +439,7 @@ impl Repr for Datetime {
.flatten()
.collect::<EcoVec<_>>();
eco_format!("datetime{}", &pretty_array_like(&filtered, false))
eco_format!("datetime{}", &repr::pretty_array_like(&filtered, false))
}
}

View File

@ -7,9 +7,8 @@ use ecow::{eco_format, EcoString};
use indexmap::IndexMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::repr::{pretty_array_like, separated_list};
use super::{array, func, scope, ty, Array, Repr, Str, Value};
use crate::diag::StrResult;
use crate::eval::{array, func, repr, scope, ty, Array, Repr, Str, Value};
use crate::syntax::is_ident;
use crate::util::ArcExt;
@ -119,7 +118,7 @@ impl Dict {
if let Some((key, _)) = self.iter().next() {
let parts: Vec<_> = expected.iter().map(|s| eco_format!("\"{s}\"")).collect();
let mut msg = format!("unexpected key {}, valid keys are ", key.repr());
msg.push_str(&separated_list(&parts, "and"));
msg.push_str(&repr::separated_list(&parts, "and"));
return Err(msg.into());
}
Ok(())
@ -236,7 +235,7 @@ impl Repr for Dict {
pieces.push(eco_format!(".. ({} pairs omitted)", self.len() - max));
}
pretty_array_like(&pieces, false).into()
repr::pretty_array_like(&pieces, false).into()
}
}

View File

@ -4,8 +4,7 @@ use std::fmt::Debug;
use std::ops::{Add, Div, Mul, Neg, Sub};
use time::ext::NumericalDuration;
use super::repr::pretty_array_like;
use super::{func, scope, ty, Repr};
use crate::eval::{func, repr, scope, ty, Repr};
/// Represents a positive or negative span of time.
#[ty(scope)]
@ -145,7 +144,7 @@ impl Repr for Duration {
vec.push(eco_format!("seconds: {}", seconds.repr()));
}
eco_format!("duration{}", &pretty_array_like(&vec, false))
eco_format!("duration{}", &repr::pretty_array_like(&vec, false))
}
}

View File

@ -4,7 +4,7 @@ use crate::diag::StrResult;
use crate::eval::Version;
use crate::geom::{Align, Length, Rel, Stroke};
use super::{IntoValue, Type, Value};
use crate::eval::{IntoValue, Type, Value};
/// Try to access a field on a value.
///

View File

@ -2,8 +2,7 @@ use std::num::ParseFloatError;
use ecow::{eco_format, EcoString};
use super::repr::{format_float, MINUS_SIGN};
use super::{cast, func, scope, ty, Repr, Str};
use crate::eval::{cast, func, repr, scope, ty, Repr, Str};
use crate::geom::Ratio;
/// A floating-point number.
@ -52,7 +51,7 @@ impl f64 {
impl Repr for f64 {
fn repr(&self) -> EcoString {
format_float(*self, None, "")
repr::format_float(*self, None, "")
}
}
@ -72,5 +71,5 @@ cast! {
}
fn parse_float(s: EcoString) -> Result<f64, ParseFloatError> {
s.replace(MINUS_SIGN, "-").parse()
s.replace(repr::MINUS_SIGN, "-").parse()
}

View File

@ -5,11 +5,11 @@ use comemo::{Prehashed, Tracked, TrackedMut};
use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy;
use super::{
use crate::diag::{bail, HintedStrResult, SourceResult, StrResult};
use crate::eval::{
cast, scope, ty, Args, CastInfo, Eval, FlowEvent, IntoValue, Route, Scope, Scopes,
Tracer, Type, Value, Vm,
};
use crate::diag::{bail, HintedStrResult, SourceResult, StrResult};
use crate::model::{
Content, DelayedErrors, Element, Introspector, Locator, Selector, Vt,
};

View File

@ -2,8 +2,7 @@ use std::num::{NonZeroI64, NonZeroIsize, NonZeroU64, NonZeroUsize, ParseIntError
use ecow::{eco_format, EcoString};
use super::repr::{format_int_with_base, MINUS_SIGN};
use super::{cast, func, scope, ty, Repr, Str, Value};
use crate::eval::{cast, func, repr, scope, ty, Repr, Str, Value};
/// A whole number.
///
@ -54,7 +53,7 @@ impl i64 {
impl Repr for i64 {
fn repr(&self) -> EcoString {
format_int_with_base(*self, 10)
repr::format_int_with_base(*self, 10)
}
}
@ -71,7 +70,7 @@ cast! {
fn parse_int(mut s: &str) -> Result<i64, ParseIntError> {
let mut sign = 1;
if let Some(rest) = s.strip_prefix('-').or_else(|| s.strip_prefix(MINUS_SIGN)) {
if let Some(rest) = s.strip_prefix('-').or_else(|| s.strip_prefix(repr::MINUS_SIGN)) {
sign = -1;
s = rest;
}

View File

@ -6,9 +6,9 @@ use comemo::Tracked;
use ecow::EcoString;
use std::sync::OnceLock;
use super::Module;
use crate::diag::SourceResult;
use crate::doc::Document;
use crate::eval::Module;
use crate::geom::{Abs, Dir};
use crate::model::{Content, Element, Introspector, Label, StyleChain, Styles, Vt};
use crate::util::hash128;

View File

@ -1,7 +1,7 @@
//! Handles special built-in methods on values.
use super::{Args, Array, Dict, Str, Type, Value};
use crate::diag::{At, SourceResult};
use crate::eval::{Args, Array, Dict, Str, Type, Value};
use crate::syntax::Span;
/// Whether a specific method is mutating.

View File

@ -3,8 +3,8 @@ use std::sync::Arc;
use ecow::{eco_format, EcoString};
use super::{ty, Content, Scope, Value};
use crate::diag::StrResult;
use crate::eval::{ty, Content, Scope, Value};
/// An evaluated module, either built-in or resulting from a file.
///

View File

@ -3,8 +3,8 @@ use std::fmt::Debug;
use serde::{Serialize, Serializer};
use super::{cast, ty, CastInfo, FromValue, IntoValue, Reflect, Repr, Type, Value};
use crate::diag::StrResult;
use crate::eval::{cast, ty, CastInfo, FromValue, IntoValue, Reflect, Repr, Type, Value};
/// A value that indicates the absence of any other value.
///

View File

@ -4,8 +4,8 @@ use std::cmp::Ordering;
use ecow::eco_format;
use super::{format_str, item, IntoValue, Regex, Repr, Smart, Value};
use crate::diag::{bail, StrResult};
use crate::eval::{format_str, item, IntoValue, Regex, Repr, Smart, Value};
use crate::geom::{Align, Length, Numeric, Rel, Stroke};
use Value::*;

View File

@ -5,8 +5,8 @@ use ecow::{eco_format, EcoString};
use std::sync::{Arc, Mutex};
use wasmi::{AsContext, AsContextMut, Caller, Engine, Linker, Module};
use super::{func, scope, ty, Bytes, Vm};
use crate::diag::{bail, At, SourceResult, StrResult};
use crate::eval::{func, scope, ty, Bytes, Vm};
use crate::syntax::Spanned;
use crate::World;

View File

@ -137,3 +137,29 @@ pub fn pretty_array_like(parts: &[impl AsRef<str>], trailing_comma: bool) -> Str
buf.push(')');
buf
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_to_base() {
assert_eq!(&format_int_with_base(0, 10), "0");
assert_eq!(&format_int_with_base(0, 16), "0");
assert_eq!(&format_int_with_base(0, 36), "0");
assert_eq!(
&format_int_with_base(i64::MAX, 2),
"111111111111111111111111111111111111111111111111111111111111111"
);
assert_eq!(
&format_int_with_base(i64::MIN, 2),
"\u{2212}1000000000000000000000000000000000000000000000000000000000000000"
);
assert_eq!(&format_int_with_base(i64::MAX, 10), "9223372036854775807");
assert_eq!(&format_int_with_base(i64::MIN, 10), "\u{2212}9223372036854775808");
assert_eq!(&format_int_with_base(i64::MAX, 16), "7fffffffffffffff");
assert_eq!(&format_int_with_base(i64::MIN, 16), "\u{2212}8000000000000000");
assert_eq!(&format_int_with_base(i64::MAX, 36), "1y2p0ij32e8e7");
assert_eq!(&format_int_with_base(i64::MIN, 36), "\u{2212}1y2p0ij32e8e8");
}
}

View File

@ -4,10 +4,10 @@ use std::hash::{Hash, Hasher};
use ecow::{eco_format, EcoString};
use indexmap::IndexMap;
use super::{
use crate::diag::{bail, HintedStrResult, HintedString, StrResult};
use crate::eval::{
Func, IntoValue, Library, Module, NativeFunc, NativeFuncData, NativeType, Type, Value,
};
use crate::diag::{bail, HintedStrResult, HintedString, StrResult};
use crate::model::{Element, NativeElement};
/// A stack of scopes.

View File

@ -7,12 +7,11 @@ use ecow::EcoString;
use serde::{Deserialize, Serialize};
use unicode_segmentation::UnicodeSegmentation;
use super::repr::{format_float, format_int_with_base};
use super::{
cast, dict, func, scope, ty, Args, Array, Bytes, Dict, Func, IntoValue, Repr, Type,
Value, Version, Vm,
};
use crate::diag::{bail, At, SourceResult, StrResult};
use crate::eval::{
cast, dict, func, repr, scope, ty, Args, Array, Bytes, Dict, Func, IntoValue, Repr,
Type, Value, Version, Vm,
};
use crate::geom::Align;
use crate::model::Label;
use crate::syntax::{Span, Spanned};
@ -164,7 +163,7 @@ impl Str {
if base.v < 2 || base.v > 36 {
bail!(base.span, "base must be between 2 and 36");
}
format_int_with_base(n, base.v).into()
repr::format_int_with_base(n, base.v).into()
}
})
}
@ -610,7 +609,7 @@ pub enum ToStr {
cast! {
ToStr,
v: i64 => Self::Int(v),
v: f64 => Self::Str(format_float(v, None, "").into()),
v: f64 => Self::Str(repr::format_float(v, None, "").into()),
v: Version => Self::Str(format_str!("{}", v)),
v: Bytes => Self::Str(
std::str::from_utf8(&v)
@ -953,29 +952,3 @@ cast! {
v: Str => Self::Str(v),
v: Func => Self::Func(v)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_to_base() {
assert_eq!(&format_int_with_base(0, 10), "0");
assert_eq!(&format_int_with_base(0, 16), "0");
assert_eq!(&format_int_with_base(0, 36), "0");
assert_eq!(
&format_int_with_base(i64::MAX, 2),
"111111111111111111111111111111111111111111111111111111111111111"
);
assert_eq!(
&format_int_with_base(i64::MIN, 2),
"\u{2212}1000000000000000000000000000000000000000000000000000000000000000"
);
assert_eq!(&format_int_with_base(i64::MAX, 10), "9223372036854775807");
assert_eq!(&format_int_with_base(i64::MIN, 10), "\u{2212}9223372036854775808");
assert_eq!(&format_int_with_base(i64::MAX, 16), "7fffffffffffffff");
assert_eq!(&format_int_with_base(i64::MIN, 16), "\u{2212}8000000000000000");
assert_eq!(&format_int_with_base(i64::MAX, 36), "1y2p0ij32e8e7");
assert_eq!(&format_int_with_base(i64::MIN, 36), "\u{2212}1y2p0ij32e8e8");
}
}

View File

@ -6,8 +6,8 @@ use std::sync::Arc;
use ecow::{eco_format, EcoString};
use serde::{Serialize, Serializer};
use super::{cast, func, scope, ty, Array};
use crate::diag::{bail, SourceResult, StrResult};
use crate::eval::{cast, func, scope, ty, Array};
use crate::syntax::{Span, Spanned};
#[doc(inline)]

View File

@ -2,8 +2,8 @@ use std::collections::HashSet;
use ecow::EcoVec;
use super::Value;
use crate::diag::SourceDiagnostic;
use crate::eval::Value;
use crate::syntax::{FileId, Span};
use crate::util::hash128;

View File

@ -4,8 +4,8 @@ use std::fmt::{self, Debug, Display, Formatter};
use ecow::{eco_format, EcoString};
use once_cell::sync::Lazy;
use super::{cast, func, Func, NativeFuncData, Repr, Scope, Value};
use crate::diag::StrResult;
use crate::eval::{cast, func, Func, NativeFuncData, Repr, Scope, Value};
use crate::util::Static;
#[doc(inline)]

View File

@ -10,13 +10,12 @@ use serde::de::{Error, MapAccess, SeqAccess, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use siphasher::sip128::{Hasher128, SipHasher13};
use super::repr::{format_float, format_int_with_base};
use super::{
fields, ops, Args, Array, AutoValue, Bytes, CastInfo, Content, Dict, Duration,
use crate::diag::StrResult;
use crate::eval::{
fields, ops, repr, Args, Array, AutoValue, Bytes, CastInfo, Content, Dict, Duration,
FromValue, Func, IntoValue, Module, NativeType, NoneValue, Plugin, Reflect, Repr,
Scope, Str, Symbol, Type, Version,
};
use crate::diag::StrResult;
use crate::eval::{item, Datetime};
use crate::geom::{Abs, Angle, Color, Em, Fr, Gradient, Length, Ratio, Rel};
use crate::model::{Label, Styles};
@ -198,8 +197,8 @@ impl Value {
pub fn display(self) -> Content {
match self {
Self::None => Content::empty(),
Self::Int(v) => item!(text)(format_int_with_base(v, 10)),
Self::Float(v) => item!(text)(format_float(v, None, "")),
Self::Int(v) => item!(text)(repr::format_int_with_base(v, 10)),
Self::Float(v) => item!(text)(repr::format_float(v, None, "")),
Self::Str(v) => item!(text)(v.into()),
Self::Version(v) => item!(text)(eco_format!("{v}")),
Self::Symbol(v) => item!(text)(v.get().into()),

View File

@ -5,9 +5,8 @@ use std::iter::repeat;
use ecow::{eco_format, EcoString, EcoVec};
use super::repr::pretty_array_like;
use super::{cast, func, scope, ty, Repr};
use crate::diag::{bail, error, StrResult};
use crate::eval::{cast, func, repr, scope, ty, Repr};
/// A version with an arbitrary number of components.
///
@ -184,7 +183,7 @@ impl Display for Version {
impl Repr for Version {
fn repr(&self) -> EcoString {
let parts: Vec<_> = self.0.iter().map(|v| eco_format!("{v}")).collect();
eco_format!("version{}", &pretty_array_like(&parts, false))
eco_format!("version{}", &repr::pretty_array_like(&parts, false))
}
}

View File

@ -5,7 +5,7 @@ use serde::{Deserialize, Serialize};
use ttf_parser::{name_id, PlatformId, Tag};
use unicode_segmentation::UnicodeSegmentation;
use super::{Font, FontStretch, FontStyle, FontVariant, FontWeight};
use crate::font::{Font, FontStretch, FontStyle, FontVariant, FontWeight};
/// Metadata about a collection of fonts.
#[derive(Debug, Default, Clone, Hash)]

View File

@ -1,5 +1,4 @@
use super::*;
use crate::eval::item;
/// Where to [align]($align) something along an axis.
///

View File

@ -9,18 +9,18 @@ use palette::{
};
use super::*;
use crate::diag::{bail, error, At, SourceResult};
use crate::eval::{cast, Args, Array, IntoValue, Module, Scope, Str};
use crate::diag::{error, At, SourceResult};
use crate::eval::{Args, IntoValue, Module, Scope, Str};
use crate::syntax::{Span, Spanned};
// Type aliases for `palette` internal types in f32.
pub type Oklab = palette::oklab::Oklaba<f32>;
pub type Oklch = palette::oklch::Oklcha<f32>;
pub type LinearRgb = palette::rgb::Rgba<Linear<encoding::Srgb>, f32>;
pub type Rgb = palette::rgb::Rgba<encoding::Srgb, f32>;
pub type Hsl = palette::hsl::Hsla<encoding::Srgb, f32>;
pub type Hsv = palette::hsv::Hsva<encoding::Srgb, f32>;
pub type Luma = palette::luma::Luma<encoding::Srgb, f32>;
pub(crate) type Oklab = palette::oklab::Oklaba<f32>;
pub(crate) type Oklch = palette::oklch::Oklcha<f32>;
pub(crate) type LinearRgb = palette::rgb::Rgba<Linear<encoding::Srgb>, f32>;
pub(crate) type Rgb = palette::rgb::Rgba<encoding::Srgb, f32>;
pub(crate) type Hsl = palette::hsl::Hsla<encoding::Srgb, f32>;
pub(crate) type Hsv = palette::hsv::Hsva<encoding::Srgb, f32>;
pub(crate) type Luma = palette::luma::Luma<encoding::Srgb, f32>;
/// Equivalent of [`std::f32::EPSILON`] but for hue angles.
const ANGLE_EPSILON: f32 = 1e-5;

View File

@ -1,5 +1,4 @@
use super::*;
use crate::eval::item;
/// A length that is relative to the font size.
///

View File

@ -5,10 +5,10 @@ use std::sync::Arc;
use kurbo::Vec2;
use super::color::{Hsl, Hsv};
use super::*;
use crate::diag::{bail, error, SourceResult};
use crate::eval::{array, cast, func, scope, ty, Args, Array, Cast, Func, IntoValue};
use crate::geom::color::{Hsl, Hsv};
use crate::geom::{ColorSpace, Smart};
use crate::syntax::{Span, Spanned};

View File

@ -31,7 +31,7 @@ pub use self::abs::{Abs, AbsUnit};
pub use self::align::{Align, FixedAlign, HAlign, VAlign};
pub use self::angle::{Angle, AngleUnit, Quadrant};
pub use self::axes::{Axes, Axis};
pub use self::color::{Color, ColorSpace, Hsl, Hsv, WeightedColor};
pub use self::color::{Color, ColorSpace, WeightedColor};
pub use self::corners::{Corner, Corners};
pub use self::dir::Dir;
pub use self::ellipse::ellipse;
@ -65,7 +65,7 @@ use ecow::{eco_format, EcoString};
use crate::diag::{bail, StrResult};
use crate::eval::repr::format_float;
use crate::eval::{array, cast, func, scope, ty, Array, Dict, Repr, Smart, Value};
use crate::eval::{array, cast, func, item, scope, ty, Array, Dict, Repr, Smart, Value};
use crate::model::{Fold, Resolve, StyleChain};
/// Generic access to a structure's components.

View File

@ -1,47 +1,5 @@
use super::*;
/// Helper to draw arcs with bezier curves.
trait PathExtension {
fn arc(&mut self, start: Point, center: Point, end: Point);
fn arc_move(&mut self, start: Point, center: Point, end: Point);
fn arc_line(&mut self, start: Point, center: Point, end: Point);
}
/// Get the control points for a bezier curve that approximates a circular arc for
/// a start point, an end point and a center of the circle whose arc connects
/// the two.
fn bezier_arc_control(start: Point, center: Point, end: Point) -> [Point; 2] {
// https://stackoverflow.com/a/44829356/1567835
let a = start - center;
let b = end - center;
let q1 = a.x.to_raw() * a.x.to_raw() + a.y.to_raw() * a.y.to_raw();
let q2 = q1 + a.x.to_raw() * b.x.to_raw() + a.y.to_raw() * b.y.to_raw();
let k2 = (4.0 / 3.0) * ((2.0 * q1 * q2).sqrt() - q2)
/ (a.x.to_raw() * b.y.to_raw() - a.y.to_raw() * b.x.to_raw());
let control_1 = Point::new(center.x + a.x - k2 * a.y, center.y + a.y + k2 * a.x);
let control_2 = Point::new(center.x + b.x + k2 * b.y, center.y + b.y - k2 * b.x);
[control_1, control_2]
}
impl PathExtension for Path {
fn arc(&mut self, start: Point, center: Point, end: Point) {
let arc = bezier_arc_control(start, center, end);
self.cubic_to(arc[0], arc[1], end);
}
fn arc_move(&mut self, start: Point, center: Point, end: Point) {
self.move_to(start);
self.arc(start, center, end);
}
fn arc_line(&mut self, start: Point, center: Point, end: Point) {
self.line_to(start);
self.arc(start, center, end);
}
}
/// Creates a new rectangle as a path.
pub fn clip_rect(
size: Size,
@ -596,3 +554,46 @@ impl ControlPoints {
})
}
}
/// Helper to draw arcs with bezier curves.
trait PathExt {
fn arc(&mut self, start: Point, center: Point, end: Point);
fn arc_move(&mut self, start: Point, center: Point, end: Point);
fn arc_line(&mut self, start: Point, center: Point, end: Point);
}
impl PathExt for Path {
fn arc(&mut self, start: Point, center: Point, end: Point) {
let arc = bezier_arc_control(start, center, end);
self.cubic_to(arc[0], arc[1], end);
}
fn arc_move(&mut self, start: Point, center: Point, end: Point) {
self.move_to(start);
self.arc(start, center, end);
}
fn arc_line(&mut self, start: Point, center: Point, end: Point) {
self.line_to(start);
self.arc(start, center, end);
}
}
/// Get the control points for a bezier curve that approximates a circular arc for
/// a start point, an end point and a center of the circle whose arc connects
/// the two.
fn bezier_arc_control(start: Point, center: Point, end: Point) -> [Point; 2] {
// https://stackoverflow.com/a/44829356/1567835
let a = start - center;
let b = end - center;
let q1 = a.x.to_raw() * a.x.to_raw() + a.y.to_raw() * a.y.to_raw();
let q2 = q1 + a.x.to_raw() * b.x.to_raw() + a.y.to_raw() * b.y.to_raw();
let k2 = (4.0 / 3.0) * ((2.0 * q1 * q2).sqrt() - q2)
/ (a.x.to_raw() * b.y.to_raw() - a.y.to_raw() * b.x.to_raw());
let control_1 = Point::new(center.x + a.x - k2 * a.y, center.y + a.y + k2 * a.x);
let control_2 = Point::new(center.x + b.x + k2 * b.y, center.y + b.y - k2 * b.x);
[control_1, control_2]
}

View File

@ -10,14 +10,15 @@ use serde::{Serialize, Serializer};
use smallvec::SmallVec;
use typst_macros::elem;
use super::{
use crate::diag::{SourceResult, StrResult};
use crate::doc::Meta;
use crate::eval::{
func, repr, scope, ty, Dict, FromValue, IntoValue, Repr, Str, Value, Vm,
};
use crate::model::{
Behave, Behaviour, Element, Guard, Label, Location, NativeElement, Recipe, Selector,
Style, Styles,
};
use crate::diag::{SourceResult, StrResult};
use crate::doc::Meta;
use crate::eval::repr::pretty_array_like;
use crate::eval::{func, scope, ty, Dict, FromValue, IntoValue, Repr, Str, Value, Vm};
use crate::syntax::Span;
/// A piece of document content.
@ -683,7 +684,7 @@ impl Repr for SequenceElem {
} else {
eco_format!(
"[{}]",
pretty_array_like(
repr::pretty_array_like(
&self.children.iter().map(|c| c.0.repr()).collect::<Vec<_>>(),
false
)

View File

@ -8,12 +8,11 @@ use comemo::{Prehashed, Track, Tracked, Validate};
use ecow::{eco_format, EcoString, EcoVec};
use indexmap::IndexMap;
use super::{Content, Selector};
use crate::diag::{bail, StrResult};
use crate::doc::{Frame, FrameItem, Meta, Position};
use crate::eval::{cast, func, scope, ty, Dict, Repr, Value, Vm};
use crate::geom::{Point, Transform};
use crate::model::Label;
use crate::model::{Content, Label, Selector};
use crate::util::NonZeroExt;
/// Identifies an element in the document.

View File

@ -2,12 +2,12 @@ use std::borrow::Cow;
use smallvec::smallvec;
use super::{
Content, Element, MetaElem, NativeElement, Recipe, Selector, StyleChain, Vt,
};
use crate::diag::SourceResult;
use crate::doc::Meta;
use crate::eval::item;
use crate::model::{
Content, Element, MetaElem, NativeElement, Recipe, Selector, StyleChain, Vt,
};
use crate::util::hash128;
/// Whether the target is affected by show rules in the given style chain.

View File

@ -5,13 +5,12 @@ use std::sync::Arc;
use ecow::{eco_format, EcoString, EcoVec};
use smallvec::SmallVec;
use super::{Content, Element, Label, Locatable, Location};
use crate::diag::{bail, StrResult};
use crate::eval::repr::pretty_array_like;
use crate::eval::{
cast, func, item, scope, ty, CastInfo, Dict, FromValue, Func, Reflect, Regex, Repr,
Str, Symbol, Type, Value,
cast, func, item, repr, scope, ty, CastInfo, Dict, FromValue, Func, Reflect, Regex,
Repr, Str, Symbol, Type, Value,
};
use crate::model::{Content, Element, Label, Locatable, Location};
/// A helper macro to create a field selector used in [`Selector::Elem`]
///
@ -259,7 +258,7 @@ impl Repr for Selector {
Self::Or(selectors) | Self::And(selectors) => {
let function = if matches!(self, Self::Or(_)) { "or" } else { "and" };
let pieces: Vec<_> = selectors.iter().map(Selector::repr).collect();
eco_format!("{}{}", function, pretty_array_like(&pieces, false))
eco_format!("{}{}", function, repr::pretty_array_like(&pieces, false))
}
Self::Location(loc) => loc.repr(),
Self::Before { selector, end: split, inclusive }

View File

@ -9,9 +9,9 @@ use ecow::{eco_vec, EcoString, EcoVec};
use once_cell::sync::Lazy;
use smallvec::SmallVec;
use super::{Block, Blockable, Content, Element, NativeElement, Selector, Vt};
use crate::diag::{SourceResult, Trace, Tracepoint};
use crate::eval::{cast, ty, Args, Func, Repr, Value, Vm};
use crate::model::{Block, Blockable, Content, Element, NativeElement, Selector, Vt};
use crate::syntax::Span;
/// A list of style properties.