Make user-facing "debug" representation use Debug instead of Display

This commit is contained in:
Laurenz 2021-08-31 16:25:12 +02:00
parent 3481d8cc81
commit 7f48e8fe66
23 changed files with 131 additions and 320 deletions

View File

@ -20,14 +20,6 @@ impl Debug for Color {
} }
} }
impl Display for Color {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
Self::Rgba(c) => Display::fmt(c, f),
}
}
}
/// An 8-bit RGBA color. /// An 8-bit RGBA color.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)] #[derive(Copy, Clone, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct RgbaColor { pub struct RgbaColor {
@ -104,19 +96,13 @@ impl Debug for RgbaColor {
f, f,
"rgba({:02}, {:02}, {:02}, {:02})", "rgba({:02}, {:02}, {:02}, {:02})",
self.r, self.g, self.b, self.a, self.r, self.g, self.b, self.a,
) )?;
} else { } else {
Display::fmt(self, f)
}
}
}
impl Display for RgbaColor {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)?; write!(f, "#{:02x}{:02x}{:02x}", self.r, self.g, self.b)?;
if self.a != 255 { if self.a != 255 {
write!(f, "{:02x}", self.a)?; write!(f, "{:02x}", self.a)?;
} }
}
Ok(()) Ok(())
} }
} }

View File

@ -1,6 +1,6 @@
use std::cmp::Ordering; use std::cmp::Ordering;
use std::convert::TryFrom; use std::convert::TryFrom;
use std::fmt::{self, Debug, Display, Formatter, Write}; use std::fmt::{self, Debug, Formatter, Write};
use std::iter::FromIterator; use std::iter::FromIterator;
use std::ops::{Add, AddAssign}; use std::ops::{Add, AddAssign};
use std::rc::Rc; use std::rc::Rc;
@ -119,16 +119,10 @@ fn out_of_bounds(index: i64, len: i64) -> String {
} }
impl Debug for Array { impl Debug for Array {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_list().entries(self.0.iter()).finish()
}
}
impl Display for Array {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_char('(')?; f.write_char('(')?;
for (i, value) in self.iter().enumerate() { for (i, value) in self.iter().enumerate() {
Display::fmt(value, f)?; value.fmt(f)?;
if i + 1 < self.0.len() { if i + 1 < self.0.len() {
f.write_str(", ")?; f.write_str(", ")?;
} }

View File

@ -1,5 +1,5 @@
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::fmt::{self, Debug, Display, Formatter, Write}; use std::fmt::{self, Debug, Formatter, Write};
use std::iter::FromIterator; use std::iter::FromIterator;
use std::ops::{Add, AddAssign}; use std::ops::{Add, AddAssign};
use std::rc::Rc; use std::rc::Rc;
@ -79,16 +79,10 @@ impl Dict {
/// The missing key access error message. /// The missing key access error message.
#[cold] #[cold]
fn missing_key(key: &Str) -> String { fn missing_key(key: &Str) -> String {
format!("dictionary does not contain key: {}", key) format!("dictionary does not contain key: {:?}", key)
} }
impl Debug for Dict { impl Debug for Dict {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_map().entries(self.0.iter()).finish()
}
}
impl Display for Dict {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_char('(')?; f.write_char('(')?;
if self.is_empty() { if self.is_empty() {
@ -97,7 +91,7 @@ impl Display for Dict {
for (i, (key, value)) in self.iter().enumerate() { for (i, (key, value)) in self.iter().enumerate() {
f.write_str(key)?; f.write_str(key)?;
f.write_str(": ")?; f.write_str(": ")?;
Display::fmt(value, f)?; value.fmt(f)?;
if i + 1 < self.0.len() { if i + 1 < self.0.len() {
f.write_str(", ")?; f.write_str(", ")?;
} }

View File

@ -1,4 +1,4 @@
use std::fmt::{self, Debug, Display, Formatter, Write}; use std::fmt::{self, Debug, Formatter, Write};
use std::rc::Rc; use std::rc::Rc;
use super::{Cast, EvalContext, Str, Value}; use super::{Cast, EvalContext, Str, Value};
@ -39,12 +39,6 @@ impl Function {
} }
impl Debug for Function { impl Debug for Function {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.debug_struct("Function").field("name", &self.0.name).finish()
}
}
impl Display for Function {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_str("<function")?; f.write_str("<function")?;
if let Some(name) = self.name() { if let Some(name) = self.name() {
@ -63,7 +57,7 @@ impl PartialEq for Function {
} }
/// Evaluated arguments to a function. /// Evaluated arguments to a function.
#[derive(Debug, Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub struct Arguments { pub struct Arguments {
/// The span of the whole argument list. /// The span of the whole argument list.
pub span: Span, pub span: Span,
@ -72,7 +66,7 @@ pub struct Arguments {
} }
/// An argument to a function call: `12` or `draw: false`. /// An argument to a function call: `12` or `draw: false`.
#[derive(Debug, Clone, PartialEq)] #[derive(Clone, PartialEq)]
pub struct Argument { pub struct Argument {
/// The span of the whole argument. /// The span of the whole argument.
pub span: Span, pub span: Span,
@ -192,15 +186,11 @@ impl Arguments {
} }
} }
impl Display for Arguments { impl Debug for Arguments {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_char('(')?; f.write_char('(')?;
for (i, arg) in self.items.iter().enumerate() { for (i, arg) in self.items.iter().enumerate() {
if let Some(name) = &arg.name { arg.fmt(f)?;
f.write_str(name)?;
f.write_str(": ")?;
}
Display::fmt(&arg.value.v, f)?;
if i + 1 < self.items.len() { if i + 1 < self.items.len() {
f.write_str(", ")?; f.write_str(", ")?;
} }
@ -209,6 +199,16 @@ impl Display for Arguments {
} }
} }
impl Debug for Argument {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if let Some(name) = &self.name {
f.write_str(name)?;
f.write_str(": ")?;
}
Debug::fmt(&self.value.v, f)
}
}
dynamic! { dynamic! {
Arguments: "arguments", Arguments: "arguments",
} }

View File

@ -1,6 +1,6 @@
use std::borrow::Borrow; use std::borrow::Borrow;
use std::convert::TryFrom; use std::convert::TryFrom;
use std::fmt::{self, Debug, Display, Formatter, Write}; use std::fmt::{self, Debug, Formatter, Write};
use std::ops::{Add, AddAssign, Deref}; use std::ops::{Add, AddAssign, Deref};
use crate::diag::StrResult; use crate::diag::StrResult;
@ -10,9 +10,9 @@ use crate::util::EcoString;
macro_rules! format_str { macro_rules! format_str {
($($tts:tt)*) => {{ ($($tts:tt)*) => {{
use std::fmt::Write; use std::fmt::Write;
let mut s = $crate::util::EcoString::new(); let mut s = $crate::eval::Str::new();
write!(s, $($tts)*).unwrap(); write!(s, $($tts)*).unwrap();
$crate::eval::Str::from(s) s
}}; }};
} }
@ -66,12 +66,6 @@ impl Deref for Str {
} }
impl Debug for Str { impl Debug for Str {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Debug::fmt(&self.0, f)
}
}
impl Display for Str {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.write_char('"')?; f.write_char('"')?;
for c in self.chars() { for c in self.chars() {
@ -103,6 +97,16 @@ impl AddAssign for Str {
} }
} }
impl Write for Str {
fn write_str(&mut self, s: &str) -> fmt::Result {
self.0.write_str(s)
}
fn write_char(&mut self, c: char) -> fmt::Result {
self.0.write_char(c)
}
}
impl AsRef<str> for Str { impl AsRef<str> for Str {
fn as_ref(&self) -> &str { fn as_ref(&self) -> &str {
self self

View File

@ -1,5 +1,5 @@
use std::convert::TryFrom; use std::convert::TryFrom;
use std::fmt::{self, Debug, Display, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::mem; use std::mem;
use std::ops::{Add, AddAssign}; use std::ops::{Add, AddAssign};
use std::rc::Rc; use std::rc::Rc;
@ -188,12 +188,6 @@ impl Template {
} }
impl Debug for Template { impl Debug for Template {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad("Template { .. }")
}
}
impl Display for Template {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad("<template>") f.pad("<template>")
} }

View File

@ -1,6 +1,6 @@
use std::any::Any; use std::any::Any;
use std::cmp::Ordering; use std::cmp::Ordering;
use std::fmt::{self, Debug, Display, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::rc::Rc; use std::rc::Rc;
use super::{ops, Array, Dict, Function, Str, Template}; use super::{ops, Array, Dict, Function, Str, Template};
@ -11,7 +11,7 @@ use crate::syntax::Spanned;
use crate::util::EcoString; use crate::util::EcoString;
/// A computational value. /// A computational value.
#[derive(Debug, Clone)] #[derive(Clone)]
pub enum Value { pub enum Value {
/// The value that indicates the absence of a meaningful value. /// The value that indicates the absence of a meaningful value.
None, None,
@ -89,6 +89,11 @@ impl Value {
T::cast(self) T::cast(self)
} }
/// Return the debug representation of the value.
pub fn repr(&self) -> Str {
format_str!("{:?}", self)
}
/// Join the value with another value. /// Join the value with another value.
pub fn join(self, rhs: Self) -> StrResult<Self> { pub fn join(self, rhs: Self) -> StrResult<Self> {
ops::join(self, rhs) ops::join(self, rhs)
@ -101,26 +106,26 @@ impl Default for Value {
} }
} }
impl Display for Value { impl Debug for Value {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self { match self {
Self::None => f.pad("none"), Self::None => f.pad("none"),
Self::Auto => f.pad("auto"), Self::Auto => f.pad("auto"),
Self::Bool(v) => Display::fmt(v, f), Self::Bool(v) => Debug::fmt(v, f),
Self::Int(v) => Display::fmt(v, f), Self::Int(v) => Debug::fmt(v, f),
Self::Float(v) => Display::fmt(v, f), Self::Float(v) => Debug::fmt(v, f),
Self::Length(v) => Display::fmt(v, f), Self::Length(v) => Debug::fmt(v, f),
Self::Angle(v) => Display::fmt(v, f), Self::Angle(v) => Debug::fmt(v, f),
Self::Relative(v) => Display::fmt(v, f), Self::Relative(v) => Debug::fmt(v, f),
Self::Linear(v) => Display::fmt(v, f), Self::Linear(v) => Debug::fmt(v, f),
Self::Fractional(v) => Display::fmt(v, f), Self::Fractional(v) => Debug::fmt(v, f),
Self::Color(v) => Display::fmt(v, f), Self::Color(v) => Debug::fmt(v, f),
Self::Str(v) => Display::fmt(v, f), Self::Str(v) => Debug::fmt(v, f),
Self::Array(v) => Display::fmt(v, f), Self::Array(v) => Debug::fmt(v, f),
Self::Dict(v) => Display::fmt(v, f), Self::Dict(v) => Debug::fmt(v, f),
Self::Template(v) => Display::fmt(v, f), Self::Template(v) => Debug::fmt(v, f),
Self::Func(v) => Display::fmt(v, f), Self::Func(v) => Debug::fmt(v, f),
Self::Dyn(v) => Display::fmt(v, f), Self::Dyn(v) => Debug::fmt(v, f),
} }
} }
} }
@ -186,7 +191,7 @@ impl Dynamic {
/// Create a new instance from any value that satisifies the required bounds. /// Create a new instance from any value that satisifies the required bounds.
pub fn new<T>(any: T) -> Self pub fn new<T>(any: T) -> Self
where where
T: Type + Debug + Display + PartialEq + 'static, T: Type + Debug + PartialEq + 'static,
{ {
Self(Rc::new(any)) Self(Rc::new(any))
} }
@ -213,19 +218,13 @@ impl Debug for Dynamic {
} }
} }
impl Display for Dynamic {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(&self.0, f)
}
}
impl PartialEq for Dynamic { impl PartialEq for Dynamic {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
self.0.dyn_eq(other) self.0.dyn_eq(other)
} }
} }
trait Bounds: Debug + Display + 'static { trait Bounds: Debug + 'static {
fn as_any(&self) -> &dyn Any; fn as_any(&self) -> &dyn Any;
fn dyn_eq(&self, other: &Dynamic) -> bool; fn dyn_eq(&self, other: &Dynamic) -> bool;
fn dyn_type_name(&self) -> &'static str; fn dyn_type_name(&self) -> &'static str;
@ -233,7 +232,7 @@ trait Bounds: Debug + Display + 'static {
impl<T> Bounds for T impl<T> Bounds for T
where where
T: Type + Debug + Display + PartialEq + 'static, T: Type + Debug + PartialEq + 'static,
{ {
fn as_any(&self) -> &dyn Any { fn as_any(&self) -> &dyn Any {
self self
@ -420,11 +419,11 @@ mod tests {
#[track_caller] #[track_caller]
fn test(value: impl Into<Value>, exp: &str) { fn test(value: impl Into<Value>, exp: &str) {
assert_eq!(value.into().to_string(), exp); assert_eq!(format!("{:?}", value.into()), exp);
} }
#[test] #[test]
fn test_value_to_string() { fn test_value_debug() {
// Primitives. // Primitives.
test(Value::None, "none"); test(Value::None, "none");
test(false, "false"); test(false, "false");

View File

@ -1,12 +1,10 @@
use std::fmt::Write;
use std::rc::Rc; use std::rc::Rc;
use super::{Eval, EvalContext, Template, Value}; use super::{Eval, EvalContext, Str, Template, Value};
use crate::diag::TypResult; use crate::diag::TypResult;
use crate::geom::Gen; use crate::geom::Gen;
use crate::layout::{ParChild, ParNode, StackChild, StackNode}; use crate::layout::{ParChild, ParNode, StackChild, StackNode};
use crate::syntax::*; use crate::syntax::*;
use crate::util::EcoString;
/// Walk a syntax node and fill the currently built template. /// Walk a syntax node and fill the currently built template.
pub trait Walk { pub trait Walk {
@ -38,13 +36,13 @@ impl Walk for SyntaxNode {
Self::Enum(enum_) => enum_.walk(ctx)?, Self::Enum(enum_) => enum_.walk(ctx)?,
Self::Expr(expr) => match expr.eval(ctx)? { Self::Expr(expr) => match expr.eval(ctx)? {
Value::None => {} Value::None => {}
Value::Int(v) => ctx.template.text(v.to_string()), Value::Int(v) => ctx.template.text(format_str!("{}", v)),
Value::Float(v) => ctx.template.text(v.to_string()), Value::Float(v) => ctx.template.text(format_str!("{}", v)),
Value::Str(v) => ctx.template.text(v), Value::Str(v) => ctx.template.text(v),
Value::Template(v) => ctx.template += v, Value::Template(v) => ctx.template += v,
// For values which can't be shown "naturally", we print the // For values which can't be shown "naturally", we print the
// representation in monospace. // representation in monospace.
other => ctx.template.monospace(other.to_string()), other => ctx.template.monospace(other.repr()),
}, },
} }
Ok(()) Ok(())
@ -91,7 +89,7 @@ impl Walk for HeadingNode {
impl Walk for ListNode { impl Walk for ListNode {
fn walk(&self, ctx: &mut EvalContext) -> TypResult<()> { fn walk(&self, ctx: &mut EvalContext) -> TypResult<()> {
let body = self.body.eval(ctx)?; let body = self.body.eval(ctx)?;
walk_item(ctx, '•'.into(), body); walk_item(ctx, Str::from('•'), body);
Ok(()) Ok(())
} }
} }
@ -99,20 +97,19 @@ impl Walk for ListNode {
impl Walk for EnumNode { impl Walk for EnumNode {
fn walk(&self, ctx: &mut EvalContext) -> TypResult<()> { fn walk(&self, ctx: &mut EvalContext) -> TypResult<()> {
let body = self.body.eval(ctx)?; let body = self.body.eval(ctx)?;
let mut label = EcoString::new(); let label = format_str!("{}.", self.number.unwrap_or(1));
write!(&mut label, "{}.", self.number.unwrap_or(1)).unwrap();
walk_item(ctx, label, body); walk_item(ctx, label, body);
Ok(()) Ok(())
} }
} }
fn walk_item(ctx: &mut EvalContext, label: EcoString, body: Template) { fn walk_item(ctx: &mut EvalContext, label: Str, body: Template) {
ctx.template += Template::from_block(move |state| { ctx.template += Template::from_block(move |state| {
let label = ParNode { let label = ParNode {
dir: state.dirs.inline, dir: state.dirs.inline,
line_spacing: state.line_spacing(), line_spacing: state.line_spacing(),
children: vec![ParChild::Text( children: vec![ParChild::Text(
label.clone(), (&label).into(),
state.aligns.inline, state.aligns.inline,
Rc::clone(&state.font), Rc::clone(&state.font),
vec![], vec![],

View File

@ -1,7 +1,7 @@
//! Font handling. //! Font handling.
use std::collections::{hash_map::Entry, BTreeMap, HashMap}; use std::collections::{hash_map::Entry, BTreeMap, HashMap};
use std::fmt::{self, Debug, Display, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::rc::Rc; use std::rc::Rc;
@ -282,7 +282,7 @@ impl Face {
} }
/// Identifies a vertical metric of a font. /// Identifies a vertical metric of a font.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum VerticalFontMetric { pub enum VerticalFontMetric {
/// The distance from the baseline to the typographic ascender. /// The distance from the baseline to the typographic ascender.
/// ///
@ -302,7 +302,7 @@ pub enum VerticalFontMetric {
Descender, Descender,
} }
impl Display for VerticalFontMetric { impl Debug for VerticalFontMetric {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self { f.pad(match self {
Self::Ascender => "ascender", Self::Ascender => "ascender",
@ -315,7 +315,7 @@ impl Display for VerticalFontMetric {
} }
/// A generic or named font family. /// A generic or named font family.
#[derive(Debug, Clone, Eq, PartialEq, Hash)] #[derive(Clone, Eq, PartialEq, Hash)]
pub enum FontFamily { pub enum FontFamily {
/// A family that has "serifs", small strokes attached to letters. /// A family that has "serifs", small strokes attached to letters.
Serif, Serif,
@ -327,7 +327,7 @@ pub enum FontFamily {
Named(String), Named(String),
} }
impl Display for FontFamily { impl Debug for FontFamily {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self { f.pad(match self {
Self::Serif => "serif", Self::Serif => "serif",
@ -409,7 +409,7 @@ pub fn find_name(mut names: ttf_parser::Names<'_>, name_id: u16) -> Option<Strin
} }
/// Properties that distinguish a face from other faces in the same family. /// Properties that distinguish a face from other faces in the same family.
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)] #[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub struct FontVariant { pub struct FontVariant {
/// The style of the face (normal / italic / oblique). /// The style of the face (normal / italic / oblique).
@ -427,14 +427,14 @@ impl FontVariant {
} }
} }
impl Display for FontVariant { impl Debug for FontVariant {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}-{}-{}", self.style, self.weight, self.stretch) write!(f, "{:?}-{:?}-{:?}", self.style, self.weight, self.stretch)
} }
} }
/// The style of a font face. /// The style of a font face.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")] #[serde(rename_all = "kebab-case")]
pub enum FontStyle { pub enum FontStyle {
@ -446,36 +446,19 @@ pub enum FontStyle {
Oblique, Oblique,
} }
impl FontStyle {
/// Create a font style from a lowercase name like `italic`.
pub fn from_str(name: &str) -> Option<FontStyle> {
Some(match name {
"normal" => Self::Normal,
"italic" => Self::Italic,
"oblique" => Self::Oblique,
_ => return None,
})
}
/// The lowercase string representation of this style.
pub fn to_str(self) -> &'static str {
match self {
Self::Normal => "normal",
Self::Italic => "italic",
Self::Oblique => "oblique",
}
}
}
impl Default for FontStyle { impl Default for FontStyle {
fn default() -> Self { fn default() -> Self {
Self::Normal Self::Normal
} }
} }
impl Display for FontStyle { impl Debug for FontStyle {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(self.to_str()) f.pad(match self {
Self::Normal => "normal",
Self::Italic => "italic",
Self::Oblique => "oblique",
})
} }
} }
@ -519,44 +502,11 @@ impl FontWeight {
Self(weight.max(100).min(900)) Self(weight.max(100).min(900))
} }
/// Create a font weight from a lowercase name like `light`.
pub fn from_str(name: &str) -> Option<Self> {
Some(match name {
"thin" => Self::THIN,
"extralight" => Self::EXTRALIGHT,
"light" => Self::LIGHT,
"regular" => Self::REGULAR,
"medium" => Self::MEDIUM,
"semibold" => Self::SEMIBOLD,
"bold" => Self::BOLD,
"extrabold" => Self::EXTRABOLD,
"black" => Self::BLACK,
_ => return None,
})
}
/// The number between 100 and 900. /// The number between 100 and 900.
pub fn to_number(self) -> u16 { pub fn to_number(self) -> u16 {
self.0 self.0
} }
/// The lowercase string representation of this weight if it is divisible by
/// 100.
pub fn to_str(self) -> Option<&'static str> {
Some(match self {
Self::THIN => "thin",
Self::EXTRALIGHT => "extralight",
Self::LIGHT => "light",
Self::REGULAR => "regular",
Self::MEDIUM => "medium",
Self::SEMIBOLD => "semibold",
Self::BOLD => "bold",
Self::EXTRABOLD => "extrabold",
Self::BLACK => "black",
_ => return None,
})
}
/// Add (or remove) weight, saturating at the boundaries of 100 and 900. /// Add (or remove) weight, saturating at the boundaries of 100 and 900.
pub fn thicken(self, delta: i16) -> Self { pub fn thicken(self, delta: i16) -> Self {
Self((self.0 as i16).saturating_add(delta).max(100).min(900) as u16) Self((self.0 as i16).saturating_add(delta).max(100).min(900) as u16)
@ -575,27 +525,18 @@ impl Default for FontWeight {
} }
impl Debug for FontWeight { impl Debug for FontWeight {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.pad(match *self {
Self::THIN => "Thin",
Self::EXTRALIGHT => "Extralight",
Self::LIGHT => "Light",
Self::REGULAR => "Regular",
Self::MEDIUM => "Medium",
Self::SEMIBOLD => "Semibold",
Self::BOLD => "Bold",
Self::EXTRABOLD => "Extrabold",
Self::BLACK => "Black",
_ => return write!(f, "{}", self.0),
})
}
}
impl Display for FontWeight {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.to_str() { match *self {
Some(name) => f.pad(name), Self::THIN => f.pad("thin"),
None => write!(f, "{}", self.0), Self::EXTRALIGHT => f.pad("extralight"),
Self::LIGHT => f.pad("light"),
Self::REGULAR => f.pad("regular"),
Self::MEDIUM => f.pad("medium"),
Self::SEMIBOLD => f.pad("semibold"),
Self::BOLD => f.pad("bold"),
Self::EXTRABOLD => f.pad("extrabold"),
Self::BLACK => f.pad("black"),
_ => write!(f, "{}", self.0),
} }
} }
} }
@ -656,44 +597,11 @@ impl FontStretch {
} }
} }
/// Create a font stretch from a lowercase name like `extra-expanded`.
pub fn from_str(name: &str) -> Option<Self> {
Some(match name {
"ultra-condensed" => Self::ULTRA_CONDENSED,
"extra-condensed" => Self::EXTRA_CONDENSED,
"condensed" => Self::CONDENSED,
"semi-condensed" => Self::SEMI_CONDENSED,
"normal" => Self::NORMAL,
"semi-expanded" => Self::SEMI_EXPANDED,
"expanded" => Self::EXPANDED,
"extra-expanded" => Self::EXTRA_EXPANDED,
"ultra-expanded" => Self::ULTRA_EXPANDED,
_ => return None,
})
}
/// The ratio between 0.5 and 2.0 corresponding to this stretch. /// The ratio between 0.5 and 2.0 corresponding to this stretch.
pub fn to_ratio(self) -> f32 { pub fn to_ratio(self) -> f32 {
self.0 as f32 / 1000.0 self.0 as f32 / 1000.0
} }
/// The lowercase string representation of this stretch is one of the named
/// ones.
pub fn to_str(self) -> Option<&'static str> {
Some(match self {
Self::ULTRA_CONDENSED => "ultra-condensed",
Self::EXTRA_CONDENSED => "extra-condensed",
Self::CONDENSED => "condensed",
Self::SEMI_CONDENSED => "semi-condensed",
Self::NORMAL => "normal",
Self::SEMI_EXPANDED => "semi-expanded",
Self::EXPANDED => "expanded",
Self::EXTRA_EXPANDED => "extra-expanded",
Self::ULTRA_EXPANDED => "ultra-expanded",
_ => return None,
})
}
/// The absolute ratio distance between this and another font stretch. /// The absolute ratio distance between this and another font stretch.
pub fn distance(self, other: Self) -> f32 { pub fn distance(self, other: Self) -> f32 {
(self.to_ratio() - other.to_ratio()).abs() (self.to_ratio() - other.to_ratio()).abs()
@ -708,26 +616,17 @@ impl Default for FontStretch {
impl Debug for FontStretch { impl Debug for FontStretch {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match *self { match *self {
s if s == Self::ULTRA_CONDENSED => "UltraCondensed", Self::ULTRA_CONDENSED => f.pad("ultra-condensed"),
s if s == Self::EXTRA_CONDENSED => "ExtraCondensed", Self::EXTRA_CONDENSED => f.pad("extra-condensed"),
s if s == Self::CONDENSED => "Condensed", Self::CONDENSED => f.pad("condensed"),
s if s == Self::SEMI_CONDENSED => "SemiCondensed", Self::SEMI_CONDENSED => f.pad("semi-condensed"),
s if s == Self::NORMAL => "Normal", Self::NORMAL => f.pad("normal"),
s if s == Self::SEMI_EXPANDED => "SemiExpanded", Self::SEMI_EXPANDED => f.pad("semi-expanded"),
s if s == Self::EXPANDED => "Expanded", Self::EXPANDED => f.pad("expanded"),
s if s == Self::EXTRA_EXPANDED => "ExtraExpanded", Self::EXTRA_EXPANDED => f.pad("extra-expanded"),
s if s == Self::ULTRA_EXPANDED => "UltraExpanded", Self::ULTRA_EXPANDED => f.pad("ultra-expanded"),
_ => return write!(f, "{}", self.0), _ => write!(f, "{}", self.to_ratio()),
})
}
}
impl Display for FontStretch {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self.to_str() {
Some(name) => f.pad(name),
None => write!(f, "{}", self.to_ratio()),
} }
} }
} }

View File

@ -1,7 +1,7 @@
use super::*; use super::*;
/// Where to align something along an axis. /// Where to align something along an axis.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub enum Align { pub enum Align {
/// Align at the start of the axis. /// Align at the start of the axis.
Start, Start,
@ -81,7 +81,7 @@ impl Default for Align {
} }
} }
impl Display for Align { impl Debug for Align {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self { f.pad(match self {
Self::Start => "start", Self::Start => "start",

View File

@ -58,13 +58,6 @@ impl Angle {
} }
impl Debug for Angle { impl Debug for Angle {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let unit = AngularUnit::Deg;
write!(f, "{}{}", self.to_unit(unit), unit)
}
}
impl Display for Angle {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
// Format with the unit that yields the shortest output, preferring // Format with the unit that yields the shortest output, preferring
// degrees when tied. // degrees when tied.
@ -74,7 +67,7 @@ impl Display for Angle {
.min_by_key(|&unit| self.to_unit(unit).to_string().len()) .min_by_key(|&unit| self.to_unit(unit).to_string().len())
.unwrap(); .unwrap();
write!(f, "{}{}", self.to_unit(unit), unit) write!(f, "{}{:?}", self.to_unit(unit), unit)
} }
} }
@ -139,7 +132,7 @@ impl Sum for Angle {
} }
} }
/// Different units of angular measurement. /// Different units of angular measurement.
#[derive(Debug, Copy, Clone, Eq, PartialEq)] #[derive(Copy, Clone, Eq, PartialEq)]
pub enum AngularUnit { pub enum AngularUnit {
/// Radians. /// Radians.
Rad, Rad,
@ -157,7 +150,7 @@ impl AngularUnit {
} }
} }
impl Display for AngularUnit { impl Debug for AngularUnit {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self { f.pad(match self {
Self::Rad => "rad", Self::Rad => "rad",

View File

@ -1,7 +1,7 @@
use super::*; use super::*;
/// The four directions into which content can be laid out. /// The four directions into which content can be laid out.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] #[derive(Copy, Clone, Eq, PartialEq, Hash)]
pub enum Dir { pub enum Dir {
/// Left to right. /// Left to right.
LTR, LTR,
@ -71,7 +71,7 @@ impl Dir {
} }
} }
impl Display for Dir { impl Debug for Dir {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self { f.pad(match self {
Self::LTR => "ltr", Self::LTR => "ltr",

View File

@ -45,12 +45,6 @@ impl Em {
} }
impl Debug for Em { impl Debug for Em {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl Display for Em {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}em", self.get()) write!(f, "{}em", self.get())
} }

View File

@ -37,12 +37,6 @@ impl Fractional {
} }
impl Debug for Fractional { impl Debug for Fractional {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl Display for Fractional {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}fr", self.get()) write!(f, "{}fr", self.get())
} }

View File

@ -115,12 +115,3 @@ impl GenAxis {
} }
} }
} }
impl Display for GenAxis {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self {
Self::Inline => "inline",
Self::Block => "block",
})
}
}

View File

@ -129,13 +129,6 @@ impl Length {
} }
impl Debug for Length { impl Debug for Length {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let unit = LengthUnit::Pt;
write!(f, "{}{}", self.to_unit(unit), unit)
}
}
impl Display for Length {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
use LengthUnit::*; use LengthUnit::*;
@ -147,7 +140,7 @@ impl Display for Length {
.min_by_key(|&unit| self.to_unit(unit).to_string().len()) .min_by_key(|&unit| self.to_unit(unit).to_string().len())
.unwrap(); .unwrap();
write!(f, "{}{}", self.to_unit(unit), unit) write!(f, "{}{:?}", self.to_unit(unit), unit)
} }
} }
@ -219,7 +212,7 @@ impl<'a> Sum<&'a Length> for Length {
} }
/// Different units of length measurement. /// Different units of length measurement.
#[derive(Debug, Copy, Clone, Eq, PartialEq)] #[derive(Copy, Clone, Eq, PartialEq)]
pub enum LengthUnit { pub enum LengthUnit {
/// Points. /// Points.
Pt, Pt,
@ -243,7 +236,7 @@ impl LengthUnit {
} }
} }
impl Display for LengthUnit { impl Debug for LengthUnit {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self { f.pad(match self {
LengthUnit::Mm => "mm", LengthUnit::Mm => "mm",
@ -265,9 +258,9 @@ mod tests {
#[test] #[test]
fn test_length_formatting() { fn test_length_formatting() {
assert_eq!(Length::pt(23.0).to_string(), "23pt"); assert_eq!(format!("{:?}", Length::pt(23.0)), "23pt");
assert_eq!(Length::pt(-28.3465).to_string(), "-1cm"); assert_eq!(format!("{:?}", Length::pt(-28.3465)), "-1cm");
assert_eq!(Length::cm(12.728).to_string(), "12.728cm"); assert_eq!(format!("{:?}", Length::cm(12.728)), "12.728cm");
assert_eq!(Length::cm(4.5).to_string(), "45mm"); assert_eq!(format!("{:?}", Length::cm(4.5)), "45mm");
} }
} }

View File

@ -53,12 +53,6 @@ impl Debug for Linear {
} }
} }
impl Display for Linear {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{} + {}", self.rel, self.abs)
}
}
impl From<Length> for Linear { impl From<Length> for Linear {
fn from(abs: Length) -> Self { fn from(abs: Length) -> Self {
Self { rel: Relative::zero(), abs } Self { rel: Relative::zero(), abs }

View File

@ -33,7 +33,7 @@ pub use size::*;
pub use spec::*; pub use spec::*;
use std::f64::consts::PI; use std::f64::consts::PI;
use std::fmt::{self, Debug, Display, Formatter}; use std::fmt::{self, Debug, Formatter};
use std::iter::Sum; use std::iter::Sum;
use std::ops::*; use std::ops::*;

View File

@ -50,12 +50,6 @@ impl Relative {
} }
impl Debug for Relative { impl Debug for Relative {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
Display::fmt(self, f)
}
}
impl Display for Relative {
fn fmt(&self, f: &mut Formatter) -> fmt::Result { fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}%", 100.0 * self.get()) write!(f, "{}%", 100.0 * self.get())
} }

View File

@ -128,12 +128,3 @@ impl SpecAxis {
} }
} }
} }
impl Display for SpecAxis {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
f.pad(match self {
Self::Horizontal => "horizontal",
Self::Vertical => "vertical",
})
}
}

View File

@ -12,7 +12,7 @@ pub fn type_(_: &mut EvalContext, args: &mut Arguments) -> TypResult<Value> {
/// `repr`: The string representation of a value. /// `repr`: The string representation of a value.
pub fn repr(_: &mut EvalContext, args: &mut Arguments) -> TypResult<Value> { pub fn repr(_: &mut EvalContext, args: &mut Arguments) -> TypResult<Value> {
Ok(args.expect::<Value>("value")?.to_string().into()) Ok(args.expect::<Value>("value")?.repr().into())
} }
/// `join`: Join a sequence of values, optionally interspersing it with another /// `join`: Join a sequence of values, optionally interspersing it with another

View File

@ -223,8 +223,8 @@ impl Pretty for Lit {
Self::Bool(_, v) => write!(p, "{}", v).unwrap(), Self::Bool(_, v) => write!(p, "{}", v).unwrap(),
Self::Int(_, v) => write!(p, "{}", v).unwrap(), Self::Int(_, v) => write!(p, "{}", v).unwrap(),
Self::Float(_, v) => write!(p, "{}", v).unwrap(), Self::Float(_, v) => write!(p, "{}", v).unwrap(),
Self::Length(_, v, u) => write!(p, "{}{}", v, u).unwrap(), Self::Length(_, v, u) => write!(p, "{}{:?}", v, u).unwrap(),
Self::Angle(_, v, u) => write!(p, "{}{}", v, u).unwrap(), Self::Angle(_, v, u) => write!(p, "{}{:?}", v, u).unwrap(),
Self::Percent(_, v) => write!(p, "{}%", v).unwrap(), Self::Percent(_, v) => write!(p, "{}%", v).unwrap(),
Self::Fractional(_, v) => write!(p, "{}fr", v).unwrap(), Self::Fractional(_, v) => write!(p, "{}fr", v).unwrap(),
Self::Str(_, v) => write!(p, "{:?}", v).unwrap(), Self::Str(_, v) => write!(p, "{:?}", v).unwrap(),

View File

@ -388,7 +388,7 @@ fn draw(ctx: &Context, frames: &[Rc<Frame>], dpp: f32) -> sk::Pixmap {
let pixel_height = (dpp * height.to_pt() as f32) as u32; let pixel_height = (dpp * height.to_pt() as f32) as u32;
if pixel_width > 4000 || pixel_height > 4000 { if pixel_width > 4000 || pixel_height > 4000 {
panic!( panic!(
"overlarge image: {} by {} ({} x {})", "overlarge image: {} by {} ({:?} x {:?})",
pixel_width, pixel_height, width, height, pixel_width, pixel_height, width, height,
); );
} }