holoconf-core 0.5.1

Core configuration library with resolver support
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
//! Interpolation parsing per ADR-011
//!
//! Parses interpolation expressions like:
//! - `${env:VAR}` - resolver with argument
//! - `${env:VAR,default}` - resolver with default
//! - `${path.to.value}` - self-reference
//! - `${.sibling}` - relative self-reference
//! - `\${escaped}` - escaped (literal) interpolation
//! - `${env:VAR,${env:OTHER,fallback}}` - nested interpolations

use crate::error::{Error, Result};
use std::collections::HashMap;

/// A parsed interpolation expression
#[derive(Debug, Clone, PartialEq)]
pub enum Interpolation {
    /// A literal string (no interpolation or escaped interpolation)
    Literal(String),
    /// A resolver call: ${resolver:arg1,arg2,key=value}
    Resolver {
        /// Resolver name (e.g., "env", "file")
        name: String,
        /// Positional arguments
        args: Vec<InterpolationArg>,
        /// Keyword arguments
        kwargs: HashMap<String, InterpolationArg>,
    },
    /// A self-reference: ${path.to.value}
    SelfRef {
        /// The path to reference
        path: String,
        /// Whether this is a relative path (starts with .)
        relative: bool,
    },
    /// A concatenation of multiple parts
    Concat(Vec<Interpolation>),
}

/// An argument to an interpolation (may itself contain interpolations)
#[derive(Debug, Clone, PartialEq)]
pub enum InterpolationArg {
    /// A literal string value
    Literal(String),
    /// A nested interpolation
    Nested(Box<Interpolation>),
}

impl InterpolationArg {
    /// Check if this argument is a simple literal
    pub fn is_literal(&self) -> bool {
        matches!(self, InterpolationArg::Literal(_))
    }

    /// Get the literal value if this is a literal
    pub fn as_literal(&self) -> Option<&str> {
        match self {
            InterpolationArg::Literal(s) => Some(s),
            _ => None,
        }
    }
}

/// Parser for interpolation expressions
pub struct InterpolationParser<'a> {
    input: &'a str,
    pos: usize,
}

impl<'a> InterpolationParser<'a> {
    /// Create a new parser for the given input
    pub fn new(input: &'a str) -> Self {
        Self { input, pos: 0 }
    }

    /// Parse the entire input string
    pub fn parse(&mut self) -> Result<Interpolation> {
        let mut parts = Vec::new();

        while !self.is_eof() {
            if self.check_escape() {
                // \${ -> literal ${
                self.advance(); // skip backslash
                self.advance(); // skip $
                self.advance(); // skip {
                parts.push(Interpolation::Literal("${".to_string()));
            } else if self.check_interpolation_start() {
                parts.push(self.parse_interpolation()?);
            } else {
                // Collect literal text until next interpolation or end
                let literal = self.collect_literal();
                if !literal.is_empty() {
                    parts.push(Interpolation::Literal(literal));
                }
            }
        }

        // Simplify result
        match parts.len() {
            0 => Ok(Interpolation::Literal(String::new())),
            1 => Ok(parts.remove(0)),
            _ => {
                // Merge adjacent literals
                let merged = merge_adjacent_literals(parts);
                if merged.len() == 1 {
                    Ok(merged.into_iter().next().unwrap())
                } else {
                    Ok(Interpolation::Concat(merged))
                }
            }
        }
    }

    /// Check if we're at end of input
    fn is_eof(&self) -> bool {
        self.pos >= self.input.len()
    }

    /// Get current character
    fn current(&self) -> Option<char> {
        self.input[self.pos..].chars().next()
    }

    /// Peek at the next character
    fn peek(&self) -> Option<char> {
        let mut chars = self.input[self.pos..].chars();
        chars.next();
        chars.next()
    }

    /// Peek at character n positions ahead
    fn peek_n(&self, n: usize) -> Option<char> {
        self.input[self.pos..].chars().nth(n)
    }

    /// Advance by one character
    fn advance(&mut self) {
        if let Some(c) = self.current() {
            self.pos += c.len_utf8();
        }
    }

    /// Check if we're at an escape sequence (\${)
    fn check_escape(&self) -> bool {
        self.current() == Some('\\') && self.peek() == Some('$') && self.peek_n(2) == Some('{')
    }

    /// Check if we're at an interpolation start (${)
    fn check_interpolation_start(&self) -> bool {
        self.current() == Some('$') && self.peek() == Some('{')
    }

    /// Collect literal text until interpolation or end
    fn collect_literal(&mut self) -> String {
        let mut result = String::new();

        while !self.is_eof() {
            if self.check_escape() {
                break;
            }
            if self.check_interpolation_start() {
                break;
            }
            if let Some(c) = self.current() {
                result.push(c);
                self.advance();
            }
        }

        result
    }

    /// Parse an interpolation expression (starting at ${)
    fn parse_interpolation(&mut self) -> Result<Interpolation> {
        // Skip ${
        self.advance(); // $
        self.advance(); // {

        // Skip whitespace
        self.skip_whitespace();

        if self.is_eof() {
            return Err(Error::parse("Unexpected end of input in interpolation"));
        }

        // Check for relative path (.sibling or ..parent)
        if self.current() == Some('.') {
            return self.parse_self_ref(true);
        }

        // Collect the identifier (resolver name or path)
        let identifier = self.collect_identifier();

        if identifier.is_empty() {
            return Err(Error::parse("Empty interpolation expression"));
        }

        self.skip_whitespace();

        // Check what follows the identifier
        match self.current() {
            Some(':') => {
                // This is a resolver call: ${resolver:args}
                self.advance(); // skip :
                self.parse_resolver_call(identifier)
            }
            Some('}') => {
                // This is a simple self-reference: ${path.to.value}
                // Convert to ref resolver: ${ref:path}
                self.advance(); // skip }
                Ok(Interpolation::Resolver {
                    name: "ref".to_string(),
                    args: vec![InterpolationArg::Literal(identifier)],
                    kwargs: HashMap::new(),
                })
            }
            Some(',') => {
                // Self-reference with kwargs: ${path,default=value}
                // Convert to ref resolver: ${ref:path,default=value}
                self.advance(); // skip comma
                self.parse_resolver_call_with_first_arg("ref".to_string(), identifier)
            }
            Some(c) => Err(Error::parse(format!(
                "Unexpected character '{}' in interpolation",
                c
            ))),
            None => Err(Error::parse("Unexpected end of input in interpolation")),
        }
    }

    /// Parse a self-reference (possibly relative)
    fn parse_self_ref(&mut self, relative: bool) -> Result<Interpolation> {
        let mut path = String::new();

        // Collect the full path including dots
        while !self.is_eof() {
            match self.current() {
                Some('}') => {
                    self.advance();
                    break;
                }
                Some(c) if c.is_alphanumeric() || c == '_' || c == '.' || c == '[' || c == ']' => {
                    path.push(c);
                    self.advance();
                }
                Some(c) => {
                    return Err(Error::parse(format!("Invalid character '{}' in path", c)));
                }
                None => {
                    return Err(Error::parse("Unexpected end of input in path"));
                }
            }
        }

        Ok(Interpolation::SelfRef { path, relative })
    }

    /// Parse a resolver call after the colon
    fn parse_resolver_call(&mut self, name: String) -> Result<Interpolation> {
        let mut args = Vec::new();
        let mut kwargs = HashMap::new();

        // Parse arguments separated by commas
        loop {
            self.skip_whitespace();

            if self.current() == Some('}') {
                self.advance();
                break;
            }

            if !args.is_empty() || !kwargs.is_empty() {
                // Expect comma separator
                if self.current() != Some(',') {
                    return Err(Error::parse("Expected ',' between arguments"));
                }
                self.advance(); // skip comma
                self.skip_whitespace();
            }

            // Try to parse as kwarg first (key=value)
            // Look ahead for = before any comma or interpolation start
            if let Some((key, value_arg)) = self.try_parse_kwarg()? {
                kwargs.insert(key, value_arg);
            } else {
                // Parse as positional argument
                let arg = self.parse_argument()?;
                args.push(arg);
            }
        }

        Ok(Interpolation::Resolver { name, args, kwargs })
    }

    /// Parse a resolver call with a pre-parsed first argument
    /// Used for ${path,kwargs} syntax which becomes ${ref:path,kwargs}
    fn parse_resolver_call_with_first_arg(
        &mut self,
        name: String,
        first_arg: String,
    ) -> Result<Interpolation> {
        let mut args = vec![InterpolationArg::Literal(first_arg)];
        let mut kwargs = HashMap::new();

        // Parse remaining arguments/kwargs separated by commas
        loop {
            self.skip_whitespace();

            if self.current() == Some('}') {
                self.advance();
                break;
            }

            // We already consumed the first comma, expect more args/kwargs
            self.skip_whitespace();

            // Try to parse as kwarg first (key=value)
            if let Some((key, value_arg)) = self.try_parse_kwarg()? {
                kwargs.insert(key, value_arg);
            } else {
                // Parse as positional argument
                let arg = self.parse_argument()?;
                args.push(arg);
            }

            self.skip_whitespace();

            // Check for comma or end
            match self.current() {
                Some(',') => {
                    self.advance();
                    continue;
                }
                Some('}') => {
                    // Will be handled at start of loop
                    continue;
                }
                Some(c) => {
                    return Err(Error::parse(format!(
                        "Expected ',' or '}}' but found '{}'",
                        c
                    )));
                }
                None => {
                    return Err(Error::parse("Unexpected end of input in interpolation"));
                }
            }
        }

        Ok(Interpolation::Resolver { name, args, kwargs })
    }

    /// Try to parse a kwarg (key=value pattern)
    /// Returns Some((key, value)) if successful, None if this isn't a kwarg
    fn try_parse_kwarg(&mut self) -> Result<Option<(String, InterpolationArg)>> {
        // Save position for backtracking
        let start_pos = self.pos;

        // Try to collect an identifier followed by =
        let mut key = String::new();
        while !self.is_eof() {
            match self.current() {
                Some(c) if c.is_alphanumeric() || c == '_' => {
                    key.push(c);
                    self.advance();
                }
                Some('=') if !key.is_empty() => {
                    // Found key=, now parse the value
                    self.advance(); // skip =
                    let value = self.parse_argument()?;
                    return Ok(Some((key, value)));
                }
                _ => {
                    // Not a kwarg pattern, backtrack
                    self.pos = start_pos;
                    return Ok(None);
                }
            }
        }

        // Reached EOF without finding =, backtrack
        self.pos = start_pos;
        Ok(None)
    }

    /// Parse a single argument (may be literal or nested interpolation)
    fn parse_argument(&mut self) -> Result<InterpolationArg> {
        self.skip_whitespace();

        if self.check_interpolation_start() {
            // Nested interpolation
            let nested = self.parse_interpolation()?;
            Ok(InterpolationArg::Nested(Box::new(nested)))
        } else {
            // Literal argument - collect until , or }
            let mut value = String::new();
            let mut depth = 0; // Track nested braces

            while !self.is_eof() {
                match self.current() {
                    Some('$') if self.peek() == Some('{') => {
                        // Nested interpolation - parse it
                        let nested = self.parse_interpolation()?;
                        return Ok(InterpolationArg::Nested(Box::new(if value.is_empty() {
                            nested
                        } else {
                            // Concatenation: literal prefix + nested
                            Interpolation::Concat(vec![Interpolation::Literal(value), nested])
                        })));
                    }
                    Some('{') => {
                        depth += 1;
                        value.push('{');
                        self.advance();
                    }
                    Some('}') => {
                        if depth == 0 {
                            break;
                        }
                        depth -= 1;
                        value.push('}');
                        self.advance();
                    }
                    Some(',') if depth == 0 => {
                        break;
                    }
                    Some(c) => {
                        value.push(c);
                        self.advance();
                    }
                    None => break,
                }
            }

            Ok(InterpolationArg::Literal(value.trim().to_string()))
        }
    }

    /// Collect an identifier (alphanumeric, _, ., [, ])
    fn collect_identifier(&mut self) -> String {
        let mut result = String::new();

        while !self.is_eof() {
            match self.current() {
                Some(c) if c.is_alphanumeric() || c == '_' || c == '.' || c == '[' || c == ']' => {
                    result.push(c);
                    self.advance();
                }
                _ => break,
            }
        }

        result
    }

    /// Skip whitespace characters
    fn skip_whitespace(&mut self) {
        while let Some(c) = self.current() {
            if c.is_whitespace() {
                self.advance();
            } else {
                break;
            }
        }
    }
}

/// Merge adjacent literal parts
fn merge_adjacent_literals(parts: Vec<Interpolation>) -> Vec<Interpolation> {
    let mut result = Vec::new();
    let mut current_literal = String::new();

    for part in parts {
        match part {
            Interpolation::Literal(s) => {
                current_literal.push_str(&s);
            }
            other => {
                if !current_literal.is_empty() {
                    result.push(Interpolation::Literal(current_literal));
                    current_literal = String::new();
                }
                result.push(other);
            }
        }
    }

    if !current_literal.is_empty() {
        result.push(Interpolation::Literal(current_literal));
    }

    result
}

/// Parse an interpolation string
pub fn parse(input: &str) -> Result<Interpolation> {
    InterpolationParser::new(input).parse()
}

/// Check if a string contains any interpolation expressions (unescaped ${...})
pub fn contains_interpolation(input: &str) -> bool {
    let mut chars = input.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\\' {
            // Skip escaped characters
            chars.next();
        } else if c == '$' && chars.peek() == Some(&'{') {
            return true;
        }
    }

    false
}

/// Check if a string needs processing (has interpolations OR escape sequences)
pub fn needs_processing(input: &str) -> bool {
    let mut chars = input.chars().peekable();

    while let Some(c) = chars.next() {
        if c == '\\' && chars.peek() == Some(&'$') {
            // Has an escape sequence
            return true;
        } else if c == '$' && chars.peek() == Some(&'{') {
            // Has an interpolation
            return true;
        }
    }

    false
}

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

    #[test]
    fn test_parse_literal() {
        let result = parse("hello world").unwrap();
        assert_eq!(result, Interpolation::Literal("hello world".into()));
    }

    #[test]
    fn test_parse_empty() {
        let result = parse("").unwrap();
        assert_eq!(result, Interpolation::Literal("".into()));
    }

    #[test]
    fn test_parse_env_resolver() {
        let result = parse("${env:MY_VAR}").unwrap();
        assert_eq!(
            result,
            Interpolation::Resolver {
                name: "env".into(),
                args: vec![InterpolationArg::Literal("MY_VAR".into())],
                kwargs: HashMap::new(),
            }
        );
    }

    #[test]
    fn test_parse_env_with_default() {
        let result = parse("${env:MY_VAR,default_value}").unwrap();
        assert_eq!(
            result,
            Interpolation::Resolver {
                name: "env".into(),
                args: vec![
                    InterpolationArg::Literal("MY_VAR".into()),
                    InterpolationArg::Literal("default_value".into()),
                ],
                kwargs: HashMap::new(),
            }
        );
    }

    #[test]
    fn test_parse_self_reference() {
        let result = parse("${database.host}").unwrap();
        // Non-relative self-references are now converted to ref resolver
        assert_eq!(
            result,
            Interpolation::Resolver {
                name: "ref".into(),
                args: vec![InterpolationArg::Literal("database.host".into())],
                kwargs: HashMap::new(),
            }
        );
    }

    #[test]
    fn test_parse_self_reference_with_default() {
        let result = parse("${database.host,default=fallback}").unwrap();
        // Self-references with kwargs converted to ref resolver
        if let Interpolation::Resolver { name, args, kwargs } = result {
            assert_eq!(name, "ref");
            assert_eq!(args.len(), 1);
            assert_eq!(args[0].as_literal(), Some("database.host"));
            assert_eq!(kwargs.len(), 1);
            assert!(kwargs.contains_key("default"));
            assert_eq!(
                kwargs.get("default").and_then(|v| v.as_literal()),
                Some("fallback")
            );
        } else {
            panic!("Expected Resolver");
        }
    }

    #[test]
    fn test_parse_relative_self_reference() {
        let result = parse("${.sibling}").unwrap();
        // The path includes the leading dot(s) for relative references
        assert_eq!(
            result,
            Interpolation::SelfRef {
                path: ".sibling".into(),
                relative: true,
            }
        );
    }

    #[test]
    fn test_parse_array_access() {
        let result = parse("${servers[0].host}").unwrap();
        // Non-relative paths are now converted to ref resolver
        assert_eq!(
            result,
            Interpolation::Resolver {
                name: "ref".into(),
                args: vec![InterpolationArg::Literal("servers[0].host".into())],
                kwargs: HashMap::new(),
            }
        );
    }

    #[test]
    fn test_parse_escaped() {
        let result = parse(r"\${not_interpolated}").unwrap();
        assert_eq!(result, Interpolation::Literal("${not_interpolated}".into()));
    }

    #[test]
    fn test_parse_concatenation() {
        let result = parse("prefix_${env:VAR}_suffix").unwrap();
        assert!(matches!(result, Interpolation::Concat(_)));

        if let Interpolation::Concat(parts) = result {
            assert_eq!(parts.len(), 3);
            assert_eq!(parts[0], Interpolation::Literal("prefix_".into()));
            assert!(matches!(parts[1], Interpolation::Resolver { .. }));
            assert_eq!(parts[2], Interpolation::Literal("_suffix".into()));
        }
    }

    #[test]
    fn test_parse_nested_interpolation() {
        let result = parse("${env:VAR,${env:DEFAULT,fallback}}").unwrap();

        if let Interpolation::Resolver { name, args, .. } = result {
            assert_eq!(name, "env");
            assert_eq!(args.len(), 2);
            assert!(matches!(args[0], InterpolationArg::Literal(_)));
            assert!(matches!(args[1], InterpolationArg::Nested(_)));
        } else {
            panic!("Expected Resolver, got {:?}", result);
        }
    }

    #[test]
    fn test_parse_kwargs() {
        let result = parse("${file:./config.yaml,parse=text}").unwrap();

        if let Interpolation::Resolver { kwargs, .. } = result {
            assert!(kwargs.contains_key("parse"));
            if let Some(InterpolationArg::Literal(value)) = kwargs.get("parse") {
                assert_eq!(value, "text");
            } else {
                panic!("Expected literal value for parse kwarg");
            }
        } else {
            panic!("Expected Resolver");
        }
    }

    #[test]
    fn test_contains_interpolation() {
        assert!(contains_interpolation("${env:VAR}"));
        assert!(contains_interpolation("prefix ${env:VAR} suffix"));
        assert!(!contains_interpolation("no interpolation"));
        assert!(!contains_interpolation(r"\${escaped}"));
        assert!(!contains_interpolation("just $dollar"));
    }

    #[test]
    fn test_parse_unclosed_interpolation() {
        let result = parse("${env:VAR");
        assert!(result.is_err());
    }

    // Edge case tests for improved coverage

    #[test]
    fn test_parse_empty_interpolation() {
        let result = parse("${}");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Empty"));
    }

    #[test]
    fn test_parse_resolver_no_args() {
        // Resolver with colon but no args - returns empty arg list
        let result = parse("${env:}").unwrap();
        if let Interpolation::Resolver { name, args, .. } = result {
            assert_eq!(name, "env");
            // Empty resolver has no args (or one empty arg depending on implementation)
            // The current behavior returns an empty arg list
            assert!(
                args.is_empty()
                    || (args.len() == 1 && args[0] == InterpolationArg::Literal("".into()))
            );
        } else {
            panic!("Expected Resolver");
        }
    }

    #[test]
    fn test_parse_whitespace_in_interpolation() {
        let result = parse("${ env:VAR }").unwrap();
        if let Interpolation::Resolver { name, .. } = result {
            assert_eq!(name, "env");
        } else {
            panic!("Expected Resolver");
        }
    }

    #[test]
    fn test_parse_multiple_escapes() {
        let result = parse(r"\${first}\${second}").unwrap();
        assert_eq!(result, Interpolation::Literal("${first}${second}".into()));
    }

    #[test]
    fn test_parse_interpolation_at_start() {
        let result = parse("${env:VAR}suffix").unwrap();
        if let Interpolation::Concat(parts) = result {
            assert_eq!(parts.len(), 2);
            assert!(matches!(parts[0], Interpolation::Resolver { .. }));
            assert_eq!(parts[1], Interpolation::Literal("suffix".into()));
        } else {
            panic!("Expected Concat");
        }
    }

    #[test]
    fn test_parse_interpolation_at_end() {
        let result = parse("prefix${env:VAR}").unwrap();
        if let Interpolation::Concat(parts) = result {
            assert_eq!(parts.len(), 2);
            assert_eq!(parts[0], Interpolation::Literal("prefix".into()));
            assert!(matches!(parts[1], Interpolation::Resolver { .. }));
        } else {
            panic!("Expected Concat");
        }
    }

    #[test]
    fn test_parse_adjacent_interpolations() {
        let result = parse("${env:A}${env:B}").unwrap();
        if let Interpolation::Concat(parts) = result {
            assert_eq!(parts.len(), 2);
            assert!(matches!(parts[0], Interpolation::Resolver { .. }));
            assert!(matches!(parts[1], Interpolation::Resolver { .. }));
        } else {
            panic!("Expected Concat");
        }
    }

    #[test]
    fn test_parse_deeply_nested_path() {
        let result = parse("${a.b.c.d.e.f.g.h}").unwrap();
        // Non-relative paths now become ref resolver
        if let Interpolation::Resolver { name, args, .. } = result {
            assert_eq!(name, "ref");
            assert_eq!(args.len(), 1);
            assert_eq!(args[0].as_literal(), Some("a.b.c.d.e.f.g.h"));
        } else {
            panic!("Expected Resolver");
        }
    }

    #[test]
    fn test_parse_multiple_array_indices() {
        let result = parse("${matrix[0][1][2]}").unwrap();
        // Non-relative paths now become ref resolver
        if let Interpolation::Resolver { name, args, .. } = result {
            assert_eq!(name, "ref");
            assert_eq!(args[0].as_literal(), Some("matrix[0][1][2]"));
        } else {
            panic!("Expected Resolver");
        }
    }

    #[test]
    fn test_parse_mixed_path_and_array() {
        let result = parse("${data.items[0].nested[1].value}").unwrap();
        // Non-relative paths now become ref resolver
        if let Interpolation::Resolver { name, args, .. } = result {
            assert_eq!(name, "ref");
            assert_eq!(args[0].as_literal(), Some("data.items[0].nested[1].value"));
        } else {
            panic!("Expected Resolver");
        }
    }

    #[test]
    fn test_parse_underscore_in_identifiers() {
        let result = parse("${my_var.some_path}").unwrap();
        // Non-relative paths now become ref resolver
        if let Interpolation::Resolver { name, args, .. } = result {
            assert_eq!(name, "ref");
            assert_eq!(args[0].as_literal(), Some("my_var.some_path"));
        } else {
            panic!("Expected Resolver");
        }
    }

    #[test]
    fn test_parse_resolver_with_multiple_args() {
        let result = parse("${resolver:arg1,arg2,arg3}").unwrap();
        if let Interpolation::Resolver { name, args, .. } = result {
            assert_eq!(name, "resolver");
            assert_eq!(args.len(), 3);
        } else {
            panic!("Expected Resolver");
        }
    }

    #[test]
    fn test_parse_mixed_escaped_and_interpolation() {
        let result = parse(r"literal \${escaped} ${env:VAR} more").unwrap();
        if let Interpolation::Concat(parts) = result {
            assert!(parts.len() >= 3);
        } else {
            panic!("Expected Concat");
        }
    }

    #[test]
    fn test_needs_processing() {
        assert!(needs_processing("${env:VAR}"));
        assert!(needs_processing(r"\${escaped}"));
        assert!(!needs_processing("no special chars"));
        assert!(!needs_processing("just $dollar"));
    }

    #[test]
    fn test_parse_invalid_char_in_path() {
        let result = parse("${path!invalid}");
        assert!(result.is_err());
    }

    #[test]
    fn test_interpolation_arg_methods() {
        let lit = InterpolationArg::Literal("test".into());
        assert!(lit.is_literal());
        assert_eq!(lit.as_literal(), Some("test"));

        let nested = InterpolationArg::Nested(Box::new(Interpolation::Literal("x".into())));
        assert!(!nested.is_literal());
        assert_eq!(nested.as_literal(), None);
    }

    #[test]
    fn test_parse_relative_parent_reference() {
        let result = parse("${..parent.value}").unwrap();
        if let Interpolation::SelfRef { path, relative } = result {
            assert!(relative);
            assert_eq!(path, "..parent.value");
        } else {
            panic!("Expected relative SelfRef");
        }
    }
}