substrait-explain 0.3.2

Explain Substrait plans as human-readable text.
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
use std::fmt;
use std::str::FromStr;

use thiserror::Error;

use super::{ParsePair, Rule, RuleIter, unescape_string, unwrap_single_pair};
use crate::extensions::registry::ExtensionType;
use crate::extensions::simple::{self, ExtensionKind};
use crate::extensions::{
    ExtensionArgs, ExtensionColumn, ExtensionRelationType, ExtensionValue, InsertError,
    RawExpression, SimpleExtensions, TupleValue,
};
use crate::parser::structural::IndentedLine;

#[derive(Debug, Clone, Error)]
pub enum ExtensionParseError {
    #[error("Unexpected line, expected {0}")]
    UnexpectedLine(ExtensionParserState),
    #[error("Error adding extension: {0}")]
    ExtensionError(#[from] InsertError),
    #[error("Error parsing message: {0}")]
    Message(#[from] super::MessageParseError),
}

/// The state of the extension parser - tracking what section of extension
/// parsing we are in.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExtensionParserState {
    // The extensions section, after parsing the 'Extensions:' header, before
    // parsing any subsection headers.
    Extensions,
    // The extension URNs section, after parsing the 'URNs:' subsection header,
    // and any URNs so far.
    ExtensionUrns,
    // In a subsection, after parsing the subsection header, and any
    // declarations so far.
    ExtensionDeclarations(ExtensionKind),
}

impl fmt::Display for ExtensionParserState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ExtensionParserState::Extensions => write!(f, "Subsection Header, e.g. 'URNs:'"),
            ExtensionParserState::ExtensionUrns => write!(f, "Extension URNs"),
            ExtensionParserState::ExtensionDeclarations(kind) => {
                write!(f, "Extension Declaration for {kind}")
            }
        }
    }
}

/// The parser for the extension section of the Substrait file format.
///
/// This is responsible for parsing the extension section of the file, which
/// contains the extension URNs and declarations. Note that this parser does not
/// parse the header; otherwise, this is symmetric with the
/// SimpleExtensions::write method.
#[derive(Debug)]
pub struct ExtensionParser {
    state: ExtensionParserState,
    extensions: SimpleExtensions,
}

impl Default for ExtensionParser {
    fn default() -> Self {
        Self {
            state: ExtensionParserState::Extensions,
            extensions: SimpleExtensions::new(),
        }
    }
}

impl ExtensionParser {
    pub fn parse_line(&mut self, line: IndentedLine) -> Result<(), ExtensionParseError> {
        if line.1.is_empty() {
            // Blank lines are allowed between subsections, so if we see
            // one, we revert out of the subsection.
            self.state = ExtensionParserState::Extensions;
            return Ok(());
        }

        match self.state {
            ExtensionParserState::Extensions => self.parse_subsection(line),
            ExtensionParserState::ExtensionUrns => self.parse_extension_urns(line),
            ExtensionParserState::ExtensionDeclarations(extension_kind) => {
                self.parse_declarations(line, extension_kind)
            }
        }
    }

    fn parse_subsection(&mut self, line: IndentedLine) -> Result<(), ExtensionParseError> {
        match line {
            IndentedLine(0, simple::EXTENSION_URNS_HEADER) => {
                self.state = ExtensionParserState::ExtensionUrns;
                Ok(())
            }
            IndentedLine(0, simple::EXTENSION_FUNCTIONS_HEADER) => {
                self.state = ExtensionParserState::ExtensionDeclarations(ExtensionKind::Function);
                Ok(())
            }
            IndentedLine(0, simple::EXTENSION_TYPES_HEADER) => {
                self.state = ExtensionParserState::ExtensionDeclarations(ExtensionKind::Type);
                Ok(())
            }
            IndentedLine(0, simple::EXTENSION_TYPE_VARIATIONS_HEADER) => {
                self.state =
                    ExtensionParserState::ExtensionDeclarations(ExtensionKind::TypeVariation);
                Ok(())
            }
            _ => Err(ExtensionParseError::UnexpectedLine(self.state)),
        }
    }

    fn parse_extension_urns(&mut self, line: IndentedLine) -> Result<(), ExtensionParseError> {
        match line {
            IndentedLine(0, _s) => self.parse_subsection(line), // Pass the original line with 0 indent
            IndentedLine(1, s) => {
                let urn =
                    URNExtensionDeclaration::from_str(s).map_err(ExtensionParseError::Message)?;
                self.extensions.add_extension_urn(urn.urn, urn.anchor)?;
                Ok(())
            }
            _ => Err(ExtensionParseError::UnexpectedLine(self.state)),
        }
    }

    fn parse_declarations(
        &mut self,
        line: IndentedLine,
        extension_kind: ExtensionKind,
    ) -> Result<(), ExtensionParseError> {
        match line {
            IndentedLine(0, _s) => self.parse_subsection(line), // Pass the original line with 0 indent
            IndentedLine(1, s) => {
                let decl = SimpleExtensionDeclaration::from_str(s)?;
                self.extensions.add_extension(
                    extension_kind,
                    decl.urn_anchor,
                    decl.anchor,
                    decl.name,
                )?;
                Ok(())
            }
            _ => Err(ExtensionParseError::UnexpectedLine(self.state)),
        }
    }

    pub fn extensions(&self) -> &SimpleExtensions {
        &self.extensions
    }

    pub fn state(&self) -> ExtensionParserState {
        self.state
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct URNExtensionDeclaration {
    pub anchor: u32,
    pub urn: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct SimpleExtensionDeclaration {
    pub anchor: u32,
    pub urn_anchor: u32,
    pub name: String,
}

impl ParsePair for URNExtensionDeclaration {
    fn rule() -> Rule {
        Rule::extension_urn_declaration
    }

    fn message() -> &'static str {
        "URNExtensionDeclaration"
    }

    fn parse_pair(pair: pest::iterators::Pair<Rule>) -> Self {
        assert_eq!(pair.as_rule(), Self::rule());

        let mut iter = RuleIter::from(pair.into_inner());
        let anchor_pair = iter.pop(Rule::urn_anchor);
        let anchor = unwrap_single_pair(anchor_pair)
            .as_str()
            .parse::<u32>()
            .unwrap();
        let urn = iter.pop(Rule::urn).as_str().to_string();
        iter.done();

        URNExtensionDeclaration { anchor, urn }
    }
}

impl FromStr for URNExtensionDeclaration {
    type Err = super::MessageParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_str(s)
    }
}

impl ParsePair for SimpleExtensionDeclaration {
    fn rule() -> Rule {
        Rule::simple_extension
    }

    fn message() -> &'static str {
        "SimpleExtensionDeclaration"
    }

    fn parse_pair(pair: pest::iterators::Pair<Rule>) -> Self {
        assert_eq!(pair.as_rule(), Self::rule());
        let mut iter = RuleIter::from(pair.into_inner());
        let anchor_pair = iter.pop(Rule::anchor);
        let anchor = unwrap_single_pair(anchor_pair)
            .as_str()
            .parse::<u32>()
            .unwrap();
        let urn_anchor_pair = iter.pop(Rule::urn_anchor);
        let urn_anchor = unwrap_single_pair(urn_anchor_pair)
            .as_str()
            .parse::<u32>()
            .unwrap();
        // compound_name handles both plain names ("add") and compound names with signatures ("equal:any_any").
        let name_pair = iter.pop(Rule::compound_name);
        let name = name_pair.as_str().to_string();
        iter.done();

        SimpleExtensionDeclaration {
            anchor,
            urn_anchor,
            name,
        }
    }
}

impl FromStr for SimpleExtensionDeclaration {
    type Err = super::MessageParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_str(s)
    }
}

// Extension relation parsing implementations
// These were moved from extensions/registry.rs to maintain clean architecture

use crate::extensions::any::Any;
use crate::parser::expressions::{FieldIndex, Name};

impl ParsePair for ExtensionValue {
    fn rule() -> Rule {
        Rule::extension_argument
    }

    fn message() -> &'static str {
        "ExtensionValue"
    }

    fn parse_pair(pair: pest::iterators::Pair<Rule>) -> Self {
        assert_eq!(pair.as_rule(), Self::rule());

        let inner = unwrap_single_pair(pair); // Extract the actual content

        match inner.as_rule() {
            Rule::enum_value => {
                // Strip leading '&' and store the identifier
                let s = inner.as_str().trim_start_matches('&').to_string();
                ExtensionValue::Enum(s)
            }
            Rule::reference => {
                // Reuse the existing FieldIndex parser, then extract the i32
                let field_index = FieldIndex::parse_pair(inner);
                ExtensionValue::Reference(field_index.0)
            }
            Rule::literal => {
                // Literal can contain integer, float, boolean, or string_literal
                let mut literal_inner = inner.into_inner();
                let value_pair = literal_inner.next().unwrap();
                match value_pair.as_rule() {
                    Rule::string_literal => ExtensionValue::String(unescape_string(value_pair)),
                    Rule::integer => {
                        let int_val = value_pair.as_str().parse::<i64>().unwrap();
                        ExtensionValue::Integer(int_val)
                    }
                    Rule::float => {
                        let float_val = value_pair.as_str().parse::<f64>().unwrap();
                        ExtensionValue::Float(float_val)
                    }
                    Rule::boolean => {
                        let bool_val = value_pair.as_str() == "true";
                        ExtensionValue::Boolean(bool_val)
                    }
                    _ => panic!("Unexpected literal value type: {:?}", value_pair.as_rule()),
                }
            }
            Rule::string_literal => ExtensionValue::String(unescape_string(inner)),
            Rule::integer => {
                // Direct integer (not wrapped in literal rule)
                let int_val = inner.as_str().parse::<i64>().unwrap();
                ExtensionValue::Integer(int_val)
            }
            Rule::float => {
                // Direct float (not wrapped in literal rule)
                let float_val = inner.as_str().parse::<f64>().unwrap();
                ExtensionValue::Float(float_val)
            }
            Rule::boolean => {
                // Direct boolean (not wrapped in literal rule)
                let bool_val = inner.as_str() == "true";
                ExtensionValue::Boolean(bool_val)
            }
            Rule::tuple => {
                let tv = inner
                    .into_inner()
                    .map(ExtensionValue::parse_pair)
                    .collect::<TupleValue>();
                ExtensionValue::Tuple(tv)
            }
            Rule::expression => {
                ExtensionValue::Expression(RawExpression::new(inner.as_str().to_string()))
            }
            _ => panic!("Unexpected extension argument type: {:?}", inner.as_rule()),
        }
    }
}

impl ParsePair for ExtensionColumn {
    fn rule() -> Rule {
        Rule::extension_column
    }

    fn message() -> &'static str {
        "ExtensionColumn"
    }

    fn parse_pair(pair: pest::iterators::Pair<Rule>) -> Self {
        assert_eq!(pair.as_rule(), Self::rule());

        let inner = unwrap_single_pair(pair); // Extract the actual content

        match inner.as_rule() {
            Rule::named_column => {
                let mut iter = inner.into_inner();
                let name_pair = iter.next().unwrap(); // Grammar guarantees name exists
                let type_pair = iter.next().unwrap(); // Grammar guarantees type exists

                let name = Name::parse_pair(name_pair).0.to_string(); // Reuse existing Name parser
                let type_spec = type_pair.as_str().to_string(); // Types are complex, store as string for now

                ExtensionColumn::Named { name, type_spec }
            }
            Rule::reference => {
                // Reuse the existing FieldIndex parser, then extract the i32
                let field_index = FieldIndex::parse_pair(inner);
                ExtensionColumn::Reference(field_index.0)
            }
            Rule::expression => {
                ExtensionColumn::Expression(RawExpression::new(inner.as_str().to_string()))
            }
            _ => panic!("Unexpected extension column type: {:?}", inner.as_rule()),
        }
    }
}

/// Fully parsed extension invocation, including the user-supplied name and the
/// structured argument payload.
#[derive(Debug, Clone)]
pub struct ExtensionInvocation {
    pub name: String,
    pub args: ExtensionArgs,
}

impl ParsePair for ExtensionInvocation {
    fn rule() -> Rule {
        Rule::extension_relation
    }

    fn message() -> &'static str {
        "ExtensionInvocation"
    }

    fn parse_pair(pair: pest::iterators::Pair<Rule>) -> Self {
        assert_eq!(pair.as_rule(), Self::rule());

        let mut iter = pair.into_inner();

        // Parse extension name to determine relation type and custom name
        let extension_name_pair = iter.next().unwrap(); // Grammar guarantees extension_name exists
        let full_extension_name = extension_name_pair.as_str();

        // Extract the relation type and custom name from the extension name
        // (e.g., "ExtensionLeaf:ParquetScan" -> "ExtensionLeaf" and "ParquetScan")
        let (relation_type_str, custom_name) = if full_extension_name.contains(':') {
            let parts: Vec<&str> = full_extension_name.splitn(2, ':').collect();
            (parts[0], parts[1].to_string())
        } else {
            (full_extension_name, "UnknownExtension".to_string())
        };

        let relation_type = ExtensionRelationType::from_str(relation_type_str).unwrap();
        let mut args = ExtensionArgs::new(relation_type);

        // Parse optional arguments
        let ext_arguments = iter.next().unwrap();
        match ext_arguments.as_rule() {
            Rule::arguments => {
                arguments_rule_parsing(ext_arguments, &mut args);
            }
            r => unreachable!("Unexpected rule in ExtensionArgs: {:?}", r),
        }

        // parse optional output columns
        let extension_columns = iter.next();
        if let Some(value) = extension_columns {
            match value.as_rule() {
                Rule::extension_columns => {
                    for col_pair in value.into_inner() {
                        if col_pair.as_rule() == Rule::extension_column {
                            let column = ExtensionColumn::parse_pair(col_pair);
                            args.output_columns.push(column);
                        }
                    }
                }
                r => unreachable!("Unexpected rule in ExtensionArgs: {:?}", r),
            }
        }

        ExtensionInvocation {
            name: custom_name,
            args,
        }
    }
}

/// A parsed `+ Enh:Name[args]` or `+ Opt:Name[args]` line.
#[derive(Debug, Clone)]
pub struct AdvExtInvocation {
    /// Whether this is an enhancement (`ExtensionType::Enhancement`) or
    /// optimization (`ExtensionType::Optimization`).  The grammar restricts
    /// the value to those two variants; `ExtensionType::Relation` will never
    /// appear here.
    pub ext_type: ExtensionType,
    pub name: String,
    pub args: ExtensionArgs,
}

impl ParsePair for AdvExtInvocation {
    fn rule() -> Rule {
        Rule::adv_extension
    }

    fn message() -> &'static str {
        "AdvExtInvocation"
    }

    fn parse_pair(pair: pest::iterators::Pair<Rule>) -> Self {
        assert_eq!(pair.as_rule(), Self::rule());

        let mut iter = pair.into_inner();

        // First token: adv_ext_type — grammar guarantees "Enh" or "Opt"
        let type_pair = iter.next().unwrap(); // Grammar guarantees adv_ext_type exists
        let ext_type = match type_pair.as_str() {
            "Enh" => ExtensionType::Enhancement,
            "Opt" => ExtensionType::Optimization,
            other => unreachable!("Unexpected adv_ext_type: {other}"),
        };

        // Second token: name
        let name_pair = iter.next().unwrap();
        let name = Name::parse_pair(name_pair).0.to_string();

        // Remaining token: arguments — grammar guarantees it is always present
        // Use Leaf as the relation_type placeholder — adv_extensions don't have children
        let mut args = ExtensionArgs::new(crate::extensions::ExtensionRelationType::Leaf);

        let arguments_pair = iter.next().unwrap();
        match arguments_pair.as_rule() {
            Rule::arguments => {
                arguments_rule_parsing(arguments_pair, &mut args);
            }
            r => unreachable!("Unexpected rule in AdvExtInvocation args: {r:?}"),
        }

        AdvExtInvocation {
            ext_type,
            name,
            args,
        }
    }
}

fn arguments_rule_parsing(inner_pair: pest::iterators::Pair<'_, Rule>, args: &mut ExtensionArgs) {
    for arg in inner_pair.into_inner() {
        match arg.as_rule() {
            Rule::extension_arguments => {
                // Parse positional arguments
                for arg_pair in arg.into_inner() {
                    assert_eq!(arg_pair.as_rule(), Rule::extension_argument);
                    args.positional.push(ExtensionValue::parse_pair(arg_pair));
                }
            }
            Rule::extension_named_arguments => {
                for arg_pair in arg.into_inner() {
                    assert_eq!(arg_pair.as_rule(), Rule::extension_named_argument);
                    let mut arg_iter = arg_pair.into_inner();
                    let name_p = arg_iter.next().unwrap();
                    let value_p = arg_iter.next().unwrap();
                    let key = Name::parse_pair(name_p).0.to_string();
                    let val = ExtensionValue::parse_pair(value_p);
                    args.named.insert(key, val);
                }
            }
            Rule::empty => {}
            r => unreachable!("Unexpected rule in extension args: {r:?}"),
        }
    }
}

impl ExtensionRelationType {
    /// Create appropriate relation structure from extension detail and children.
    /// This method handles the structural logic for creating different extension relation types.
    pub fn create_rel(
        self,
        detail: Option<Any>,
        children: Vec<Box<substrait::proto::Rel>>,
    ) -> Result<substrait::proto::Rel, String> {
        use substrait::proto::rel::RelType;
        use substrait::proto::{ExtensionLeafRel, ExtensionMultiRel, ExtensionSingleRel};

        // Validate child count matches relation type
        self.validate_child_count(children.len())?;

        // The output column count is returned alongside the Rel by parse_extension_relation
        // and flows up the parse tree through Rust return values
        let rel_type = match self {
            ExtensionRelationType::Leaf => RelType::ExtensionLeaf(ExtensionLeafRel {
                common: None,
                detail: detail.map(Into::into),
            }),
            ExtensionRelationType::Single => {
                let input = children.into_iter().next().map(|child| *child);
                RelType::ExtensionSingle(Box::new(ExtensionSingleRel {
                    common: None,
                    detail: detail.map(Into::into),
                    input: input.map(Box::new),
                }))
            }
            ExtensionRelationType::Multi => {
                let inputs = children.into_iter().map(|child| *child).collect();
                RelType::ExtensionMulti(ExtensionMultiRel {
                    common: None,
                    detail: detail.map(Into::into),
                    inputs,
                })
            }
        };

        Ok(substrait::proto::Rel {
            rel_type: Some(rel_type),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::extensions::ExtensionValue;
    use crate::fixtures::TestContext;
    use crate::parser::Parser;

    #[test]
    fn test_parse_urn_extension_declaration() {
        let line = "@1: /my/urn1";
        let urn = URNExtensionDeclaration::parse_str(line).unwrap();
        assert_eq!(urn.anchor, 1);
        assert_eq!(urn.urn, "/my/urn1");
    }

    #[test]
    fn test_parse_simple_extension_declaration() {
        // Assumes a format like "@anchor: urn_anchor:name"
        let line = "#5@2: my_function_name";
        let decl = SimpleExtensionDeclaration::from_str(line).unwrap();
        assert_eq!(decl.anchor, 5);
        assert_eq!(decl.urn_anchor, 2);
        assert_eq!(decl.name, "my_function_name");

        // Test with a different name format, e.g. with underscores and numbers
        let line2 = "#10  @200: another_ext_123";
        let decl = SimpleExtensionDeclaration::from_str(line2).unwrap();
        assert_eq!(decl.anchor, 10);
        assert_eq!(decl.urn_anchor, 200);
        assert_eq!(decl.name, "another_ext_123");
    }

    #[test]
    fn test_parse_urn_extension_declaration_str() {
        let line = "@1: /my/urn1";
        let urn = URNExtensionDeclaration::parse_str(line).unwrap();
        assert_eq!(urn.anchor, 1);
        assert_eq!(urn.urn, "/my/urn1");
    }

    #[test]
    fn test_extensions_round_trip_plan() {
        let input = r#"
=== Extensions
URNs:
  @  1: /urn/common
  @  2: /urn/specific_funcs
Functions:
  # 10 @  1: func_a
  # 11 @  2: func_b_special
Types:
  # 20 @  1: SomeType
Type Variations:
  # 30 @  2: VarX
"#
        .trim_start();

        // Parse the input using the structural parser
        let plan = Parser::parse(input).unwrap();

        // Verify the plan has the expected extensions
        assert_eq!(plan.extension_urns.len(), 2);
        assert_eq!(plan.extensions.len(), 4);

        // Convert the plan extensions back to SimpleExtensions
        let (extensions, errors) =
            SimpleExtensions::from_extensions(&plan.extension_urns, &plan.extensions);

        assert!(errors.is_empty());
        // Convert back to string
        let output = extensions.to_string("  ");

        // The output should match the input
        assert_eq!(output, input);
    }

    #[test]
    fn test_parse_simple_extension_declaration_compound_name() {
        // A function name that includes a Substrait signature suffix
        let line = "#1 @2: equal:any_any";
        let decl = SimpleExtensionDeclaration::from_str(line).unwrap();
        assert_eq!(decl.anchor, 1);
        assert_eq!(decl.urn_anchor, 2);
        assert_eq!(decl.name, "equal:any_any");
    }

    #[test]
    fn test_parse_simple_extension_declaration_compound_name_multi_segment() {
        let line = "#3 @1: regexp_match_substring:str_str_i64";
        let decl = SimpleExtensionDeclaration::from_str(line).unwrap();
        assert_eq!(decl.anchor, 3);
        assert_eq!(decl.urn_anchor, 1);
        assert_eq!(decl.name, "regexp_match_substring:str_str_i64");
    }

    #[test]
    fn test_extensions_round_trip_plan_with_compound_names() {
        let input = r#"=== Extensions
URNs:
  @  1: extension:io.substrait:functions_string
  @  2: extension:io.substrait:functions_comparison
Functions:
  #  1 @  2: equal:any_any
  #  2 @  1: regexp_match_substring:str_str
  #  3 @  1: regexp_match_substring:str_str_i64
"#;
        let plan = Parser::parse(input).unwrap();
        let (extensions, errors) =
            SimpleExtensions::from_extensions(&plan.extension_urns, &plan.extensions);
        assert!(errors.is_empty());
        // Compound names must survive the roundtrip
        assert_eq!(
            extensions
                .find_by_anchor(crate::extensions::simple::ExtensionKind::Function, 1)
                .unwrap()
                .1
                .full(),
            "equal:any_any"
        );
        assert_eq!(
            extensions
                .find_by_anchor(crate::extensions::simple::ExtensionKind::Function, 3)
                .unwrap()
                .1
                .full(),
            "regexp_match_substring:str_str_i64"
        );
        // Text output must reproduce the input exactly
        assert_eq!(extensions.to_string("  "), input);
    }

    #[test]
    fn test_tuple_mixed_types_parses() {
        // tuple has overlapping grammar syntax with expression.
        let val = ExtensionValue::parse_str("(&HASH, 8, 'hello')").unwrap();
        let ExtensionValue::Tuple(items) = val else {
            panic!("expected Tuple, got {val:?}");
        };
        assert_eq!(items.len(), 3);
        let items: Vec<&ExtensionValue> = items.iter().collect();
        assert!(matches!(items[0], ExtensionValue::Enum(s) if s == "HASH"));
        assert!(matches!(items[1], ExtensionValue::Integer(8)));
        assert!(matches!(items[2], ExtensionValue::String(s) if s == "hello"));
    }

    #[test]
    fn test_empty_tuple_parses() {
        let val = ExtensionValue::parse_str("()").unwrap();
        let ExtensionValue::Tuple(items) = val else {
            panic!("expected Tuple, got {val:?}");
        };
        assert!(items.is_empty());
    }

    #[test]
    fn test_nested_tuple_parses() {
        let val = ExtensionValue::parse_str("((&HASH, &RANGE), 8)").unwrap();
        let ExtensionValue::Tuple(outer) = val else {
            panic!("expected Tuple, got {val:?}");
        };
        assert_eq!(outer.len(), 2);
        let ExtensionValue::Tuple(inner) = outer.iter().next().unwrap() else {
            panic!("expected inner Tuple");
        };
        assert_eq!(inner.len(), 2);
        assert!(matches!(inner.iter().next().unwrap(), ExtensionValue::Enum(s) if s == "HASH"));
        assert!(matches!(
            outer.iter().nth(1).unwrap(),
            ExtensionValue::Integer(8)
        ));
    }

    #[test]
    fn test_tuple_in_adv_extension_parses() {
        let inv = AdvExtInvocation::parse_str("+ Enh:Foo[(&HASH, &RANGE), count=8]").unwrap();
        assert_eq!(inv.name, "Foo");
        assert_eq!(inv.args.positional.len(), 1);
        let ExtensionValue::Tuple(items) = &inv.args.positional[0] else {
            panic!("expected Tuple positional arg");
        };
        assert_eq!(items.len(), 2);
        let items: Vec<&ExtensionValue> = items.iter().collect();
        assert!(matches!(items[0], ExtensionValue::Enum(s) if s == "HASH"));
        assert!(matches!(items[1], ExtensionValue::Enum(s) if s == "RANGE"));
        assert_eq!(inv.args.named.len(), 1);
    }

    #[test]
    fn test_tuple_textify_roundtrip() {
        let ctx = TestContext::new();
        for text in &[
            "(&HASH, &RANGE)",
            "(&HASH, 8, 'hello')",
            "()",
            "(&HASH,)",
            "((&HASH, &RANGE), 8)",
        ] {
            let val = ExtensionValue::parse_str(text).unwrap();
            let rendered = ctx.textify_no_errors(&val);
            assert_eq!(&rendered, text, "roundtrip failed for {text}");
        }
    }
}