Skip to main content

nmbrs_workload/
report.rs

1// Copyright 2024-2026 Jonathan Shook
2// SPDX-License-Identifier: Apache-2.0
3
4//! Unified `report:` block — plots and tables under one schema.
5//!
6//! See SRD-46 (`docs/SRD/46_reports.md`) for the authoritative
7//! design. This module owns:
8//!
9//! - The data model: [`Report`] / [`ReportGroup`] / [`ReportItem`]
10//!   / [`Kind`] / [`Style`].
11//! - The directive-string tokenizer that splits a group's body
12//!   into items keyed by leading `plot <name>` / `table <name>`.
13//! - The JSON sub-block parser for `series ... {…}` style
14//!   overrides (strict JSON only — relies on the existing rule
15//!   that Polydat `{...}` is unambiguously not JSON).
16//! - Style cascade helpers: `defaults` at workload root,
17//!   `defaults` at group level, then per-item directives.
18//!
19//! The crate is parser-only. Renderers in `crates/nmbrs/src/plot_metrics.rs`
20//! and the corresponding table renderer consume `ReportItem.body`
21//! plus the resolved [`Style`] — they don't touch the raw YAML
22//! again.
23
24use serde::{Deserialize, Serialize};
25use std::collections::{HashMap, HashSet};
26
27pub mod vocab;
28pub use vocab::{
29    AGG_FNS, ALL_DIRECTIVES, AXIS_SCALES, Directive, DirectiveTarget, KindMask, LINE_STYLES,
30    MARKER_SHAPES, PALETTE_NAMES, ValueProvider, YamlForm, cli_flags_for, directive_by_cli_flag,
31    directive_by_yaml_keyword, directives_for,
32};
33
34/// Top-level `report:` block.
35#[derive(Debug, Clone, Default, Serialize, Deserialize)]
36pub struct Report {
37    /// Cross-cutting style + metadata defaults declared via the
38    /// reserved `defaults:` mapping. Cascade into every group.
39    #[serde(default)]
40    pub defaults: Style,
41    /// Groups in YAML declaration order. Each group's name becomes
42    /// a markdown section heading; items render in body order.
43    #[serde(default)]
44    pub groups: Vec<ReportGroup>,
45}
46
47impl Report {
48    /// Iterate every item across every group in declaration order.
49    pub fn items(&self) -> impl Iterator<Item = &ReportItem> {
50        self.groups.iter().flat_map(|g| g.items.iter())
51    }
52
53    /// Find an item by canonical name. Returns the first match in
54    /// declaration order. Names should be unique within a `Report`
55    /// (collisions are caught at parse time).
56    pub fn find(&self, name: &str) -> Option<&ReportItem> {
57        self.items().find(|i| i.name == name)
58    }
59
60    /// Merge a child's report into this one, by group name (SRD-72,
61    /// SRD-108): a group this report lacks is appended, a group of the
62    /// same name replaces this report's whole, a group declared `none`
63    /// removes it, and `defaults` merge per directive with the child's
64    /// winning.
65    ///
66    /// Returns warnings: a `none` group that names nothing to remove.
67    /// An item name that ends up declared twice is an error, as it is
68    /// within one document.
69    pub fn merge_child(&mut self, child: Report) -> Result<Vec<String>, String> {
70        let mut warnings = Vec::new();
71        self.defaults.merge_from(&child.defaults);
72        for group in child.groups {
73            let at = self.groups.iter().position(|g| g.name == group.name);
74            match (at, group.removed) {
75                (Some(i), true) => {
76                    self.groups.remove(i);
77                }
78                (None, true) => warnings.push(format!(
79                    "report.{}: `none` removes a group of that name, and none is inherited",
80                    group.name
81                )),
82                (Some(i), false) => self.groups[i] = group,
83                (None, false) => self.groups.push(group),
84            }
85        }
86        self.check_names_and_stamp_order()?;
87        Ok(warnings)
88    }
89
90    /// Drop every group declared `none`, returning a warning for each:
91    /// in a document with nothing to inherit from, such a group removes
92    /// nothing.
93    pub fn drop_removed(&mut self) -> Vec<String> {
94        let mut warnings = Vec::new();
95        self.groups.retain(|g| {
96            if g.removed {
97                warnings.push(format!(
98                    "report.{}: `none` removes a group of that name, and none is inherited",
99                    g.name
100                ));
101            }
102            !g.removed
103        });
104        warnings
105    }
106
107    /// Enforce the one-name-per-item rule across every group, and
108    /// stamp each item's declaration ordinal.
109    ///
110    /// A `file` directive is a scope onto an output file, not a named
111    /// item (SRD-46 §"Shared file targets"), so the same filename in
112    /// two groups is allowed; two labels for one file are not.
113    fn check_names_and_stamp_order(&mut self) -> Result<(), String> {
114        let mut seen: HashSet<String> = HashSet::new();
115        let mut file_labels: HashMap<String, Option<String>> = HashMap::new();
116        let mut ordinal: usize = 0;
117        for group in &mut self.groups {
118            for item in &mut group.items {
119                if item.kind == Kind::File {
120                    match file_labels.get(&item.name) {
121                        Some(first) if item.label.is_some() && first != &item.label => {
122                            return Err(format!(
123                                "report.{}: file '{}' is labelled {:?} here and {:?} earlier; \
124                                 a file has one label",
125                                group.name, item.name, item.label, first
126                            ));
127                        }
128                        Some(_) => {}
129                        None => {
130                            file_labels.insert(item.name.clone(), item.label.clone());
131                        }
132                    }
133                } else if !seen.insert(item.name.clone()) {
134                    return Err(format!(
135                        "duplicate report item name '{}' (within scope: workload root)",
136                        item.name
137                    ));
138                }
139                item.order = Some(ordinal);
140                ordinal += 1;
141            }
142        }
143        Ok(())
144    }
145
146    /// Resolve the effective style for one item, walking the
147    /// cascade: report defaults → group defaults → item directives.
148    pub fn effective_style(&self, group: &ReportGroup, item: &ReportItem) -> Style {
149        let mut s = self.defaults.clone();
150        s.merge_from(&group.defaults);
151        s.merge_from(&item.style);
152        s
153    }
154}
155
156/// One named container in `report:`. Holds zero or more items
157/// plus group-level defaults.
158#[derive(Debug, Clone, Default, Serialize, Deserialize)]
159pub struct ReportGroup {
160    /// YAML key the group was declared under (e.g.
161    /// `recall_block`). Used as the markdown section heading.
162    pub name: String,
163    /// Group-level style defaults (from `defaults <directives>`
164    /// lines at the start of the group body). Cascade into every
165    /// item in this group.
166    #[serde(default)]
167    pub defaults: Style,
168    /// Items declared in this group, in body declaration order.
169    #[serde(default)]
170    pub items: Vec<ReportItem>,
171    /// The group was declared with the value `none`: it holds no
172    /// items and exists to remove the group of the same name that a
173    /// parent (`extends:`) or a blueprint (`implements:`) declares.
174    /// [`Report::merge_child`] consumes it.
175    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
176    pub removed: bool,
177}
178
179/// One renderable report item — either a plot or a table.
180#[derive(Debug, Clone, Default, Serialize, Deserialize)]
181pub struct ReportItem {
182    /// `plot` or `table`.
183    pub kind: Kind,
184    /// Canonical name (the token after `plot` / `table`).
185    pub name: String,
186    /// Display label (`label "..."`). Falls back to a prettified
187    /// form of `name` when absent.
188    #[serde(default)]
189    pub label: Option<String>,
190    /// Output-filename stem (`as <stem>`). When absent, default
191    /// is `plot_<name>` / `table_<name>` derived at render time.
192    #[serde(default)]
193    pub as_stem: Option<String>,
194    /// Per-item style overrides parsed from the directive body.
195    #[serde(default)]
196    pub style: Style,
197    /// Raw spec body — the directive lines following the
198    /// `<kind> <name>` line, with `as`/`label`/style directives
199    /// stripped out (they live on the [`ReportItem`] / [`Style`]
200    /// fields). Renderers parse this exactly the way they parse
201    /// the legacy CLI spec strings.
202    #[serde(default)]
203    pub body: String,
204    /// Output file this item flows into when the markdown
205    /// assembler runs. `None` ⇒ default `summary.md`. Set by a
206    /// preceding `file <filename>` directive in the same group.
207    /// Resolved at parse time so consumers don't need to walk
208    /// the group order.
209    #[serde(default, skip_serializing_if = "Option::is_none")]
210    pub target_file: Option<String>,
211    /// Declaration ordinal across the whole `report:` block,
212    /// stamped by [`parse_report`] and persisted as an
213    /// `order <n>` directive line, so a db-sourced render
214    /// (`report.<name>` metadata rows, which iterate in key
215    /// order) can restore declaration order. `serde(skip)`:
216    /// positional metadata derived at parse, not document
217    /// content.
218    #[serde(skip)]
219    pub order: Option<usize>,
220    /// Plot-only directive: when `true`, the renderer
221    /// emits a companion table immediately after the plot
222    /// in the same markdown file, sharing the plot's
223    /// underlying query data. The companion table reuses
224    /// the plot's name with a `_table` suffix for its
225    /// anchor and figure-numbering slot, so users can
226    /// link to either view independently.
227    ///
228    /// Set via `with-table: true` in the plot's body.
229    /// No-op for `Kind::Table` and other non-plot items.
230    /// Default `false` — plots without an explicit toggle
231    /// keep their existing single-image behaviour.
232    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
233    pub with_table: bool,
234    /// Plot-only directive: when non-empty, the renderer
235    /// emits one companion table per distinct value tuple
236    /// of the listed label keys. Each table is filtered to
237    /// rows whose labels match that tuple, and gets its own
238    /// markdown section / standalone file named with the
239    /// tuple values appended.
240    ///
241    /// Set via `with-tables: [label1, label2, …]` in the
242    /// plot body. Independent of (and composes with)
243    /// `with-table: true` — the singular form still emits
244    /// a single un-faceted table when set.
245    #[serde(default, skip_serializing_if = "Vec::is_empty")]
246    pub with_tables: Vec<String>,
247}
248
249/// Kind discriminator. Identifies which renderer owns the item.
250///
251/// `Plot` and `Table` are figures — they carry data and get a
252/// figure number. `Text` is markdown prose; `File` is a scope
253/// directive that switches subsequent items' output file.
254/// `Details` is an auto-injected session-context block (the
255/// runner emits one to every target markdown file at end-of-
256/// run; users can also declare it explicitly to control its
257/// position). Only Plot and Table participate in figure
258/// numbering.
259#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
260#[serde(rename_all = "lowercase")]
261#[derive(Default)]
262pub enum Kind {
263    #[default]
264    Plot,
265    Table,
266    Text,
267    File,
268    Details,
269}
270
271impl Kind {
272    pub fn as_str(&self) -> &'static str {
273        match self {
274            Kind::Plot => "plot",
275            Kind::Table => "table",
276            Kind::Text => "text",
277            Kind::File => "file",
278            Kind::Details => "details",
279        }
280    }
281
282    /// True for kinds that contribute a figure to the report
283    /// (plot, table). Used by the figure-numbering pass.
284    pub fn is_figure(&self) -> bool {
285        matches!(self, Kind::Plot | Kind::Table)
286    }
287}
288
289/// SRD-46 output destination for a rendered report item.
290///
291/// The set is declared with `to <dest>[, <dest>…]` and rides the
292/// style cascade (report defaults → group defaults → item), so a
293/// whole report can be routed in one line. An inner declaration
294/// REPLACES an outer one rather than unioning with it — routing
295/// you can't take back would make the outer default a trap.
296#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
297#[serde(rename_all = "lowercase")]
298pub enum Destination {
299    /// The session directory: standalone artifact + markdown
300    /// upsert. The default when nothing is declared.
301    SessionDir,
302    /// The console form on stdout. Never implied — see
303    /// [`vocab::DESTINATION_NAMES`].
304    Stdout,
305    /// The console form on stderr.
306    Stderr,
307    /// Render nothing.
308    None,
309}
310
311impl Destination {
312    /// Parse one destination name — exactly one of
313    /// [`vocab::DESTINATION_NAMES`], case-sensitive.
314    pub fn parse(s: &str) -> Option<Self> {
315        Some(match s.trim() {
316            "sessiondir" => Self::SessionDir,
317            "stdout" => Self::Stdout,
318            "stderr" => Self::Stderr,
319            "none" => Self::None,
320            _ => return None,
321        })
322    }
323
324    /// Retired destination spellings and the name that replaced
325    /// each; an error names the replacement, never accepts it.
326    fn retired_replacement(s: &str) -> Option<&'static str> {
327        match s {
328            "session" | "session_dir" => Some("sessiondir"),
329            "off" => Some("none"),
330            _ => None,
331        }
332    }
333
334    pub fn as_str(self) -> &'static str {
335        match self {
336            Self::SessionDir => "sessiondir",
337            Self::Stdout => "stdout",
338            Self::Stderr => "stderr",
339            Self::None => "none",
340        }
341    }
342
343    /// Parse a comma- (or whitespace-) separated destination
344    /// list. `none` anywhere in the list wins outright: it is a
345    /// suppression, not a peer.
346    pub fn parse_list(s: &str) -> Result<Vec<Self>, String> {
347        let mut out: Vec<Self> = Vec::new();
348        for tok in s.split([',', ' ', '\t']).filter(|t| !t.trim().is_empty()) {
349            let tok = tok.trim();
350            let d = Self::parse(tok).ok_or_else(|| match Self::retired_replacement(tok) {
351                Some(canonical) => format!("destination '{tok}' — write '{canonical}'"),
352                None => format!(
353                    "unknown destination '{tok}' — expected one of: {}",
354                    vocab::DESTINATION_NAMES.join(", ")
355                ),
356            })?;
357            if !out.contains(&d) {
358                out.push(d);
359            }
360        }
361        // `none` suppresses delivery; beside a real destination it
362        // would silently cancel it, so the mix is an error.
363        if out.contains(&Self::None) && out.len() > 1 {
364            return Err("`to: none` suppresses delivery and can't be combined with \
365                 other destinations — write `none` alone, or drop it"
366                .to_string());
367        }
368        if out.is_empty() {
369            return Err(format!(
370                "`to` needs at least one destination — expected one of: {}",
371                vocab::DESTINATION_NAMES.join(", ")
372            ));
373        }
374        Ok(out)
375    }
376}
377
378/// Style and figure-metadata bag. Every field optional; cascade
379/// is "first non-`None` wins outer-to-inner".
380#[derive(Debug, Clone, Default, Serialize, Deserialize)]
381pub struct Style {
382    /// Palette name or numeric index (`"wong"`, `"3"`).
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    pub palette: Option<String>,
385    /// Line-dash style: `solid`, `dashed`, `dotted`, `dashdot`,
386    /// `none`.
387    #[serde(default, skip_serializing_if = "Option::is_none")]
388    pub line: Option<String>,
389    /// Stroke width in pixels.
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    pub width: Option<f32>,
392    /// Marker shape: `none`, `circle`, `square`, `triangle`,
393    /// `diamond`, `plus`, `cross`.
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub marker: Option<String>,
396    /// Marker radius in pixels.
397    #[serde(default, skip_serializing_if = "Option::is_none")]
398    pub size: Option<f32>,
399    /// Hex color override (`#RRGGBB`).
400    #[serde(default, skip_serializing_if = "Option::is_none")]
401    pub color: Option<String>,
402    /// Figure width in pixels.
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    pub figure_width: Option<u32>,
405    /// Figure height in pixels.
406    #[serde(default, skip_serializing_if = "Option::is_none")]
407    pub figure_height: Option<u32>,
408    /// Per-series JSON sub-block overrides keyed by the
409    /// `<key>=<value>` discriminator after the `series` directive.
410    /// Values are arbitrary JSON objects; renderers consume the
411    /// fields they recognise.
412    #[serde(default, skip_serializing_if = "Vec::is_empty")]
413    pub series: Vec<SeriesOverride>,
414    /// SRD-46 output routing (`to stdout, sessiondir`). `None`
415    /// means "not declared at this level" — the cascade keeps
416    /// looking outward, and the render entry point supplies the
417    /// default when nothing declared it anywhere.
418    #[serde(default, skip_serializing_if = "Option::is_none")]
419    pub destinations: Option<Vec<Destination>>,
420}
421
422/// One `series <key>=<value> {...}` directive.
423#[derive(Debug, Clone, Serialize, Deserialize)]
424pub struct SeriesOverride {
425    /// Discriminator key (e.g. `profile`).
426    pub key: String,
427    /// Discriminator value (e.g. `hnsw`).
428    pub value: String,
429    /// Style overrides — strict JSON object verbatim, parsed
430    /// into a Style at apply time.
431    pub style: Style,
432}
433
434impl ReportItem {
435    /// Render this item back to its canonical YAML directive
436    /// form — the same string shape the workload-YAML parser
437    /// in `parse_group` consumes. Round-trips:
438    /// `parse_group(... item.to_yaml_directive_string() ...) == item`.
439    ///
440    /// The output is one or more lines:
441    ///
442    /// ```text
443    /// plot <name>
444    ///   as <stem>
445    ///   label "<label>"
446    ///   palette=<v>
447    ///   line=<v> width=<n> marker=<v> size=<n> color=<#hex>
448    ///   <body lines verbatim>
449    ///   series <key>=<val> {<json>}
450    /// ```
451    ///
452    /// Order matches [`vocab::ALL_DIRECTIVES`] so the
453    /// round-trip is stable. Style fields that are `None` are
454    /// omitted; the body is appended verbatim (it carries the
455    /// renderer-consumed `over` / `by` / `where` / `agg` /
456    /// `xlabel` / etc. lines).
457    pub fn to_yaml_directive_string(&self) -> String {
458        let mut out = String::new();
459        // Header line: `<kind> <name>`. `Details` items also
460        // round-trip; `File` directives use their target stem
461        // as the "name" (a `file <stem>` line).
462        out.push_str(self.kind.as_str());
463        out.push(' ');
464        out.push_str(&self.name);
465        // Text headers need the trailing colon: it is the parser's
466        // "named" signal (a bare `text <word>` line is the legacy
467        // anonymous single-line body form). Without it the
468        // round-trip anonymized the item and leaked the name into
469        // the rendered prose.
470        if matches!(self.kind, Kind::Text) {
471            out.push(':');
472        }
473        out.push('\n');
474
475        // `as <stem>` and `label "<text>"` come first when
476        // present — the reader expects identity directives
477        // before the per-renderer body.
478        if let Some(stem) = &self.as_stem {
479            out.push_str("  as ");
480            out.push_str(stem);
481            out.push('\n');
482        }
483        if let Some(label) = &self.label {
484            out.push_str("  label \"");
485            out.push_str(&label.replace('\\', "\\\\").replace('"', "\\\""));
486            out.push_str("\"\n");
487        }
488        if let Some(target) = &self.target_file {
489            out.push_str("  target ");
490            out.push_str(target);
491            out.push('\n');
492        }
493        // Routing travels with the item so a persisted item
494        // replayed by `nmbrs report` lands where it was declared
495        // to land, not where the replaying command defaults.
496        if let Some(dests) = &self.style.destinations {
497            out.push_str("  to ");
498            out.push_str(
499                &dests
500                    .iter()
501                    .map(|d| d.as_str())
502                    .collect::<Vec<_>>()
503                    .join(", "),
504            );
505            out.push('\n');
506        }
507        if let Some(order) = self.order {
508            out.push_str("  order ");
509            out.push_str(&order.to_string());
510            out.push('\n');
511        }
512        if self.with_table {
513            out.push_str("  with-table true\n");
514        }
515        if !self.with_tables.is_empty() {
516            out.push_str("  with-tables [");
517            out.push_str(&self.with_tables.join(", "));
518            out.push_str("]\n");
519        }
520
521        // Style scalars in declaration order from the vocab
522        // registry. Each is `<key>=<value>` on its own line —
523        // matches the existing parser's `apply_one_style_kv`
524        // contract.
525        for line in self.style.scalar_directive_lines() {
526            out.push_str("  ");
527            out.push_str(&line);
528            out.push('\n');
529        }
530
531        // Body lines (over / by / where / agg / xlabel / etc.)
532        // are passed through verbatim. The body is already in
533        // the canonical form the renderer expects.
534        if !self.body.trim().is_empty() {
535            for line in self.body.split('\n') {
536                if line.trim().is_empty() {
537                    continue;
538                }
539                out.push_str("  ");
540                out.push_str(line.trim_start());
541                out.push('\n');
542            }
543        }
544
545        // Per-series sub-blocks. Use the brace-free directive
546        // form (`series profile=hnsw line=dashed`) when only
547        // simple key=value scalars are involved; fall back to
548        // the JSON form for completeness when the series style
549        // carries series-style fields that don't survive the
550        // simple form (today they all do, but reserved for
551        // future extension).
552        for s in &self.style.series {
553            out.push_str("  style ");
554            out.push_str(&s.key);
555            out.push('=');
556            out.push_str(&s.value);
557            for line in s.style.scalar_directive_lines() {
558                out.push(' ');
559                out.push_str(&line);
560            }
561            out.push('\n');
562        }
563
564        out
565    }
566}
567
568impl Style {
569    /// Render the scalar (non-series) fields of this style
570    /// as a list of `key=value` directive lines, in the
571    /// canonical [`vocab::ALL_DIRECTIVES`] order. Used by
572    /// [`ReportItem::to_yaml_directive_string`] and by
573    /// the `series` sub-block renderer.
574    ///
575    /// `None` fields are skipped; only fields whose vocab
576    /// `target` is [`vocab::DirectiveTarget::StyleField`]
577    /// are emitted.
578    pub fn scalar_directive_lines(&self) -> Vec<String> {
579        let mut out = Vec::new();
580        for d in vocab::ALL_DIRECTIVES {
581            if !matches!(d.target, vocab::DirectiveTarget::StyleField) {
582                continue;
583            }
584            let value: Option<String> = match d.yaml_directive {
585                "palette" => self.palette.clone(),
586                "line" => self.line.clone(),
587                "width" => self.width.map(|v| v.to_string()),
588                "marker" => self.marker.clone(),
589                "size" => self.size.map(|v| v.to_string()),
590                "color" => self.color.clone(),
591                "figure_width" => self.figure_width.map(|v| v.to_string()),
592                "figure_height" => self.figure_height.map(|v| v.to_string()),
593                _ => None,
594            };
595            if let Some(v) = value {
596                out.push(format!("{}={}", d.yaml_directive, v));
597            }
598        }
599        out
600    }
601
602    /// Merge `other` into `self`: every `Some(_)` field in `other`
603    /// overrides the corresponding field in `self`. Used to walk
604    /// the cascade outer → inner.
605    pub fn merge_from(&mut self, other: &Style) {
606        if other.palette.is_some() {
607            self.palette = other.palette.clone();
608        }
609        if other.line.is_some() {
610            self.line = other.line.clone();
611        }
612        if other.width.is_some() {
613            self.width = other.width;
614        }
615        if other.marker.is_some() {
616            self.marker = other.marker.clone();
617        }
618        if other.size.is_some() {
619            self.size = other.size;
620        }
621        if other.color.is_some() {
622            self.color = other.color.clone();
623        }
624        if other.figure_width.is_some() {
625            self.figure_width = other.figure_width;
626        }
627        if other.figure_height.is_some() {
628            self.figure_height = other.figure_height;
629        }
630        if !other.series.is_empty() {
631            for s in &other.series {
632                self.series
633                    .retain(|t| !(t.key == s.key && t.value == s.value));
634                self.series.push(s.clone());
635            }
636        }
637        // Routing REPLACES rather than unions: an item declaring
638        // `to stdout` means stdout, not "stdout on top of
639        // whatever the group defaulted to".
640        if other.destinations.is_some() {
641            self.destinations = other.destinations.clone();
642        }
643    }
644
645    /// The declared destination set, or `default_to` when no
646    /// level of the cascade declared one. Callers pass the
647    /// default their entry point implies — files-only for
648    /// automatic end-of-run rendering, files+stdout for an
649    /// explicit `nmbrs report` invocation.
650    pub fn destinations_or(&self, default_to: &[Destination]) -> Vec<Destination> {
651        match &self.destinations {
652            Some(d) => d.clone(),
653            None => default_to.to_vec(),
654        }
655    }
656}
657
658// ---------------------------------------------------------------------------
659// Parsing
660// ---------------------------------------------------------------------------
661
662/// Reserved directive keywords. Used to:
663/// (1) reject group child keys that collide with directive names
664///     (warn / error in strict mode),
665/// (2) detect when a directive line is the start of a new item
666///     (`plot`, `table`) vs a continuation directive.
667const STYLE_DIRECTIVE_KEYWORDS: &[&str] = &[
668    "palette",
669    "line",
670    "width",
671    "marker",
672    "size",
673    "color",
674    "figure_width",
675    "figure_height",
676    "style",
677    "label",
678    "as",
679    "to",
680];
681
682const ITEM_KIND_KEYWORDS: &[&str] = &["plot", "table", "text", "file"];
683
684const ALL_RESERVED_DIRECTIVES: &[&str] = &[
685    "defaults",
686    "plot",
687    "table",
688    "text",
689    "file",
690    "palette",
691    "line",
692    "width",
693    "marker",
694    "size",
695    "color",
696    "figure_width",
697    "figure_height",
698    "style",
699    "label",
700    "as",
701    "to",
702];
703
704/// Parse a `report:` value (a YAML mapping) into a [`Report`].
705///
706/// Errors describe the offending input precisely; warnings (e.g.
707/// empty groups, kind-mismatched directives) are collected
708/// alongside so callers can decide whether to surface or promote
709/// to errors under strict mode.
710pub fn parse_report(value: &serde_json::Value) -> Result<ParsedReport, String> {
711    let map = value
712        .as_object()
713        .ok_or_else(|| "report: must be a mapping".to_string())?;
714
715    let mut report = Report::default();
716    let mut warnings: Vec<String> = Vec::new();
717    // Global counter for anonymous text item naming so the
718    // round-trip identity (`report.<name>` keys) stays unique
719    // across the whole document, not just within one group.
720    let mut text_counter: usize = 0;
721
722    for (key, v) in map {
723        let key: &str = key.as_str();
724        if key == "defaults" {
725            report.defaults =
726                parse_style_mapping(v).map_err(|e| format!("report.defaults: {e}"))?;
727            continue;
728        }
729        if STYLE_DIRECTIVE_KEYWORDS.contains(&key) {
730            warnings.push(format!(
731                "report.{key}: bare directive keyword used as a group name; \
732                 nest under `defaults:` to set as a default, or rename the group"
733            ));
734        }
735
736        let body = match v {
737            serde_json::Value::String(s) => s.clone(),
738            serde_json::Value::Null => String::new(),
739            _ => {
740                return Err(format!(
741                    "report.{key}: must be a string (single-line or block scalar) \
742                 of directive lines starting with `plot` / `table`"
743                ));
744            }
745        };
746
747        if body.trim() == "none" {
748            report.groups.push(ReportGroup {
749                name: key.to_string(),
750                removed: true,
751                ..ReportGroup::default()
752            });
753            continue;
754        }
755
756        let group = parse_group(key, &body, &mut warnings, &mut text_counter)?;
757        if group.items.is_empty() {
758            warnings.push(format!(
759                "report.{key}: empty group (no `plot` or `table` items)"
760            ));
761        }
762        report.groups.push(group);
763    }
764
765    // One name per item, and the declaration ordinal across the whole
766    // block. The persisted form (`order <n>`) carries the ordinal
767    // through the db so `nmbrs report` renders items in declaration
768    // order even when the metadata rows iterate alphabetically by key.
769    report.check_names_and_stamp_order()?;
770
771    Ok(ParsedReport { report, warnings })
772}
773
774/// Result of parsing a `report:` block. Warnings are non-fatal
775/// in normal mode; callers running under SRD-15 strict mode
776/// should promote them to errors.
777#[derive(Debug, Clone, Default)]
778pub struct ParsedReport {
779    pub report: Report,
780    pub warnings: Vec<String>,
781}
782
783/// Parse a single persisted-form report item — header line
784/// (`<kind> <name>`) followed by indented directive lines, as
785/// produced by [`ReportItem::to_yaml_directive_string`]. Used by
786/// the session-db fallback path in `nmbrs report` so the
787/// directive-form knowledge lives in one place.
788pub fn parse_persisted_item(body: &str) -> Result<ReportItem, String> {
789    let mut warnings: Vec<String> = Vec::new();
790    let mut text_counter: usize = 0;
791    let group = parse_group("__persisted__", body, &mut warnings, &mut text_counter)?;
792    group
793        .items
794        .into_iter()
795        .next()
796        .ok_or_else(|| "persisted report item body did not yield any item".to_string())
797}
798
799fn parse_group(
800    name: &str,
801    body: &str,
802    warnings: &mut Vec<String>,
803    text_counter: &mut usize,
804) -> Result<ReportGroup, String> {
805    let mut group = ReportGroup {
806        name: name.to_string(),
807        ..Default::default()
808    };
809    let mut current: Option<PartialItem> = None;
810    // Active output file scope (set by a `file <filename>` line).
811    // Items declared after a `file` directive inherit this until
812    // the next `file` directive in the same group.
813    let mut current_file: Option<String> = None;
814
815    let emit = |partial: PartialItem,
816                target_file: &Option<String>,
817                group: &mut ReportGroup,
818                warnings: &mut Vec<String>|
819     -> Result<(), String> {
820        let mut item = partial.finalize(warnings)?;
821        if item.target_file.is_none() {
822            item.target_file = target_file.clone();
823        }
824        group.items.push(item);
825        Ok(())
826    };
827
828    for (lineno, raw_line) in body.lines().enumerate() {
829        // Strip `#` line comments (SRD-46) before parsing —
830        // honours quoted strings so `label "see #1 above"`
831        // survives.
832        let stripped = strip_line_comment(raw_line);
833        let line = stripped.trim();
834        if line.is_empty() {
835            continue;
836        }
837        let line_no = lineno + 1;
838
839        // `defaults <directives>` — group-level defaults. Only
840        // valid before any item starts (since otherwise the
841        // intent is ambiguous: do they apply to subsequent items
842        // only? to all items? we pick "before-first-item" so
843        // there's exactly one place defaults can land).
844        if let Some(rest) = strip_directive_keyword(line, "defaults") {
845            if current.is_some() {
846                return Err(format!(
847                    "report.{name}:{line_no}: `defaults` must precede the first \
848                     item in the group"
849                ));
850            }
851            apply_directives_to_style(rest, &mut group.defaults, name, line_no)?;
852            continue;
853        }
854
855        // `<kind> <args>` — start of new item.
856        if let Some((kind, rest)) = strip_kind_keyword(line) {
857            if let Some(prev) = current.take() {
858                emit(prev, &current_file, &mut group, warnings)?;
859            }
860            match kind {
861                Kind::Plot | Kind::Table => {
862                    let mut tokens = rest.splitn(2, char::is_whitespace);
863                    let raw_item_name =
864                        tokens.next().filter(|s| !s.is_empty()).ok_or_else(|| {
865                            format!(
866                                "report.{name}:{line_no}: `{}` must be followed by a name",
867                                kind.as_str()
868                            )
869                        })?;
870                    // Allow trailing `:` on the block header
871                    // (`plot recall_vs_qps:`) for visual parity with
872                    // the body's `name: value` directives. The
873                    // colon is a delimiter — strip it before the
874                    // reserved-keyword check so `plot text:` still
875                    // sees the name as `text`.
876                    let item_name = raw_item_name.strip_suffix(':').unwrap_or(raw_item_name);
877                    if item_name.is_empty() {
878                        return Err(format!(
879                            "report.{name}:{line_no}: `{}` must be followed by a name",
880                            kind.as_str()
881                        ));
882                    }
883                    if ALL_RESERVED_DIRECTIVES.contains(&item_name) {
884                        return Err(format!(
885                            "report.{name}:{line_no}: item name '{item_name}' \
886                             collides with a reserved directive keyword"
887                        ));
888                    }
889                    let trailing = tokens.next().unwrap_or("");
890                    let mut p = PartialItem::new(kind, item_name, name.to_string(), line_no);
891                    if !trailing.trim().is_empty() {
892                        p.directives.push(trailing.to_string());
893                    }
894                    current = Some(p);
895                }
896                Kind::Text => {
897                    // Three surface forms for a `text` block:
898                    //   text <body>                              — anonymous, body on this line
899                    //   text <name>[:]                           — named, body on continuation lines
900                    //   text <name> as "<label>"[:]              — named + alias for the markdown heading
901                    //
902                    // The trailing `:` (per the new uniform
903                    // `name: value` style) is decorative and
904                    // gets stripped before the name is captured.
905                    // A bare `text` with no first token degrades
906                    // to the anonymous auto-name form, preserving
907                    // the legacy single-line shape.
908                    let rest = rest.trim();
909                    // Strip the trailing block-header colon from
910                    // the WHOLE line before tokenising, so it
911                    // doesn't get sucked into the `as "..."`
912                    // alias as `"...":`.
913                    let body = rest.strip_suffix(':').unwrap_or(rest).trim_end();
914                    let header_has_colon = body.len() < rest.len();
915                    let mut tokens = body.splitn(2, char::is_whitespace);
916                    let first = tokens.next().unwrap_or("").trim();
917                    let after = tokens.next().unwrap_or("").trim();
918                    // Decide between named and anonymous. A `text`
919                    // block is named only when the author opted in
920                    // with a positive signal:
921                    //   - a trailing `:` on the header line, or
922                    //   - an `as "<label>"` clause.
923                    // A bare `text <word>` line stays anonymous —
924                    // it's the legacy "single-line text body"
925                    // shape (preserves `text First` / `text Second`
926                    // auto-numbering tests + workloads in the wild).
927                    let has_as_alias = strip_directive_keyword(after, "as").is_some();
928                    let looks_named = !first.is_empty()
929                        && is_bare_text_name(first)
930                        && (header_has_colon || has_as_alias);
931                    let (item_name, alias) = if looks_named {
932                        let alias = strip_directive_keyword(after, "as").map(parse_quoted_or_bare);
933                        (first.to_string(), alias)
934                    } else {
935                        // Anonymous — auto-name globally so the
936                        // persistence round-trip keeps unique
937                        // `report.<name>` keys.
938                        *text_counter += 1;
939                        let auto = format!("text_{:03}", *text_counter);
940                        (auto, None)
941                    };
942                    let mut p = PartialItem::new(Kind::Text, &item_name, name.to_string(), line_no);
943                    if let Some(label) = alias {
944                        p.directives.push(format!("label {label}"));
945                    } else if !looks_named && !rest.is_empty() {
946                        // Anonymous: keep the original-line body
947                        // as a directive (legacy shape).
948                        p.directives.push(rest.to_string());
949                    }
950                    current = Some(p);
951                }
952                Kind::File => {
953                    // `file <filename> [as <label>]` — switches
954                    // the active output file. The directive is
955                    // also persisted as a Kind::File item so the
956                    // listing surface can show it; no body
957                    // attaches.
958                    let mut tokens = rest.splitn(2, char::is_whitespace);
959                    let filename = tokens
960                        .next()
961                        .filter(|s| !s.is_empty())
962                        .ok_or_else(|| {
963                            format!(
964                                "report.{name}:{line_no}: `file` must be followed by a filename"
965                            )
966                        })?
967                        .to_string();
968                    let trailing = tokens.next().unwrap_or("");
969                    let mut p = PartialItem::new(Kind::File, &filename, name.to_string(), line_no);
970                    // Honor optional `as '<label>'` on the same
971                    // line (passed through to finalize via the
972                    // directive list — the `label` extractor
973                    // already understands quoted strings).
974                    if !trailing.trim().is_empty() {
975                        // Translate `as 'X'` → `label X` so the
976                        // existing label extractor handles it.
977                        let trailing = trailing.trim();
978                        if let Some(rest) = strip_directive_keyword(trailing, "as") {
979                            p.directives.push(format!("label {rest}"));
980                        } else {
981                            p.directives.push(trailing.to_string());
982                        }
983                    }
984                    current_file = Some(filename);
985                    current = Some(p);
986                }
987                Kind::Details => {
988                    // Auto-injected at end-of-run; explicit
989                    // `details` declarations are accepted so the
990                    // author can pin position. Body is whatever
991                    // the assembler decides — usually empty
992                    // when declared explicitly (the runtime
993                    // fills it in).
994                    let mut p =
995                        PartialItem::new(Kind::Details, "details", name.to_string(), line_no);
996                    if !rest.trim().is_empty() {
997                        p.directives.push(rest.to_string());
998                    }
999                    current = Some(p);
1000                }
1001            }
1002            continue;
1003        }
1004
1005        // Continuation directive line for the current item.
1006        match current.as_mut() {
1007            Some(p) => p.directives.push(line.to_string()),
1008            None => {
1009                return Err(format!(
1010                    "report.{name}:{line_no}: directive `{line}` precedes any \
1011                 kind keyword (plot / table / text / file)"
1012                ));
1013            }
1014        }
1015    }
1016
1017    if let Some(p) = current.take() {
1018        emit(p, &current_file, &mut group, warnings)?;
1019    }
1020    Ok(group)
1021}
1022
1023struct PartialItem {
1024    kind: Kind,
1025    name: String,
1026    group: String,
1027    line_no: usize,
1028    directives: Vec<String>,
1029}
1030
1031impl PartialItem {
1032    fn new(kind: Kind, name: &str, group: String, line_no: usize) -> Self {
1033        Self {
1034            kind,
1035            name: name.to_string(),
1036            group,
1037            line_no,
1038            directives: Vec::new(),
1039        }
1040    }
1041
1042    /// Pull `label` / `as` / style directives out of the directive
1043    /// body. Anything else is left in `body` for the kind-specific
1044    /// renderer to consume.
1045    fn finalize(self, warnings: &mut Vec<String>) -> Result<ReportItem, String> {
1046        let mut item = ReportItem {
1047            kind: self.kind,
1048            name: self.name.clone(),
1049            label: None,
1050            as_stem: None,
1051            style: Style::default(),
1052            body: String::new(),
1053            target_file: None,
1054            order: None,
1055            with_table: false,
1056            with_tables: Vec::new(),
1057        };
1058
1059        // Text items: body is verbatim markdown. Pull out a
1060        // leading `label "..."` line if present (so the heading
1061        // can carry a title) plus the identity directives the
1062        // persisted round-trip emits — `target <file>` (only when
1063        // the remainder is a single token, so prose that happens
1064        // to start with the word stays prose) and `order <n>`
1065        // (only when the remainder is a number). Every other
1066        // line stays as prose. Style / series / `as` directives
1067        // don't apply to text — preserved in body if the user
1068        // wrote them (most likely they meant prose).
1069        if matches!(self.kind, Kind::Text) {
1070            let mut body_lines: Vec<String> = Vec::new();
1071            for line in &self.directives {
1072                let trimmed = line.trim();
1073                if trimmed.is_empty() {
1074                    body_lines.push(String::new());
1075                    continue;
1076                }
1077                if let Some(rest) = strip_directive_keyword(trimmed, "label") {
1078                    item.label = Some(parse_quoted_or_bare(rest));
1079                    continue;
1080                }
1081                if let Some(rest) = strip_directive_keyword(trimmed, "to") {
1082                    item.style.destinations = Some(
1083                        Destination::parse_list(rest)
1084                            .map_err(|e| format!("text '{}': {e}", self.name))?,
1085                    );
1086                    continue;
1087                }
1088                if let Some(rest) = strip_directive_keyword(trimmed, "target") {
1089                    let rest = rest.trim();
1090                    if !rest.is_empty() && !rest.contains(char::is_whitespace) {
1091                        item.target_file = Some(rest.to_string());
1092                        continue;
1093                    }
1094                }
1095                if let Some(rest) = strip_directive_keyword(trimmed, "order")
1096                    && let Ok(n) = rest.trim().parse::<usize>()
1097                {
1098                    item.order = Some(n);
1099                    continue;
1100                }
1101                body_lines.push(line.clone());
1102            }
1103            item.body = body_lines.join("\n");
1104            return Ok(item);
1105        }
1106
1107        let mut residual: Vec<String> = Vec::new();
1108        for line in &self.directives {
1109            let line = line.trim();
1110            if line.is_empty() {
1111                continue;
1112            }
1113
1114            if let Some(rest) = strip_directive_keyword(line, "label") {
1115                item.label = Some(parse_quoted_or_bare(rest));
1116                continue;
1117            }
1118            if let Some(rest) = strip_directive_keyword(line, "to") {
1119                item.style.destinations = Some(
1120                    Destination::parse_list(rest)
1121                        .map_err(|e| format!("{} '{}': {e}", self.kind.as_str(), self.name))?,
1122                );
1123                continue;
1124            }
1125            if let Some(rest) = strip_directive_keyword(line, "as") {
1126                item.as_stem = Some(rest.trim().to_string());
1127                continue;
1128            }
1129            // `target <filename>` — per-item override that pins
1130            // the output markdown file independently of any
1131            // surrounding `file <filename>` scope. Used by the
1132            // persisted form (runner emits it for every item so
1133            // the round-trip through the db preserves the
1134            // target the workload's `file` scope assigned).
1135            if let Some(rest) = strip_directive_keyword(line, "target") {
1136                item.target_file = Some(rest.trim().to_string());
1137                continue;
1138            }
1139            // `order <n>` — declaration ordinal, emitted by the
1140            // persisted form so db-sourced renders keep the
1141            // workload's declaration order.
1142            if let Some(rest) = strip_directive_keyword(line, "order")
1143                && let Ok(n) = rest.trim().parse::<usize>()
1144            {
1145                item.order = Some(n);
1146                continue;
1147            }
1148            // `with-tables: [label1, label2, …]` — plot-only
1149            // multi-table fan-out. Emits one companion
1150            // table per distinct value tuple of the listed
1151            // labels. Comes before `with-table` matching so
1152            // the plural form isn't shadowed by the
1153            // prefix-trimmed singular.
1154            if let Some(rest) = strip_directive_keyword(line, "with-tables") {
1155                let trimmed = rest.trim().trim_matches(':').trim();
1156                let inner = trimmed.strip_prefix('[')
1157                    .and_then(|s| s.strip_suffix(']'))
1158                    .ok_or_else(|| format!(
1159                        "report.{}:{} `with-tables`: expected `[label1, label2, …]`, got `{trimmed}`",
1160                        self.group, self.line_no,
1161                    ))?;
1162                let labels: Vec<String> = inner
1163                    .split(',')
1164                    .map(|s| s.trim().trim_matches('"').trim_matches('\'').to_string())
1165                    .filter(|s| !s.is_empty())
1166                    .collect();
1167                if labels.is_empty() {
1168                    return Err(format!(
1169                        "report.{}:{} `with-tables`: list is empty — drop the directive \
1170                         or list one or more label keys",
1171                        self.group, self.line_no,
1172                    ));
1173                }
1174                if !matches!(self.kind, Kind::Plot) {
1175                    warnings.push(format!(
1176                        "report.{}:{} item '{}' uses `with-tables` but is a {}; \
1177                         only plots can have a faceted companion table.",
1178                        self.group,
1179                        self.line_no,
1180                        item.name,
1181                        item.kind.as_str(),
1182                    ));
1183                } else {
1184                    item.with_tables = labels;
1185                }
1186                continue;
1187            }
1188            // `with-table: true|false` — plot-only flag
1189            // that asks the renderer to emit a companion
1190            // table immediately after the plot, sharing
1191            // the plot's underlying query data. SRD-46
1192            // §"Table-from-plot". Accepted-but-warned for
1193            // non-plot items.
1194            if let Some(rest) = strip_directive_keyword(line, "with-table") {
1195                let v = rest.trim().trim_matches(':').trim();
1196                item.with_table = crate::boolean::parse_bool("with-table", v)
1197                    .map_err(|e| format!("report.{}:{} {e}", self.group, self.line_no))?;
1198                if item.with_table && !matches!(self.kind, Kind::Plot) {
1199                    warnings.push(format!(
1200                        "report.{}:{} item '{}' uses `with-table` but is a {}; \
1201                         only plots can have a companion table.",
1202                        self.group,
1203                        self.line_no,
1204                        item.name,
1205                        item.kind.as_str(),
1206                    ));
1207                    item.with_table = false;
1208                }
1209                continue;
1210            }
1211            if let Some(rest) = strip_directive_keyword(line, "style") {
1212                let so = parse_series_override(rest).map_err(|e| {
1213                    format!("report.{}:{} `style`: {}", self.group, self.line_no, e,)
1214                })?;
1215                item.style.series.push(so);
1216                continue;
1217            }
1218
1219            if let Some(applied) = try_apply_style_directives(line, &mut item.style)? {
1220                if !applied {
1221                    residual.push(line.to_string());
1222                } else {
1223                    // Per-item directive that doesn't apply to the
1224                    // item's kind: warn (SRD-46 strict-mode hook).
1225                    if !style_directive_applies_to_kind(line, item.kind) {
1226                        warnings.push(format!(
1227                            "report.{}:{} item '{}' is a {} but uses \
1228                             directive `{}`, which has no effect on this kind",
1229                            self.group,
1230                            self.line_no,
1231                            item.name,
1232                            item.kind.as_str(),
1233                            line
1234                        ));
1235                    }
1236                }
1237                continue;
1238            }
1239
1240            residual.push(line.to_string());
1241        }
1242        item.body = residual.join("\n");
1243        Ok(item)
1244    }
1245}
1246
1247fn strip_directive_keyword<'a>(line: &'a str, kw: &str) -> Option<&'a str> {
1248    let line = line.trim_start();
1249    if let Some(rest) = line.strip_prefix(kw) {
1250        let next = rest.chars().next();
1251        if next.is_none()
1252            || next == Some(' ')
1253            || next == Some('\t')
1254            || next == Some('=')
1255            || next == Some(':')
1256        {
1257            return Some(rest.trim_start_matches([' ', '\t', '=', ':']));
1258        }
1259    }
1260    None
1261}
1262
1263fn strip_kind_keyword(line: &str) -> Option<(Kind, &str)> {
1264    for kw in ITEM_KIND_KEYWORDS {
1265        if let Some(rest) = line.strip_prefix(kw)
1266            && let Some(next) = rest.chars().next()
1267            && next.is_whitespace()
1268        {
1269            let kind = match *kw {
1270                "plot" => Kind::Plot,
1271                "table" => Kind::Table,
1272                "text" => Kind::Text,
1273                "file" => Kind::File,
1274                _ => unreachable!(),
1275            };
1276            return Some((kind, rest.trim_start()));
1277        }
1278    }
1279    None
1280}
1281
1282/// `true` when `s` is a bare identifier-shaped token suitable to
1283/// use as the name of a `text <name>` block — `[A-Za-z_][A-Za-z0-9_-]*`.
1284/// Falls back to anonymous-text auto-naming when the first token
1285/// has whitespace, punctuation, or starts with a digit; that's
1286/// the legacy single-line `text <body>` shape.
1287fn is_bare_text_name(s: &str) -> bool {
1288    let mut chars = s.chars();
1289    match chars.next() {
1290        Some(c) if c.is_ascii_alphabetic() || c == '_' => {}
1291        _ => return false,
1292    }
1293    chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
1294}
1295
1296fn parse_quoted_or_bare(s: &str) -> String {
1297    let s = s.trim();
1298    if let Some(stripped) = s.strip_prefix('"').and_then(|x| x.strip_suffix('"')) {
1299        return stripped.to_string();
1300    }
1301    if let Some(stripped) = s.strip_prefix('\'').and_then(|x| x.strip_suffix('\'')) {
1302        return stripped.to_string();
1303    }
1304    s.to_string()
1305}
1306
1307/// Apply style directives from a single line (any combination
1308/// of `key=value` pairs separated by whitespace or commas) to
1309/// the given Style. Returns `Ok(Some(true))` if every token on
1310/// the line was a recognized style directive, `Ok(Some(false))`
1311/// if some tokens belonged to the kind-specific spec body, or
1312/// `Ok(None)` if the line doesn't look like a style directive
1313/// line at all (no `=` and no leading style keyword).
1314fn try_apply_style_directives(line: &str, style: &mut Style) -> Result<Option<bool>, String> {
1315    if !line.contains('=') && !line_starts_with_any(line, STYLE_DIRECTIVE_KEYWORDS) {
1316        return Ok(None);
1317    }
1318    let mut all_consumed = true;
1319    for (position, token) in tokenize_directive_line(line).into_iter().enumerate() {
1320        if let Some((k, v)) = token.split_once('=') {
1321            if STYLE_DIRECTIVE_KEYWORDS.contains(&k) {
1322                apply_one_style_kv(k, v, style)?;
1323            } else {
1324                all_consumed = false;
1325            }
1326        } else if position == 0 && STYLE_DIRECTIVE_KEYWORDS.contains(&token.as_str()) {
1327            // A line that OPENS with a bare style keyword is a style
1328            // directive missing its value. The same word later on a
1329            // line is the body's own: a label named `size` in
1330            // `group_by: ds, size` or `by (ds, size)` is not a
1331            // directive.
1332            return Err(format!("style directive `{token}` requires a value"));
1333        } else {
1334            all_consumed = false;
1335        }
1336    }
1337    Ok(Some(all_consumed))
1338}
1339
1340fn apply_one_style_kv(k: &str, v: &str, style: &mut Style) -> Result<(), String> {
1341    let v = v.trim().trim_matches('"').trim_matches('\'');
1342    match k {
1343        "palette" => style.palette = Some(v.to_string()),
1344        "line" => style.line = Some(v.to_string()),
1345        "width" => {
1346            style.width = Some(
1347                v.parse()
1348                    .map_err(|_| format!("`width={v}` is not a number"))?,
1349            )
1350        }
1351        "marker" => style.marker = Some(v.to_string()),
1352        "size" => {
1353            style.size = Some(
1354                v.parse()
1355                    .map_err(|_| format!("`size={v}` is not a number"))?,
1356            )
1357        }
1358        "color" => style.color = Some(v.to_string()),
1359        "figure_width" => {
1360            style.figure_width = Some(
1361                v.parse()
1362                    .map_err(|_| format!("`figure_width={v}` is not an integer"))?,
1363            )
1364        }
1365        "figure_height" => {
1366            style.figure_height = Some(
1367                v.parse()
1368                    .map_err(|_| format!("`figure_height={v}` is not an integer"))?,
1369            )
1370        }
1371        // Routing, not cosmetics — but it cascades through the
1372        // same `defaults:` mapping, so it is applied here.
1373        "to" => style.destinations = Some(Destination::parse_list(v)?),
1374        _ => return Err(format!("unknown style directive `{k}`")),
1375    }
1376    Ok(())
1377}
1378
1379fn tokenize_directive_line(line: &str) -> Vec<String> {
1380    // Split on whitespace and commas at depth 0. Quoted values
1381    // stay together. No JSON braces here — those are only inside
1382    // `series` sub-blocks and parsed separately.
1383    let mut out: Vec<String> = Vec::new();
1384    let mut cur = String::new();
1385    let mut quote: Option<char> = None;
1386    for ch in line.chars() {
1387        match quote {
1388            Some(q) if ch == q => {
1389                quote = None;
1390                cur.push(ch);
1391            }
1392            Some(_) => cur.push(ch),
1393            None => match ch {
1394                '"' | '\'' => {
1395                    quote = Some(ch);
1396                    cur.push(ch);
1397                }
1398                ' ' | '\t' | ',' => {
1399                    if !cur.is_empty() {
1400                        out.push(std::mem::take(&mut cur));
1401                    }
1402                }
1403                _ => cur.push(ch),
1404            },
1405        }
1406    }
1407    if !cur.is_empty() {
1408        out.push(cur);
1409    }
1410    out
1411}
1412
1413fn line_starts_with_any(line: &str, kws: &[&str]) -> bool {
1414    let trimmed = line.trim_start();
1415    kws.iter().any(|kw| {
1416        trimmed.starts_with(kw)
1417            && trimmed
1418                .as_bytes()
1419                .get(kw.len())
1420                .is_none_or(|c| matches!(*c, b' ' | b'\t' | b'='))
1421    })
1422}
1423
1424fn style_directive_applies_to_kind(line: &str, kind: Kind) -> bool {
1425    let head = tokenize_directive_line(line)
1426        .first()
1427        .map(|s| {
1428            s.split_once('=')
1429                .map(|(k, _)| k.to_string())
1430                .unwrap_or_else(|| s.clone())
1431        })
1432        .unwrap_or_default();
1433    !matches!(
1434        (kind, head.as_str()),
1435        (Kind::Table, "line" | "width" | "marker" | "size")
1436    )
1437}
1438
1439fn parse_series_override(s: &str) -> Result<SeriesOverride, String> {
1440    // Shape: `<key>=<value> {<json>}`, `<key>=<value> <directives>`,
1441    // or the colon-separator form `<key>=<value>:<directives>` (same
1442    // shape the plot DSL's --style flag accepts; lets workload
1443    // authors write `style phase=pvs_query:line=dotted` without
1444    // having to remember which directive uses which separator).
1445    let s = s.trim();
1446    // Try `:` first when it appears before any whitespace — that's
1447    // the colon-form. Otherwise the head ends at the first
1448    // whitespace boundary as before.
1449    let first_colon = s.find(':');
1450    let first_ws = s.find(char::is_whitespace);
1451    let split_at = match (first_colon, first_ws) {
1452        (Some(c), Some(w)) if c < w => Some((c, 1)), // colon wins
1453        (Some(c), None) => Some((c, 1)),
1454        (_, Some(w)) => Some((w, 1)),
1455        (None, None) => None,
1456    };
1457    let (head, rest) = match split_at {
1458        Some((idx, n)) => (&s[..idx], s[idx + n..].trim_start()),
1459        None => (s, ""),
1460    };
1461    let (key, value) = head
1462        .split_once('=')
1463        .ok_or_else(|| format!("series discriminator must be <key>=<value>, got `{head}`"))?;
1464
1465    let mut style = Style::default();
1466    let rest = rest.trim();
1467
1468    if rest.starts_with('{') {
1469        // JSON sub-block — strict.
1470        if !rest.ends_with('}') {
1471            return Err("JSON sub-block must close with `}` on the same line".to_string());
1472        }
1473        let json: serde_json::Value =
1474            serde_json::from_str(rest).map_err(|e| format!("JSON sub-block parse error: {e}"))?;
1475        apply_json_to_style(&json, &mut style)?;
1476    } else if !rest.is_empty() {
1477        // Brace-free directive form.
1478        try_apply_style_directives(rest, &mut style)?;
1479    }
1480
1481    Ok(SeriesOverride {
1482        key: key.trim().to_string(),
1483        value: value
1484            .trim()
1485            .trim_matches('"')
1486            .trim_matches('\'')
1487            .to_string(),
1488        style,
1489    })
1490}
1491
1492fn apply_json_to_style(v: &serde_json::Value, style: &mut Style) -> Result<(), String> {
1493    let map = v
1494        .as_object()
1495        .ok_or_else(|| "series JSON sub-block must be an object".to_string())?;
1496    for (k, val) in map {
1497        let v_str = match val {
1498            serde_json::Value::String(s) => s.clone(),
1499            serde_json::Value::Number(n) => n.to_string(),
1500            serde_json::Value::Bool(b) => b.to_string(),
1501            _ => {
1502                return Err(format!(
1503                    "series JSON sub-block: value for `{k}` must be a string, number, or bool"
1504                ));
1505            }
1506        };
1507        apply_one_style_kv(k, &v_str, style)?;
1508    }
1509    Ok(())
1510}
1511
1512fn apply_directives_to_style(
1513    line: &str,
1514    style: &mut Style,
1515    group: &str,
1516    line_no: usize,
1517) -> Result<(), String> {
1518    match try_apply_style_directives(line, style) {
1519        Ok(_) => Ok(()),
1520        Err(e) => Err(format!("report.{group}:{line_no}: {e}")),
1521    }
1522}
1523
1524/// Strip a `#` line comment from one source line. A `#` starts
1525/// a comment only when it is at line start or preceded by
1526/// whitespace — so hex colors (`#117733`) and JSON sub-blocks
1527/// (`{"color": "#fff"}`) are unaffected. Quoted strings are
1528/// honoured so `label "see #1 above"` keeps its `#`.
1529fn strip_line_comment(line: &str) -> &str {
1530    let mut quote: Option<char> = None;
1531    let mut prev_ws = true; // start-of-line counts as whitespace boundary
1532    for (i, ch) in line.char_indices() {
1533        match quote {
1534            Some(q) if ch == q => {
1535                quote = None;
1536                prev_ws = false;
1537            }
1538            Some(_) => {
1539                prev_ws = false;
1540            }
1541            None => match ch {
1542                '"' | '\'' => {
1543                    quote = Some(ch);
1544                    prev_ws = false;
1545                }
1546                '#' if prev_ws => return &line[..i],
1547                c if c.is_whitespace() => {
1548                    prev_ws = true;
1549                }
1550                _ => {
1551                    prev_ws = false;
1552                }
1553            },
1554        }
1555    }
1556    line
1557}
1558
1559fn parse_style_mapping(v: &serde_json::Value) -> Result<Style, String> {
1560    let map = v
1561        .as_object()
1562        .ok_or_else(|| "must be a mapping of style directives".to_string())?;
1563    let mut style = Style::default();
1564    for (key, val) in map {
1565        let key = key.as_str();
1566        let value: String = match val {
1567            serde_json::Value::String(s) => s.clone(),
1568            serde_json::Value::Number(n) => n.to_string(),
1569            serde_json::Value::Bool(b) => b.to_string(),
1570            serde_json::Value::Null => continue,
1571            _ => {
1572                return Err(format!(
1573                    "value for `{key}` must be a scalar (string, number, or bool)"
1574                ));
1575            }
1576        };
1577        apply_one_style_kv(key, &value, &mut style)?;
1578    }
1579    Ok(style)
1580}
1581
1582#[cfg(test)]
1583mod tests {
1584    use super::*;
1585
1586    fn parse(yaml: &str) -> ParsedReport {
1587        let v: serde_json::Value = serde_yaml::from_str(yaml).unwrap();
1588        parse_report(&v).unwrap()
1589    }
1590
1591    #[test]
1592    fn single_plot_minimal() {
1593        let p = parse(
1594            r#"
1595recall_block: |
1596  plot recall_at_k10
1597    over limit by profile
1598    label "Recall@10 vs k limit"
1599"#,
1600        );
1601        assert_eq!(p.report.groups.len(), 1);
1602        let g = &p.report.groups[0];
1603        assert_eq!(g.name, "recall_block");
1604        assert_eq!(g.items.len(), 1);
1605        let item = &g.items[0];
1606        assert_eq!(item.kind, Kind::Plot);
1607        assert_eq!(item.name, "recall_at_k10");
1608        assert_eq!(item.label.as_deref(), Some("Recall@10 vs k limit"));
1609        assert!(item.body.contains("over limit"));
1610    }
1611
1612    #[test]
1613    fn defaults_at_root_and_group() {
1614        let p = parse(
1615            r#"
1616defaults:
1617  palette: wong
1618  width: 1024
1619
1620recall_block: |
1621  defaults palette=tol_muted
1622  plot recall_at_k10 over limit
1623"#,
1624        );
1625        assert_eq!(p.report.defaults.palette.as_deref(), Some("wong"));
1626        assert_eq!(p.report.defaults.width, Some(1024.0));
1627        let g = &p.report.groups[0];
1628        assert_eq!(g.defaults.palette.as_deref(), Some("tol_muted"));
1629        // Item-level inherits via merge_from at apply time.
1630        let s = p.report.effective_style(g, &g.items[0]);
1631        assert_eq!(s.palette.as_deref(), Some("tol_muted"));
1632        assert_eq!(s.width, Some(1024.0));
1633    }
1634
1635    #[test]
1636    fn plots_and_tables_in_one_group() {
1637        let p = parse(
1638            r#"
1639combo: |
1640  plot recall_at_k10 over limit
1641  table recall_summary metric=recall@.* group_by=profile
1642"#,
1643        );
1644        let items = &p.report.groups[0].items;
1645        assert_eq!(items.len(), 2);
1646        assert_eq!(items[0].kind, Kind::Plot);
1647        assert_eq!(items[0].name, "recall_at_k10");
1648        assert_eq!(items[1].kind, Kind::Table);
1649        assert_eq!(items[1].name, "recall_summary");
1650    }
1651
1652    #[test]
1653    fn style_json_sub_block() {
1654        let p = parse(
1655            r#"
1656g: |
1657  plot p1 over x
1658    style profile=hnsw {"line": "dashed", "marker": "triangle"}
1659"#,
1660        );
1661        let item = &p.report.groups[0].items[0];
1662        assert_eq!(item.style.series.len(), 1);
1663        let so = &item.style.series[0];
1664        assert_eq!(so.key, "profile");
1665        assert_eq!(so.value, "hnsw");
1666        assert_eq!(so.style.line.as_deref(), Some("dashed"));
1667        assert_eq!(so.style.marker.as_deref(), Some("triangle"));
1668    }
1669
1670    #[test]
1671    fn style_directive_form() {
1672        let p = parse(
1673            r#"
1674g: |
1675  plot p1 over x
1676    style profile=ivf line=dotted color=#117733
1677"#,
1678        );
1679        let so = &p.report.groups[0].items[0].style.series[0];
1680        assert_eq!(so.value, "ivf");
1681        assert_eq!(so.style.line.as_deref(), Some("dotted"));
1682        assert_eq!(so.style.color.as_deref(), Some("#117733"));
1683    }
1684
1685    #[test]
1686    fn duplicate_name_is_error() {
1687        let v: serde_json::Value = serde_yaml::from_str(
1688            r#"
1689g1: "plot dup over x"
1690g2: "plot dup over y"
1691"#,
1692        )
1693        .unwrap();
1694        assert!(parse_report(&v).is_err());
1695    }
1696
1697    #[test]
1698    fn empty_group_warns() {
1699        let p = parse(
1700            r#"
1701empty_block: ""
1702"#,
1703        );
1704        assert_eq!(p.report.groups.len(), 1);
1705        assert!(p.warnings.iter().any(|w| w.contains("empty_block")));
1706    }
1707
1708    #[test]
1709    fn persisted_text_item_round_trips_name_target_and_order() {
1710        // The full text-identity round trip: named text with a
1711        // heading label, a file target, and a declaration
1712        // ordinal must come back from the persisted form with
1713        // NOTHING leaked into the prose body. (Before this, the
1714        // header lost its named signal — the name and `target`
1715        // line rendered as prose and the section fell back to
1716        // summary.md.)
1717        let item = ReportItem {
1718            kind: Kind::Text,
1719            name: "key_metrics_overview".to_string(),
1720            label: Some("Overview".to_string()),
1721            target_file: Some("key_metrics.md".to_string()),
1722            order: Some(3),
1723            body: "First prose line.\ntarget audience is prose, not a directive.".to_string(),
1724            ..Default::default()
1725        };
1726        let persisted = item.to_yaml_directive_string();
1727        let back = parse_persisted_item(&persisted).expect("round-trip parse");
1728        assert_eq!(back.kind, Kind::Text);
1729        assert_eq!(back.name, "key_metrics_overview");
1730        assert_eq!(back.label.as_deref(), Some("Overview"));
1731        assert_eq!(back.target_file.as_deref(), Some("key_metrics.md"));
1732        assert_eq!(back.order, Some(3));
1733        // Prose survives verbatim — including a line that merely
1734        // STARTS with the word `target` (multi-token ⇒ prose).
1735        assert_eq!(back.body, item.body);
1736    }
1737
1738    #[test]
1739    fn destination_list_parses_spellings_and_rejects_junk() {
1740        use Destination::*;
1741        assert_eq!(Destination::parse_list("stdout").unwrap(), vec![Stdout]);
1742        // Comma, whitespace, and mixed separators all work.
1743        assert_eq!(
1744            Destination::parse_list("stdout, sessiondir").unwrap(),
1745            vec![Stdout, SessionDir]
1746        );
1747        assert_eq!(
1748            Destination::parse_list("sessiondir stderr").unwrap(),
1749            vec![SessionDir, Stderr]
1750        );
1751        // Retired spellings and case variants are errors naming the
1752        // canonical word.
1753        for (retired, canonical) in [
1754            ("session", "sessiondir"),
1755            ("session_dir", "sessiondir"),
1756            ("off", "none"),
1757        ] {
1758            let err = Destination::parse_list(retired).unwrap_err();
1759            assert!(err.contains(&format!("write '{canonical}'")), "{err}");
1760        }
1761        assert!(Destination::parse_list("STDOUT").is_err());
1762        // Duplicates collapse rather than double-delivering.
1763        assert_eq!(
1764            Destination::parse_list("stdout,stdout").unwrap(),
1765            vec![Stdout]
1766        );
1767        // `none` is a suppression, not a peer: alone it suppresses;
1768        // beside a real destination it is an error, not a silent win.
1769        assert_eq!(Destination::parse_list("none").unwrap(), vec![None]);
1770        assert!(Destination::parse_list("stdout, none, sessiondir").is_err());
1771        // An unknown destination names the vocabulary.
1772        let err = Destination::parse_list("syslog").unwrap_err();
1773        assert!(err.contains("syslog"), "{err}");
1774        assert!(err.contains("sessiondir"), "names the vocabulary: {err}");
1775        // An empty list is an error, not a silent no-op.
1776        assert!(Destination::parse_list("  ").is_err());
1777    }
1778
1779    #[test]
1780    fn to_directive_parses_and_cascades_replacing_outer() {
1781        let yaml: serde_json::Value = serde_yaml::from_str(
1782            r#"
1783defaults:
1784  to: sessiondir
1785routed: |
1786  table alpha:
1787    to stdout
1788    query: v: avg(x)
1789  table beta:
1790    query: v: avg(y)
1791"#,
1792        )
1793        .expect("yaml");
1794        let parsed = parse_report(&yaml).expect("parse report");
1795        let group = &parsed.report.groups[0];
1796        let alpha = parsed.report.find("alpha").expect("alpha");
1797        let beta = parsed.report.find("beta").expect("beta");
1798
1799        // The item declaration REPLACES the report default rather
1800        // than unioning with it — `to stdout` means stdout, not
1801        // "stdout on top of sessiondir".
1802        assert_eq!(
1803            parsed.report.effective_style(group, alpha).destinations,
1804            Some(vec![Destination::Stdout])
1805        );
1806        // An item that declared nothing inherits the cascade.
1807        assert_eq!(
1808            parsed.report.effective_style(group, beta).destinations,
1809            Some(vec![Destination::SessionDir])
1810        );
1811    }
1812
1813    #[test]
1814    fn undeclared_routing_stays_none_so_the_caller_supplies_the_default() {
1815        // Nothing anywhere in the cascade declared `to`, so the
1816        // parsed style carries `None` — the render entry point
1817        // decides, and the two entry points differ (files-only for
1818        // the automatic run-end render, files+stdout for an
1819        // explicit `nmbrs report`).
1820        let yaml: serde_json::Value = serde_yaml::from_str(
1821            r#"
1822plain: |
1823  table alpha:
1824    query: v: avg(x)
1825"#,
1826        )
1827        .expect("yaml");
1828        let parsed = parse_report(&yaml).expect("parse report");
1829        let group = &parsed.report.groups[0];
1830        let alpha = parsed.report.find("alpha").expect("alpha");
1831        assert_eq!(
1832            parsed.report.effective_style(group, alpha).destinations,
1833            Option::None
1834        );
1835        assert_eq!(
1836            parsed
1837                .report
1838                .effective_style(group, alpha)
1839                .destinations_or(&[Destination::SessionDir]),
1840            vec![Destination::SessionDir]
1841        );
1842    }
1843
1844    #[test]
1845    fn routing_round_trips_through_the_persisted_form() {
1846        // `to` must survive the db round-trip, or an item replayed
1847        // by `nmbrs report` would land where the replaying command
1848        // defaults instead of where it was declared.
1849        let yaml: serde_json::Value = serde_yaml::from_str(
1850            r#"
1851routed: |
1852  table alpha:
1853    to stdout, sessiondir
1854    query: v: avg(x)
1855"#,
1856        )
1857        .expect("yaml");
1858        let parsed = parse_report(&yaml).expect("parse report");
1859        let item = parsed.report.find("alpha").expect("alpha");
1860        let persisted = item.to_yaml_directive_string();
1861        assert!(
1862            persisted.contains("to stdout, sessiondir"),
1863            "persisted form carries routing: {persisted}"
1864        );
1865        let back = parse_persisted_item(&persisted).expect("round-trip");
1866        assert_eq!(
1867            back.style.destinations,
1868            Some(vec![Destination::Stdout, Destination::SessionDir])
1869        );
1870    }
1871
1872    #[test]
1873    fn parse_report_stamps_declaration_ordinals() {
1874        let yaml: serde_json::Value = serde_yaml::from_str(
1875            r#"
1876section_a: |
1877  table alpha:
1878    query: v: avg(x)
1879  text zeta as "Z":
1880   prose
1881section_b: |
1882  table beta:
1883    query: v: avg(y)
1884"#,
1885        )
1886        .expect("yaml");
1887        let parsed = parse_report(&yaml).expect("parse report");
1888        let orders: Vec<(String, Option<usize>)> = parsed
1889            .report
1890            .items()
1891            .map(|i| (i.name.clone(), i.order))
1892            .collect();
1893        assert_eq!(
1894            orders,
1895            vec![
1896                ("alpha".to_string(), Some(0)),
1897                ("zeta".to_string(), Some(1)),
1898                ("beta".to_string(), Some(2)),
1899            ]
1900        );
1901    }
1902
1903    #[test]
1904    fn parse_persisted_item_strips_with_table_from_body() {
1905        // Verbatim shape produced by `to_yaml_directive_string`
1906        // and written to `session_metadata.report.<name>`.
1907        // Lines start at column 0 (no indentation in the
1908        // persisted form). The plot must survive a round-trip
1909        // with `with_table=true` and no `with-table` line in
1910        // the body.
1911        let body = "plot recall_1_mean
1912label \"ALL 1-recall@R, oracles & PVS\"
1913target oracles_report.md
1914legend: bottom-right
1915x: r
1916y1: avg(recall_mean{k=\"1\"}) by (k,r)
1917y-ranges: [[0.0,1.0]]
1918with-table: true";
1919        let item = parse_persisted_item(body).expect("parse_persisted_item should succeed");
1920        assert_eq!(item.name, "recall_1_mean");
1921        assert!(item.with_table, "with_table should be set");
1922        assert!(
1923            !item.body.contains("with-table"),
1924            "body should not contain with-table line; got: {:?}",
1925            item.body,
1926        );
1927    }
1928
1929    #[test]
1930    fn with_table_colon_form_consumed_not_in_body() {
1931        // Regression: the YAML colon form `with-table: true` used
1932        // to fall through `strip_directive_keyword` (which only
1933        // accepted space/tab/`=` separators), leaving the line in
1934        // `item.body`. The plot renderer then saw it as an
1935        // unknown directive and failed every plot it touched.
1936        let p = parse(
1937            r#"
1938g: |
1939  plot p1
1940    over limit
1941    with-table: true
1942"#,
1943        );
1944        let item = &p.report.groups[0].items[0];
1945        assert!(item.with_table, "with-table flag should be set");
1946        assert!(
1947            !item.body.contains("with-table"),
1948            "with-table line should be stripped from body, got: {:?}",
1949            item.body,
1950        );
1951    }
1952
1953    #[test]
1954    fn unknown_directive_falls_into_body() {
1955        let p = parse(
1956            r#"
1957g: |
1958  plot p1
1959    over limit
1960    where dataset=example
1961    custom_directive=foo
1962"#,
1963        );
1964        let item = &p.report.groups[0].items[0];
1965        assert!(item.body.contains("over limit"));
1966        assert!(item.body.contains("custom_directive=foo"));
1967    }
1968
1969    #[test]
1970    fn label_with_quotes() {
1971        let p = parse(
1972            r#"
1973g: |
1974  plot p1 over x
1975    label 'p99 latency'
1976"#,
1977        );
1978        assert_eq!(
1979            p.report.groups[0].items[0].label.as_deref(),
1980            Some("p99 latency")
1981        );
1982    }
1983
1984    #[test]
1985    fn item_name_collides_with_directive_keyword_errors() {
1986        let v: serde_json::Value = serde_yaml::from_str(
1987            r#"
1988g: "plot palette over x"
1989"#,
1990        )
1991        .unwrap();
1992        assert!(parse_report(&v).is_err());
1993    }
1994
1995    #[test]
1996    fn declaration_order_preserved_across_groups() {
1997        let p = parse(
1998            r#"
1999zzz_block: "plot z over x"
2000aaa_block: "plot a over x"
2001mmm_block: "plot m over x"
2002"#,
2003        );
2004        let names: Vec<_> = p.report.groups.iter().map(|g| g.name.clone()).collect();
2005        assert_eq!(names, vec!["zzz_block", "aaa_block", "mmm_block"]);
2006    }
2007
2008    #[test]
2009    fn style_cascade_root_to_item() {
2010        let p = parse(
2011            r#"
2012defaults:
2013  palette: wong
2014  width: 1024
2015
2016g: |
2017  defaults palette=tol_muted
2018  plot p1 over x
2019    palette=ibm
2020"#,
2021        );
2022        let g = &p.report.groups[0];
2023        let item = &g.items[0];
2024        let s = p.report.effective_style(g, item);
2025        assert_eq!(s.palette.as_deref(), Some("ibm"));
2026        assert_eq!(s.width, Some(1024.0));
2027    }
2028
2029    #[test]
2030    fn text_kind_keeps_body_verbatim() {
2031        let p = parse(
2032            r#"
2033intro: |
2034  text Welcome to the report.
2035   Multi-line prose continues here
2036   with arbitrary text.
2037"#,
2038        );
2039        let item = &p.report.groups[0].items[0];
2040        assert_eq!(item.kind, Kind::Text);
2041        assert_eq!(item.name, "text_001");
2042        assert!(item.body.contains("Welcome to the report"));
2043        assert!(item.body.contains("arbitrary text"));
2044    }
2045
2046    #[test]
2047    fn file_directive_scopes_following_items() {
2048        let p = parse(
2049            r#"
2050sections: |
2051  file my_report.md as 'Markdown Report'
2052    text Intro paragraph
2053    plot recall_at_k10 over limit
2054    table summary metric=recall@.* group_by=p
2055"#,
2056        );
2057        let items = &p.report.groups[0].items;
2058        assert_eq!(items.len(), 4);
2059        assert_eq!(items[0].kind, Kind::File);
2060        assert_eq!(items[0].name, "my_report.md");
2061        assert_eq!(items[0].label.as_deref(), Some("Markdown Report"));
2062        // Subsequent items inherit the file as target.
2063        for it in &items[1..] {
2064            assert_eq!(
2065                it.target_file.as_deref(),
2066                Some("my_report.md"),
2067                "item {} should target my_report.md, got {:?}",
2068                it.name,
2069                it.target_file
2070            );
2071        }
2072    }
2073
2074    #[test]
2075    fn file_switch_resets_scope() {
2076        let p = parse(
2077            r#"
2078two_files: |
2079  file alpha.md as 'Alpha'
2080    plot p1 over x
2081  file beta.md
2082    plot p2 over y
2083"#,
2084        );
2085        let items = &p.report.groups[0].items;
2086        // Items 0=file alpha, 1=plot p1 (alpha), 2=file beta, 3=plot p2 (beta)
2087        assert_eq!(items[0].name, "alpha.md");
2088        assert_eq!(items[1].target_file.as_deref(), Some("alpha.md"));
2089        assert_eq!(items[2].name, "beta.md");
2090        assert_eq!(items[3].target_file.as_deref(), Some("beta.md"));
2091    }
2092
2093    #[test]
2094    fn items_before_any_file_have_no_target() {
2095        let p = parse(
2096            r#"
2097mixed: |
2098  plot orphan over x
2099  file r.md
2100    plot inside over x
2101"#,
2102        );
2103        let items = &p.report.groups[0].items;
2104        assert_eq!(items[0].name, "orphan");
2105        assert_eq!(items[0].target_file, None);
2106        assert_eq!(items[2].name, "inside");
2107        assert_eq!(items[2].target_file.as_deref(), Some("r.md"));
2108    }
2109
2110    #[test]
2111    fn hash_line_comments_stripped() {
2112        let p = parse(
2113            r#"
2114g: |
2115  # comment line — ignored
2116  plot p1   # trailing comment
2117    over limit  # also stripped
2118    label "Mean recall"  # don't strip inside quotes
2119"#,
2120        );
2121        let item = &p.report.groups[0].items[0];
2122        assert_eq!(item.kind, Kind::Plot);
2123        assert_eq!(item.name, "p1");
2124        assert!(
2125            item.body.contains("over limit"),
2126            "body kept: {:?}",
2127            item.body
2128        );
2129        assert!(
2130            !item.body.contains("trailing"),
2131            "comment leaked: {:?}",
2132            item.body
2133        );
2134        assert_eq!(item.label.as_deref(), Some("Mean recall"));
2135    }
2136
2137    #[test]
2138    fn auto_text_names_unique_across_document() {
2139        let p = parse(
2140            r#"
2141g1: |
2142  text First
2143  text Second
2144g2: |
2145  text Third
2146"#,
2147        );
2148        let g1 = &p.report.groups[0];
2149        assert_eq!(g1.items[0].name, "text_001");
2150        assert_eq!(g1.items[1].name, "text_002");
2151        // Counter is global, not per-group, so persistence keys
2152        // (`report.<name>`) stay unique.
2153        let g2 = &p.report.groups[1];
2154        assert_eq!(g2.items[0].name, "text_003");
2155    }
2156
2157    #[test]
2158    fn label_directive_strips_quotes() {
2159        let p = parse(
2160            r#"
2161g: |
2162  plot p1 over x
2163    label "My label"
2164  plot p2 over x
2165    label 'Another'
2166"#,
2167        );
2168        let items = &p.report.groups[0].items;
2169        assert_eq!(items[0].label.as_deref(), Some("My label"));
2170        assert_eq!(items[1].label.as_deref(), Some("Another"));
2171    }
2172
2173    // ------------------------------------------------------------------
2174    // Round-trip emitter — Phase A SRD-64 contract test
2175    // ------------------------------------------------------------------
2176    //
2177    // For every report-grammar shape we accept, the emitter
2178    // must produce a string that re-parses to an equal AST.
2179    // That's the contract that lets `--add` write the same
2180    // grammar back to YAML faithfully.
2181
2182    fn round_trip_via_group(item: &ReportItem) -> ReportItem {
2183        let group_body = item.to_yaml_directive_string();
2184        let yaml = format!(
2185            "g: |\n{}",
2186            group_body
2187                .lines()
2188                .map(|l| format!("  {l}"))
2189                .collect::<Vec<_>>()
2190                .join("\n")
2191        );
2192        let parsed = parse(&yaml);
2193        assert_eq!(
2194            parsed.report.groups.len(),
2195            1,
2196            "round-trip should yield one group, got: {parsed:#?}"
2197        );
2198        let items = &parsed.report.groups[0].items;
2199        assert_eq!(
2200            items.len(),
2201            1,
2202            "round-trip should yield one item, got: {items:#?}"
2203        );
2204        items[0].clone()
2205    }
2206
2207    fn assert_round_trip_eq(item: ReportItem) {
2208        let recovered = round_trip_via_group(&item);
2209        // Compare individual fields for clearer diffs on failure.
2210        assert_eq!(recovered.kind, item.kind);
2211        assert_eq!(recovered.name, item.name);
2212        assert_eq!(recovered.label, item.label);
2213        assert_eq!(recovered.as_stem, item.as_stem);
2214        assert_eq!(recovered.style.palette, item.style.palette);
2215        assert_eq!(recovered.style.line, item.style.line);
2216        assert_eq!(recovered.style.width, item.style.width);
2217        assert_eq!(recovered.style.marker, item.style.marker);
2218        assert_eq!(recovered.style.size, item.style.size);
2219        assert_eq!(recovered.style.color, item.style.color);
2220        assert_eq!(recovered.style.figure_width, item.style.figure_width);
2221        assert_eq!(recovered.style.figure_height, item.style.figure_height);
2222        assert_eq!(recovered.style.series.len(), item.style.series.len());
2223        for (a, b) in recovered.style.series.iter().zip(&item.style.series) {
2224            assert_eq!(a.key, b.key);
2225            assert_eq!(a.value, b.value);
2226        }
2227        // Body comparison is whitespace-tolerant: the emitter
2228        // re-indents to canonical 2-space, the parser strips
2229        // leading whitespace anyway.
2230        let normalize = |s: &str| {
2231            s.split('\n')
2232                .map(|l| l.trim())
2233                .filter(|l| !l.is_empty())
2234                .collect::<Vec<_>>()
2235                .join("\n")
2236        };
2237        assert_eq!(normalize(&recovered.body), normalize(&item.body));
2238    }
2239
2240    #[test]
2241    fn round_trip_minimal_plot() {
2242        let item = ReportItem {
2243            kind: Kind::Plot,
2244            name: "demo".to_string(),
2245            body: "over cycle\nmetric=throughput".to_string(),
2246            ..Default::default()
2247        };
2248        assert_round_trip_eq(item);
2249    }
2250
2251    #[test]
2252    fn round_trip_plot_with_label_and_palette() {
2253        let mut item = ReportItem {
2254            kind: Kind::Plot,
2255            name: "recall".to_string(),
2256            label: Some("Recall@10".to_string()),
2257            body: "over limit\nby profile".to_string(),
2258            ..Default::default()
2259        };
2260        item.style.palette = Some("wong".to_string());
2261        assert_round_trip_eq(item);
2262    }
2263
2264    #[test]
2265    fn round_trip_plot_full_style() {
2266        let mut item = ReportItem {
2267            kind: Kind::Plot,
2268            name: "full".to_string(),
2269            label: Some("Full".to_string()),
2270            as_stem: Some("plot_full".to_string()),
2271            body: "over limit\nby profile\nwhere dataset=example\nagg=mean".to_string(),
2272            ..Default::default()
2273        };
2274        item.style.palette = Some("tol_muted".to_string());
2275        item.style.line = Some("dashed".to_string());
2276        item.style.width = Some(2.0);
2277        item.style.marker = Some("circle".to_string());
2278        item.style.size = Some(4.0);
2279        item.style.color = Some("#117733".to_string());
2280        item.style.figure_width = Some(800);
2281        item.style.figure_height = Some(600);
2282        assert_round_trip_eq(item);
2283    }
2284
2285    #[test]
2286    fn round_trip_table() {
2287        let mut item = ReportItem {
2288            kind: Kind::Table,
2289            name: "summary".to_string(),
2290            label: Some("Summary".to_string()),
2291            body: "metric=recall@.*\ngroup_by=profile".to_string(),
2292            ..Default::default()
2293        };
2294        item.style.palette = Some("wong".to_string());
2295        assert_round_trip_eq(item);
2296    }
2297
2298    #[test]
2299    fn round_trip_with_series_overrides() {
2300        let mut item = ReportItem {
2301            kind: Kind::Plot,
2302            name: "perseries".to_string(),
2303            body: "over limit\nby profile".to_string(),
2304            ..Default::default()
2305        };
2306        let s1 = Style {
2307            line: Some("dashed".to_string()),
2308            marker: Some("triangle".to_string()),
2309            ..Default::default()
2310        };
2311        item.style.series.push(SeriesOverride {
2312            key: "profile".to_string(),
2313            value: "hnsw".to_string(),
2314            style: s1,
2315        });
2316        let s2 = Style {
2317            line: Some("solid".to_string()),
2318            ..Default::default()
2319        };
2320        item.style.series.push(SeriesOverride {
2321            key: "profile".to_string(),
2322            value: "ivf".to_string(),
2323            style: s2,
2324        });
2325        let recovered = round_trip_via_group(&item);
2326        assert_eq!(recovered.style.series.len(), 2);
2327        assert_eq!(recovered.style.series[0].key, "profile");
2328        assert_eq!(recovered.style.series[0].value, "hnsw");
2329        assert_eq!(
2330            recovered.style.series[0].style.line.as_deref(),
2331            Some("dashed")
2332        );
2333        assert_eq!(
2334            recovered.style.series[0].style.marker.as_deref(),
2335            Some("triangle")
2336        );
2337        assert_eq!(recovered.style.series[1].value, "ivf");
2338        assert_eq!(
2339            recovered.style.series[1].style.line.as_deref(),
2340            Some("solid")
2341        );
2342    }
2343
2344    #[test]
2345    fn round_trip_label_with_internal_quotes_is_escaped() {
2346        let item = ReportItem {
2347            kind: Kind::Plot,
2348            name: "tricky".to_string(),
2349            label: Some(r#"He said "hi""#.to_string()),
2350            body: "over cycle".to_string(),
2351            ..Default::default()
2352        };
2353        // The emitter must escape the inner quotes so the
2354        // parser sees a single label string. (The parser today
2355        // strips outer quotes only; if it doesn't honour the
2356        // escape, the test catches that as a real bug to fix.)
2357        let group_body = item.to_yaml_directive_string();
2358        assert!(
2359            group_body.contains(r#"label "He said \"hi\"""#),
2360            "emitter should escape inner quotes; got:\n{group_body}"
2361        );
2362    }
2363
2364    #[test]
2365    fn emitter_orders_directives_canonically() {
2366        // `as` comes before `label`; identity before style;
2367        // style (scalar fields) before body; body before
2368        // per-series style overrides. This is the canonical
2369        // order from vocab::ALL_DIRECTIVES so the round-trip
2370        // stays stable.
2371        let mut item = ReportItem {
2372            kind: Kind::Plot,
2373            name: "ordered".to_string(),
2374            label: Some("L".to_string()),
2375            as_stem: Some("S".to_string()),
2376            body: "over cycle".to_string(),
2377            ..Default::default()
2378        };
2379        item.style.palette = Some("wong".to_string());
2380        item.style.series.push(SeriesOverride {
2381            key: "k".to_string(),
2382            value: "v".to_string(),
2383            style: Style::default(),
2384        });
2385        let s = item.to_yaml_directive_string();
2386        let pos = |needle: &str| {
2387            s.find(needle)
2388                .unwrap_or_else(|| panic!("missing {needle} in:\n{s}"))
2389        };
2390        let pos_as = pos("as S");
2391        let pos_label = pos("label \"L\"");
2392        let pos_style = pos("palette=wong");
2393        let pos_body = pos("over cycle");
2394        let pos_per_series = pos("style k=v");
2395        assert!(pos_as < pos_label, "as before label");
2396        assert!(pos_label < pos_style, "label before style");
2397        assert!(pos_style < pos_body, "style before body");
2398        assert!(
2399            pos_body < pos_per_series,
2400            "body before per-series style overrides"
2401        );
2402    }
2403}