helm-schema-syntax 0.0.4

Generate an accurate JSON schema for any helm chart
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
//! The layout parser: a single pass over source lines that builds the CST
//! node forest and the per-line open-slot chain index.
//!
//! Container structure is decided purely by the visible YAML lines (indent
//! discipline); blank lines, comment lines, and lines that begin with a
//! template action are transparent to layout. This is deliberate: Helm
//! control actions routinely open a mapping entry in one branch and populate
//! it after `{{ end }}`, so control regions overlay the container structure
//! instead of bracketing it. The open/close rules below are the layout
//! semantics that helm-schema's attribution has always used (previously
//! recovered per query by an O(n²) line replay); the parser applies them
//! once and freezes the result into [`Frame`] chains.

use std::collections::HashMap;

use crate::actions::{ActionToken, TokenKind};
use crate::cst::{
    BlockScalar, CommentLine, ControlBranch, ControlKind, ControlRegion, MappingEntry, Node,
    OpaqueKind, OpaqueNode, OutputAction, ScalarLine, ScalarPart, ScalarParts, SequenceItem, Span,
    TemplatedDocument,
};
use crate::lines::LineIndex;
use crate::yaml_scan::{structural_mapping_colon, unquote_yaml_scalar};

/// One open-container record. Frames are arena-allocated so that per-line
/// chain snapshots stay valid after the container closes; only `marked_at`
/// is set later (once), recording when the container first saw a deeper
/// visible child — the moment it stops accepting same-indent sequence items.
#[derive(Debug)]
pub(crate) struct Frame {
    pub(crate) parent: Option<usize>,
    pub(crate) indent: usize,
    /// The entry's inline value was empty when the scope opened.
    pub(crate) opened_empty: bool,
    pub(crate) block: bool,
    /// Line start of the first deeper visible child line, if any.
    pub(crate) marked_at: Option<usize>,
}

pub(crate) fn parse_document(source: &str, tokens: Vec<ActionToken>) -> TemplatedDocument<'_> {
    let lines = LineIndex::new(source);
    let parser = Parser {
        source,
        tokens,
        frames: Vec::new(),
        head: None,
        owners: vec![OwnerFrame::root()],
        region_modes: HashMap::new(),
        next_token: 0,
    };
    parser.run(&lines)
}

enum RegionMode {
    /// Opened on a standalone action line; a branch owner is live.
    Structured,
    /// Opened inline in YAML content or inside a suppressed context; its
    /// remaining bracket tokens are consumed without structural effect.
    Consumed,
}

struct OwnerFrame {
    children: Vec<Node>,
    data: OwnerData,
}

impl OwnerFrame {
    fn root() -> Self {
        Self {
            children: Vec::new(),
            data: OwnerData::Root,
        }
    }

    fn container(data: OwnerData) -> Self {
        Self {
            children: Vec::new(),
            data,
        }
    }
}

enum OwnerData {
    Root,
    Entry(EntrySeed),
    Item(ItemSeed),
    Branch(BranchSeed),
}

struct EntrySeed {
    frame: usize,
    span: Span,
    indent: usize,
    key: ScalarParts,
    value: Option<ScalarParts>,
    block: Option<BlockSeed>,
}

struct ItemSeed {
    frame: usize,
    span: Span,
    indent: usize,
    value: Option<ScalarParts>,
    block: Option<BlockSeed>,
}

struct BlockSeed {
    header: Span,
    body: Option<Span>,
}

struct BranchSeed {
    region: usize,
    builder: RegionBuilder,
    header: Span,
}

struct RegionBuilder {
    kind: ControlKind,
    span: Span,
    branches: Vec<ControlBranch>,
    well_nested: bool,
}

struct Parser<'src> {
    source: &'src str,
    tokens: Vec<ActionToken>,
    frames: Vec<Frame>,
    head: Option<usize>,
    owners: Vec<OwnerFrame>,
    region_modes: HashMap<usize, RegionMode>,
    next_token: usize,
}

impl<'src> Parser<'src> {
    fn run(mut self, lines: &LineIndex) -> TemplatedDocument<'src> {
        for line in 0..lines.count() {
            let (ls, le) = lines.span(line);
            let followed_by_newline = line + 1 < lines.count();
            self.process_line(ls, le, followed_by_newline);
        }
        self.close_all();
        let roots = self
            .owners
            .pop()
            .map(|owner| owner.children)
            .unwrap_or_default();
        TemplatedDocument {
            source: self.source,
            roots,
            document_spans: document_spans(self.source),
        }
    }

    fn process_line(&mut self, ls: usize, le: usize, followed_by_newline: bool) {
        let raw = self.source.get(ls..le).unwrap_or_default();
        // Mirror `str::lines()`: the replay side never sees a trailing `\r`
        // that precedes a newline (a final newline-less line keeps it).
        let replay = if followed_by_newline {
            raw.strip_suffix('\r').unwrap_or(raw)
        } else {
            raw
        };
        let trimmed = replay.trim_start();
        let indent = replay.len() - trimmed.len();
        if trimmed.is_empty() {
            return;
        }
        // Body of an open block scalar: any line deeper than the block
        // header is suppressed content, regardless of its own shape.
        if self
            .head
            .and_then(|head| self.frames.get(head))
            .is_some_and(|frame| frame.block && indent > frame.indent)
        {
            self.extend_block_body(ls, le);
            self.consume_line_tokens(le, false);
            return;
        }
        if trimmed.starts_with('#') {
            let content = self.parts_for_span(ls + indent, le);
            self.consume_line_tokens(le, false);
            self.attach(Node::Comment(CommentLine {
                span: Span::new(ls + indent, le),
                content,
            }));
            return;
        }
        if trimmed.starts_with("{{") {
            self.process_action_line(ls, le);
            return;
        }
        self.process_content_line(ls, le, trimmed, indent);
    }

    /// A visible YAML content line: apply the pop/mark/push layout rules.
    fn process_content_line(&mut self, ls: usize, le: usize, trimmed: &str, indent: usize) {
        if let Some(after_dash) = trimmed.strip_prefix('-') {
            self.seq_pop(indent);
            self.consume_line_tokens(le, true);
            if !after_dash.is_empty() && !after_dash.starts_with(char::is_whitespace) {
                // `-foo` / `---`: a plain scalar; only its pops count.
                let content = self.parts_for_span(ls + indent, le);
                self.attach(Node::Scalar(ScalarLine {
                    span: Span::new(ls + indent, le),
                    indent,
                    content,
                }));
                return;
            }
            self.mark(indent, ls);
            self.sequence_item_line(ls, le, after_dash, indent);
            return;
        }
        self.pop(indent);
        self.consume_line_tokens(le, true);
        self.mark(indent, ls);
        self.entry_line(trimmed, indent, ls + indent, le);
    }

    fn sequence_item_line(&mut self, ls: usize, le: usize, after_dash: &str, indent: usize) {
        let nested = after_dash.trim_start();
        let nested_start = ls + indent + 1 + (after_dash.len() - nested.len());
        let item_block = nested.starts_with('|') || nested.starts_with('>');
        let frame = self.push_frame(indent, false, item_block);
        let mut seed = ItemSeed {
            frame,
            span: Span::new(ls + indent, le),
            indent,
            value: None,
            block: item_block.then(|| BlockSeed {
                header: Span::new(nested_start, nested_start + nested.len()),
                body: None,
            }),
        };
        if !nested.is_empty() && !item_block {
            if structural_mapping_colon(nested).is_some() {
                self.owners
                    .push(OwnerFrame::container(OwnerData::Item(seed)));
                self.entry_line(nested, indent + 2, nested_start, le);
                return;
            }
            seed.value = Some(self.parts_for_span(nested_start, nested_start + nested.len()));
        }
        self.owners
            .push(OwnerFrame::container(OwnerData::Item(seed)));
    }

    /// A (potential) `key: …` line at `eff_indent`. Pops and marks have
    /// already been applied by the caller.
    fn entry_line(&mut self, text: &str, eff_indent: usize, text_start: usize, le: usize) {
        let Some(colon) = structural_mapping_colon(text) else {
            let content = self.parts_for_span(text_start, text_start + text.len());
            self.attach(Node::Scalar(ScalarLine {
                span: Span::new(text_start, le),
                indent: eff_indent,
                content,
            }));
            return;
        };
        let value_text = &text[colon + 1..];
        let value = value_text.trim();
        let block = value.starts_with('|') || value.starts_with('>');
        let template_value = value.contains("{{");
        let key_trimmed = text[..colon].trim_end();
        let key_text = unquote_yaml_scalar(key_trimmed);
        let key_invalid = key_text.is_empty() || key_text.contains("{{") || key_text.contains("}}");
        let key = self.parts_for_span(text_start, text_start + key_trimmed.len());
        let leading = value_text.len() - value_text.trim_start().len();
        let value_start = text_start + colon + 1 + leading;
        let value_parts = (!value.is_empty() && !block)
            .then(|| self.parts_for_span(value_start, value_start + value.len()));

        let closed = !value.is_empty() && !block && !template_value;
        if closed || key_invalid {
            self.attach(Node::Mapping(MappingEntry {
                span: Span::new(text_start, le),
                indent: eff_indent,
                key,
                value: value_parts,
                block: None,
                opens_scope: false,
                children: Vec::new(),
            }));
            return;
        }
        let frame = self.push_frame(eff_indent, value.is_empty(), block);
        self.owners
            .push(OwnerFrame::container(OwnerData::Entry(EntrySeed {
                frame,
                span: Span::new(text_start, le),
                indent: eff_indent,
                key,
                value: value_parts,
                block: block.then(|| BlockSeed {
                    header: Span::new(value_start, value_start + value.len()),
                    body: None,
                }),
            })));
    }

    /// A line whose first content is a template action: transparent to
    /// layout; its tokens carry the structure (control regions, outputs).
    fn process_action_line(&mut self, ls: usize, le: usize) {
        let mut pos = ls;
        while let Some(token) = self
            .tokens
            .get(self.next_token)
            .copied()
            .filter(|token| token.span.start < le)
        {
            self.next_token += 1;
            self.attach_gap_text(pos, token.span.start.min(le));
            pos = pos.max(token.span.end);
            self.handle_token_structural(token);
        }
        self.attach_gap_text(pos, le);
    }

    fn attach_gap_text(&mut self, start: usize, end: usize) {
        if start >= end {
            return;
        }
        let text = &self.source[start..end];
        if text.trim().is_empty() {
            return;
        }
        let lead = text.len() - text.trim_start().len();
        let content_start = start + lead;
        let content_end = content_start + text.trim().len();
        self.attach(Node::Opaque(OpaqueNode {
            span: Span::new(content_start, content_end),
            kind: OpaqueKind::ActionLineText,
        }));
    }

    fn handle_token_structural(&mut self, token: ActionToken) {
        match token.kind {
            TokenKind::Output { expr_span } => self.attach(Node::Output(OutputAction {
                span: token.span,
                expr_span,
            })),
            TokenKind::Assign => self.attach_opaque(token.span, OpaqueKind::Assignment),
            TokenKind::TemplateComment => {
                self.attach_opaque(token.span, OpaqueKind::TemplateComment);
            }
            TokenKind::Break => self.attach_opaque(token.span, OpaqueKind::Break),
            TokenKind::Continue => self.attach_opaque(token.span, OpaqueKind::Continue),
            TokenKind::Error => self.attach_opaque(token.span, OpaqueKind::ParseError),
            TokenKind::RegionOpen {
                region,
                kind,
                region_end,
            } => {
                self.region_modes.insert(region, RegionMode::Structured);
                self.owners.push(OwnerFrame {
                    children: Vec::new(),
                    data: OwnerData::Branch(BranchSeed {
                        region,
                        builder: RegionBuilder {
                            kind,
                            span: Span::new(token.span.start, region_end),
                            branches: Vec::new(),
                            well_nested: true,
                        },
                        header: token.span,
                    }),
                });
            }
            TokenKind::RegionBranch { region } => self.rotate_branch(region, token.span, true),
            TokenKind::RegionEnd { region } => self.end_region(region, true),
        }
    }

    fn rotate_branch(&mut self, region: usize, header: Span, clean_boundary: bool) {
        if let Some((mut seed, _)) = self.close_branch(region, clean_boundary) {
            seed.header = header;
            self.owners.push(OwnerFrame {
                children: Vec::new(),
                data: OwnerData::Branch(seed),
            });
        }
    }

    fn end_region(&mut self, region: usize, clean_boundary: bool) {
        if let Some((seed, index)) = self.close_branch(region, clean_boundary) {
            self.region_modes.remove(&region);
            // Attach below where the branch sat, not to a container that
            // escaped it: the region is a sibling of the escaped container.
            self.attach_at(
                index.saturating_sub(1),
                Node::Control(ControlRegion {
                    kind: seed.builder.kind,
                    span: seed.builder.span,
                    branches: seed.builder.branches,
                    well_nested: seed.builder.well_nested,
                }),
            );
        }
    }

    /// Close the live branch owner of `region`, folding its children into
    /// the region builder; returns the seed and the stack index the branch
    /// occupied. Containers still open above the branch escape it: they stay
    /// open (layout is decided by lines alone) and the region is flagged as
    /// not well-nested.
    fn close_branch(&mut self, region: usize, clean_boundary: bool) -> Option<(BranchSeed, usize)> {
        if !matches!(self.region_modes.get(&region), Some(RegionMode::Structured)) {
            return None;
        }
        let index = self.owners.iter().rposition(
            |owner| matches!(&owner.data, OwnerData::Branch(seed) if seed.region == region),
        )?;
        let escaped = self.owners.len() - 1 - index;
        let owner = self.owners.remove(index);
        let OwnerData::Branch(mut seed) = owner.data else {
            return None;
        };
        if escaped > 0 || !clean_boundary {
            seed.builder.well_nested = false;
        }
        seed.builder.branches.push(ControlBranch {
            header: seed.header,
            body: owner.children,
        });
        Some((seed, index))
    }

    /// Consume the tokens of a line that is not a standalone action line.
    /// Output/comment tokens become holes in the surrounding text (no
    /// nodes); a region opening here cannot bracket layout, so it is
    /// consumed — and, on a visible content line, degraded to an opaque node
    /// covering the whole region ("never guess" — the raw span is
    /// preserved). A structured region's `else`/`end` landing here still
    /// rotates/closes the region, flagged as an unclean boundary.
    fn consume_line_tokens(&mut self, le: usize, opaque_inline_regions: bool) {
        while let Some(token) = self
            .tokens
            .get(self.next_token)
            .copied()
            .filter(|token| token.span.start < le)
        {
            self.next_token += 1;
            match token.kind {
                TokenKind::RegionOpen {
                    region, region_end, ..
                } => {
                    self.region_modes.insert(region, RegionMode::Consumed);
                    if opaque_inline_regions {
                        self.attach(Node::Opaque(OpaqueNode {
                            span: Span::new(token.span.start, region_end),
                            kind: OpaqueKind::InlineRegion,
                        }));
                    }
                }
                TokenKind::RegionBranch { region } => self.rotate_branch(region, token.span, false),
                TokenKind::RegionEnd { region } => self.end_region(region, false),
                _ => {}
            }
        }
    }

    fn extend_block_body(&mut self, ls: usize, le: usize) {
        for owner in self.owners.iter_mut().rev() {
            let block = match &mut owner.data {
                OwnerData::Entry(seed) => seed.block.as_mut(),
                OwnerData::Item(seed) => seed.block.as_mut(),
                OwnerData::Root | OwnerData::Branch(_) => continue,
            };
            if let Some(block) = block {
                let start = block.body.map_or(ls, |span| span.start);
                block.body = Some(Span::new(start, le));
            }
            return;
        }
    }

    fn push_frame(&mut self, indent: usize, opened_empty: bool, block: bool) -> usize {
        let id = self.frames.len();
        self.frames.push(Frame {
            parent: self.head,
            indent,
            opened_empty,
            block,
            marked_at: None,
        });
        self.head = Some(id);
        id
    }

    /// Content-line pops: close containers at `indent` or deeper.
    fn pop(&mut self, indent: usize) {
        while let Some(head) = self.head {
            if self
                .frames
                .get(head)
                .is_some_and(|frame| frame.indent >= indent)
            {
                self.close_container();
            } else {
                break;
            }
        }
    }

    /// Sequence-item pops: a container at the item's own indent survives
    /// while it still accepts same-indent items (empty value, unmarked).
    fn seq_pop(&mut self, indent: usize) {
        while let Some(head) = self.head {
            let Some(frame) = self.frames.get(head) else {
                self.head = None;
                break;
            };
            let allow = frame.opened_empty && frame.marked_at.is_none();
            if frame.indent > indent || (frame.indent == indent && !allow) {
                self.close_container();
            } else {
                break;
            }
        }
    }

    /// Record that the nearest shallower container saw a visible child line.
    fn mark(&mut self, indent: usize, ls: usize) {
        let mut current = self.head;
        while let Some(id) = current {
            let Some(frame) = self.frames.get_mut(id) else {
                self.head = None;
                return;
            };
            if frame.indent < indent {
                if frame.marked_at.is_none() {
                    frame.marked_at = Some(ls);
                }
                return;
            }
            current = frame.parent;
        }
    }

    /// Close the innermost open container. Branch owners above it stay live
    /// (regions overlay containers); the closed node attaches to the owner
    /// directly beneath it.
    fn close_container(&mut self) {
        let Some(index) = self
            .owners
            .iter()
            .rposition(|owner| matches!(owner.data, OwnerData::Entry(_) | OwnerData::Item(_)))
        else {
            self.head = None;
            return;
        };
        let owner = self.owners.remove(index);
        let children = owner.children;
        let (node, frame) = match owner.data {
            OwnerData::Entry(seed) => (
                Node::Mapping(MappingEntry {
                    span: seed.span,
                    indent: seed.indent,
                    key: seed.key,
                    value: seed.value,
                    block: seed.block.map(|block| self.finish_block(&block)),
                    opens_scope: true,
                    children,
                }),
                seed.frame,
            ),
            OwnerData::Item(seed) => (
                Node::Sequence(SequenceItem {
                    span: seed.span,
                    indent: seed.indent,
                    value: seed.value,
                    block: seed.block.map(|block| self.finish_block(&block)),
                    children,
                }),
                seed.frame,
            ),
            OwnerData::Root | OwnerData::Branch(_) => {
                // Unreachable by construction: `index` matched a container.
                self.head = None;
                return;
            }
        };
        self.head = self.frames.get(frame).and_then(|frame| frame.parent);
        self.attach_at(index.saturating_sub(1), node);
    }

    fn finish_block(&self, seed: &BlockSeed) -> BlockScalar {
        let body = seed
            .body
            .unwrap_or(Span::new(seed.header.end, seed.header.end));
        let holes = self
            .tokens
            .iter()
            .filter(|token| token.span.start >= body.start && token.span.start < body.end)
            .map(|token| token.span)
            .collect();
        BlockScalar {
            header: seed.header,
            body,
            holes,
        }
    }

    fn close_all(&mut self) {
        while self.owners.len() > 1 {
            let top = self.owners.len() - 1;
            let Some(owner) = self.owners.get(top) else {
                break;
            };
            match &owner.data {
                OwnerData::Entry(_) | OwnerData::Item(_) => self.close_container(),
                OwnerData::Branch(seed) => {
                    let region = seed.region;
                    self.end_region(region, false);
                }
                OwnerData::Root => break,
            }
        }
    }

    fn attach(&mut self, node: Node) {
        let index = self.owners.len() - 1;
        self.attach_at(index, node);
    }

    fn attach_at(&mut self, index: usize, node: Node) {
        if let Some(owner) = self.owners.get_mut(index) {
            owner.children.push(node);
        }
    }

    fn attach_opaque(&mut self, span: Span, kind: OpaqueKind) {
        self.attach(Node::Opaque(OpaqueNode { span, kind }));
    }

    /// Split `[start, end)` into literal text runs and action holes. Holes
    /// keep their full token span, which may extend past `end` for
    /// multi-line actions.
    fn parts_for_span(&self, start: usize, end: usize) -> ScalarParts {
        let mut parts = Vec::new();
        let mut pos = start;
        let first = self.tokens.partition_point(|token| token.span.end <= start);
        for token in self.tokens.get(first..).unwrap_or_default() {
            if token.span.start >= end {
                break;
            }
            if token.span.start > pos {
                parts.push(ScalarPart::Text(Span::new(pos, token.span.start)));
            }
            parts.push(ScalarPart::Hole(token.span));
            pos = pos.max(token.span.end);
        }
        if pos < end {
            parts.push(ScalarPart::Text(Span::new(pos, end)));
        }
        ScalarParts {
            span: Span::new(start, end),
            parts,
        }
    }
}

/// Top-level document spans, split at lines whose trimmed text is exactly
/// `---`. Mirrors the resource-identity splitter: only nonempty spans.
fn document_spans(source: &str) -> Vec<Span> {
    let mut spans = Vec::new();
    let mut start = 0usize;
    let mut byte = 0usize;
    for line in source.split_inclusive('\n') {
        if line.trim() == "---" {
            if start < byte {
                spans.push(Span::new(start, byte));
            }
            start = byte + line.len();
        }
        byte += line.len();
    }
    if start < source.len() {
        spans.push(Span::new(start, source.len()));
    }
    spans
}