use std::collections::{BTreeMap, HashMap, HashSet};
use crate::compact::{has_header_modifier, is_hoisted_heading};
use crate::entry_syntax::{
is_simple_segment, match_entry, quoted_end, read_key, CHILD_SUFFIX, CHILD_TAG, MAX_CHILD_DEPTH,
NAMED_MARKER,
};
use crate::error::Error;
use crate::table_encode::{plan_table, table_header, LegacyFormat};
use crate::value::{JsonObject, JsonString, JsonValue};
#[derive(Clone, Copy)]
struct RowRange {
start: usize,
end: usize,
}
struct ChildCandidate<'a> {
rows: Vec<&'a JsonObject>,
groups: BTreeMap<usize, RowRange>,
}
struct ChildColumnEnc {
groups: BTreeMap<usize, RowRange>,
table: ChildTableEnc,
}
struct GroupRef {
heading: String,
position: usize,
range: RowRange,
child_index: usize,
}
struct ChildTableEnc {
header: String,
rows: Vec<String>,
trim_trailing: bool,
children: Vec<(JsonString, ChildColumnEnc)>,
groups: HashMap<usize, Vec<GroupRef>>,
}
fn list_of_rows(value: &JsonValue) -> Option<Vec<&JsonObject>> {
let JsonValue::Array(arr) = value else {
return None;
};
if arr.is_empty() {
return None;
}
let mut rows = Vec::with_capacity(arr.len());
for item in arr {
match item {
JsonValue::Object(obj) => rows.push(obj),
_ => return None,
}
}
Some(rows)
}
fn collect_children<'a>(
rows: &[&'a JsonObject],
depth: usize,
write_cell: &dyn Fn(&JsonValue) -> String,
compact16: bool,
) -> Vec<(JsonString, ChildColumnEnc)> {
let mut cand_order: Vec<JsonString> = Vec::new();
let mut candidates: HashMap<JsonString, ChildCandidate<'a>> = HashMap::new();
let mut blocked: HashSet<JsonString> = HashSet::new();
for (index, row) in rows.iter().enumerate() {
for (field, value) in row.ordered_entries() {
if !value.is_null() && !matches!(value, JsonValue::Array(_)) {
blocked.insert(field.clone());
}
if blocked.contains(field) {
continue;
}
let Some(child_rows) = list_of_rows(value) else {
continue;
};
if !candidates.contains_key(field) {
cand_order.push(field.clone());
candidates.insert(
field.clone(),
ChildCandidate {
rows: Vec::new(),
groups: BTreeMap::new(),
},
);
}
let cand = candidates.get_mut(field).unwrap();
let start = cand.rows.len();
cand.rows.extend(child_rows);
cand.groups.insert(
index,
RowRange {
start,
end: cand.rows.len(),
},
);
}
}
let mut children = Vec::new();
for field in cand_order {
if blocked.contains(&field) {
continue;
}
let cand = candidates.remove(&field).unwrap();
if let Some(table) = plan_child_table(&cand.rows, &[], depth + 1, write_cell, compact16) {
children.push((
field,
ChildColumnEnc {
groups: cand.groups,
table,
},
));
}
}
children
}
fn plan_child_table(
rows: &[&JsonObject],
keys: &[&JsonString],
depth: usize,
write_cell: &dyn Fn(&JsonValue) -> String,
compact16: bool,
) -> Option<ChildTableEnc> {
let mut children_map: HashMap<JsonString, ChildColumnEnc> = if depth < MAX_CHILD_DEPTH {
collect_children(rows, depth, write_cell, compact16)
.into_iter()
.collect()
} else {
HashMap::new()
};
loop {
if depth == 0 && children_map.is_empty() {
return None;
}
let projected_owned: Vec<JsonObject>;
let projected_refs: Vec<&JsonObject> = if children_map.is_empty() {
rows.to_vec()
} else {
projected_owned = rows
.iter()
.enumerate()
.map(|(index, row)| {
let mut obj = JsonObject::with_capacity(row.len());
for (field, value) in row.ordered_entries() {
let replaced = children_map
.get(field)
.is_some_and(|c| c.groups.contains_key(&index));
obj.push_unique(
field.clone(),
if replaced {
JsonValue::Number(0.0)
} else {
value.clone()
},
);
}
obj
})
.collect();
projected_owned.iter().collect()
};
let skip_mod: Option<HashSet<JsonString>> = if children_map.is_empty() {
None
} else {
Some(children_map.keys().cloned().collect())
};
let plan = plan_table(
&projected_refs,
LegacyFormat::V1_4,
keys,
usize::MAX,
write_cell,
depth > 0,
compact16,
skip_mod.as_ref(),
None,
)?;
let mut ordered_fields: Vec<JsonString> = Vec::new();
let mut matched_headings: Vec<(usize, JsonString, String, usize)> = Vec::new();
for (position, heading) in plan.headings.iter().enumerate() {
if children_map.is_empty() || (!keys.is_empty() && position == 0) {
continue;
}
let active_pos = plan.active_positions[position];
if active_pos < 0 {
continue;
}
let quoted = heading.starts_with('"');
let is_plain = if quoted {
quoted_end(heading, 0) == Some(heading.len())
} else {
!heading.contains('.')
&& !heading.contains('=')
&& !heading.contains('~')
&& !heading.contains('+')
};
if !is_plain {
continue;
}
let field = if quoted {
match read_key(heading) {
Ok(k) => k,
Err(_) => continue,
}
} else {
JsonString::from(heading.as_str())
};
let Some(child) = children_map.get(&field) else {
continue;
};
if child.groups.keys().any(|idx| plan.break_rows.contains(idx)) {
continue;
}
ordered_fields.push(field.clone());
matched_headings.push((position, field, heading.clone(), active_pos as usize));
}
if ordered_fields.len() == children_map.len() {
let mut headings = plan.headings.clone();
let mut ordered_children: Vec<(JsonString, ChildColumnEnc)> =
Vec::with_capacity(ordered_fields.len());
let mut groups: HashMap<usize, Vec<GroupRef>> = HashMap::new();
for (child_idx, (position, field, heading, active_pos)) in
matched_headings.into_iter().enumerate()
{
headings[position] = format!("{}{}", heading, CHILD_SUFFIX);
let child = children_map.remove(&field).unwrap();
for (&row_idx, &range) in &child.groups {
groups.entry(row_idx).or_default().push(GroupRef {
heading: heading.clone(),
position: active_pos,
range,
child_index: child_idx,
});
}
ordered_children.push((field, child));
}
let trim_trailing = compact16
&& !plan.named
&& plan.headings.iter().enumerate().any(|(i, h)| {
plan.active_positions[i] == -1
|| h.contains('~')
|| h.contains('=')
|| h.contains("?.")
});
return Some(ChildTableEnc {
header: table_header(&headings, plan.named),
rows: plan.rows,
trim_trailing,
children: ordered_children,
groups,
});
}
let keep: HashSet<JsonString> = ordered_fields.into_iter().collect();
children_map.retain(|k, _| keep.contains(k));
}
}
fn render_child_table(table: &ChildTableEnc) -> String {
let mut out: Vec<String> = Vec::new();
fn write_headers(plan: &ChildTableEnc, indent: &str, out: &mut Vec<String>) {
out.push(format!("{}{}", indent, plan.header));
let next_indent = format!("{} ", indent);
for (_, child) in &plan.children {
write_headers(&child.table, &next_indent, out);
}
}
fn write_rows(plan: &ChildTableEnc, range: RowRange, indent: &str, out: &mut Vec<String>) {
let next_indent = format!("{} ", indent);
for row_idx in range.start..range.end {
let row = &plan.rows[row_idx];
let Some(groups) = plan.groups.get(&row_idx) else {
out.push(format!("{}{}", indent, row));
continue;
};
let omitted: HashSet<usize> = groups.iter().map(|g| g.position).collect();
let mut kept: Vec<&str> = row
.split('\t')
.enumerate()
.filter(|(pos, _)| !omitted.contains(pos))
.map(|(_, cell)| cell)
.collect();
if plan.trim_trailing {
while kept.last().is_some_and(|s| s.is_empty()) {
kept.pop();
}
}
out.push(format!("{}{}", indent, kept.join("\t")));
for group in groups {
if plan.children.len() > 1 {
out.push(format!("{}{}{}", next_indent, CHILD_TAG, group.heading));
}
write_rows(
&plan.children[group.child_index].1.table,
group.range,
&next_indent,
out,
);
}
}
}
write_headers(table, "", &mut out);
write_rows(
table,
RowRange {
start: 0,
end: table.rows.len(),
},
"",
&mut out,
);
out.join("\n")
}
pub(crate) fn child_table_candidate(
value: &JsonValue,
baseline: &str,
write_cell: &dyn Fn(&JsonValue) -> String,
compact16: bool,
) -> String {
if let JsonValue::Array(arr) = value {
if arr.len() < 2 {
return baseline.to_owned();
}
let Some(rows) = list_of_rows(value) else {
return baseline.to_owned();
};
return match plan_child_table(&rows, &[], 0, write_cell, compact16) {
Some(table) => format!("[{}]\n{}", arr.len(), render_child_table(&table)),
None => baseline.to_owned(),
};
}
if baseline == "{}" {
return baseline.to_owned();
}
let lines: Vec<&str> = baseline.split('\n').collect();
let mut parts: Vec<String> = Vec::new();
let mut index = 0;
while index < lines.len() {
let line = lines[index];
let Ok(Some(m)) = match_entry(line, true) else {
return baseline.to_owned();
};
let count_str = m.list_count.or(m.keyed_count);
let next = match count_str {
None => index + 1,
Some(cs) => {
let Ok(n) = cs.parse::<usize>() else {
return baseline.to_owned();
};
index + n + 2
}
};
let mut entry: Option<&JsonValue> = Some(value);
for key_raw in &m.keys {
entry = match entry {
Some(JsonValue::Object(obj)) => {
read_key(key_raw).ok().and_then(|k| obj.get_json(&k))
}
_ => None,
};
}
let mut keyed_keys: Vec<&JsonString> = Vec::new();
let mut table_rows: Option<Vec<&JsonObject>> = None;
if m.keyed_count.is_some() {
if let Some(JsonValue::Object(obj)) = entry {
let ordered = obj.ordered_entries();
if ordered.len() >= 2
&& ordered
.iter()
.all(|(_, v)| matches!(v, JsonValue::Object(_)))
{
let mut rows = Vec::with_capacity(ordered.len());
for (k, v) in ordered {
keyed_keys.push(k);
if let JsonValue::Object(o) = v {
rows.push(o);
}
}
table_rows = Some(rows);
}
}
} else if let Some(ent) = entry {
if let Some(rows) = list_of_rows(ent) {
if rows.len() >= 2 {
table_rows = Some(rows);
}
}
}
let built = table_rows
.and_then(|rows| plan_child_table(&rows, &keyed_keys, 0, write_cell, compact16));
if let Some(table) = built {
let name = m.keys.join("/");
let count_part = if !keyed_keys.is_empty() {
format!("{{{}}}", keyed_keys.len())
} else {
format!("[{}]", table.rows.len())
};
parts.push(format!(
"{}{}:\n{}",
name,
count_part,
render_child_table(&table)
));
} else {
parts.push(lines[index..next.min(lines.len())].join("\n"));
}
index = next;
}
parts.join("\n")
}
fn is_child_column_heading(heading: &str) -> bool {
let Some(name) = heading.strip_suffix(CHILD_SUFFIX) else {
return false;
};
if name.starts_with('"') {
quoted_end(name, 0) == Some(name.len())
} else {
!name.contains('=') && !name.contains('+') && !name.contains('~') && !name.contains("?.")
}
}
pub(crate) fn has_child_heading(header: Option<&str>) -> bool {
let Some(h) = header else {
return false;
};
if !h.contains(CHILD_SUFFIX) {
return false;
}
h.split('\t').any(is_child_column_heading)
}
fn indent_of(line: Option<&str>) -> isize {
let Some(l) = line else {
return -1;
};
l.bytes().take_while(|&b| b == b' ').count() as isize
}
struct ChildColumnDec {
name: String,
position: usize,
field: JsonString,
table: ChildTableDec,
groups: BTreeMap<usize, RowRange>,
}
struct ChildTableDec {
lines: Vec<String>,
keyed: bool,
row_depth: usize,
width: usize,
trimmed: bool,
children: Vec<ChildColumnDec>,
}
pub(crate) struct ChildTableResult {
pub value: JsonValue,
pub next: usize,
pub tagged: bool,
}
pub(crate) fn read_child_table<F>(
lines: &[&str],
start: usize,
count: usize,
keyed: bool,
row_depth: usize,
read_table: &mut F,
) -> Result<ChildTableResult, Error>
where
F: FnMut(&[&str], usize, usize, bool, usize) -> Result<JsonValue, Error>,
{
if count > lines.len().saturating_sub(start + 1) {
return Err(Error::syntax("Row count mismatch."));
}
let mut cursor = start;
let mut tagged = false;
fn take<'a>(lines: &[&'a str], cursor: &mut usize, depth: usize) -> Result<&'a str, Error> {
let line = lines.get(*cursor).copied();
if line.is_none() || indent_of(line) != depth as isize {
return Err(Error::syntax("Wrong child indentation or row count."));
}
*cursor += 1;
Ok(&line.unwrap()[depth..])
}
fn read_header(
lines: &[&str],
cursor: &mut usize,
depth: usize,
keyed: bool,
row_depth: usize,
) -> Result<ChildTableDec, Error> {
if depth > MAX_CHILD_DEPTH {
return Err(Error::syntax("Too many child levels."));
}
let mut headings: Vec<String> = take(lines, cursor, depth)?
.split('\t')
.map(str::to_owned)
.collect();
let named = headings.last().is_some_and(|h| h == NAMED_MARKER);
let pos_count = headings.len() - usize::from(named);
let mut children: Vec<ChildColumnDec> = Vec::new();
let mut child_names: HashSet<String> = HashSet::new();
let mut active_pos = 0usize;
let mut has_mod = false;
for (position, heading_slot) in headings.iter_mut().enumerate().take(pos_count) {
let heading = heading_slot.clone();
if keyed && position == 0 {
active_pos += 1;
continue;
}
if is_child_column_heading(&heading) {
let name = &heading[..heading.len() - CHILD_SUFFIX.len()];
if !name.starts_with('"') && !is_simple_segment(name) {
return Err(Error::syntax("Invalid child heading."));
}
if !child_names.insert(name.to_owned()) {
return Err(Error::syntax("Duplicate or conflicting header."));
}
*heading_slot = name.to_owned();
let field = read_key(name)?;
let child_table = read_header(lines, cursor, depth + 1, false, row_depth + 2)?;
children.push(ChildColumnDec {
name: name.to_owned(),
position: active_pos,
field,
table: child_table,
groups: BTreeMap::new(),
});
active_pos += 1;
continue;
}
if has_header_modifier(&heading) {
has_mod = true;
}
if !is_hoisted_heading(&heading) {
active_pos += 1;
}
}
Ok(ChildTableDec {
lines: vec![headings.join("\t")],
keyed,
row_depth,
width: active_pos,
trimmed: has_mod && !named,
children,
})
}
fn read_row(
lines: &[&str],
cursor: &mut usize,
tagged: &mut bool,
table: &mut ChildTableDec,
depth: usize,
) -> Result<(), Error> {
let raw = take(lines, cursor, depth)?;
let mut omitted: HashSet<usize> = HashSet::new();
let mut prior: isize = -1;
let row_index = table.lines.len() - 1;
while indent_of(lines.get(*cursor).copied()) == (depth + 1) as isize {
let child_idx = if table.children.len() > 1 {
let tag = take(lines, cursor, depth + 1)?;
let found = tag
.strip_prefix(CHILD_TAG)
.and_then(|name| table.children.iter().position(|c| c.name == name));
match found {
Some(idx) if (table.children[idx].position as isize) > prior => {
*tagged = true;
idx
}
_ => return Err(Error::syntax("Invalid child group tag or order.")),
}
} else if table.children.len() == 1 {
0
} else {
return Err(Error::syntax("Unexpected child rows."));
};
let child_pos = table.children[child_idx].position;
let start = table.children[child_idx].table.lines.len() - 1;
while indent_of(lines.get(*cursor).copied()) == (depth + 1) as isize
&& !lines[*cursor][depth + 1..].starts_with(CHILD_TAG)
{
read_row(
lines,
cursor,
tagged,
&mut table.children[child_idx].table,
depth + 1,
)?;
}
let end = table.children[child_idx].table.lines.len() - 1;
if start == end {
return Err(Error::syntax("Empty child group."));
}
table.children[child_idx]
.groups
.insert(row_index, RowRange { start, end });
omitted.insert(child_pos);
prior = child_pos as isize;
}
if indent_of(lines.get(*cursor).copied()) > (depth + 1) as isize {
return Err(Error::syntax("Wrong child indentation or row count."));
}
if omitted.is_empty() {
table.lines.push(raw.to_owned());
return Ok(());
}
let cells: Vec<&str> = if raw.is_empty() && (omitted.len() == table.width || table.trimmed)
{
Vec::new()
} else {
raw.split('\t').collect()
};
let mut restored: Vec<&str> = Vec::new();
let mut cell_idx = 0usize;
let total_positions = if table.trimmed {
table.width.max(cells.len() + omitted.len())
} else {
cells.len() + omitted.len()
};
for pos in 0..total_positions {
if omitted.contains(&pos) {
restored.push("0");
} else if cell_idx < cells.len() {
restored.push(cells[cell_idx]);
cell_idx += 1;
} else {
restored.push("");
}
}
if cell_idx != cells.len() {
return Err(Error::syntax("Wrong cell count."));
}
if table.trimmed {
while restored.last().is_some_and(|s| s.is_empty()) {
restored.pop();
}
}
table.lines.push(restored.join("\t"));
Ok(())
}
fn materialize<F>(table: ChildTableDec, read_table: &mut F) -> Result<JsonValue, Error>
where
F: FnMut(&[&str], usize, usize, bool, usize) -> Result<JsonValue, Error>,
{
let line_refs: Vec<&str> = table.lines.iter().map(String::as_str).collect();
let mut value = read_table(
&line_refs,
0,
table.lines.len() - 1,
table.keyed,
table.row_depth,
)?;
for child in table.children {
if child.groups.is_empty() {
return Err(Error::syntax("Missing child rows."));
}
let child_val = materialize(child.table, read_table)?;
let JsonValue::Array(values) = child_val else {
return Err(Error::syntax("Expected child rows."));
};
for (index, range) in child.groups {
let row_opt = match &mut value {
JsonValue::Array(arr) => arr.get_mut(index),
JsonValue::Object(obj) => {
let key = obj.ordered_keys().get(index).cloned().cloned();
key.and_then(|k| obj.get_json_mut(&k))
}
_ => None,
};
let Some(JsonValue::Object(row_obj)) = row_opt else {
return Err(Error::syntax("Missing child cell."));
};
match row_obj.get_json_mut(&child.field) {
Some(slot) => {
if matches!(slot, JsonValue::Number(n) if *n == 0.0) {
*slot = JsonValue::Array(values[range.start..range.end].to_vec());
} else {
return Err(Error::syntax("Missing child cell."));
}
}
None => return Err(Error::syntax("Missing child cell.")),
}
}
}
Ok(value)
}
let mut table = read_header(lines, &mut cursor, 0, keyed, row_depth)?;
for _ in 0..count {
read_row(lines, &mut cursor, &mut tagged, &mut table, 0)?;
}
if indent_of(lines.get(cursor).copied()) > 0 {
return Err(Error::syntax("Wrong child indentation or row count."));
}
let value = materialize(table, read_table)?;
Ok(ChildTableResult {
value,
next: cursor,
tagged,
})
}