zenith-core 0.0.5

Zenith core: KDL parser adapter, semantic AST, canonical formatter, tokens, validation, and diagnostics.
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
//! Per-kind checks for the "special" leaf nodes that were already extracted as
//! helpers: `polygon`, `polyline`, `instance`, `field`, `toc`, and `footnote`.
//! None of these recurse into laid-out children at this site.

use std::collections::BTreeSet;

use crate::ast::node::{FieldNode, FootnoteNode, InstanceNode, PolygonNode, PolylineNode, TocNode};
use crate::diagnostics::Diagnostic;

use super::shared::{
    AnchorParentCtx, AnchorProps, check_anchor, check_dimension_geom, check_spans, check_style_ref,
};
use super::suggest::check_unknown_props;
use crate::validate::check::nodes::WalkCtx;
use crate::validate::check::register_id;
use crate::validate::check::visual::{VisualExpect, check_visual_prop};

// ── polygon / polyline validation ─────────────────────────────────────────────

pub(in crate::validate::check) fn check_polygon(
    poly: &PolygonNode,
    ctx: WalkCtx,
    seen_ids: &mut BTreeSet<String>,
    referenced_token_ids: &mut BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let WalkCtx {
        resolved_tokens,
        declared_style_ids,
        ..
    } = ctx;
    register_id(&poly.id, seen_ids, diagnostics);
    check_style_ref(
        &poly.id,
        poly.style.as_deref(),
        declared_style_ids,
        poly.source_span,
        diagnostics,
    );

    // Validate each point's x and y (both must be present with a known unit).
    for (idx, pt) in poly.points.iter().enumerate() {
        let x_label = format!("point[{idx}].x");
        let y_label = format!("point[{idx}].y");
        check_dimension_geom(
            &poly.id,
            &x_label,
            pt.x.as_ref(),
            true,
            poly.source_span,
            diagnostics,
        );
        check_dimension_geom(
            &poly.id,
            &y_label,
            pt.y.as_ref(),
            true,
            poly.source_span,
            diagnostics,
        );
    }

    // polygon requires at least 3 points.
    if poly.points.len() < 3 {
        diagnostics.push(Diagnostic::error(
            "shape.insufficient_points",
            format!(
                "polygon '{}': requires at least 3 points, got {}",
                poly.id,
                poly.points.len()
            ),
            poly.source_span,
            Some(poly.id.clone()),
        ));
    }

    // Visual properties. Fill accepts a color OR a gradient token (the scene
    // paints any geometry uniformly); stroke is color-only.
    check_visual_prop(
        &poly.id,
        "fill",
        poly.fill.as_ref(),
        VisualExpect::ColorOrGradient,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &poly.id,
        "stroke",
        poly.stroke.as_ref(),
        VisualExpect::Color,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &poly.id,
        "stroke-width",
        poly.stroke_width.as_ref(),
        VisualExpect::Dimension,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );

    // fill-rule: only "nonzero" and "evenodd" are valid.
    if let Some(fr) = &poly.fill_rule
        && !matches!(fr.as_str(), "nonzero" | "evenodd")
    {
        diagnostics.push(Diagnostic::warning(
            "node.unknown_property",
            format!(
                "polygon '{}': unrecognized fill-rule '{}' (version-relative; \
                 allowed values are nonzero, evenodd)",
                poly.id, fr
            ),
            poly.source_span,
            Some(poly.id.clone()),
        ));
    }

    // stroke-alignment: only "inside", "center", "outside" are valid.
    if let Some(sa) = &poly.stroke_alignment
        && !matches!(sa.as_str(), "inside" | "center" | "outside")
    {
        diagnostics.push(Diagnostic::warning(
            "node.unknown_property",
            format!(
                "polygon '{}': unrecognized stroke-alignment '{}' (version-relative; \
                 allowed values are inside, center, outside)",
                poly.id, sa
            ),
            poly.source_span,
            Some(poly.id.clone()),
        ));
    }

    // Unknown properties.
    check_unknown_props(
        "polygon",
        &poly.id,
        &poly.unknown_props,
        poly.source_span,
        diagnostics,
    );
    // polygon is a LEAF: no child-node recursion (points are sub-data).
}

pub(in crate::validate::check) fn check_polyline(
    poly: &PolylineNode,
    ctx: WalkCtx,
    seen_ids: &mut BTreeSet<String>,
    referenced_token_ids: &mut BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let WalkCtx {
        resolved_tokens,
        declared_style_ids,
        ..
    } = ctx;
    register_id(&poly.id, seen_ids, diagnostics);
    check_style_ref(
        &poly.id,
        poly.style.as_deref(),
        declared_style_ids,
        poly.source_span,
        diagnostics,
    );

    // Validate each point's x and y.
    for (idx, pt) in poly.points.iter().enumerate() {
        let x_label = format!("point[{idx}].x");
        let y_label = format!("point[{idx}].y");
        check_dimension_geom(
            &poly.id,
            &x_label,
            pt.x.as_ref(),
            true,
            poly.source_span,
            diagnostics,
        );
        check_dimension_geom(
            &poly.id,
            &y_label,
            pt.y.as_ref(),
            true,
            poly.source_span,
            diagnostics,
        );
    }

    // polyline requires at least 2 points.
    if poly.points.len() < 2 {
        diagnostics.push(Diagnostic::error(
            "shape.insufficient_points",
            format!(
                "polyline '{}': requires at least 2 points, got {}",
                poly.id,
                poly.points.len()
            ),
            poly.source_span,
            Some(poly.id.clone()),
        ));
    }

    // Visual properties. Fill accepts a color OR a gradient token (the scene
    // paints any geometry uniformly); stroke is color-only.
    check_visual_prop(
        &poly.id,
        "fill",
        poly.fill.as_ref(),
        VisualExpect::ColorOrGradient,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &poly.id,
        "stroke",
        poly.stroke.as_ref(),
        VisualExpect::Color,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &poly.id,
        "stroke-width",
        poly.stroke_width.as_ref(),
        VisualExpect::Dimension,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );

    // fill-rule: only "nonzero" and "evenodd" are valid.
    if let Some(fr) = &poly.fill_rule
        && !matches!(fr.as_str(), "nonzero" | "evenodd")
    {
        diagnostics.push(Diagnostic::warning(
            "node.unknown_property",
            format!(
                "polyline '{}': unrecognized fill-rule '{}' (version-relative; \
                 allowed values are nonzero, evenodd)",
                poly.id, fr
            ),
            poly.source_span,
            Some(poly.id.clone()),
        ));
    }

    // Unknown properties.
    check_unknown_props(
        "polyline",
        &poly.id,
        &poly.unknown_props,
        poly.source_span,
        diagnostics,
    );
    // polyline is a LEAF: no child-node recursion (points are sub-data).
}

// ── instance validation ───────────────────────────────────────────────────────

/// Validate an `instance` node:
/// - its own `id` participates in GLOBAL uniqueness;
/// - `component` must reference a declared component → else
///   `component.unknown_reference` (Error);
/// - each override `ref` must match a LOCAL descendant id of the referenced
///   component → else `component.unknown_override_target` (Warning).
///
/// The instance is a container-ish node but it does NOT recurse here: its
/// expanded subtree (and the component definition's own ids) are validated at
/// the component definition site, not per-instance, so token/asset refs are
/// checked once.
pub(in crate::validate::check) fn check_instance(
    inst: &InstanceNode,
    ctx: WalkCtx,
    seen_ids: &mut BTreeSet<String>,
    referenced_token_ids: &mut BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let WalkCtx {
        resolved_tokens,
        declared_component_ids,
        component_local_ids,
        ..
    } = ctx;
    register_id(&inst.id, seen_ids, diagnostics);

    let component_known = declared_component_ids.contains(&inst.component);
    if !component_known {
        diagnostics.push(Diagnostic::error(
            "component.unknown_reference",
            format!(
                "instance '{}': references component '{}' which is not declared in the \
                 components block",
                inst.id, inst.component
            ),
            inst.source_span,
            Some(inst.id.clone()),
        ));
    }

    // Override targets are only checkable when the component is known. Look up the
    // referenced component's local-id set; an override `ref` that matches no local
    // descendant id → warning.
    let local_ids = component_local_ids.get(&inst.component);
    for ov in &inst.overrides {
        // Validate (and register as referenced) any token refs the override
        // carries, so an override-only token is not falsely flagged unused and
        // a bad override fill/span fill is type-checked like a node fill.
        check_visual_prop(
            &inst.id,
            "fill",
            ov.fill.as_ref(),
            VisualExpect::Color,
            referenced_token_ids,
            resolved_tokens,
            diagnostics,
        );
        if let Some(spans) = &ov.spans {
            for span in spans {
                check_visual_prop(
                    &inst.id,
                    "fill",
                    span.fill.as_ref(),
                    VisualExpect::Color,
                    referenced_token_ids,
                    resolved_tokens,
                    diagnostics,
                );
            }
        }

        let target_known = local_ids
            .map(|ids| ids.contains(&ov.ref_id))
            .unwrap_or(false);
        if component_known && !target_known {
            diagnostics.push(Diagnostic::warning(
                "component.unknown_override_target",
                format!(
                    "instance '{}': override ref '{}' matches no descendant id in component '{}'",
                    inst.id, ov.ref_id, inst.component
                ),
                ov.source_span.or(inst.source_span),
                Some(inst.id.clone()),
            ));
        }
    }

    // Unknown properties on the instance node.
    check_unknown_props(
        "instance",
        &inst.id,
        &inst.unknown_props,
        inst.source_span,
        diagnostics,
    );
}

// ── field validation ──────────────────────────────────────────────────────────

/// The known v0 field types.
const KNOWN_FIELD_TYPES: &[&str] = &[
    "running-head",
    "page-number",
    "page-ref",
    "page-count",
    "section-page-number",
    "section-page-count",
    "section-name",
];

/// Validate a `field` node:
/// - its own `id` participates in GLOBAL uniqueness;
/// - `type` must be one of the known field types → else `field.unknown_type`
///   (Warning);
/// - a `page-ref` field whose `target` matches no node id anywhere in the
///   document → `field.unresolved_ref` (Warning);
/// - `style`/`fill`/`font-family`/`font-size` are validated like a text node's,
///   and any token refs are registered so they are not flagged unused.
///
/// A field is a leaf — it does not recurse. Geometry is optional (an absent
/// x/w defaults to the page live area at compile time), so no missing-geometry
/// error is raised here.
pub(in crate::validate::check) fn check_field(
    field: &FieldNode,
    ctx: WalkCtx,
    seen_ids: &mut BTreeSet<String>,
    referenced_token_ids: &mut BTreeSet<String>,
    parent_ctx: AnchorParentCtx,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let WalkCtx {
        resolved_tokens,
        declared_style_ids,
        all_node_ids,
        zone_ids,
        ..
    } = ctx;
    register_id(&field.id, seen_ids, diagnostics);
    check_style_ref(
        &field.id,
        field.style.as_deref(),
        declared_style_ids,
        field.source_span,
        diagnostics,
    );

    // Validate the anchor value (geometry is all-optional for fields anyway).
    check_anchor(
        &field.id,
        AnchorProps {
            anchor: field.anchor.as_deref(),
            anchor_zone: field.anchor_zone.as_deref(),
            anchor_sibling: field.anchor_sibling.as_deref(),
            anchor_parent: field.anchor_parent == Some(true),
            anchor_edge: field.anchor_edge.as_deref(),
            anchor_gap: field.anchor_gap.as_ref(),
        },
        parent_ctx,
        zone_ids,
        field.source_span,
        diagnostics,
    );

    // Unknown field type → Warning (never a hard error; the field simply renders
    // nothing at compile time).
    if !KNOWN_FIELD_TYPES.contains(&field.field_type.as_str()) {
        diagnostics.push(Diagnostic::warning(
            "field.unknown_type",
            format!(
                "field '{}': unknown type '{}'; expected one of {}",
                field.id,
                field.field_type,
                KNOWN_FIELD_TYPES.join(", ")
            ),
            field.source_span,
            Some(field.id.clone()),
        ));
    }

    // A page-ref field with an unresolvable target → Warning. A page-ref with no
    // target at all is also unresolved (nothing to point at).
    if field.field_type == "page-ref" {
        let resolved = field
            .target
            .as_ref()
            .map(|t| all_node_ids.contains(t))
            .unwrap_or(false);
        if !resolved {
            diagnostics.push(Diagnostic::warning(
                "field.unresolved_ref",
                format!(
                    "field '{}': page-ref target {} matches no node id in the document",
                    field.id,
                    field
                        .target
                        .as_deref()
                        .map(|t| format!("'{t}'"))
                        .unwrap_or_else(|| "(absent)".to_owned())
                ),
                field.source_span,
                Some(field.id.clone()),
            ));
        }
    }

    // Visual properties (mirror the text-node checks).
    check_visual_prop(
        &field.id,
        "fill",
        field.fill.as_ref(),
        VisualExpect::Color,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &field.id,
        "font-family",
        field.font_family.as_ref(),
        VisualExpect::FontFamily,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &field.id,
        "font-size",
        field.font_size.as_ref(),
        VisualExpect::Dimension,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );

    // Unknown properties on the field node.
    check_unknown_props(
        "field",
        &field.id,
        &field.unknown_props,
        field.source_span,
        diagnostics,
    );
}

/// Validate a [`TocNode`]: id uniqueness, style ref, visual properties, and
/// the `toc.no_selector` advisory when both `match_role` and `match_style` are
/// absent (the toc would collect no entries at compile time).
pub(in crate::validate::check) fn check_toc(
    toc: &TocNode,
    ctx: WalkCtx,
    seen_ids: &mut BTreeSet<String>,
    referenced_token_ids: &mut BTreeSet<String>,
    parent_ctx: AnchorParentCtx,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let WalkCtx {
        resolved_tokens,
        declared_style_ids,
        zone_ids,
        ..
    } = ctx;
    register_id(&toc.id, seen_ids, diagnostics);
    check_style_ref(
        &toc.id,
        toc.style.as_deref(),
        declared_style_ids,
        toc.source_span,
        diagnostics,
    );

    // Validate the anchor value (geometry is all-optional for toc anyway).
    check_anchor(
        &toc.id,
        AnchorProps {
            anchor: toc.anchor.as_deref(),
            anchor_zone: toc.anchor_zone.as_deref(),
            anchor_sibling: toc.anchor_sibling.as_deref(),
            anchor_parent: toc.anchor_parent == Some(true),
            anchor_edge: toc.anchor_edge.as_deref(),
            anchor_gap: toc.anchor_gap.as_ref(),
        },
        parent_ctx,
        zone_ids,
        toc.source_span,
        diagnostics,
    );

    // Warn when neither selector is set: the toc will collect no entries.
    if toc.match_role.is_none() && toc.match_style.is_none() {
        diagnostics.push(Diagnostic::warning(
            "toc.no_selector",
            format!(
                "toc '{}' has neither match-role nor match-style; it will collect no entries",
                toc.id
            ),
            toc.source_span,
            Some(toc.id.clone()),
        ));
    }

    // Visual properties (mirror the field-node checks).
    check_visual_prop(
        &toc.id,
        "fill",
        toc.fill.as_ref(),
        VisualExpect::Color,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &toc.id,
        "font-family",
        toc.font_family.as_ref(),
        VisualExpect::FontFamily,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &toc.id,
        "font-size",
        toc.font_size.as_ref(),
        VisualExpect::Dimension,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );

    // Unknown properties on the toc node.
    check_unknown_props(
        "toc",
        &toc.id,
        &toc.unknown_props,
        toc.source_span,
        diagnostics,
    );
}

/// Validate a [`FootnoteNode`]: id uniqueness, style ref, the content-span and
/// node visual properties (fill/font-family/font-size, plus per-span fill/weight
/// so raw visual literals are surfaced like any text), and unknown properties.
///
/// The structural `footnote.unresolved_ref` check (a span `footnote-ref` that
/// names no footnote on the same page) is done at the PAGE level (it needs the
/// page's footnote-id set), not here. A footnote has no geometry, so there are
/// no geometry checks.
pub(in crate::validate::check) fn check_footnote(
    footnote: &FootnoteNode,
    ctx: WalkCtx,
    seen_ids: &mut BTreeSet<String>,
    referenced_token_ids: &mut BTreeSet<String>,
    diagnostics: &mut Vec<Diagnostic>,
) {
    let WalkCtx {
        resolved_tokens,
        declared_style_ids,
        ..
    } = ctx;
    register_id(&footnote.id, seen_ids, diagnostics);
    check_style_ref(
        &footnote.id,
        footnote.style.as_deref(),
        declared_style_ids,
        footnote.source_span,
        diagnostics,
    );

    check_visual_prop(
        &footnote.id,
        "fill",
        footnote.fill.as_ref(),
        VisualExpect::Color,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &footnote.id,
        "font-family",
        footnote.font_family.as_ref(),
        VisualExpect::FontFamily,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );
    check_visual_prop(
        &footnote.id,
        "font-size",
        footnote.font_size.as_ref(),
        VisualExpect::Dimension,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );

    // Per-span visual props (mirror the text-node span checks) so token refs are
    // registered and raw visual literals are flagged `token.raw_visual_literal`.
    check_spans(
        &footnote.id,
        &footnote.spans,
        referenced_token_ids,
        resolved_tokens,
        diagnostics,
    );

    check_unknown_props(
        "footnote",
        &footnote.id,
        &footnote.unknown_props,
        footnote.source_span,
        diagnostics,
    );
}