quillmark-core 0.101.0

Core types and functionality for the Quillmark schema-driven document engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
//! # Error Handling
//!
//! Error types and diagnostics for parsing and rendering, with source location tracking.
//!
//! ## Document path anchors
//!
//! A [`Diagnostic`] carries two independent "where" anchors, both optional:
//!
//! - [`Diagnostic::location`]: source-text anchor (`file:line:column`).
//!   Produced by parsers and backend compilers operating on raw text.
//! - [`Diagnostic::path`]: document-model anchor into the typed
//!   [`crate::document::Document`]. Produced by schema validation and
//!   coercion, which run on the typed model after line spans are gone.
//!
//! [`DocPath`](crate::path::DocPath) is the one type that constructs, renders,
//! and parses the path, no site assembles one with `format!`. Its module doc
//! carries the grammar; `prose/canon/ERROR.md` tabulates the anchors.

use std::collections::BTreeMap;

use crate::OutputFormat;

/// Build a [`Diagnostic::args`] map. Values pass through `serde_json`, so a
/// list arrives as a list and a count as a number: the shapes a consumer
/// needs to join and pluralize in its own locale.
macro_rules! diag_args {
    ($($key:literal => $value:expr),* $(,)?) => {{
        #[allow(unused_mut)]
        let mut map = ::std::collections::BTreeMap::<String, ::serde_json::Value>::new();
        $(map.insert($key.to_string(), ::serde_json::json!($value));)*
        map
    }};
}

pub(crate) use diag_args;

/// Maximum input size for markdown (10 MiB)
pub const MAX_INPUT_SIZE: usize = 10 * 1024 * 1024;

/// Maximum YAML size (1 MiB)
pub const MAX_YAML_SIZE: usize = 1024 * 1024;

/// Maximum nesting depth for markdown structures (100 levels). Owned by the
/// markdown codecs in `quillmark-content` (the import guard) and re-exported
/// here so the typst backend's markup converter shares one limit: a document
/// that imports also renders, and vice versa.
pub use quillmark_content::MAX_NESTING_DEPTH;

/// Re-exported from [`crate::document::limits::MAX_YAML_DEPTH`].
pub use crate::document::limits::MAX_YAML_DEPTH;

/// Maximum number of card blocks allowed per document
pub const MAX_CARD_COUNT: usize = 1000;

/// Maximum number of fields allowed per document
pub const MAX_FIELD_COUNT: usize = 1000;

/// A YAML parse or emit failure, owned by this crate.
///
/// The YAML engine is `serde-saphyr`. Returning its error types from a public
/// signature would chain this crate's major version to that crate's, and to
/// the choice of engine at all, so the boundary converts to this type instead
/// and no public signature names the engine. The engine is an implementation
/// detail; this is what the contract says it is.
///
/// `line`/`column` are 1-indexed and present only when the engine located the
/// failure: always absent on the emit side, which has no input to point at.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct YamlError {
    message: String,
    hint: Option<String>,
    line: Option<u32>,
    column: Option<u32>,
}

impl YamlError {
    /// What went wrong, in YAML terms.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// The concrete textual fix, when the failure is one this crate recognizes.
    pub fn hint(&self) -> Option<&str> {
        self.hint.as_deref()
    }

    /// 1-indexed line of the failure, when the engine located one.
    pub fn line(&self) -> Option<u32> {
        self.line
    }

    /// 1-indexed column of the failure, paired with [`Self::line`].
    pub fn column(&self) -> Option<u32> {
        self.column
    }

    /// A diagnostic under `code`, carrying the hint and (when the engine
    /// located the failure) a [`Location`] against `file`.
    pub fn to_diagnostic(&self, code: &str, file: &str) -> Diagnostic {
        let mut diag = Diagnostic::new(Severity::Error, self.message.clone())
            .with_code(code.to_string());
        if let (Some(line), Some(column)) = (self.line, self.column) {
            diag = diag.with_location(Location::new(file.to_string(), line, column));
        }
        match &self.hint {
            Some(h) => diag.with_hint(h.clone()),
            None => diag,
        }
    }

    /// `yaml` is the text that failed to parse: the hint derivation inspects
    /// it to name the offending construct.
    pub(crate) fn from_de(err: serde_saphyr::Error, yaml: &str) -> Self {
        // The engine appends its own Rust API names to some messages
        // (`from_multiple`, `DuplicateKeyPolicy`); the enricher strips them, so
        // "no public signature names the engine" holds for the message too, not
        // just the type.
        let enriched = crate::document::yaml_hints::enrich_yaml_error(&err.to_string(), yaml);
        // `Location`'s accessors widen to u64; the fields behind them are u32,
        // so the narrowing is lossless.
        let loc = err.location();
        Self {
            message: enriched.message,
            hint: enriched.hint,
            line: loc.and_then(|l| u32::try_from(l.line()).ok()),
            column: loc.and_then(|l| u32::try_from(l.column()).ok()),
        }
    }

    /// Emission has no input to point at, so no position and no hint.
    pub(crate) fn from_ser(err: serde_saphyr::ser::Error) -> Self {
        Self {
            message: err.to_string(),
            hint: None,
            line: None,
            column: None,
        }
    }
}

impl std::fmt::Display for YamlError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // The message already opens with the position and carries the engine's
        // caret diagram; [`Self::line`]/[`Self::column`] are the structured
        // reading of the same fact, not a second one to append.
        f.write_str(&self.message)
    }
}

impl std::error::Error for YamlError {}

/// Fatality is this two-value ladder and nothing else: `Error` blocks the
/// stage that emits it, `Warning` never does. There is no lint-level
/// configuration and no warning-to-error promotion; an informational aside is
/// a [`Diagnostic::hint`], not a severity.
///
/// A `_` arm over this enum has a safe direction: escalate to
/// [`Severity::Error`]. Treating an unrecognized level as fatal over-reports;
/// treating it as a warning could hide one. Nothing here fails silently, so the
/// enum is open ([`COMPATIBILITY`]).
///
/// [`COMPATIBILITY`]: https://github.com/borb-sh/quillmark/blob/main/prose/canon/COMPATIBILITY.md
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Severity {
    /// Fatal error that prevents completion
    Error,
    /// Non-fatal issue that may need attention
    Warning,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Location {
    /// Source file name (e.g., "plate.typ", "template.typ", "input.md")
    pub file: String,
    /// Line number (1-indexed)
    pub line: u32,
    /// Column number (1-indexed)
    pub column: u32,
}

impl Location {
    /// The three coordinates a text anchor always carries. `line` and `column`
    /// are 1-indexed.
    pub fn new(file: String, line: u32, column: u32) -> Self {
        Self { file, line, column }
    }
}

/// Structured diagnostic information.
///
/// `source_chain` is a flat list of error messages from any attached
/// `std::error::Error` cause chain, eagerly walked at construction time so
/// the diagnostic remains trivially `Clone` and fully serializable across
/// every binding boundary.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Diagnostic {
    pub severity: Severity,
    /// Optional error code (e.g., "E001", "typst::syntax")
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub code: Option<String>,
    pub message: String,
    /// Primary source location (text anchor: file/line/column).
    ///
    /// Set by parsers and backend compilers. May co-exist with [`Self::path`]:
    /// the two anchors are independent.
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub location: Option<Location>,
    /// Document-model anchor: a dotted/bracketed path into the typed
    /// [`crate::document::Document`].
    ///
    /// Set by schema validation and coercion. See the module-level docs for
    /// the path grammar and conventions. May co-exist with [`Self::location`].
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub hint: Option<String>,
    /// The facts [`Self::message`] interpolates, keyed by name: with
    /// [`Self::code`], the substitution unit a consumer needs to word this
    /// diagnostic in its own language.
    ///
    /// One code carries one key set, tabulated per code in
    /// `prose/canon/ERROR.md` § "Diagnostic args" and tested against it.
    /// Values keep their JSON shape, so joining and pluralizing stay the
    /// consumer's locale decisions.
    ///
    /// Empty either because the code is outside the structured surface or
    /// because its sentence needs no facts beyond the code; canon tells the
    /// two apart. Engine prose never rides under a key: a consumer's sentence
    /// may be coarser than ours, never half-translated.
    #[serde(skip_serializing_if = "BTreeMap::is_empty", default)]
    pub args: BTreeMap<String, serde_json::Value>,
    /// Flattened cause chain (outermost first). Upstream English, and
    /// untranslatable for the same reason the prose it wraps is.
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub source_chain: Vec<String>,
}

impl Diagnostic {
    pub fn new(severity: Severity, message: String) -> Self {
        Self {
            severity,
            code: None,
            message,
            location: None,
            path: None,
            hint: None,
            args: BTreeMap::new(),
            source_chain: Vec::new(),
        }
    }

    pub fn with_code(mut self, code: String) -> Self {
        self.code = Some(code);
        self
    }

    pub fn with_location(mut self, location: Location) -> Self {
        self.location = Some(location);
        self
    }

    /// Set the document-model path anchor.
    ///
    /// See the module-level docs for the path grammar and conventions.
    pub fn with_path(mut self, path: String) -> Self {
        self.path = Some(path);
        self
    }

    pub fn with_hint(mut self, hint: String) -> Self {
        self.hint = Some(hint);
        self
    }

    /// Attach the message's substitution facts. See [`Self::args`].
    pub fn with_args(mut self, args: BTreeMap<String, serde_json::Value>) -> Self {
        self.args = args;
        self
    }

    /// Attach an error cause chain, walked eagerly into `source_chain`.
    pub fn with_source(mut self, source: &(dyn std::error::Error + 'static)) -> Self {
        let mut current: Option<&(dyn std::error::Error + 'static)> = Some(source);
        while let Some(err) = current {
            self.source_chain.push(err.to_string());
            current = err.source();
        }
        self
    }

    pub fn fmt_pretty(&self) -> String {
        let mut result = format!(
            "[{}] {}",
            match self.severity {
                Severity::Error => "ERROR",
                Severity::Warning => "WARN",
            },
            self.message
        );

        if let Some(ref code) = self.code {
            result.push_str(&format!(" ({})", code));
        }

        if let Some(ref loc) = self.location {
            result.push_str(&format!("\n  --> {}:{}:{}", loc.file, loc.line, loc.column));
        }

        if let Some(ref path) = self.path {
            result.push_str(&format!("\n  at {}", path));
        }

        if let Some(ref hint) = self.hint {
            result.push_str(&format!("\n  hint: {}", hint));
        }

        result
    }

}

impl std::fmt::Display for Diagnostic {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)
    }
}

#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum ParseError {
    #[error("Input too large: {size} bytes (max: {max} bytes)")]
    InputTooLarge { size: usize, max: usize },

    #[error("Invalid YAML structure: {0}")]
    InvalidStructure(String),

    /// Markdown input was empty or whitespace-only.
    ///
    /// Emitted as code `parse::empty_input` so consumers can pattern-match
    /// without inspecting the message text.
    #[error("{0}")]
    EmptyInput(String),

    /// The document is missing its root `~~~` card-yaml block, or that block
    /// does not declare the required `$quill` system metadata.
    ///
    /// Emitted as code `parse::missing_quill` so consumers can
    /// pattern-match without inspecting the message text.
    #[error("{0}")]
    MissingQuill(String),

    /// A `$quill` reference failed to parse as a [`crate::version::QuillReference`].
    /// Code `parse::invalid_quill_reference`; carries
    /// [`crate::version::quill_ref_hint`] as its diagnostic hint.
    #[error("Invalid $quill reference '{value}': {reason}")]
    InvalidQuillReference {
        value: String,
        /// The `from_str` violation.
        reason: String,
    },

    /// A card body's markdown could not be imported into the content model:
    /// today only when container nesting exceeds
    /// [`MAX_NESTING_DEPTH`]. Code `parse::body_import`.
    #[error("{0}")]
    BodyImport(String),

    #[error("YAML error at line {line}: {message}")]
    YamlErrorWithLocation {
        message: String,
        /// Line number in the source document (1-indexed)
        line: usize,
        /// Index of the metadata block (0-indexed)
        block_index: usize,
        /// Optional actionable hint attached when the YAML parser's message
        /// is too cryptic to be recoverable on its own. Derived by the
        /// internal `document::yaml_hints` enrichment pass.
        hint: Option<String>,
    },
}

impl ParseError {
    /// The facts this error's message interpolates. See [`Diagnostic::args`].
    ///
    /// The four `String` variants contribute no keys, for two different
    /// reasons canon distinguishes: `EmptyInput` is one fixed sentence, while
    /// `InvalidStructure`, `BodyImport`, and `MissingQuill` carry prose minted
    /// per-site. `MissingQuill` looks fixed and is not: it picks one of three
    /// sentences by re-reading the source, and no field records which.
    pub fn args(&self) -> BTreeMap<String, serde_json::Value> {
        match self {
            ParseError::InputTooLarge { size, max } => diag_args! {
                "size" => size,
                "max" => max,
            },
            ParseError::InvalidStructure(_) => diag_args! {},
            ParseError::EmptyInput(_) => diag_args! {},
            ParseError::MissingQuill(_) => diag_args! {},
            ParseError::BodyImport(_) => diag_args! {},
            // `reason` is the `from_str` violation in English and stays in
            // `message`; `value` alone carries the consumer's sentence.
            ParseError::InvalidQuillReference { value, reason: _ } => diag_args! {
                "value" => value,
            },
            // This diagnostic sets no `location`, so `args` is the only
            // structured route to the coordinates the message names. The
            // message is the YAML engine's own prose and keeps no key.
            ParseError::YamlErrorWithLocation {
                message: _,
                line,
                block_index,
                hint: _,
            } => diag_args! {
                "line" => line,
                "blockIndex" => block_index,
            },
        }
    }

    pub fn to_diagnostic(&self) -> Diagnostic {
        let diag = match self {
            ParseError::InputTooLarge { size, max } => Diagnostic::new(
                Severity::Error,
                format!("Input too large: {} bytes (max: {} bytes)", size, max),
            )
            .with_code("parse::input_too_large".to_string()),
            ParseError::InvalidStructure(msg) => Diagnostic::new(Severity::Error, msg.clone())
                .with_code("parse::invalid_structure".to_string()),
            ParseError::EmptyInput(msg) => Diagnostic::new(Severity::Error, msg.clone())
                .with_code("parse::empty_input".to_string()),
            ParseError::MissingQuill(msg) => Diagnostic::new(Severity::Error, msg.clone())
                .with_code("parse::missing_quill".to_string()),
            ParseError::BodyImport(msg) => Diagnostic::new(Severity::Error, msg.clone())
                .with_code("parse::body_import".to_string()),
            ParseError::InvalidQuillReference { value, reason } => Diagnostic::new(
                Severity::Error,
                format!("Invalid $quill reference '{}': {}", value, reason),
            )
            .with_code("parse::invalid_quill_reference".to_string())
            .with_hint(crate::version::quill_ref_hint().to_string()),
            ParseError::YamlErrorWithLocation {
                message,
                line,
                block_index,
                hint,
            } => {
                let mut d = Diagnostic::new(
                    Severity::Error,
                    format!(
                        "YAML error at line {} (block {}): {}",
                        line, block_index, message
                    ),
                )
                .with_code("parse::yaml_error_with_location".to_string());
                if let Some(h) = hint {
                    d = d.with_hint(h.clone());
                }
                d
            }
        };
        diag.with_args(self.args())
    }
}

/// Main error type for rendering operations: a non-empty collection of
/// [`Diagnostic`]s.
///
/// There is no failure taxonomy beyond the diagnostics themselves: the
/// machine-routable identity of a failure is each diagnostic's namespaced
/// `code` (`parse::*`, `validation::*`, `quill::*`, `typst::*`, `backend::*`,
/// `engine::*`). Every consumer, and every language binding, handles all
/// rendering errors through this single shape; route on
/// `diagnostics()[..].code`, not on a type.
#[derive(Debug)]
pub struct RenderError {
    /// Always non-empty; held by the constructors.
    diags: Vec<Diagnostic>,
}

impl RenderError {
    /// Wrap `diags` as a failure. `diags` should be non-empty; the invariant is
    /// enforced only by `debug_assert!`, so a release build can construct an
    /// empty `RenderError`. That is deliberately non-fatal: the `Display` impl
    /// carries an `[]` fallback branch rather than promising the invariant is
    /// load-bearing. Every internal caller passes a non-empty vec.
    pub fn new(diags: Vec<Diagnostic>) -> Self {
        debug_assert!(
            !diags.is_empty(),
            "RenderError requires at least one diagnostic"
        );
        Self { diags }
    }

    /// Wrap a single diagnostic as a failure.
    pub fn from_diag(diag: Diagnostic) -> Self {
        Self { diags: vec![diag] }
    }

    /// Returns all diagnostics for this error. Non-empty by construction (see
    /// [`RenderError::new`]'s debug-asserted invariant).
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diags
    }

    /// Consume the error and return its diagnostics.
    pub fn into_diagnostics(self) -> Vec<Diagnostic> {
        self.diags
    }

    /// The count-based summary line shared by `Display` and every binding's
    /// exception message: the sole diagnostic's `message` for one, an
    /// `"<N> error(s): <first message>"` aggregate for more. The single source
    /// of truth for this rule: bindings delegate here rather than re-deriving
    /// it. An empty slice yields `"render error"` defensively (see
    /// [`RenderError::new`]'s debug-only non-empty invariant).
    pub fn summary_message(diags: &[Diagnostic]) -> String {
        match diags {
            [d] => d.message.clone(),
            [first, ..] => format!("{} error(s): {}", diags.len(), first.message),
            [] => "render error".to_string(),
        }
    }
}

/// The primary message for a single diagnostic; an
/// `"<N> error(s): <first message>"` aggregate for more: the same rule the
/// WASM binding applies to thrown `Error.message`.
impl std::fmt::Display for RenderError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", Self::summary_message(&self.diags))
    }
}

impl std::error::Error for RenderError {}

impl From<ParseError> for RenderError {
    fn from(err: ParseError) -> Self {
        RenderError::from_diag(err.to_diagnostic())
    }
}

#[derive(Debug)]
#[non_exhaustive]
pub struct RenderResult {
    pub artifacts: Vec<crate::Artifact>,
    pub warnings: Vec<Diagnostic>,
    pub output_format: OutputFormat,
    /// Schema-field geometry sidecar, populated only when
    /// [`RenderOptions::regions`](crate::RenderOptions) is set (empty
    /// otherwise). The same entries [`LiveSession::regions`](crate::LiveSession::regions)
    /// serves, for consumers without a live session. Whole-document geometry:
    /// page indices are document-space even under a `pages` subset render.
    pub regions: Vec<crate::RenderedRegion>,
}

impl RenderResult {
    pub fn new(artifacts: Vec<crate::Artifact>, output_format: OutputFormat) -> Self {
        Self {
            artifacts,
            warnings: Vec::new(),
            output_format,
            regions: Vec::new(),
        }
    }
}

pub fn print_errors(err: &RenderError) {
    for d in err.diagnostics() {
        eprintln!("{}", d.fmt_pretty());
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_diagnostic_with_source_chain() {
        let root_err = std::io::Error::new(std::io::ErrorKind::NotFound, "File not found");
        let diag =
            Diagnostic::new(Severity::Error, "Rendering failed".to_string()).with_source(&root_err);

        assert_eq!(diag.source_chain.len(), 1);
        assert!(diag.source_chain[0].contains("File not found"));
    }

    #[test]
    fn test_diagnostic_serialization() {
        let diag = Diagnostic::new(Severity::Error, "Test error".to_string())
            .with_code("E001".to_string())
            .with_location(Location {
                file: "test.typ".to_string(),
                line: 10,
                column: 5,
            });

        let json = serde_json::to_string(&diag).unwrap();
        assert!(json.contains("Test error"));
        assert!(json.contains("E001"));
        assert!(json.contains("\"severity\":\"error\""));
        assert!(json.contains("\"column\":5"));
    }

    #[test]
    fn test_render_error_single_diagnostic_shape() {
        let err = RenderError::from_diag(Diagnostic::new(
            Severity::Error,
            "no such backend".to_string(),
        ));
        assert_eq!(err.diagnostics().len(), 1);
        assert_eq!(err.to_string(), "no such backend");

        let owned = err.into_diagnostics();
        assert_eq!(owned.len(), 1);
        assert_eq!(owned[0].message, "no such backend");
    }

    #[test]
    fn test_render_error_display_aggregates_multi_diagnostic() {
        let err = RenderError::new(vec![
            Diagnostic::new(Severity::Error, "a".to_string()),
            Diagnostic::new(Severity::Error, "b".to_string()),
        ]);
        assert_eq!(err.to_string(), "2 error(s): a");
    }

    #[test]
    fn test_diagnostic_fmt_pretty() {
        let diag = Diagnostic::new(Severity::Warning, "Deprecated field used".to_string())
            .with_code("W001".to_string())
            .with_location(Location {
                file: "input.md".to_string(),
                line: 5,
                column: 10,
            })
            .with_hint("Use the new field name instead".to_string());

        let output = diag.fmt_pretty();
        assert!(output.contains("[WARN]"));
        assert!(output.contains("Deprecated field used"));
        assert!(output.contains("W001"));
        assert!(output.contains("input.md:5:10"));
        assert!(output.contains("hint:"));
    }

    #[test]
    fn test_diagnostic_with_path() {
        let diag = Diagnostic::new(Severity::Error, "Type mismatch".to_string())
            .with_code("validation::type_mismatch".to_string())
            .with_path("cards.indorsement[0].signature_block".to_string());

        assert_eq!(
            diag.path.as_deref(),
            Some("cards.indorsement[0].signature_block")
        );

        let json = serde_json::to_string(&diag).unwrap();
        assert!(json.contains("\"path\":\"cards.indorsement[0].signature_block\""));

        let pretty = diag.fmt_pretty();
        assert!(pretty.contains("at cards.indorsement[0].signature_block"));
    }

}

/// The canon table in `prose/canon/ERROR.md` § "Diagnostic args" is the contract
/// a consumer writes its string table against, so it is tested like one rather
/// than maintained by hand beside the code.
#[cfg(test)]
mod args_canon {
    use std::collections::BTreeMap;

    use super::ParseError;
    use crate::document::EditError;
    use crate::quill::{CoercionError, ValidationError};

    /// `code` → its arg keys, sorted. Every variant of every enum on the
    /// structured surface appears once.
    fn minted() -> BTreeMap<String, Vec<String>> {
        let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();
        let mut add = |code: &str, args: BTreeMap<String, serde_json::Value>| {
            let keys: Vec<String> = args.keys().cloned().collect();
            assert!(
                out.insert(code.to_string(), keys).is_none(),
                "two samples for `{code}`: one code carries one payload"
            );
        };

        for e in [
            ValidationError::TypeMismatch {
                path: "main.n".into(),
                expected: "string".into(),
                actual: "integer".into(),
                source_token: "42".into(),
                default: Some("\"x\"".into()),
            },
            ValidationError::EnumViolation {
                path: "main.tone".into(),
                value: "loud".into(),
                allowed: vec!["quiet".into()],
            },
            ValidationError::FormatViolation {
                path: "main.when".into(),
                format: "date".into(),
            },
            ValidationError::UnknownCard {
                path: "cards[0]".into(),
                card: "ghost".into(),
            },
            ValidationError::BodyDisabled {
                path: "cards.sig[0].body".into(),
                card: "sig".into(),
            },
            ValidationError::NotInline {
                path: "main.title".into(),
            },
            ValidationError::NotPlain {
                path: "main.title".into(),
            },
        ] {
            add(e.code(), e.args());
        }

        for e in [
            EditError::InvalidFieldName("9bad".into()),
            EditError::UnknownField("nope".into()),
            EditError::InvalidKindName("Bad".into()),
            EditError::ReservedKind,
            EditError::IndexOutOfRange { index: 3, len: 1 },
            EditError::ValueTooDeep { max: 8 },
            EditError::Import(quillmark_content::import::ImportError::NestingTooDeep {
                depth: 9,
                max: 8,
            }),
            EditError::FieldRichtextDecode {
                field: "body".into(),
                message: "x".into(),
            },
            EditError::FieldNotContent {
                field: "qty".into(),
                declared: "integer".into(),
            },
            EditError::FieldRichtextNotInline("body".into()),
            EditError::FieldConform {
                field: "n".into(),
                target: "integer".into(),
                message: "x".into(),
            },
            EditError::ContentApply(quillmark_content::ApplyError::LineOutOfRange {
                line: 3,
                lines: 1,
            }),
        ] {
            add(e.code(), e.args());
        }

        // The `conform::*` family: the strict write's refusals, re-namespaced by
        // `conform_diagnostic`. Minted through that function rather than
        // re-derived, so the table cannot drift from the code that stamps it.
        for e in [
            EditError::InvalidFieldName("9bad".into()),
            EditError::ValueTooDeep { max: 8 },
            EditError::FieldRichtextNotInline("body".into()),
            EditError::FieldRichtextDecode {
                field: "body".into(),
                message: "x".into(),
            },
            EditError::FieldConform {
                field: "n".into(),
                target: "integer".into(),
                message: "x".into(),
            },
        ] {
            let diag = crate::quill::conform::conform_diagnostic(&e, &crate::DocPath::main());
            add(
                diag.code.as_deref().expect("conform diagnostics carry a code"),
                diag.args,
            );
        }

        for e in [
            ParseError::InputTooLarge { size: 2, max: 1 },
            ParseError::InvalidStructure("x".into()),
            ParseError::EmptyInput("x".into()),
            ParseError::MissingQuill("x".into()),
            ParseError::BodyImport("x".into()),
            ParseError::InvalidQuillReference {
                value: "a@b".into(),
                reason: "x".into(),
            },
            ParseError::YamlErrorWithLocation {
                message: "x".into(),
                line: 3,
                block_index: 1,
                hint: None,
            },
        ] {
            let diag = e.to_diagnostic();
            add(diag.code.as_deref().expect("parse errors carry a code"), diag.args);
        }

        // Two codes are minted beside their error rather than from a variant:
        // `compose::coercion_error` wraps the whole `CoercionError`, and
        // `compose::fill_warning` has no error type at all.
        add(
            "validation::coercion_failed",
            CoercionError::Uncoercible {
                path: "card_kinds.sig.n".into(),
                value: "\"x\"".into(),
                target: "integer".into(),
                reason: "string is not a valid integer".into(),
            }
            .args(),
        );
        add("validation::must_fill", BTreeMap::new());

        out
    }

    /// The `| code | args | outcome |` rows of the canon table, keyed the same
    /// way. `—` is no keys; a trailing `?` marks a conditional key, which the
    /// sample above supplies.
    fn declared() -> BTreeMap<String, Vec<String>> {
        let canon = include_str!("../../../prose/canon/ERROR.md");
        let mut rows = canon
            .lines()
            .skip_while(|l| !l.starts_with("| Code | Args | Outcome |"))
            .skip(2)
            .take_while(|l| l.starts_with('|'));

        let mut out = BTreeMap::new();
        for row in &mut rows {
            let cells: Vec<&str> = row.trim_matches('|').split('|').map(str::trim).collect();
            assert_eq!(cells.len(), 3, "malformed canon row: {row}");
            let code = cells[0].trim_matches('`').to_string();
            let keys = if cells[1] == "" {
                Vec::new()
            } else {
                let mut keys: Vec<String> = cells[1]
                    .split(',')
                    .map(|k| k.trim().trim_end_matches('?').trim_matches('`').to_string())
                    .collect();
                keys.sort();
                keys
            };
            assert!(out.insert(code, keys).is_none(), "duplicate canon row: {row}");
        }
        assert!(!out.is_empty(), "canon args table not found in ERROR.md");
        out
    }

    /// The other direction: a code off the table carries no args, so a
    /// consumer's template falls back rather than half-filling. `quill::*` is
    /// the largest such family and the one with `format!`-built codes.
    #[test]
    fn out_of_scope_codes_carry_no_args() {
        let diags = crate::quill::QuillConfig::from_yaml_with_warnings(
            r#"
Quill:
  name: t
  version: "1.0"
  backend: typst
  description: A slot whose literal contradicts its declared type

main:
  fields:
    title:
      type: string
      default: 42
"#,
        )
        .expect_err("a default that contradicts its type fails config validation");

        assert!(
            diags.iter().any(|d| d
                .code
                .as_deref()
                .is_some_and(|c| c.starts_with("quill::"))),
            "expected a quill:: diagnostic, got {:?}",
            diags.iter().map(|d| &d.code).collect::<Vec<_>>()
        );
        for d in &diags {
            assert!(
                d.args.is_empty(),
                "`{:?}` is off the canon table and must carry no args",
                d.code
            );
        }
    }

    #[test]
    fn diagnostic_args_match_canon() {
        assert_eq!(
            declared(),
            minted(),
            "`ERROR.md` § \"Diagnostic args\" and the minted args disagree"
        );
    }
}