compose-lens 0.1.0

Loss-aware parsing, processing, validation, and rendering of Compose projects
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
//! Explicit, non-destructive Compose variable interpolation.

use crate::diagnostic::{Diagnostic, DiagnosticCode, DiagnosticLabel, Severity};
use crate::source::{SourceId, SourceSpan};
use crate::syntax::SyntaxDocument;
use std::collections::BTreeMap;

/// An unset direct substitution was replaced according to the configured policy.
pub const UNSET_VARIABLE: DiagnosticCode = DiagnosticCode::new("compose.interpolation.unset-variable");

/// A required interpolation variable was unset or empty.
pub const REQUIRED_VARIABLE: DiagnosticCode = DiagnosticCode::new("compose.interpolation.required-variable");

/// A braced interpolation expression is malformed or unsupported.
pub const INVALID_EXPRESSION: DiagnosticCode = DiagnosticCode::new("compose.interpolation.invalid-expression");

/// Nested interpolation exceeded the configured safety limit.
pub const NESTING_LIMIT: DiagnosticCode = DiagnosticCode::new("compose.interpolation.nesting-limit");

/// One value supplied by an explicit interpolation environment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvironmentValue {
    value: String,
    sensitive: bool,
}

impl EnvironmentValue {
    /// Creates a non-sensitive value.
    #[must_use]
    pub fn plain(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            sensitive: false,
        }
    }

    /// Creates a value whose use makes the interpolation result sensitive.
    #[must_use]
    pub fn sensitive(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            sensitive: true,
        }
    }

    /// Returns the supplied value.
    #[must_use]
    pub fn value(&self) -> &str {
        &self.value
    }

    /// Reports whether callers should redact the value when displaying the result.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

/// Supplies variables to interpolation without granting implicit process-environment access.
pub trait EnvironmentProvider {
    /// Returns a variable value, or `None` when the variable is unset.
    fn get(&self, name: &str) -> Option<EnvironmentValue>;
}

/// An explicit environment that never contains a variable.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EmptyEnvironment;

impl EnvironmentProvider for EmptyEnvironment {
    fn get(&self, _name: &str) -> Option<EnvironmentValue> {
        None
    }
}

/// A deterministic caller-owned interpolation environment.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MapEnvironment {
    values: BTreeMap<String, EnvironmentValue>,
}

impl MapEnvironment {
    /// Creates an empty environment map.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            values: BTreeMap::new(),
        }
    }

    /// Inserts a non-sensitive value and returns the replaced value, if any.
    pub fn insert(&mut self, name: impl Into<String>, value: impl Into<String>) -> Option<EnvironmentValue> {
        self.values.insert(name.into(), EnvironmentValue::plain(value))
    }

    /// Inserts a sensitive value and returns the replaced value, if any.
    pub fn insert_sensitive(&mut self, name: impl Into<String>, value: impl Into<String>) -> Option<EnvironmentValue> {
        self.values.insert(name.into(), EnvironmentValue::sensitive(value))
    }

    /// Inserts an already classified value and returns the replaced value, if any.
    pub fn insert_value(&mut self, name: impl Into<String>, value: EnvironmentValue) -> Option<EnvironmentValue> {
        self.values.insert(name.into(), value)
    }

    /// Returns the number of configured variables.
    #[must_use]
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Reports whether no variables are configured.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }
}

impl EnvironmentProvider for MapEnvironment {
    fn get(&self, name: &str) -> Option<EnvironmentValue> {
        self.values.get(name).cloned()
    }
}

/// Behavior for an unset direct `$VAR` or `${VAR}` substitution.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum MissingVariablePolicy {
    /// Match Compose's documented behavior: warn and substitute an empty string.
    EmptyWithWarning,
    /// Warn and retain the original expression in the recovered value.
    PreserveWithWarning,
    /// Emit an error and retain the original expression in the recovered value.
    Error,
}

/// Controls one explicit interpolation operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InterpolationOptions {
    missing_variable: MissingVariablePolicy,
    max_nesting: usize,
}

impl InterpolationOptions {
    /// Creates options using the requested missing-variable policy.
    #[must_use]
    pub const fn new(missing_variable: MissingVariablePolicy) -> Self {
        Self {
            missing_variable,
            max_nesting: 32,
        }
    }

    /// Sets the maximum nested-expression depth; zero is promoted to one.
    #[must_use]
    pub fn with_max_nesting(mut self, max_nesting: usize) -> Self {
        self.max_nesting = max_nesting.max(1);
        self
    }

    /// Returns the direct missing-variable policy.
    #[must_use]
    pub const fn missing_variable(self) -> MissingVariablePolicy {
        self.missing_variable
    }

    /// Returns the maximum nested-expression depth.
    #[must_use]
    pub const fn max_nesting(self) -> usize {
        self.max_nesting
    }
}

impl Default for InterpolationOptions {
    fn default() -> Self {
        Self::new(MissingVariablePolicy::EmptyWithWarning)
    }
}

/// A source-aware scalar supplied to the interpolation kernel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InterpolationInput<'a> {
    value: &'a str,
    span: SourceSpan,
    sensitive: bool,
}

impl<'a> InterpolationInput<'a> {
    /// Creates a non-sensitive input.
    #[must_use]
    pub const fn new(value: &'a str, span: SourceSpan) -> Self {
        Self {
            value,
            span,
            sensitive: false,
        }
    }

    /// Marks the authored scalar as sensitive.
    #[must_use]
    pub const fn sensitive(mut self) -> Self {
        self.sensitive = true;
        self
    }

    /// Returns the uninterpolated semantic scalar.
    #[must_use]
    pub const fn value(self) -> &'a str {
        self.value
    }

    /// Returns the scalar's source span.
    #[must_use]
    pub const fn span(self) -> SourceSpan {
        self.span
    }

    /// Reports whether the authored scalar is sensitive.
    #[must_use]
    pub const fn is_sensitive(self) -> bool {
        self.sensitive
    }
}

/// The operator used by one interpolation expression.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum InterpolationOperator {
    /// `$VAR` or `${VAR}`.
    Direct,
    /// `${VAR:-default}`.
    DefaultIfUnsetOrEmpty,
    /// `${VAR-default}`.
    DefaultIfUnset,
    /// `${VAR:?message}`.
    RequiredIfUnsetOrEmpty,
    /// `${VAR?message}`.
    RequiredIfUnset,
    /// `${VAR:+alternative}`.
    AlternativeIfSetAndNonEmpty,
    /// `${VAR+alternative}`.
    AlternativeIfSet,
}

/// How one expression contributed to the resolved value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SubstitutionOutcome {
    /// An environment value was inserted.
    Environment,
    /// A default operand was inserted.
    Default,
    /// An alternative operand was inserted.
    Alternative,
    /// The expression intentionally produced an empty string.
    Empty,
    /// A direct variable was unset.
    Missing,
    /// A required variable was unset or empty.
    RequiredMissing,
}

/// Provenance for one evaluated variable expression.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Substitution {
    name: String,
    operator: InterpolationOperator,
    outcome: SubstitutionOutcome,
    span: SourceSpan,
    sensitive: bool,
}

impl Substitution {
    /// Returns the referenced variable name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the expression operator.
    #[must_use]
    pub const fn operator(&self) -> InterpolationOperator {
        self.operator
    }

    /// Returns how the expression contributed to the result.
    #[must_use]
    pub const fn outcome(&self) -> SubstitutionOutcome {
        self.outcome
    }

    /// Returns the containing scalar's source span.
    #[must_use]
    pub const fn span(&self) -> SourceSpan {
        self.span
    }

    /// Reports whether this substitution inserted sensitive content.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }
}

/// A recoverable, non-destructive interpolation result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InterpolationResult {
    original: String,
    resolved: String,
    span: SourceSpan,
    sensitive: bool,
    substitutions: Vec<Substitution>,
    diagnostics: Vec<Diagnostic>,
}

/// A non-destructive interpolation overlay for one syntax document.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DocumentInterpolation {
    source_id: SourceId,
    values: Vec<InterpolationResult>,
    diagnostics: Vec<Diagnostic>,
}

impl DocumentInterpolation {
    /// Returns the interpolated source-document identifier.
    #[must_use]
    pub const fn source_id(&self) -> SourceId {
        self.source_id
    }

    /// Returns eligible value-scalar results in source order.
    #[must_use]
    pub fn values(&self) -> &[InterpolationResult] {
        &self.values
    }

    /// Finds the result for an exact value-scalar span.
    #[must_use]
    pub fn value(&self, span: SourceSpan) -> Option<&InterpolationResult> {
        self.values.iter().find(|value| value.span == span)
    }

    /// Returns aggregated interpolation diagnostics in source order.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Reports whether no value produced an error diagnostic.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        !self
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.severity() == Severity::Error)
    }
}

impl InterpolationResult {
    /// Returns the uninterpolated semantic scalar.
    #[must_use]
    pub fn original(&self) -> &str {
        &self.original
    }

    /// Returns the recovered resolved value.
    ///
    /// Required-variable and invalid-expression errors retain the offending expression so callers
    /// can continue analysis without silently losing source intent.
    #[must_use]
    pub fn resolved(&self) -> &str {
        &self.resolved
    }

    /// Returns the source span of the containing scalar.
    #[must_use]
    pub const fn span(&self) -> SourceSpan {
        self.span
    }

    /// Reports whether the input or an inserted value is sensitive.
    #[must_use]
    pub const fn is_sensitive(&self) -> bool {
        self.sensitive
    }

    /// Returns evaluated expressions in evaluation order.
    #[must_use]
    pub fn substitutions(&self) -> &[Substitution] {
        &self.substitutions
    }

    /// Returns interpolation diagnostics.
    #[must_use]
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }

    /// Reports whether interpolation emitted no error diagnostics.
    #[must_use]
    pub fn is_valid(&self) -> bool {
        !self
            .diagnostics
            .iter()
            .any(|diagnostic| diagnostic.severity() == Severity::Error)
    }
}

/// Interpolates one scalar using Compose's documented direct, default, required, and alternative
/// operators.
#[must_use]
pub fn interpolate(input: InterpolationInput<'_>, environment: &dyn EnvironmentProvider) -> InterpolationResult {
    interpolate_with_options(input, environment, InterpolationOptions::default())
}

/// Interpolates one scalar with explicit missing-variable and nesting policies.
#[must_use]
pub fn interpolate_with_options(
    input: InterpolationInput<'_>,
    environment: &dyn EnvironmentProvider,
    options: InterpolationOptions,
) -> InterpolationResult {
    let mut context = Context {
        environment,
        options,
        span: input.span,
        diagnostics: Vec::new(),
        substitutions: Vec::new(),
    };
    let fragment = context.interpolate_text(input.value, 0);
    InterpolationResult {
        original: input.value.to_owned(),
        resolved: fragment.value,
        span: input.span,
        sensitive: input.sensitive || fragment.sensitive,
        substitutions: context.substitutions,
        diagnostics: context.diagnostics,
    }
}

/// Interpolates eligible YAML value scalars in one syntax document without modifying its source.
///
/// Mapping keys, single-quoted scalars, literal block scalars, and folded block scalars are not
/// eligible. The returned overlay contains only values that included a dollar sign.
#[must_use]
pub fn interpolate_document(document: &SyntaxDocument, environment: &dyn EnvironmentProvider) -> DocumentInterpolation {
    interpolate_document_with_options(document, environment, InterpolationOptions::default())
}

/// Interpolates eligible YAML value scalars with explicit options.
#[must_use]
pub fn interpolate_document_with_options(
    document: &SyntaxDocument,
    environment: &dyn EnvironmentProvider,
    options: InterpolationOptions,
) -> DocumentInterpolation {
    let values: Vec<_> = document
        .interpolatable_value_scalars()
        .into_iter()
        .map(|value| interpolate_with_options(InterpolationInput::new(&value.value, value.span), environment, options))
        .collect();
    let diagnostics = values
        .iter()
        .flat_map(|value| value.diagnostics.iter().cloned())
        .collect();
    DocumentInterpolation {
        source_id: document.source_id(),
        values,
        diagnostics,
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Fragment {
    value: String,
    sensitive: bool,
}

impl Fragment {
    fn plain(value: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            sensitive: false,
        }
    }
}

struct Context<'a> {
    environment: &'a dyn EnvironmentProvider,
    options: InterpolationOptions,
    span: SourceSpan,
    diagnostics: Vec<Diagnostic>,
    substitutions: Vec<Substitution>,
}

impl Context<'_> {
    fn interpolate_text(&mut self, text: &str, depth: usize) -> Fragment {
        if depth > self.options.max_nesting {
            self.diagnostics.push(
                Diagnostic::new(
                    NESTING_LIMIT,
                    Severity::Error,
                    "interpolation nesting exceeds the configured safety limit",
                )
                .with_label(DiagnosticLabel::primary(self.span, "nested expression limit reached")),
            );
            return Fragment::plain(text);
        }

        let mut resolved = String::with_capacity(text.len());
        let mut sensitive = false;
        let mut cursor = 0;
        while let Some(relative) = text[cursor..].find('$') {
            let dollar = cursor + relative;
            resolved.push_str(&text[cursor..dollar]);
            let after_dollar = dollar + 1;
            if after_dollar == text.len() {
                resolved.push('$');
                cursor = after_dollar;
                break;
            }

            let next = text.as_bytes()[after_dollar];
            if next == b'$' {
                resolved.push('$');
                cursor = after_dollar + 1;
                continue;
            }
            if next == b'{' {
                let expression_start = after_dollar + 1;
                let Some(close) = find_closing_brace(text, expression_start) else {
                    self.invalid_expression();
                    resolved.push_str(&text[dollar..]);
                    cursor = text.len();
                    break;
                };
                let expression = &text[expression_start..close];
                let original = &text[dollar..=close];
                let fragment = self.evaluate_braced(expression, original, depth);
                resolved.push_str(&fragment.value);
                sensitive |= fragment.sensitive;
                cursor = close + 1;
                continue;
            }
            if is_name_start(next) {
                let mut end = after_dollar + 1;
                while end < text.len() && is_name_continue(text.as_bytes()[end]) {
                    end += 1;
                }
                let name = &text[after_dollar..end];
                let original = &text[dollar..end];
                let fragment = self.evaluate(name, InterpolationOperator::Direct, "", original, depth);
                resolved.push_str(&fragment.value);
                sensitive |= fragment.sensitive;
                cursor = end;
                continue;
            }

            resolved.push('$');
            cursor = after_dollar;
        }
        resolved.push_str(&text[cursor..]);
        Fragment {
            value: resolved,
            sensitive,
        }
    }

    fn evaluate_braced(&mut self, expression: &str, original: &str, depth: usize) -> Fragment {
        let Some((name, operator, operand)) = parse_braced_expression(expression) else {
            self.invalid_expression();
            return Fragment::plain(original);
        };
        self.evaluate(name, operator, operand, original, depth)
    }

    fn evaluate(
        &mut self,
        name: &str,
        operator: InterpolationOperator,
        operand: &str,
        original: &str,
        depth: usize,
    ) -> Fragment {
        let environment = self.environment.get(name);
        let is_set = environment.is_some();
        let is_non_empty = environment.as_ref().is_some_and(|value| !value.value.is_empty());

        let (fragment, outcome) = match operator {
            InterpolationOperator::Direct => environment.map_or_else(
                || self.missing_direct(name, original),
                |value| {
                    let fragment = Fragment {
                        value: value.value,
                        sensitive: value.sensitive,
                    };
                    (fragment, SubstitutionOutcome::Environment)
                },
            ),
            InterpolationOperator::DefaultIfUnsetOrEmpty if !is_non_empty => {
                (self.interpolate_text(operand, depth + 1), SubstitutionOutcome::Default)
            }
            InterpolationOperator::DefaultIfUnset if !is_set => {
                (self.interpolate_text(operand, depth + 1), SubstitutionOutcome::Default)
            }
            InterpolationOperator::RequiredIfUnsetOrEmpty if !is_non_empty => {
                self.required_missing(name);
                (Fragment::plain(original), SubstitutionOutcome::RequiredMissing)
            }
            InterpolationOperator::RequiredIfUnset if !is_set => {
                self.required_missing(name);
                (Fragment::plain(original), SubstitutionOutcome::RequiredMissing)
            }
            InterpolationOperator::AlternativeIfSetAndNonEmpty if is_non_empty => (
                self.interpolate_text(operand, depth + 1),
                SubstitutionOutcome::Alternative,
            ),
            InterpolationOperator::AlternativeIfSet if is_set => (
                self.interpolate_text(operand, depth + 1),
                SubstitutionOutcome::Alternative,
            ),
            InterpolationOperator::AlternativeIfSetAndNonEmpty | InterpolationOperator::AlternativeIfSet => {
                (Fragment::plain(""), SubstitutionOutcome::Empty)
            }
            InterpolationOperator::DefaultIfUnsetOrEmpty
            | InterpolationOperator::DefaultIfUnset
            | InterpolationOperator::RequiredIfUnsetOrEmpty
            | InterpolationOperator::RequiredIfUnset => {
                let value = environment.unwrap_or_else(|| EnvironmentValue::plain(""));
                (
                    Fragment {
                        value: value.value,
                        sensitive: value.sensitive,
                    },
                    SubstitutionOutcome::Environment,
                )
            }
        };

        self.substitutions.push(Substitution {
            name: name.to_owned(),
            operator,
            outcome,
            span: self.span,
            sensitive: fragment.sensitive,
        });
        fragment
    }

    fn missing_direct(&mut self, name: &str, original: &str) -> (Fragment, SubstitutionOutcome) {
        let (severity, value) = match self.options.missing_variable {
            MissingVariablePolicy::EmptyWithWarning => (Severity::Warning, ""),
            MissingVariablePolicy::PreserveWithWarning => (Severity::Warning, original),
            MissingVariablePolicy::Error => (Severity::Error, original),
        };
        self.diagnostics.push(
            Diagnostic::new(
                UNSET_VARIABLE,
                severity,
                format!("interpolation variable `{name}` is not set"),
            )
            .with_label(DiagnosticLabel::primary(self.span, "unresolved variable expression")),
        );
        (Fragment::plain(value), SubstitutionOutcome::Missing)
    }

    fn required_missing(&mut self, name: &str) {
        self.diagnostics.push(
            Diagnostic::new(
                REQUIRED_VARIABLE,
                Severity::Error,
                format!("required interpolation variable `{name}` is unset or empty"),
            )
            .with_label(DiagnosticLabel::primary(self.span, "required variable is unavailable")),
        );
    }

    fn invalid_expression(&mut self) {
        self.diagnostics.push(
            Diagnostic::new(
                INVALID_EXPRESSION,
                Severity::Error,
                "interpolation expression is malformed or unsupported",
            )
            .with_label(DiagnosticLabel::primary(self.span, "invalid interpolation expression")),
        );
    }
}

fn parse_braced_expression(expression: &str) -> Option<(&str, InterpolationOperator, &str)> {
    let bytes = expression.as_bytes();
    let first = *bytes.first()?;
    if !is_name_start(first) {
        return None;
    }
    let mut name_end = 1;
    while name_end < bytes.len() && is_name_continue(bytes[name_end]) {
        name_end += 1;
    }
    let name = &expression[..name_end];
    let remainder = &expression[name_end..];
    if remainder.is_empty() {
        return Some((name, InterpolationOperator::Direct, ""));
    }

    for (prefix, operator) in [
        (":-", InterpolationOperator::DefaultIfUnsetOrEmpty),
        (":?", InterpolationOperator::RequiredIfUnsetOrEmpty),
        (":+", InterpolationOperator::AlternativeIfSetAndNonEmpty),
        ("-", InterpolationOperator::DefaultIfUnset),
        ("?", InterpolationOperator::RequiredIfUnset),
        ("+", InterpolationOperator::AlternativeIfSet),
    ] {
        if let Some(operand) = remainder.strip_prefix(prefix) {
            return Some((name, operator, operand));
        }
    }
    None
}

fn find_closing_brace(text: &str, start: usize) -> Option<usize> {
    let mut depth = 1usize;
    let mut cursor = start;
    while cursor < text.len() {
        if text[cursor..].starts_with("${") {
            depth += 1;
            cursor += 2;
            continue;
        }
        let character = text[cursor..].chars().next()?;
        if character == '}' {
            depth -= 1;
            if depth == 0 {
                return Some(cursor);
            }
        }
        cursor += character.len_utf8();
    }
    None
}

const fn is_name_start(byte: u8) -> bool {
    byte == b'_' || byte.is_ascii_alphabetic()
}

const fn is_name_continue(byte: u8) -> bool {
    is_name_start(byte) || byte.is_ascii_digit()
}