diff --git a/docs/native-api.md b/docs/native-api.md index ee55e50..7e0a020 100644 --- a/docs/native-api.md +++ b/docs/native-api.md @@ -37,6 +37,8 @@ reports. Both comparison types provide `render_text_with_ascii_hierarchy` to render a combined report with redundant terminal edges omitted. Pass `TextReportOptions { details: true, ..Default::default() }` to `render_text_with_options` to show individual object evidence. +Use `TextReport::new(true)` with `write_text_report`, `write_canonical_dump`, +or `write_record_dump` to get plain text and style ranges for presentation. Use `RevisionPair::parse(&old_bytes, &new_bytes)` for an unscoped comparison that can reuse matching cells. Its `compare` and `compare_text` methods return diff --git a/src/bin/pheon.rs b/src/bin/pheon.rs index 5b99354..72db205 100644 --- a/src/bin/pheon.rs +++ b/src/bin/pheon.rs @@ -5,13 +5,15 @@ use flate2::read::MultiGzDecoder; use pheon::review::report::{ReportInputs, ReportOptions, failure_report}; use pheon::review::{ Comparison, Diagnostic, Document, Layer, Outcome, RevisionPair, Side, TextComparison, - TextReportOptions, dump_records, + TextReportOptions, TextStyle, names::{parse_layer, parse_layer_name, resolve_layer_name, write_layer_names}, selection::{DisplayFilter, Scope}, + write_record_dump, }; use std::{ collections::BTreeMap, ffi::{OsStr, OsString}, + fmt::Write as _, fs, io::{self, Read, Write}, path::PathBuf, @@ -423,16 +425,14 @@ fn run(args: &[OsString]) -> Result { return Err("format must be ascii or mermaid (diff also accepts none)".to_string()); } let read = |path: &OsString| read_input(path).map_err(|error| error.message); + let printer = color::Printer::new(color_choice); if raw { if selectors.scope != Scope::default() || selectors.layer_name.is_some() { return Err("record dumps do not accept object scope selectors".to_string()); } - color::print( - &dump_records(&read(&paths[0])?)?, - color::Report::Records, - color_choice, - ) - .map_err(|error| error.to_string())?; + let mut report = printer.report(); + write_record_dump(&mut report, &read(&paths[0])?)?; + printer.print(&report).map_err(|error| error.to_string())?; return Ok(0); } if !compare { @@ -443,8 +443,9 @@ fn run(args: &[OsString]) -> Result { .map_err(|error| error.message)?; let doc = doc.selected(&selectors.scope, false)?; if command == "dump" { - color::print(&doc.canonical_dump(), color::Report::Dump, color_choice) - .map_err(|error| error.to_string())?; + let mut report = printer.report(); + doc.write_canonical_dump(&mut report); + printer.print(&report).map_err(|error| error.to_string())?; } else { stdout(&doc.hierarchy(format == "mermaid", depth))?; for diagnostic in &doc.diagnostics { @@ -464,7 +465,7 @@ fn run(args: &[OsString]) -> Result { |pair| pair.compare_text(), ) .map_err(|error| error.message)?; - let mut output = String::new(); + let mut output = printer.report(); if git { let action = match (old_missing, new_missing) { (true, false) => " added", @@ -472,19 +473,28 @@ fn run(args: &[OsString]) -> Result { _ => "", }; if paths.len() == 9 { - output.push_str(&format!( - "layout {:?} -> {:?}{action}\n", - paths[0], paths[7] - )); + output.write_styled( + TextStyle::Heading, + format_args!("layout {:?} -> {:?}{action}", paths[0], paths[7]), + ); } else { - output.push_str(&format!("layout {:?}{action}\n", paths[0])); + output.write_styled( + TextStyle::Heading, + format_args!("layout {:?}{action}", paths[0]), + ); } + writeln!(output).unwrap(); if !old_missing && !new_missing && paths[3] != paths[6] { - output.push_str(&format!("mode {:?} -> {:?}\n", paths[3], paths[6])); + output.write_styled( + TextStyle::Heading, + format_args!("mode {:?} -> {:?}", paths[3], paths[6]), + ); + writeln!(output).unwrap(); } } let show_library_presence = !old_missing && !new_missing; - output.push_str(&diff.render_text_with_options( + diff.write_text_report( + &mut output, max_changes, &selectors.filter, show_library_presence, @@ -492,13 +502,12 @@ fn run(args: &[OsString]) -> Result { details, ascii_depth: (format == "ascii").then_some(depth), }, - )); + ); if format == "mermaid" { - output.push_str("Hierarchy\n```mermaid\n"); - output.push_str(&diff.hierarchy(true, depth)); - output.push_str("```\n"); + output.write_styled(TextStyle::Heading, format_args!("Hierarchy")); + writeln!(output, "\n```mermaid\n{}```", diff.hierarchy(true, depth)).unwrap(); } - color::print(&output, color::Report::Diff, color_choice).map_err(|error| error.to_string())?; + printer.print(&output).map_err(|error| error.to_string())?; // Git's external driver expects successful rendering for either equality // or differences. Actual comparison/input failures remain nonzero. Ok(if git && diff.outcome().exit_code() == 1 { diff --git a/src/bin/pheon/color.rs b/src/bin/pheon/color.rs index e7ba8a0..82fb933 100644 --- a/src/bin/pheon/color.rs +++ b/src/bin/pheon/color.rs @@ -1,15 +1,7 @@ -use std::{ - fmt, - io::{self, IsTerminal, Write}, -}; +use pheon::review::{TextReport, TextStyle}; +use std::io::{self, IsTerminal, Write}; use termcolor::{BufferedStandardStream, Color, ColorChoice, ColorSpec, WriteColor}; -pub(super) enum Report { - Diff, - Dump, - Records, -} - pub(super) fn parse_choice(value: &str) -> Result { match value { "auto" => Ok(ColorChoice::Auto), @@ -19,218 +11,47 @@ pub(super) fn parse_choice(value: &str) -> Result { } } -pub(super) fn print(text: &str, report: Report, choice: ColorChoice) -> io::Result<()> { - let stdout = io::stdout(); - if choice == ColorChoice::Never || (choice == ColorChoice::Auto && !stdout.is_terminal()) { - return stdout.lock().write_all(text.as_bytes()); - } - let mut out = BufferedStandardStream::stdout(choice); - if !out.supports_color() { - out.write_all(text.as_bytes())?; - return out.flush(); - } +pub(super) struct Printer(Option); - let mut in_cells = false; - let mut in_hierarchy = false; - let mut in_mermaid = false; - for line in text.split_inclusive('\n') { - let body = line.strip_suffix('\n').unwrap_or(line); - match report { - Report::Diff => match body { - "```mermaid" => { - in_mermaid = true; - out.write_all(body.as_bytes())?; - } - "```" => { - in_mermaid = false; - out.write_all(body.as_bytes())?; - } - _ if in_mermaid => out.write_all(body.as_bytes())?, - _ => { - match body { - "Cells:" => in_cells = true, - "Hierarchy" => { - in_cells = false; - in_hierarchy = true; - } - "Diagnostics" => in_cells = false, - _ => (), - } - diff_line(&mut out, body, in_cells, in_hierarchy)?; - } - }, - Report::Dump => dump_line(&mut out, body)?, - Report::Records => record_line(&mut out, body)?, - } - if line.ends_with('\n') { - out.write_all(b"\n")?; +impl Printer { + pub fn new(choice: ColorChoice) -> Self { + if choice == ColorChoice::Never + || (choice == ColorChoice::Auto && !io::stdout().is_terminal()) + { + return Self(None); } + let stream = BufferedStandardStream::stdout(choice); + Self(stream.supports_color().then_some(stream)) } - out.flush() -} -fn paint( - out: &mut impl WriteColor, - value: impl fmt::Display, - color: Color, - bold: bool, -) -> io::Result<()> { - out.set_color(ColorSpec::new().set_fg(Some(color)).set_bold(bold))?; - let result = write!(out, "{value}"); - result.and(out.reset()) -} - -fn change_color(marker: &str) -> Option { - match marker { - "+" => Some(Color::Green), - "-" => Some(Color::Red), - "*" | "~" => Some(Color::Yellow), - _ => None, + pub fn report(&self) -> TextReport { + TextReport::new(self.0.is_some()) } -} -fn folded_endpoint(line: &str) -> Option<(&str, &str)> { - let mut chars = line.char_indices(); - let mut quoted = false; - let mut endpoint = None; - while let Some((index, ch)) = chars.next() { - match ch { - '"' => quoted = !quoted, - '\\' if quoted => { - chars.next(); - } - '→' if !quoted && line[index..].starts_with("→ ") => { - endpoint = Some(line.split_at(index + "→ ".len())); - } - _ => (), - } - } - endpoint -} - -fn diff_line( - out: &mut impl WriteColor, - line: &str, - in_cells: bool, - in_hierarchy: bool, -) -> io::Result<()> { - let content = line.trim_start_matches(' '); - let indent = &line[..line.len() - content.len()]; - let first = content.split_once(' ').map_or(content, |(word, _)| word); - if indent.is_empty() { - let color = match first { - "Equal" => Some(Color::Green), - "Different" | "Incomplete" | "Omitted" => Some(Color::Yellow), - "Failed" => Some(Color::Red), - "Cells:" | "Hierarchy" | "Diagnostics" | "Scope" | "Display" | "layout" | "mode" => { - Some(Color::Cyan) - } - _ => None, + pub fn print(self, report: &TextReport) -> io::Result<()> { + let text = report.as_str().as_bytes(); + let Some(mut out) = self.0 else { + return io::stdout().lock().write_all(text); }; - if let Some(color) = color { - return paint(out, line, color, true); + let mut end = 0; + for (range, style) in report.styles() { + out.write_all(&text[end..range.start])?; + let (color, bold) = match style { + TextStyle::Heading => (Color::Cyan, true), + TextStyle::Layer => (Color::Cyan, false), + TextStyle::Added => (Color::Green, false), + TextStyle::Removed => (Color::Red, false), + TextStyle::Changed => (Color::Yellow, false), + TextStyle::Success => (Color::Green, true), + TextStyle::Warning => (Color::Yellow, true), + TextStyle::Error => (Color::Red, true), + }; + out.set_color(ColorSpec::new().set_fg(Some(color)).set_bold(bold))?; + let written = out.write_all(&text[range.clone()]); + written.and(out.reset())?; + end = range.end; } - } - if let Some(color) = change_color(first) { - out.write_all(indent.as_bytes())?; - return paint(out, content, color, false); - } - if in_hierarchy - && line.contains('→') - && let Some((path, cell)) = folded_endpoint(line) - && let Some((marker, _)) = cell.split_once(' ') - && let Some(color) = change_color(marker) - { - out.write_all(path.as_bytes())?; - return paint(out, cell, color, false); - } - if in_cells && indent == " " { - if (layer_token(content).is_some() || content.starts_with("unknown layer: ")) - && let Some((layer, counts)) = content.rsplit_once(": ") - { - out.write_all(indent.as_bytes())?; - paint(out, layer, Color::Cyan, false)?; - out.write_all(b": ")?; - for (index, clause) in counts.split(" · ").enumerate() { - if index > 0 { - out.write_all(" · ".as_bytes())?; - } - let color = match clause.rsplit_once(' ').map(|(_, action)| action) { - Some("added") => Color::Green, - Some("removed") => Color::Red, - _ => Color::Yellow, - }; - paint(out, clause, color, false)?; - } - return Ok(()); - } - if let Some((target, counts)) = content.rsplit_once(" · -") - && let Some((removed, added)) = counts.split_once(", +") - { - let (added, totals) = added - .split_once(" · ") - .map_or((added, None), |(added, totals)| (added, Some(totals))); - write!(out, "{indent}{target} · ")?; - paint(out, format_args!("-{removed}"), Color::Red, false)?; - out.write_all(b", ")?; - paint(out, format_args!("+{added}"), Color::Green, false)?; - if let Some(totals) = totals { - write!(out, " · {totals}")?; - } - return Ok(()); - } - } - out.write_all(line.as_bytes()) -} - -fn layer_token(line: &str) -> Option<&str> { - let token = line.split([' ', ':']).next()?; - let (layer, datatype) = token.split_once('/')?; - (layer.parse::().is_ok() && datatype.parse::().is_ok()).then_some(token) -} - -fn dump_line(out: &mut impl WriteColor, line: &str) -> io::Result<()> { - if line.starts_with("cell ") || line.starts_with("library ") || line.starts_with("Scope ") { - return paint(out, line, Color::Cyan, true); - } - if line.starts_with("INCOMPLETE: ") { - return paint(out, line, Color::Yellow, true); - } - let mut object = line.trim_start_matches(' '); - if let Some((token, rest)) = object.split_once(' ') - && token - .strip_suffix('x') - .is_some_and(|count| count.parse::().is_ok()) - { - object = rest; - } - let heading = layer_token(object).or_else(|| { - ["reference", "array reference"] - .into_iter() - .find(|heading| { - object - .strip_prefix(heading) - .is_some_and(|rest| rest.starts_with(' ')) - }) - }); - if let Some(heading) = heading { - let prefix = &line[..line.len() - object.len()]; - out.write_all(prefix.as_bytes())?; - paint(out, heading, Color::Cyan, false)?; - return out.write_all(object[heading.len()..].as_bytes()); - } - out.write_all(line.as_bytes()) -} - -fn record_line(out: &mut impl WriteColor, line: &str) -> io::Result<()> { - let mut parts = line.splitn(4, ' '); - if let (Some(offset), Some(tag), Some(name), Some(data)) = - (parts.next(), parts.next(), parts.next(), parts.next()) - { - write!(out, "{offset} {tag} ")?; - paint(out, name, Color::Cyan, false)?; - write!(out, " {data}") - } else { - out.write_all(line.as_bytes()) + out.write_all(&text[end..])?; + out.flush() } } diff --git a/src/review.rs b/src/review.rs index fc9e16e..a9f23ae 100644 --- a/src/review.rs +++ b/src/review.rs @@ -17,11 +17,14 @@ pub mod names; mod pair; pub mod report; pub mod selection; +mod text; use changes::Replacement; use pair::CellReuse; pub use pair::RevisionPair; use selection::{DisplayFilter, Scope}; +use text::CellText; +pub use text::{TextReport, TextStyle}; /// Input revision associated with a diagnostic. #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -166,12 +169,13 @@ impl Object<'_> { } } -fn format_object<'a>( - out: &mut fmt::Formatter<'_>, +fn format_object<'a, W: fmt::Write>( + out: &mut W, kind: u16, layer: Option, fields: impl Iterator + Clone, properties: impl IntoIterator, + heading: impl FnOnce(&mut W, &'static str) -> fmt::Result, ) -> fmt::Result { let field = |tag| { fields @@ -193,10 +197,7 @@ fn format_object<'a>( } else { None }; - if let Some((layer, datatype)) = layer { - write!(out, "{layer}/{datatype}: ")?; - } - out.write_str(object_name(kind, rectangle.is_some()))?; + heading(out, object_name(kind, rectangle.is_some()))?; if let Some(target) = target { write!(out, " {}", quoted(target))?; } @@ -236,7 +237,7 @@ fn array_dimensions(data: &[u8]) -> Option<[u16; 2]> { const POINTS_PER_LINE: usize = 4; -fn write_points(out: &mut fmt::Formatter<'_>, data: &[u8]) -> fmt::Result { +fn write_points(out: &mut impl fmt::Write, data: &[u8]) -> fmt::Result { let mut points = XY::points(data); if points.len() == 1 { let [x, y] = points.next().unwrap(); @@ -258,6 +259,27 @@ fn write_points(out: &mut fmt::Formatter<'_>, data: &[u8]) -> fmt::Result { impl fmt::Display for Object<'_> { fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { + self.format_with_heading(out, |out, name| write_object_heading(out, self.layer, name)) + } +} + +fn write_object_heading( + out: &mut impl fmt::Write, + layer: Option, + name: &str, +) -> fmt::Result { + if let Some((layer, datatype)) = layer { + write!(out, "{layer}/{datatype}: ")?; + } + out.write_str(name) +} + +impl Object<'_> { + fn format_with_heading( + &self, + out: &mut W, + heading: impl FnOnce(&mut W, &'static str) -> fmt::Result, + ) -> fmt::Result { format_object( out, self.kind, @@ -267,6 +289,7 @@ impl fmt::Display for Object<'_> { .iter() .map(|(tag, data)| (*tag, data.as_ref())), self.key.properties.iter().copied(), + heading, ) } } @@ -886,12 +909,21 @@ impl<'a> Document<'a> { pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String { let revision = Revision::from_document(self); - render_hierarchy(&revision, &revision, None, mermaid, max_depth, None) + render_hierarchy(&revision, &revision, None, mermaid, max_depth) } pub fn canonical_dump(&self) -> String { + let mut out = TextReport::default(); + self.write_canonical_dump(&mut out); + out.into_string() + } + + /// Append the canonical object dump and its presentation roles. + pub fn write_canonical_dump(&self, out: &mut TextReport) { if !self.present { - return "library absent\n".to_string(); + out.write_styled(TextStyle::Heading, format_args!("library absent")); + out.push('\n'); + return; } let version_index = self .header @@ -901,23 +933,29 @@ impl<'a> Document<'a> { let header = |tag| self.header.iter().find(|(t, _)| *t == tag).unwrap().1; let (user, meters) = header(RTAG_UNITS).split_at(8); let version = i16::from_be_bytes(self.header[version_index].1.try_into().unwrap()); - let mut out = format!( - "library {} (GDSII {version}, {} user units/dbu, {} m/dbu)\n", - quoted(header(RTAG_LIBNAME)), - format_exact_value(RTAG_UNITS, user), - format_exact_value(RTAG_UNITS, meters) + out.write_styled( + TextStyle::Heading, + format_args!( + "library {} (GDSII {version}, {} user units/dbu, {} m/dbu)", + quoted(header(RTAG_LIBNAME)), + format_exact_value(RTAG_UNITS, user), + format_exact_value(RTAG_UNITS, meters) + ), ); - self.scope.write_restrictions(&mut out); + out.push('\n'); + self.scope.write_restrictions(out); for (index, (tag, data)) in self.header.iter().enumerate() { if index != version_index && !matches!(*tag, RTAG_LIBNAME | RTAG_UNITS) { writeln!(out, "{}={}", tag_name(*tag), format_exact_value(*tag, data)).unwrap(); } } for ((layer, dtype), name) in &self.layer_names { - writeln!(out, "{layer}/{dtype}: name {name:?}").unwrap(); + out.write_styled(TextStyle::Layer, format_args!("{layer}/{dtype}")); + writeln!(out, ": name {name:?}").unwrap(); } for (name, cell) in &self.cells { - writeln!(out, "cell {name:?}").unwrap(); + out.write_styled(TextStyle::Heading, format_args!("cell {name:?}")); + out.push('\n'); for (tag, data) in &cell.attributes { writeln!( out, @@ -937,17 +975,34 @@ impl<'a> Document<'a> { while objects.next_if(|next| next.key == object.key).is_some() { count += 1; } - if count == 1 { - writeln!(out, " {object}").unwrap(); - } else { - writeln!(out, " {count}x {object}").unwrap(); + out.push_str(" "); + if count != 1 { + write!(out, "{count}x ").unwrap(); } + object + .format_with_heading(out, |out, name| { + if let Some((layer, datatype)) = object.layer { + out.write_styled(TextStyle::Layer, format_args!("{layer}/{datatype}")); + out.push_str(": "); + } + if matches!(object.kind, RTAG_SREF | RTAG_AREF) && object.layer.is_none() { + out.write_styled(TextStyle::Layer, format_args!("{name}")); + } else { + out.push_str(name); + } + Ok(()) + }) + .unwrap(); + out.push('\n'); } } for diagnostic in &self.diagnostics { - writeln!(out, "INCOMPLETE: {}", diagnostic.message).unwrap(); + out.write_styled( + TextStyle::Warning, + format_args!("INCOMPLETE: {}", diagnostic.message), + ); + out.push('\n'); } - out } pub fn record_dump(&self) -> String { @@ -957,18 +1012,30 @@ impl<'a> Document<'a> { /// Inspect record boundaries even when object grammar or metadata is invalid. pub fn dump_records(input: &[u8]) -> Result { - Ok(format_records(&read_records(input)?)) + let mut out = TextReport::default(); + write_record_dump(&mut out, input)?; + Ok(out.into_string()) +} + +/// Append the raw record dump and its presentation roles. +pub fn write_record_dump(out: &mut TextReport, input: &[u8]) -> Result<(), String> { + write_records(out, &read_records(input)?); + Ok(()) } fn format_records(records: &[Record<'_>]) -> String { - let mut out = String::new(); + let mut out = TextReport::default(); + write_records(&mut out, records); + out.into_string() +} + +fn write_records(out: &mut TextReport, records: &[Record<'_>]) { for record in records { + write!(out, "{:010} {:04x} ", record.offset, record.tag).unwrap(); + out.write_styled(TextStyle::Layer, format_args!("{}", tag_name(record.tag))); writeln!( out, - "{:010} {:04x} {} size={} {}", - record.offset, - record.tag, - tag_name(record.tag), + " size={} {}", record.data.len() + 4, format_data( record.tag, @@ -981,7 +1048,6 @@ fn format_records(records: &[Record<'_>]) -> String { ) .unwrap(); } - out } /// A retained comparison field. Polygon coordinates and string padding follow @@ -1019,6 +1085,16 @@ pub struct ObjectChange { impl fmt::Display for ObjectChange { fn fmt(&self, out: &mut fmt::Formatter<'_>) -> fmt::Result { + self.format_with_heading(out, |out, name| write_object_heading(out, self.layer, name)) + } +} + +impl ObjectChange { + fn format_with_heading( + &self, + out: &mut W, + heading: impl FnOnce(&mut W, &'static str) -> fmt::Result, + ) -> fmt::Result { format_object( out, self.kind, @@ -1029,6 +1105,7 @@ impl fmt::Display for ObjectChange { self.properties .iter() .map(|(attribute, data)| (*attribute, data.as_slice())), + heading, ) } } @@ -1249,6 +1326,18 @@ impl TextComparison { .render_text_with_options(max_objects, show, show_library_presence, options) } + pub fn write_text_report( + &self, + out: &mut TextReport, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + options: TextReportOptions, + ) { + self.comparison + .write_text_report(out, max_objects, show, show_library_presence, options); + } + /// Render the cell changes and their ASCII hierarchy together. pub fn render_text_with_ascii_hierarchy( &self, @@ -1450,14 +1539,7 @@ impl Comparison { /// Render the affected hierarchy. ASCII output shows relationships between cells. pub fn hierarchy(&self, mermaid: bool, max_depth: usize) -> String { - render_hierarchy( - &self.old, - &self.new, - Some(&self.cells), - mermaid, - max_depth, - None, - ) + render_hierarchy(&self.old, &self.new, Some(&self.cells), mermaid, max_depth) } /// Limit presentation only: the complete comparison has already been made. @@ -1512,19 +1594,59 @@ impl Comparison { show_library_presence: bool, options: TextReportOptions, ) -> String { - let TextReportOptions { - details, - ascii_depth, - } = options; + let mut out = TextReport::default(); + self.write_text_report(&mut out, max_objects, show, show_library_presence, options); + out.into_string() + } + + /// Append the selected changes and their presentation roles to a text report. + pub fn write_text_report( + &self, + out: &mut TextReport, + max_objects: usize, + show: &DisplayFilter, + show_library_presence: bool, + options: TextReportOptions, + ) { + let selection = selection::TextSelection::new(&self.cells, show, max_objects); let outcome = self.outcome(); - let mut out = match outcome { - Outcome::Equal => "Equal", - Outcome::Different => "Different", - Outcome::Incomplete { .. } => "Incomplete", - Outcome::Failed => "Failed", + let headline = out.len(); + let (result, style) = match outcome { + Outcome::Equal => ("Equal", TextStyle::Success), + Outcome::Different => ("Different", TextStyle::Warning), + Outcome::Incomplete { .. } => ("Incomplete", TextStyle::Warning), + Outcome::Failed => ("Failed", TextStyle::Error), + }; + out.push_str(result); + let has_omissions = selection.filtered_objects != 0 + || selection.limited_objects != 0 + || selection.filtered_cells != 0; + if !self.cells.is_empty() + && (self.cells.len() > 3 || !outcome.is_complete() || has_omissions) + { + let (mut modified, mut added, mut removed) = (0, 0, 0); + for cell in &self.cells { + match cell_marker(cell.old.is_some(), cell.new.is_some()) { + '-' => removed += 1, + '+' => added += 1, + _ => modified += 1, + } + } + let mut counts = [ + (modified, "modified"), + (added, "added"), + (removed, "removed"), + ] + .into_iter() + .filter(|(count, _)| *count != 0); + if let Some((count, action)) = counts.next() { + let noun = if count == 1 { "cell" } else { "cells" }; + write!(out, " · {count} {noun} {action}").unwrap(); + for (count, action) in counts { + write!(out, ", {count} {action}").unwrap(); + } + } } - .to_string(); - let headline_end = out.len(); let library_changes = self.library_changes.iter().filter(|change| { show_library_presence || !matches!(change, LibraryChange::Presence { .. }) }); @@ -1537,9 +1659,11 @@ impl Comparison { write!(out, " · {count} {label}{plural}").unwrap(); } } + out.mark(headline, style); out.push('\n'); - self.old.scope.write_restrictions(&mut out); + self.old.scope.write_restrictions(out); if show.cell.is_some() || show.layer.is_some() { + let start = out.len(); out.push_str("Display filter"); if let Some(cell) = &show.cell { write!(out, " cell={cell:?}").unwrap(); @@ -1547,9 +1671,29 @@ impl Comparison { if let Some((layer, datatype)) = show.layer { write!(out, " layer={layer}/{datatype}").unwrap(); } + out.mark(start, TextStyle::Heading); + out.push('\n'); + } + if has_omissions { + let start = out.len(); + out.push_str("Omitted"); + for (count, label, reason) in [ + (selection.filtered_objects, "object change", "filtered out"), + (selection.limited_objects, "object change", "over the limit"), + ( + selection.filtered_cells, + "cell-level change", + "filtered out", + ), + ] { + if count != 0 { + let plural = if count == 1 { "" } else { "s" }; + write!(out, " · {count} {label}{plural} {reason}").unwrap(); + } + } + out.mark(start, TextStyle::Warning); out.push('\n'); } - let notice_start = out.len(); for change in library_changes { writeln!(out, "library {change}").unwrap(); } @@ -1578,229 +1722,39 @@ impl Comparison { ) .unwrap(); } - let body_start = out.len(); - let selection = selection::TextSelection::new(&self.cells, show, max_objects); - let mut layers = changes::LayerRows::new(&self.layer_legend, &self.layer_names); - let mut annotations = Vec::new(); + + let mut body = CellText::new(&self.layer_legend, &self.layer_names, out.is_styled()); let mut covered_edges = BTreeSet::new(); for selected in &selection.modified_cells { - let cell = selected.cell; - let name = cell_label(&cell.name); - let note = if selected.attributes_changed { - " (attributes changed)" - } else { - "" - }; - writeln!(out, "* {name}{note}").unwrap(); - let mut polygons = changes::PolygonChanges::default(); - let mut shown_refs = BTreeMap::<&str, changes::ShownReferences>::new(); - for &(a, b) in &selected.replacements { - if !details && a.layer == b.layer && is_polygon(a.kind) { - polygons.replacement(a, b); - } else { - out.push_str(" ~ "); - let row_start = out.len(); - if a.layer != b.layer { - changes::write_layer_transition(&mut out, a, b, Some(&mut layers)); - } else { - layers.record(a.layer, row_start); - if details { - out.push_str(&changes::replacement_heading(a, b)); - } else { - out.push_str(&changes::replacement_summary(a, b)); - } - } - out.push('\n'); - if details { - changes::write_replacement_objects(&mut out, a, b); - } - if let Some(target) = &a.target { - shown_refs - .entry(target) - .or_default() - .replacement(a, b, row_start); - } - } - } - let mut removed_refs = BTreeMap::new(); - let mut added_refs = BTreeMap::new(); - for (removed, objects, references) in [ - (true, &selected.removed, &mut removed_refs), - (false, &selected.added, &mut added_refs), - ] { - let sign = if removed { "-" } else { "+" }; - let mut unmatched: Vec<(&ObjectChange, usize)> = Vec::new(); - for &object in objects { - if !details && is_polygon(object.kind) { - polygons.unmatched(object, removed); - } else if !details && let Some(target) = object.target.as_deref() { - let (_, counts) = references - .entry(target) - .or_insert_with(|| (object, changes::ReferenceCounts::default())); - counts.add(object); - } else if let Some((last, count)) = unmatched.last_mut() - && last.kind == object.kind - && last.fields == object.fields - && last.properties == object.properties - { - *count += 1; - } else { - unmatched.push((object, 1)); - } - } - // The comparison orders these objects by kind, fields, and properties. - for (object, count) in unmatched { - write!(out, " {sign} ").unwrap(); - if count > 1 { - write!(out, "{count}× ").unwrap(); - } - let row_start = out.len(); - layers.record(object.layer, row_start); - if details { - writeln!(out, "{object}").unwrap(); - if let Some(target) = object.target.as_deref() { - shown_refs - .entry(target) - .or_default() - .individual(object, removed, count, row_start); - } - } else { - changes::write_unmatched(&mut out, object); - } - } - } - let no_refs = changes::ReferenceCounts::default(); - for (target, (first, counts)) in removed_refs { - let row_start = out.len(); - if let Some((_, added)) = added_refs.remove(target) { - counts.write_change(&mut out, target, &added); - shown_refs - .entry(target) - .or_default() - .unmatched(&counts, &added, row_start); - } else { - counts.write(&mut out, "-", target, first); - shown_refs - .entry(target) - .or_default() - .unmatched(&counts, &no_refs, row_start); - } - } - for (target, (first, counts)) in added_refs { - let row_start = out.len(); - counts.write(&mut out, "+", target, first); - shown_refs - .entry(target) - .or_default() - .unmatched(&no_refs, &counts, row_start); - } - if !shown_refs.is_empty() { - for target in cell - .removed - .iter() - .chain(&cell.added) - .filter_map(|o| o.target.as_deref()) - { - if let Some(shown) = shown_refs.get_mut(target) { - shown.count_change(); - } - } - for (target, shown) in shown_refs { - if shown.complete() { - let edge = (cell.name.clone(), target.to_owned()); - let old = self.old.edges.get(&edge).copied().unwrap_or(0); - let new = self.new.edges.get(&edge).copied().unwrap_or(0); - shown.annotate(&out, &mut annotations, old, new); - if ascii_depth.is_some() && outcome.is_complete() { - covered_edges.insert(edge); - } - } - } - } - polygons.write(&mut out, &mut layers); - } - let mut before_cells = String::new(); - layers.finish(&out, &mut annotations, &mut before_cells); - // Resolve row offsets before inserting the section headers. - if !annotations.is_empty() { - annotations.sort_unstable_by_key(|(at, _)| *at); - let mut annotated = String::with_capacity(out.len()); - let mut start = 0; - for (at, annotation) in annotations { - annotated.push_str(&out[start..at]); - annotated.push_str(&annotation); - start = at; - } - annotated.push_str(&out[start..]); - out = annotated; + self.write_cell_details( + &mut body, + selected, + options.details, + (options.ascii_depth.is_some() && outcome.is_complete()) + .then_some(&mut covered_edges), + ); } + body.write_legend(out); if !selection.modified_cells.is_empty() || !selection.removed_cells.is_empty() || !selection.added_cells.is_empty() { - before_cells.push_str("Cells:\n"); + out.write_styled(TextStyle::Heading, format_args!("Cells:")); + out.push('\n'); for name in selection.removed_cells { - writeln!(before_cells, "- {}", cell_label(name)).unwrap(); + out.write_styled(TextStyle::Removed, format_args!("- {}", cell_label(name))); + out.push('\n'); } for name in selection.added_cells { - writeln!(before_cells, "+ {}", cell_label(name)).unwrap(); - } - } - out.insert_str(body_start, &before_cells); - let mut omissions = Vec::new(); - for (count, label, reason) in [ - (selection.filtered_objects, "object change", "filtered out"), - (selection.limited_objects, "object change", "over the limit"), - ( - selection.filtered_cells, - "cell-level change", - "filtered out", - ), - ] { - if count != 0 { - let plural = if count == 1 { "" } else { "s" }; - omissions.push(format!("{count} {label}{plural} {reason}")); - } - } - if !omissions.is_empty() { - out.insert_str( - notice_start, - &format!("Omitted · {}\n", omissions.join(" · ")), - ); - } - const COMPACT_HEADLINE_CELL_LIMIT: usize = 3; - if !self.cells.is_empty() - && (self.cells.len() > COMPACT_HEADLINE_CELL_LIMIT - || !outcome.is_complete() - || !omissions.is_empty()) - { - let (mut modified, mut added, mut removed) = (0_usize, 0_usize, 0_usize); - for cell in &self.cells { - match cell_marker(cell.old.is_some(), cell.new.is_some()) { - '-' => removed += 1, - '+' => added += 1, - _ => modified += 1, - } - } - let mut counts = [ - (modified, "modified"), - (added, "added"), - (removed, "removed"), - ] - .into_iter() - .filter(|(count, _)| *count != 0); - if let Some((count, action)) = counts.next() { - let noun = if count == 1 { "cell" } else { "cells" }; - let mut summary = format!(" · {count} {noun} {action}"); - for (count, action) in counts { - write!(summary, ", {count} {action}").unwrap(); - } - out.insert_str(headline_end, &summary); + out.write_styled(TextStyle::Added, format_args!("+ {}", cell_label(name))); + out.push('\n'); } + body.write_body(out); } // General comparison errors precede revision-specific errors in text. if !self.diagnostics.is_empty() { - out.push_str("Diagnostics\n"); + out.write_styled(TextStyle::Heading, format_args!("Diagnostics")); + out.push('\n'); for diagnostic in self .diagnostics .iter() @@ -1810,17 +1764,167 @@ impl Comparison { writeln!(out, " {diagnostic}").unwrap(); } } - if let Some(max_depth) = ascii_depth { - out.push_str(&render_hierarchy( + if let Some(max_depth) = options.ascii_depth { + write_hierarchy( + out, &self.old, &self.new, Some(&self.cells), false, max_depth, Some(&covered_edges), - )); + ); } - out + } + + fn write_cell_details( + &self, + out: &mut CellText<'_>, + selected: &selection::TextCellSelection<'_>, + details: bool, + mut covered_edges: Option<&mut BTreeSet<(String, String)>>, + ) { + let cell = selected.cell; + let name = cell_label(&cell.name); + let note = if selected.attributes_changed { + " (attributes changed)" + } else { + "" + }; + out.style(Some(TextStyle::Changed)); + writeln!(out, "* {name}{note}").unwrap(); + let mut polygons = changes::PolygonChanges::default(); + let mut shown_refs = BTreeMap::<&str, changes::ShownReferences>::new(); + for &(a, b) in &selected.replacements { + if !details && a.layer == b.layer && is_polygon(a.kind) { + polygons.replacement(a, b); + continue; + } + out.push_str(" "); + out.style(Some(TextStyle::Changed)); + out.push_str("~ "); + if a.layer != b.layer { + changes::write_layer_transition(out, a, b); + out.push('\n'); + } else { + if let Some(layer) = a.layer { + out.write_layer(layer, None); + out.push_str(": "); + } + let description = changes::replacement_description(a, b, details); + let (heading, rest) = match description.split_once('\n') { + Some((heading, rest)) => (heading, Some(rest)), + None => (description.as_str(), None), + }; + out.push_str(heading); + if let Some(target) = &a.target { + let placements = out.reserve_placements(); + shown_refs + .entry(target) + .or_default() + .replacement(a, b, placements); + } + out.push('\n'); + if let Some(rest) = rest { + writeln!(out, "{rest}").unwrap(); + } + } + if details { + changes::write_replacement_objects(out, a, b); + } + } + let mut removed_refs = BTreeMap::new(); + let mut added_refs = BTreeMap::new(); + for (removed, objects, references) in [ + (true, &selected.removed, &mut removed_refs), + (false, &selected.added, &mut added_refs), + ] { + let sign = if removed { '-' } else { '+' }; + let mut unmatched: Vec<(&ObjectChange, usize)> = Vec::new(); + for &object in objects { + if !details && is_polygon(object.kind) { + polygons.unmatched(object, removed); + } else if !details && let Some(target) = object.target.as_deref() { + let (_, counts) = references + .entry(target) + .or_insert_with(|| (object, changes::ReferenceCounts::default())); + counts.add(object); + } else if let Some((last, count)) = unmatched.last_mut() + && last.kind == object.kind + && last.fields == object.fields + && last.properties == object.properties + { + *count += 1; + } else { + unmatched.push((object, 1)); + } + } + // The comparison orders these objects by kind, fields, and properties. + for (object, count) in unmatched { + out.push_str(" "); + out.style(Some(TextStyle::change(sign))); + write!(out, "{sign} ").unwrap(); + if count > 1 { + write!(out, "{count}× ").unwrap(); + } + changes::write_unmatched(out, object, details); + if let Some(target) = object.target.as_deref() { + let placements = out.reserve_placements(); + shown_refs + .entry(target) + .or_default() + .individual(object, removed, count, placements); + } + out.push('\n'); + } + } + let no_refs = changes::ReferenceCounts::default(); + for (target, (first, counts)) in removed_refs { + if let Some((_, added)) = added_refs.remove(target) { + let placements = counts.write_change(out, target, &added); + shown_refs + .entry(target) + .or_default() + .unmatched(&counts, &added, placements); + } else { + let placements = counts.write(out, '-', target, first); + shown_refs + .entry(target) + .or_default() + .unmatched(&counts, &no_refs, placements); + } + } + for (target, (first, counts)) in added_refs { + let placements = counts.write(out, '+', target, first); + shown_refs + .entry(target) + .or_default() + .unmatched(&no_refs, &counts, placements); + } + if !shown_refs.is_empty() { + for target in cell + .removed + .iter() + .chain(&cell.added) + .filter_map(|o| o.target.as_deref()) + { + if let Some(shown) = shown_refs.get_mut(target) { + shown.count_change(); + } + } + for (target, shown) in shown_refs { + if shown.complete() { + let edge = (cell.name.clone(), target.to_owned()); + let old = self.old.edges.get(&edge).copied().unwrap_or(0); + let new = self.new.edges.get(&edge).copied().unwrap_or(0); + shown.write_placements(out, old, new); + if let Some(covered) = covered_edges.as_deref_mut() { + covered.insert(edge); + } + } + } + } + polygons.write(out); } } @@ -1885,10 +1989,23 @@ fn render_hierarchy( changes: Option<&[CellChange]>, mermaid: bool, max_depth: usize, - covered_edges: Option<&BTreeSet<(String, String)>>, ) -> String { + let mut out = TextReport::default(); + write_hierarchy(&mut out, old, new, changes, mermaid, max_depth, None); + out.into_string() +} + +fn write_hierarchy( + out: &mut TextReport, + old: &Revision, + new: &Revision, + changes: Option<&[CellChange]>, + mermaid: bool, + max_depth: usize, + covered_edges: Option<&BTreeSet<(String, String)>>, +) { if !mermaid && changes.is_some_and(<[CellChange]>::is_empty) { - return String::new(); + return; } let HierarchyAnalysis { @@ -1952,7 +2069,7 @@ fn render_hierarchy( visible.retain(|name| children.contains_key(name) || targets.contains(name)); } if changes.is_some() && !mermaid && children.is_empty() { - return String::new(); + return; } let roots: Vec<_> = visible.difference(&targets).cloned().collect(); // Distinguish rootless cycles from descendants hidden by the depth limit. @@ -2052,7 +2169,7 @@ fn render_hierarchy( .enumerate() .map(|(i, n)| (n, i)) .collect(); - let mut out = "flowchart TD\n".to_string(); + out.push_str("flowchart TD\n"); if changes.is_none() && new.scope != Scope::default() { writeln!(out, " %% {}", new.scope.description()).unwrap(); } @@ -2074,7 +2191,6 @@ fn render_hierarchy( if rows.is_empty() { out.push_str(" empty[\"No changed hierarchy\"]\n"); } - out } else { let single_placement = |parent: &String, target: &String| { let key = (parent.clone(), target.clone()); @@ -2097,9 +2213,10 @@ fn render_hierarchy( && (old.cells.contains(&child.name) || new.cells.contains(&child.name)) && single_placement(&parent.name, &child.name) }; - let mut out = "Hierarchy\n".to_string(); + out.write_styled(TextStyle::Heading, format_args!("Hierarchy")); + out.push('\n'); if changes.is_none() { - new.scope.write_restrictions(&mut out); + new.scope.write_restrictions(out); } let mut index = 0; let mut ancestor_depths = Vec::new(); @@ -2130,6 +2247,7 @@ fn render_hierarchy( ancestor_depths.pop(); } out.push_str(&" ".repeat(ancestor_depths.len())); + let mut change = None; for (i, row) in rows[index..=end].iter().enumerate() { let name = &row.name; if i != 0 { @@ -2137,6 +2255,7 @@ fn render_hierarchy( } if direct.contains(name) { let marker = cell_marker(old.cells.contains(name), new.cells.contains(name)); + change = Some((out.len(), TextStyle::change(marker))); write!(out, "{marker} ").unwrap(); } if changes.is_some() { @@ -2151,14 +2270,17 @@ fn render_hierarchy( } } let last = &rows[end]; - writeln!(out, "{}{}", status(&last.name), last.note).unwrap(); + write!(out, "{}{}", status(&last.name), last.note).unwrap(); + if let Some((start, style)) = change { + out.mark(start, style); + } + out.push('\n'); ancestor_depths.push(last.depth); index = end + 1; } if visible.is_empty() { out.push_str("No changed hierarchy\n"); } - out } } diff --git a/src/review/changes.rs b/src/review/changes.rs index 824b00d..c5a69cf 100644 --- a/src/review/changes.rs +++ b/src/review/changes.rs @@ -137,12 +137,8 @@ pub(super) fn field_changes<'a>( .filter_map(|(tag, (before, after))| (before != after).then_some((tag, before, after))) } -fn polygon_heading(object: &ObjectChange, rectangular: bool) -> String { - object_heading(object, object_name(object.kind, rectangular)) -} - -fn object_heading(object: &ObjectChange, kind: &str) -> String { - match object.layer { +fn object_heading(object: &ObjectChange, kind: &str, with_layer: bool) -> String { + match object.layer.filter(|_| with_layer) { Some((layer, datatype)) => format!("{layer}/{datatype}: {kind}"), None => kind.to_string(), } @@ -156,25 +152,39 @@ fn object_xy(object: &ObjectChange) -> &[u8] { .map_or(&[], |field| field.data.as_slice()) } -pub(super) fn write_unmatched(out: &mut String, object: &ObjectChange) { - if object.kind == RTAG_PATH +fn write_cell_heading(out: &mut CellText<'_>, layer: Option, name: &str) { + if let Some(layer) = layer { + out.write_layer(layer, None); + out.push_str(": "); + } + out.push_str(name); +} + +pub(super) fn write_unmatched(out: &mut CellText<'_>, object: &ObjectChange, details: bool) { + if !details + && object.kind == RTAG_PATH && let Some([xmin, ymin, xmax, ymax]) = object.bounds { let vertices = XY::points(object_xy(object)).len(); if vertices > POINTS_PER_LINE { - let heading = object_heading(object, "path"); + write_cell_heading(out, object.layer, "path"); let width = object .width .map_or_else(|| "absent".to_string(), |width| format!("{width} dbu")); - writeln!( + write!( out, - "{heading} · width {width} · {vertices} vertices · bounds ({xmin}, {ymin}) to ({xmax}, {ymax}) dbu" + " · width {width} · {vertices} vertices · bounds ({xmin}, {ymin}) to ({xmax}, {ymax}) dbu" ) .unwrap(); return; } } - writeln!(out, "{object}").unwrap(); + object + .format_with_heading(out, |out, name| { + write_cell_heading(out, object.layer, name); + Ok(()) + }) + .unwrap(); } fn vertex_count(xy: &[u8]) -> usize { @@ -269,25 +279,27 @@ impl PolygonChanges { shapes.add(object, None); } - pub fn write(&self, out: &mut String, layers: &mut LayerRows<'_>) { + pub fn write(&self, out: &mut CellText<'_>) { for (layer, counts) in &self.0 { out.push_str(" "); - layers.record(*layer, out.len()); - if let Some((layer, datatype)) = layer { - write!(out, "{layer}/{datatype}: ").unwrap(); + out.style(Some(TextStyle::Layer)); + if let Some(layer) = layer { + out.write_layer(*layer, None); } else { - out.push_str("unknown layer: "); + out.push_str("unknown layer"); } + out.style(None); + out.push_str(": "); let groups = [ - ("changed", &counts.changed), - ("moved", &counts.moved), - ("removed", &counts.removed), - ("added", &counts.added), + ("changed", TextStyle::Changed, &counts.changed), + ("moved", TextStyle::Changed, &counts.moved), + ("removed", TextStyle::Removed, &counts.removed), + ("added", TextStyle::Added, &counts.added), ]; if let Some([dx, dy]) = counts.displacement && groups .iter() - .map(|(_, shapes)| shapes.total()) + .map(|(_, _, shapes)| shapes.total()) .sum::() == 1 { @@ -298,11 +310,12 @@ impl PolygonChanges { } else { "polygon" }; + out.style(Some(TextStyle::Changed)); writeln!(out, "{shape} moved by ({dx}, {dy}) dbu").unwrap(); continue; } let mut separator = ""; - for (action, shapes) in groups { + for (action, style, shapes) in groups { let terms = [ (shapes.rectangles, "rectangle", "rectangles"), (shapes.polygons, "polygon", "polygons"), @@ -316,7 +329,10 @@ impl PolygonChanges { }) .collect::>(); if !terms.is_empty() { - write!(out, "{separator}{} {action}", terms.join(", ")).unwrap(); + out.push_str(separator); + out.style(Some(style)); + write!(out, "{} {action}", terms.join(", ")).unwrap(); + out.style(None); separator = " · "; } } @@ -342,33 +358,49 @@ impl ReferenceCounts { self.placements += reference_placements(object); } - pub fn write(&self, out: &mut String, sign: &str, target: &str, first: &ObjectChange) { + pub fn write( + &self, + out: &mut CellText<'_>, + sign: char, + target: &str, + first: &ObjectChange, + ) -> usize { + out.push_str(" "); + out.style(Some(TextStyle::change(sign))); + write!(out, "{sign} ").unwrap(); if self.len() == 1 { - writeln!(out, " {sign} {first}").unwrap(); - return; + write!(out, "{first}").unwrap(); + } else { + self.write_counts(out, ""); + write!(out, " to {}", cell_label(target)).unwrap(); + self.write_placements(out); } - write!(out, " {sign} ").unwrap(); - self.write_counts(out, ""); - write!(out, " to {}", cell_label(target)).unwrap(); - self.write_placements(out); + let placements = out.reserve_placements(); out.push('\n'); + placements } fn len(&self) -> usize { self.singles + self.arrays } - pub fn write_change(&self, out: &mut String, target: &str, added: &Self) { + pub fn write_change(&self, out: &mut CellText<'_>, target: &str, added: &Self) -> usize { write!(out, " {} · ", cell_label(target)).unwrap(); + out.style(Some(TextStyle::Removed)); self.write_counts(out, "-"); self.write_placements(out); + out.style(None); out.push_str(", "); + out.style(Some(TextStyle::Added)); added.write_counts(out, "+"); added.write_placements(out); + out.style(None); + let placements = out.reserve_placements(); out.push('\n'); + placements } - fn write_counts(&self, out: &mut String, sign: &str) { + fn write_counts(&self, out: &mut CellText<'_>, sign: &str) { if self.singles > 0 { let suffix = if self.singles == 1 { "" } else { "s" }; write!(out, "{sign}{} ref{suffix}", self.singles).unwrap(); @@ -382,7 +414,7 @@ impl ReferenceCounts { } } - fn write_placements(&self, out: &mut String) { + fn write_placements(&self, out: &mut CellText<'_>) { if self.arrays > 0 { let suffix = if self.placements == 1 { "" } else { "s" }; write!(out, " ({} placement{suffix})", self.placements).unwrap(); @@ -403,27 +435,27 @@ pub(super) struct ShownReferences { total: usize, removed: u128, added: u128, - row_start: usize, + placement_slot: usize, } impl ShownReferences { - pub fn replacement(&mut self, old: &ObjectChange, new: &ObjectChange, row_start: usize) { + pub fn replacement(&mut self, old: &ObjectChange, new: &ObjectChange, placement_slot: usize) { self.shown += 2; self.removed += reference_placements(old); self.added += reference_placements(new); - self.row_start = row_start; + self.placement_slot = placement_slot; } pub fn unmatched( &mut self, removed: &ReferenceCounts, added: &ReferenceCounts, - row_start: usize, + placement_slot: usize, ) { self.shown += removed.len() + added.len(); self.removed += removed.placements; self.added += added.placements; - self.row_start = row_start; + self.placement_slot = placement_slot; } pub fn individual( @@ -431,7 +463,7 @@ impl ShownReferences { object: &ObjectChange, removed: bool, count: usize, - row_start: usize, + placement_slot: usize, ) { let placements = if removed { &mut self.removed @@ -440,7 +472,7 @@ impl ShownReferences { }; *placements += reference_placements(object) * count as u128; self.shown += count; - self.row_start = row_start; + self.placement_slot = placement_slot; } pub fn count_change(&mut self) { @@ -451,106 +483,36 @@ impl ShownReferences { self.shown == self.total } - pub fn annotate(&self, text: &str, annotations: &mut Vec<(usize, String)>, old: u64, new: u64) { - if (u128::from(old), u128::from(new)) == (self.removed, self.added) { - return; - } - let at = self.row_start + text[self.row_start..].find('\n').unwrap(); - let totals = if old == new { - let suffix = if new == 1 { "" } else { "s" }; - format!(" · {new} total placement{suffix}") - } else { - format!(" · placements {old} -> {new}") - }; - annotations.push((at, totals)); - } -} - -pub(super) struct LayerRows<'a> { - names: &'a BTreeMap, - name_changes: &'a [LayerNameChange], - rows: BTreeMap>, -} - -impl<'a> LayerRows<'a> { - pub fn new(names: &'a BTreeMap, name_changes: &'a [LayerNameChange]) -> Self { - Self { - names, - name_changes, - rows: BTreeMap::new(), - } - } - - fn write_transition_layer(&mut self, out: &mut String, layer: Layer, side: Side) { - self.record(Some(layer), out.len()); - write!(out, "{}/{}", layer.0, layer.1).unwrap(); - if let Ok(index) = self - .name_changes - .binary_search_by_key(&layer, |change| change.layer) - { - let change = &self.name_changes[index]; - let name = match side { - Side::Old => &change.old, - Side::New => &change.new, - }; - if let Some(name) = name { - write!(out, " ({})", cell_label(name)).unwrap(); - } - } - } - - pub fn record(&mut self, layer: Option, row_start: usize) { - if let Some(layer) = layer - && self.names.contains_key(&layer) - { - self.rows - .entry(layer) - .and_modify(|first| *first = None) - .or_insert(Some(row_start)); - } - } - - pub fn finish(self, text: &str, annotations: &mut Vec<(usize, String)>, legend: &mut String) { - for (layer, first) in self.rows { - let name = &self.names[&layer]; - if let Some(at) = first { - let at = at - + text[at..] - .bytes() - .take_while(|b| b.is_ascii_digit() || *b == b'/') - .count(); - annotations.push((at, format!(" ({})", cell_label(name)))); - } else { - writeln!(legend, "{}/{}: name {name:?}", layer.0, layer.1).unwrap(); - } + pub fn write_placements(&self, out: &mut CellText<'_>, old: u64, new: u64) { + if (u128::from(old), u128::from(new)) != (self.removed, self.added) { + out.set_placements(self.placement_slot, old, new); } } } pub(super) fn write_layer_transition( - out: &mut String, + out: &mut CellText<'_>, old: &ObjectChange, new: &ObjectChange, - layers: Option<&mut LayerRows<'_>>, ) { - let (from, to) = (old.layer.unwrap(), new.layer.unwrap()); - if let Some(layers) = layers { - layers.write_transition_layer(out, from, Side::Old); - out.push_str(" → "); - layers.write_transition_layer(out, to, Side::New); - } else { - write!(out, "{}/{} → {}/{}", from.0, from.1, to.0, to.1).unwrap(); - } - let rectangular = is_polygon(old.kind) && rectangle_size(object_xy(old)).is_some(); - write!(out, " · {}", object_name(old.kind, rectangular)).unwrap(); + out.write_layer(old.layer.unwrap(), Some(Side::Old)); + out.push_str(" → "); + out.write_layer(new.layer.unwrap(), Some(Side::New)); + write!(out, " · {}", transition_shape(old)).unwrap(); } -fn polygon_replacement(old: &ObjectChange, new: &ObjectChange) -> String { +fn transition_shape(old: &ObjectChange) -> &'static str { + let rectangular = is_polygon(old.kind) && rectangle_size(object_xy(old)).is_some(); + object_name(old.kind, rectangular) +} + +fn polygon_replacement(old: &ObjectChange, new: &ObjectChange, with_layer: bool) -> String { let before = object_xy(old); let after = object_xy(new); let old_size = rectangle_size(before); let new_size = rectangle_size(after); - let mut out = polygon_heading(old, old_size.is_some() && new_size.is_some()); + let name = object_name(old.kind, old_size.is_some() && new_size.is_some()); + let mut out = object_heading(old, name, with_layer); if before == after { out.push_str(" modified"); } else { @@ -572,22 +534,28 @@ fn polygon_replacement(old: &ObjectChange, new: &ObjectChange) -> String { out } -pub(super) fn replacement_heading(old: &ObjectChange, new: &ObjectChange) -> String { +fn replacement_heading(old: &ObjectChange, new: &ObjectChange, with_layer: bool) -> String { let rectangular = is_polygon(old.kind) && rectangle_size(object_xy(old)).is_some() && rectangle_size(object_xy(new)).is_some(); - let mut heading = object_heading(old, object_name(old.kind, rectangular)); + let mut heading = object_heading(old, object_name(old.kind, rectangular), with_layer); if let Some(target) = &old.target { write!(heading, " {target:?}").unwrap(); } heading } -pub(super) fn write_replacement_objects(out: &mut String, old: &ObjectChange, new: &ObjectChange) { +pub(super) fn write_replacement_objects( + out: &mut CellText<'_>, + old: &ObjectChange, + new: &ObjectChange, +) { for (sign, object) in [('-', old), ('+', new)] { let description = object.to_string(); let mut lines = description.split('\n'); - writeln!(out, " {sign} {}", lines.next().unwrap()).unwrap(); + out.push_str(" "); + out.style(Some(TextStyle::change(sign))); + writeln!(out, "{sign} {}", lines.next().unwrap()).unwrap(); for line in lines { writeln!(out, " {line}").unwrap(); } @@ -595,16 +563,35 @@ pub(super) fn write_replacement_objects(out: &mut String, old: &ObjectChange, ne } pub(super) fn replacement_summary(old: &ObjectChange, new: &ObjectChange) -> String { - if old.layer != new.layer && old.layer.is_some() && new.layer.is_some() { - let mut out = String::new(); - write_layer_transition(&mut out, old, new, None); - return out; + if let (Some((from, from_type)), Some((to, to_type))) = (old.layer, new.layer) + && old.layer != new.layer + { + return format!( + "{from}/{from_type} → {to}/{to_type} · {}", + transition_shape(old) + ); } + replacement_fields(old, new, true) +} + +pub(super) fn replacement_description( + old: &ObjectChange, + new: &ObjectChange, + details: bool, +) -> String { + if details { + replacement_heading(old, new, false) + } else { + replacement_fields(old, new, false) + } +} + +fn replacement_fields(old: &ObjectChange, new: &ObjectChange, with_layer: bool) -> String { let polygon = is_polygon(old.kind); let mut out = if polygon { - polygon_replacement(old, new) + polygon_replacement(old, new, with_layer) } else { - replacement_heading(old, new) + replacement_heading(old, new, with_layer) }; let mut separator = if polygon { "\n " } else { " " }; diff --git a/src/review/selection.rs b/src/review/selection.rs index 71b2594..4e3491f 100644 --- a/src/review/selection.rs +++ b/src/review/selection.rs @@ -115,10 +115,11 @@ impl<'a> TextSelection<'a> { } impl Scope { - pub(super) fn write_restrictions(&self, out: &mut String) { + pub(super) fn write_restrictions(&self, out: &mut TextReport) { if self == &Self::default() { return; } + let start = out.len(); out.push_str("Scope"); if let Some(top) = &self.top { write!(out, " top={top:?}").unwrap(); @@ -129,6 +130,7 @@ impl Scope { if let Some((layer, datatype)) = self.layer { write!(out, " layer={layer}/{datatype}").unwrap(); } + out.mark(start, TextStyle::Heading); out.push('\n'); } diff --git a/src/review/text.rs b/src/review/text.rs new file mode 100644 index 0000000..f2692da --- /dev/null +++ b/src/review/text.rs @@ -0,0 +1,252 @@ +//! Text output and presentation roles shared with the terminal. + +use super::*; +use std::ops::Range; + +/// A presentation role for a span of report text. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum TextStyle { + Heading, + Layer, + Added, + Removed, + Changed, + Success, + Warning, + Error, +} + +impl TextStyle { + pub(super) fn change(marker: char) -> Self { + match marker { + '+' => Self::Added, + '-' => Self::Removed, + _ => Self::Changed, + } + } +} + +/// A plain text report with optional style spans. +#[derive(Default)] +pub struct TextReport { + text: String, + spans: Option, TextStyle)>>, +} + +impl TextReport { + pub fn new(styled: bool) -> Self { + Self { + text: String::new(), + spans: styled.then(Vec::new), + } + } + + pub fn as_str(&self) -> &str { + &self.text + } + + pub fn into_string(self) -> String { + self.text + } + + /// Byte ranges are in output order and never overlap. + pub fn styles(&self) -> &[(Range, TextStyle)] { + self.spans.as_deref().unwrap_or(&[]) + } + + pub(super) fn is_styled(&self) -> bool { + self.spans.is_some() + } + + pub fn write_styled(&mut self, style: TextStyle, text: fmt::Arguments<'_>) { + let start = self.len(); + self.write_fmt(text).unwrap(); + self.mark(start, style); + } + + pub(super) fn push_str(&mut self, text: &str) { + self.text.push_str(text); + } + + pub(super) fn push(&mut self, ch: char) { + self.text.push(ch); + } + + pub(super) fn len(&self) -> usize { + self.text.len() + } + + pub(super) fn mark(&mut self, start: usize, style: TextStyle) { + let end = self.text.len(); + if start < end + && let Some(spans) = &mut self.spans + { + if let Some((range, previous)) = spans.last_mut() + && range.end == start + && *previous == style + { + range.end = end; + } else { + spans.push((start..end, style)); + } + } + } +} + +impl fmt::Write for TextReport { + fn write_str(&mut self, text: &str) -> fmt::Result { + self.push_str(text); + Ok(()) + } +} + +enum Part { + Text(String), + Layer(Layer), + Placements(Option<(u64, u64)>), +} + +/// Cell details awaiting inline layer labels and reference placement totals. +pub(super) struct CellText<'a> { + names: &'a BTreeMap, + name_changes: &'a [LayerNameChange], + layers: BTreeMap, + parts: Vec<(Option, Part)>, + styled: bool, + style: Option, +} + +impl<'a> CellText<'a> { + pub fn new( + names: &'a BTreeMap, + name_changes: &'a [LayerNameChange], + styled: bool, + ) -> Self { + Self { + names, + name_changes, + layers: BTreeMap::new(), + parts: Vec::new(), + styled, + style: None, + } + } + + pub fn style(&mut self, style: Option) { + self.style = style.filter(|_| self.styled); + } + + pub fn write_layer(&mut self, layer: Layer, side: Option) { + if self.names.contains_key(&layer) { + self.layers + .entry(layer) + .and_modify(|repeated| *repeated = true) + .or_insert(false); + self.parts.push((self.style, Part::Layer(layer))); + } else { + write!(self, "{}/{}", layer.0, layer.1).unwrap(); + if let Some(name) = self.transition_name(layer, side) { + write!(self, " ({})", cell_label(name)).unwrap(); + } + } + } + + pub fn reserve_placements(&mut self) -> usize { + let index = self.parts.len(); + self.parts.push((self.style, Part::Placements(None))); + index + } + + pub fn set_placements(&mut self, index: usize, old: u64, new: u64) { + self.parts[index].1 = Part::Placements(Some((old, new))); + } + + pub fn push_str(&mut self, text: &str) { + self.write_str(text).unwrap(); + } + + pub fn push(&mut self, ch: char) { + self.write_char(ch).unwrap(); + } + + fn append(&mut self, text: &str) { + if text.is_empty() { + return; + } + if let Some((style, Part::Text(current))) = self.parts.last_mut() + && *style == self.style + { + current.push_str(text); + } else { + self.parts.push((self.style, Part::Text(text.to_string()))); + } + } + + fn transition_name(&self, layer: Layer, side: Option) -> Option<&'a str> { + let side = side?; + let at = self + .name_changes + .binary_search_by_key(&layer, |change| change.layer) + .ok()?; + let change = &self.name_changes[at]; + match side { + Side::Old => change.old.as_deref(), + Side::New => change.new.as_deref(), + } + } + + pub fn write_legend(&self, out: &mut TextReport) { + for (&(layer, datatype), &repeated) in &self.layers { + if repeated { + writeln!( + out, + "{layer}/{datatype}: name {:?}", + self.names[&(layer, datatype)] + ) + .unwrap(); + } + } + } + + pub fn write_body(self, out: &mut TextReport) { + for (style, part) in self.parts { + let start = out.len(); + match part { + Part::Text(text) => out.push_str(&text), + Part::Layer((layer, datatype)) => { + write!(out, "{layer}/{datatype}").unwrap(); + if !self.layers[&(layer, datatype)] { + write!(out, " ({})", cell_label(&self.names[&(layer, datatype)])).unwrap(); + } + } + Part::Placements(Some((old, new))) if old == new => { + let suffix = if new == 1 { "" } else { "s" }; + write!(out, " · {new} total placement{suffix}").unwrap(); + } + Part::Placements(Some((old, new))) => { + write!(out, " · placements {old} -> {new}").unwrap(); + } + Part::Placements(None) => (), + } + if let Some(style) = style { + out.mark(start, style); + } + } + } +} + +impl fmt::Write for CellText<'_> { + fn write_str(&mut self, text: &str) -> fmt::Result { + if self.style.is_some() + && let Some((first, rest)) = text.split_once('\n') + { + self.append(first); + self.style = None; + self.append("\n"); + self.append(rest); + } else { + self.append(text); + } + Ok(()) + } +}