Improve symbol repr (#5505)

This commit is contained in:
Malo 2024-12-16 15:10:42 +01:00 committed by GitHub
parent 1b10d19d76
commit 8b1e0d3a23
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 103 additions and 1 deletions

View File

@ -246,10 +246,50 @@ impl Debug for List {
impl crate::foundations::Repr for Symbol {
fn repr(&self) -> EcoString {
eco_format!("\"{}\"", self.get())
match &self.0 {
Repr::Single(c) => eco_format!("symbol(\"{}\")", *c),
Repr::Complex(variants) => {
eco_format!("symbol{}", repr_variants(variants.iter().copied(), ""))
}
Repr::Modified(arc) => {
let (list, modifiers) = arc.as_ref();
if modifiers.is_empty() {
eco_format!("symbol{}", repr_variants(list.variants(), ""))
} else {
eco_format!("symbol{}", repr_variants(list.variants(), modifiers))
}
}
}
}
}
fn repr_variants<'a>(
variants: impl Iterator<Item = (&'a str, char)>,
applied_modifiers: &str,
) -> String {
crate::foundations::repr::pretty_array_like(
&variants
.filter(|(variant, _)| {
// Only keep variants that can still be accessed, i.e., variants
// that contain all applied modifiers.
parts(applied_modifiers).all(|am| variant.split('.').any(|m| m == am))
})
.map(|(variant, c)| {
let trimmed_variant = variant
.split('.')
.filter(|&m| parts(applied_modifiers).all(|am| m != am));
if trimmed_variant.clone().all(|m| m.is_empty()) {
eco_format!("\"{c}\"")
} else {
let trimmed_modifiers = trimmed_variant.collect::<Vec<_>>().join(".");
eco_format!("(\"{}\", \"{}\")", trimmed_modifiers, c)
}
})
.collect::<Vec<_>>(),
false,
)
}
impl Serialize for Symbol {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where

View File

@ -49,3 +49,65 @@
--- symbol-unknown-modifier ---
// Error: 13-20 unknown symbol modifier
#emoji.face.garbage
--- symbol-repr ---
#test(
repr(sym.amp),
`symbol("&", ("inv", "⅋"))`.text,
)
#test(
repr(sym.amp.inv),
`symbol("⅋")`.text,
)
#test(
repr(sym.arrow.double.r),
```
symbol(
"⇒",
("bar", "⤇"),
("long", "⟹"),
("long.bar", "⟾"),
("not", "⇏"),
("l", "⇔"),
("l.long", "⟺"),
("l.not", "⇎"),
)
```.text,
)
#test(repr(sym.smash), "symbol(\"\")")
#let envelope = symbol(
"🖂",
("stamped", "🖃"),
("stamped.pen", "🖆"),
("lightning", "🖄"),
("fly", "🖅"),
)
#test(
repr(envelope),
```
symbol(
"🖂",
("stamped", "🖃"),
("stamped.pen", "🖆"),
("lightning", "🖄"),
("fly", "🖅"),
)
```.text,
)
#test(
repr(envelope.stamped),
`symbol("🖃", ("pen", "🖆"))`.text,
)
#test(
repr(envelope.stamped.pen),
`symbol("🖆")`.text,
)
#test(
repr(envelope.lightning),
`symbol("🖄")`.text,
)
#test(
repr(envelope.fly),
`symbol("🖅")`.text,
)