Skip to content

Commit

Permalink
feat(table): improve pretty-printing for simple tables and lists
Browse files Browse the repository at this point in the history
  • Loading branch information
vhyrro committed Nov 5, 2024
1 parent bb31134 commit 01a406a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 8 deletions.
41 changes: 35 additions & 6 deletions src/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -777,16 +777,45 @@ impl Table {
let mut pairs = self.pairs::<Value, Value>().flatten().collect::<Vec<_>>();
// Sort keys
pairs.sort_by(|(a, _), (b, _)| a.sort_cmp(b));
let is_sequence = pairs.iter().enumerate().all(|(i, (k, _))| {
if let Value::Integer(n) = k {
*n == (i + 1) as Integer
} else {
false
}
});
if pairs.is_empty() {
return write!(fmt, "{{}}");
}
writeln!(fmt, "{{")?;
for (key, value) in pairs {
write!(fmt, "{}[", " ".repeat(ident + 2))?;
key.fmt_pretty(fmt, false, ident + 2, visited)?;
write!(fmt, "] = ")?;
value.fmt_pretty(fmt, true, ident + 2, visited)?;
writeln!(fmt, ",")?;
if is_sequence {
// Format as list
for (_, value) in pairs {
write!(fmt, "{}", " ".repeat(ident + 2))?;
value.fmt_pretty(fmt, true, ident + 2, visited)?;
writeln!(fmt, ",")?;
}
} else {
for (key, value) in pairs {
match key {
Value::String(key)
if key
.to_string_lossy()
.chars()
.all(|c| matches!(c, 'a'..='z' | 'A'..='Z' | '0'..='9' | '_')) =>
{
write!(fmt, "{}{}", " ".repeat(ident + 2), key.to_string_lossy())?;
write!(fmt, " = ")?;
}
_ => {
write!(fmt, "{}[", " ".repeat(ident + 2))?;
key.fmt_pretty(fmt, false, ident + 2, visited)?;
write!(fmt, "] = ")?;
}
}
value.fmt_pretty(fmt, true, ident + 2, visited)?;
writeln!(fmt, ",")?;
}
}
write!(fmt, "{}}}", " ".repeat(ident))
}
Expand Down
2 changes: 1 addition & 1 deletion tests/debug.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ fn test_debug_format() -> Result<()> {
// Globals
let globals = lua.globals();
let dump = format!("{globals:#?}");
assert!(dump.starts_with("{\n [\"_G\"] = table:"));
assert!(dump.starts_with("{\n _G = table:"));

// TODO: Other cases

Expand Down
3 changes: 2 additions & 1 deletion tests/table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,6 +397,7 @@ fn test_table_fmt() -> Result<()> {
.load(
r#"
local t = {1, 2, 3, a = 5, b = { 6 }}
t["special-<chars>"] = 10
t[9.2] = 9.2
t[1.99] = 1.99
t[true] = true
Expand All @@ -410,7 +411,7 @@ fn test_table_fmt() -> Result<()> {
// Pretty print
assert_eq!(
format!("{table:#?}"),
"{\n [false] = false,\n [true] = true,\n [1] = 1,\n [1.99] = 1.99,\n [2] = 2,\n [3] = 3,\n [9.2] = 9.2,\n [\"a\"] = 5,\n [\"b\"] = {\n [1] = 6,\n },\n}"
"{\n [false] = false,\n [true] = true,\n [1] = 1,\n [1.99] = 1.99,\n [2] = 2,\n [3] = 3,\n [9.2] = 9.2,\n a = 5,\n b = {\n 6,\n },\n [\"special-<chars>\"] = 10,\n}"
);

Ok(())
Expand Down

0 comments on commit 01a406a

Please sign in to comment.