telltale-language 11.3.0

Shared choreography frontend for Telltale DSL parsing, projection, and macro code generation
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
//! DSL Extension System for Telltale
//!
//! This module provides a clean, composable system for extending choreographic DSL syntax.
//! Extensions can add new grammar rules, custom statement parsers, and protocol behaviors
//! while maintaining compatibility with the core choreographic infrastructure.

use crate::ast::{LocalType, Role};
use crate::compiler::projection::ProjectionError;
use std::any::{Any, TypeId};
use std::collections::BTreeMap;
use std::fmt::Debug;

/// Documentation for an extension
#[derive(Debug, Clone)]
pub struct ExtensionDocumentation {
    pub overview: String,
    pub syntax_guide: String,
    pub use_cases: Vec<String>,
    pub limitations: Vec<String>,
    pub see_also: Vec<String>,
}

impl Default for ExtensionDocumentation {
    fn default() -> Self {
        Self {
            overview: "No documentation provided".to_string(),
            syntax_guide: "No syntax guide provided".to_string(),
            use_cases: vec![],
            limitations: vec![],
            see_also: vec![],
        }
    }
}

/// Example usage for an extension
#[derive(Debug, Clone)]
pub struct ExtensionExample {
    pub title: String,
    pub description: String,
    pub code: String,
    pub expected_output: Option<String>,
}

/// Trait for adding new grammar rules to the choreographic DSL
pub trait GrammarExtension: Send + Sync + Debug {
    /// Return the Pest grammar rules this extension provides
    fn grammar_rules(&self) -> &'static str;

    /// List of statement rule names this extension handles
    fn statement_rules(&self) -> Vec<&'static str>;

    /// Priority for conflict resolution (higher = more precedence)
    fn priority(&self) -> u32 {
        100
    }

    /// Extension identifier for debugging and registration
    fn extension_id(&self) -> &'static str;
}

/// Trait for self-documenting extensions
pub trait DocumentedGrammarExtension: GrammarExtension {
    /// Documentation for this extension
    fn documentation(&self) -> ExtensionDocumentation {
        ExtensionDocumentation::default()
    }

    /// Examples showing how to use this extension
    fn examples(&self) -> Vec<ExtensionExample> {
        vec![]
    }

    /// Grammar rules with human-readable descriptions
    fn rule_descriptions(&self) -> std::collections::HashMap<String, String> {
        std::collections::HashMap::new()
    }
}

/// Trait for parsing custom protocol statements
pub trait StatementParser: Send + Sync + Debug {
    /// Check if this parser can handle the given rule name
    fn can_parse(&self, rule_name: &str) -> bool;

    /// Return all rules this parser supports
    fn supported_rules(&self) -> Vec<String>;

    /// Parse a statement into a protocol extension
    ///
    /// # Arguments
    /// * `rule_name` - The grammar rule name being parsed
    /// * `content` - The matched content as a string
    /// * `context` - Parsing context with declared roles
    ///
    /// # Returns
    /// A boxed protocol extension representing the parsed statement
    fn parse_statement(
        &self,
        rule_name: &str,
        content: &str,
        context: &ParseContext,
    ) -> Result<Box<dyn ProtocolExtension>, ParseError>;
}

/// Trait for custom protocol behaviors that can be projected and validated
pub trait ProtocolExtension: Send + Sync + Debug {
    /// Unique identifier for this protocol extension type
    fn type_name(&self) -> &'static str;

    /// Check if this protocol mentions a specific role
    fn mentions_role(&self, role: &Role) -> bool;

    /// Validate this protocol against declared roles
    fn validate(&self, roles: &[Role]) -> Result<(), ExtensionValidationError>;

    /// Project this protocol to a local type for a specific role
    fn project(
        &self,
        role: &Role,
        context: &ProjectionContext,
    ) -> Result<LocalType, ProjectionError>;

    /// Generate code for this protocol extension
    fn generate_code(&self, context: &CodegenContext) -> proc_macro2::TokenStream;

    /// For trait object safety and downcasting
    fn as_any(&self) -> &dyn Any;
    fn as_any_mut(&mut self) -> &mut dyn Any;
    fn type_id(&self) -> TypeId;
    fn clone_box(&self) -> Box<dyn ProtocolExtension>;
}

impl Clone for Box<dyn ProtocolExtension> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

/// Registry for managing DSL extensions with conflict resolution
#[derive(Debug, Default)]
pub struct ExtensionRegistry {
    grammar_extensions: BTreeMap<String, Box<dyn GrammarExtension>>,
    statement_parsers: BTreeMap<String, Box<dyn StatementParser>>,
    rule_to_parser: BTreeMap<String, String>,
    /// Track rule conflicts for resolution
    rule_conflicts: BTreeMap<String, Vec<String>>,
    /// Extension dependencies
    extension_dependencies: BTreeMap<String, Vec<String>>,
    /// Extension version information for compatibility checking
    extension_versions: BTreeMap<String, String>,
}

impl ExtensionRegistry {
    /// Create a new empty extension registry
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a grammar extension with conflict detection
    pub fn register_grammar<T: GrammarExtension + 'static>(
        &mut self,
        extension: T,
    ) -> Result<(), ParseError> {
        let id = extension.extension_id().to_string();
        let rules = extension.statement_rules();
        let priority = extension.priority();

        // Check for conflicts and resolve by priority
        for rule in &rules {
            if let Some(existing_id) = self.rule_to_parser.get(*rule) {
                let existing_priority = self
                    .grammar_extensions
                    .get(existing_id)
                    .map(|e| e.priority())
                    .unwrap_or(0);

                if priority > existing_priority {
                    // New extension wins, record conflict
                    self.rule_conflicts
                        .entry((*rule).to_string())
                        .or_default()
                        .push(existing_id.clone());
                    self.rule_to_parser.insert((*rule).to_string(), id.clone());
                } else if priority == existing_priority {
                    // Equal priority - this is a conflict
                    return Err(ParseError::PriorityConflict {
                        extension1: existing_id.clone(),
                        extension2: id.clone(),
                        priority1: existing_priority,
                        priority2: priority,
                        rule: (*rule).to_string(),
                    });
                }
                // Lower priority - existing extension wins
            } else {
                self.rule_to_parser.insert((*rule).to_string(), id.clone());
            }
        }

        self.grammar_extensions
            .insert(id.clone(), Box::new(extension));
        // Set default version if not specified
        self.extension_versions
            .entry(id)
            .or_insert_with(|| "0.1.0".to_string());
        Ok(())
    }

    /// Register a statement parser
    pub fn register_parser<T: StatementParser + 'static>(&mut self, parser: T, parser_id: String) {
        self.statement_parsers.insert(parser_id, Box::new(parser));
    }

    /// Get all grammar rules from registered extensions
    pub fn compose_grammar(&self, base_grammar: &str) -> String {
        let mut composed = base_grammar.to_string();

        // Sort extensions by priority (highest first)
        let mut extensions: Vec<_> = self.grammar_extensions.iter().collect();
        extensions.sort_by(|(id_a, ext_a), (id_b, ext_b)| {
            std::cmp::Reverse(ext_a.priority())
                .cmp(&std::cmp::Reverse(ext_b.priority()))
                .then_with(|| id_a.cmp(id_b))
        });

        for (_, extension) in extensions {
            composed.push('\n');
            composed.push_str(extension.grammar_rules());
        }

        composed
    }

    /// Find parser for a given rule name
    pub fn find_parser(&self, rule_name: &str) -> Option<&dyn StatementParser> {
        if let Some(parser_id) = self.rule_to_parser.get(rule_name) {
            self.statement_parsers.get(parser_id).map(|p| p.as_ref())
        } else {
            None
        }
    }

    /// Check if a rule is handled by an extension
    pub fn can_handle(&self, rule_name: &str) -> bool {
        self.rule_to_parser.contains_key(rule_name)
    }

    /// Check if any extensions are registered
    pub fn has_extensions(&self) -> bool {
        !self.grammar_extensions.is_empty() || !self.statement_parsers.is_empty()
    }

    /// Get all grammar extensions
    pub fn grammar_extensions(&self) -> impl Iterator<Item = &dyn GrammarExtension> {
        let mut ordered: Vec<_> = self.grammar_extensions.iter().collect();
        ordered.sort_by(|(id_a, _), (id_b, _)| id_a.cmp(id_b));
        ordered.into_iter().map(|(_, e)| e.as_ref())
    }

    /// Check if a specific extension is registered
    pub fn has_extension(&self, extension_id: &str) -> bool {
        self.grammar_extensions.contains_key(extension_id)
    }

    /// Get parser for a rule name
    pub fn get_parser_for_rule(&self, rule_name: &str) -> Option<&str> {
        self.rule_to_parser.get(rule_name).map(String::as_str)
    }

    /// Get statement parser by ID
    pub fn get_statement_parser(&self, parser_id: &str) -> Option<&dyn StatementParser> {
        self.statement_parsers.get(parser_id).map(|p| p.as_ref())
    }

    /// Get the number of registered statement parsers.
    pub fn statement_parser_count(&self) -> usize {
        self.statement_parsers.len()
    }

    /// Get the registered extension statement rules in stable order.
    pub fn statement_rules(&self) -> Vec<&str> {
        let mut rules: Vec<_> = self.rule_to_parser.keys().map(String::as_str).collect();
        rules.sort_unstable();
        rules
    }

    /// Add dependency between extensions
    pub fn add_dependency(&mut self, dependent: &str, required: &str) {
        self.extension_dependencies
            .entry(dependent.to_string())
            .or_default()
            .push(required.to_string());
    }

    /// Validate all extension dependencies are satisfied
    pub fn validate_dependencies(&self) -> Result<(), ParseError> {
        for (dependent, requirements) in &self.extension_dependencies {
            for required in requirements {
                if !self.grammar_extensions.contains_key(required) {
                    return Err(ParseError::MissingDependency {
                        extension: dependent.clone(),
                        dependency: required.clone(),
                    });
                }
            }
        }
        Ok(())
    }

    /// Get all rule conflicts for debugging
    pub fn get_conflicts(&self) -> &BTreeMap<String, Vec<String>> {
        &self.rule_conflicts
    }

    /// Get detailed conflict information with resolution suggestions
    pub fn get_detailed_conflicts(&self) -> Vec<String> {
        let mut details = Vec::new();
        let unknown_ext = "unknown".to_string();

        let mut conflicts: Vec<_> = self.rule_conflicts.iter().collect();
        conflicts.sort_by(|(rule_a, _), (rule_b, _)| rule_a.cmp(rule_b));

        for (rule, conflicting_extensions) in conflicts {
            if !conflicting_extensions.is_empty() {
                let active_extension = self.rule_to_parser.get(rule).unwrap_or(&unknown_ext);
                let active_priority = self
                    .grammar_extensions
                    .get(active_extension)
                    .map(|e| e.priority())
                    .unwrap_or(0);

                let mut conflicting_extensions = conflicting_extensions.clone();
                conflicting_extensions.sort();

                for conflicting in &conflicting_extensions {
                    let conflicting_priority = self
                        .grammar_extensions
                        .get(conflicting)
                        .map(|e| e.priority())
                        .unwrap_or(0);

                    details.push(format!(
                        "Rule '{}': Extension '{}' (priority {}) overrode '{}' (priority {}). \
                         To resolve: 1) Adjust priorities, 2) Use different rule names, or 3) Merge functionality.",
                        rule, active_extension, active_priority, conflicting, conflicting_priority
                    ));
                }
            }
        }

        details
    }

    /// Check extension compatibility
    pub fn check_compatibility(&self, extension_ids: &[&str]) -> Result<(), ParseError> {
        // Check for direct conflicts between the specified extensions
        let mut rules_used = BTreeMap::new();

        for &extension_id in extension_ids {
            if let Some(extension) = self.grammar_extensions.get(extension_id) {
                for rule in extension.statement_rules() {
                    if let Some(existing) = rules_used.get(rule) {
                        if existing != &extension_id {
                            return Err(ParseError::IncompatibleExtensions {
                                details: format!(
                                    "Extensions '{}' and '{}' both define rule '{}'. Use different rule names or register extensions with different priorities.",
                                    existing, extension_id, rule
                                ),
                            });
                        }
                    }
                    rules_used.insert(rule.to_string(), extension_id);
                }
            }
        }
        Ok(())
    }

    /// Create a registry with built-in extensions
    pub fn with_builtin_extensions() -> Self {
        let mut registry = Self::new();

        // Register timeout extension
        registry
            .register_grammar(timeout::TimeoutGrammarExtension)
            .expect("builtin timeout extension should register successfully");
        registry.register_parser(timeout::TimeoutStatementParser, "timeout".to_string());

        registry
    }

    /// Create a minimal registry for 3rd party integration
    pub fn for_third_party() -> Self {
        Self::new()
    }

    /// Generate basic documentation for all registered extensions
    pub fn generate_docs(&self) -> String {
        let mut docs = String::from("# Extension Documentation\n\n");

        let mut entries: Vec<_> = self.grammar_extensions.iter().collect();
        entries.sort_by(|(id_a, _), (id_b, _)| id_a.cmp(id_b));

        for (id, extension) in entries {
            docs.push_str(&format!("## {}\n\n", id));
            docs.push_str(&format!("**Priority:** {}\n\n", extension.priority()));
            docs.push_str(&format!(
                "**Rules:** {}\n\n",
                extension.statement_rules().join(", ")
            ));

            if let Some(version) = self.extension_versions.get(id) {
                docs.push_str(&format!("**Version:** {}\n\n", version));
            }

            docs.push_str("**Grammar:**\n```\n");
            docs.push_str(extension.grammar_rules());
            docs.push_str("\n```\n\n");
        }

        docs
    }
}

/// Context provided during statement parsing
#[derive(Debug)]
pub struct ParseContext<'a> {
    /// Roles declared in the choreography
    pub declared_roles: &'a [Role],
    /// Original input string for error reporting
    pub input: &'a str,
}

/// Context provided during projection
#[derive(Debug)]
pub struct ProjectionContext<'a> {
    /// All roles in the choreography
    pub all_roles: &'a [Role],
    /// Current role being projected
    pub current_role: &'a Role,
}

/// Context provided during code generation
#[derive(Debug)]
pub struct CodegenContext<'a> {
    /// The choreography being generated
    pub choreography_name: &'a str,
    /// All roles in the choreography
    pub roles: &'a [Role],
    /// Namespace for generated code
    pub namespace: Option<&'a str>,
}

impl<'a> Default for CodegenContext<'a> {
    fn default() -> Self {
        Self {
            choreography_name: "Default",
            roles: &[],
            namespace: None,
        }
    }
}

/// Errors that can occur during extension parsing
#[derive(Debug, thiserror::Error)]
pub enum ParseError {
    #[error("Syntax error: {message}")]
    Syntax { message: String },

    #[error("Unknown role '{role}' used in extension")]
    UnknownRole { role: String },

    #[error("Invalid extension syntax: {details}")]
    InvalidSyntax { details: String },

    #[error("Extension conflict: {message}")]
    Conflict { message: String },

    #[error("Extension priority conflict: Extension '{extension1}' (priority {priority1}) conflicts with '{extension2}' (priority {priority2}) for rule '{rule}'. Consider adjusting priorities or using different rule names.")]
    PriorityConflict {
        extension1: String,
        extension2: String,
        priority1: u32,
        priority2: u32,
        rule: String,
    },

    #[error("Missing dependency: Extension '{extension}' requires '{dependency}' which is not registered. Please register the required extension first.")]
    MissingDependency {
        extension: String,
        dependency: String,
    },

    #[error("Extension registration failed: Extension '{extension}' with rule '{rule}' cannot be registered. {details}")]
    RegistrationFailed {
        extension: String,
        rule: String,
        details: String,
    },

    #[error("Incompatible extensions: {details}")]
    IncompatibleExtensions { details: String },
}

/// Validation errors for protocol extensions
#[derive(Debug, thiserror::Error)]
pub enum ExtensionValidationError {
    #[error("Role '{role}' not declared")]
    UndeclaredRole { role: String },

    #[error("Invalid protocol structure: {reason}")]
    InvalidStructure { reason: String },

    #[error("Extension validation failed: {message}")]
    ExtensionFailed { message: String },
}

/// Convenience macro for registering extensions
#[macro_export]
macro_rules! register_extension {
    ($registry:expr, $extension:expr) => {{
        let ext = $extension;
        let id = ext.extension_id().to_string();
        $registry.register_grammar(ext);
    }};
}

/// Utility trait for easy extension registration
pub trait RegisterExtension {
    fn register_all(registry: &mut ExtensionRegistry);
}

pub mod discovery;
/// Built-in extensions
pub mod timeout;

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

    #[derive(Debug)]
    struct MockGrammarExtension;

    impl GrammarExtension for MockGrammarExtension {
        fn grammar_rules(&self) -> &'static str {
            "timeout_stmt = { \"timeout\" ~ integer ~ protocol_block }"
        }

        fn statement_rules(&self) -> Vec<&'static str> {
            vec!["timeout_stmt"]
        }

        fn extension_id(&self) -> &'static str {
            "mock_timeout"
        }
    }

    #[test]
    fn test_extension_registry() {
        let mut registry = ExtensionRegistry::new();

        // Register extension
        registry
            .register_grammar(MockGrammarExtension)
            .expect("extension registration should succeed");

        // Test rule mapping
        assert!(registry.can_handle("timeout_stmt"));
        assert!(!registry.can_handle("unknown_rule"));

        // Test grammar composition
        let base = "basic_rule = { \"test\" }";
        let composed = registry.compose_grammar(base);
        assert!(composed.contains("basic_rule"));
        assert!(composed.contains("timeout_stmt"));
    }

    #[test]
    fn test_enhanced_error_messages() {
        use crate::extensions::ParseError;

        // Test priority conflict error
        let err = ParseError::PriorityConflict {
            extension1: "ext1".to_string(),
            extension2: "ext2".to_string(),
            priority1: 100,
            priority2: 100,
            rule: "test_rule".to_string(),
        };
        assert!(err.to_string().contains("Consider adjusting priorities"));

        // Test missing dependency error
        let err = ParseError::MissingDependency {
            extension: "dependent_ext".to_string(),
            dependency: "required_ext".to_string(),
        };
        assert!(err
            .to_string()
            .contains("Please register the required extension first"));

        // Test incompatible extensions error
        let err = ParseError::IncompatibleExtensions {
            details: "Test incompatibility".to_string(),
        };
        assert!(err.to_string().contains("Incompatible extensions"));
    }

    #[test]
    fn test_detailed_conflicts() {
        #[derive(Debug)]
        struct TestExt1;
        impl GrammarExtension for TestExt1 {
            fn grammar_rules(&self) -> &'static str {
                "rule1 = { \"test1\" }"
            }
            fn statement_rules(&self) -> Vec<&'static str> {
                vec!["rule1"]
            }
            fn priority(&self) -> u32 {
                200
            }
            fn extension_id(&self) -> &'static str {
                "test_ext1"
            }
        }

        #[derive(Debug)]
        struct TestExt2;
        impl GrammarExtension for TestExt2 {
            fn grammar_rules(&self) -> &'static str {
                "rule1 = { \"test2\" }"
            }
            fn statement_rules(&self) -> Vec<&'static str> {
                vec!["rule1"]
            }
            fn priority(&self) -> u32 {
                100
            }
            fn extension_id(&self) -> &'static str {
                "test_ext2"
            }
        }

        let mut registry = ExtensionRegistry::new();

        // Register lower priority first
        registry
            .register_grammar(TestExt2)
            .expect("lower priority extension should register");
        // Register higher priority second (should override)
        registry
            .register_grammar(TestExt1)
            .expect("higher priority extension should override");

        let conflicts = registry.get_detailed_conflicts();
        assert!(!conflicts.is_empty());
        assert!(conflicts[0].contains("overrode"));
        assert!(conflicts[0].contains("priority"));
    }

    #[test]
    fn test_documentation_system() {
        let mut registry = ExtensionRegistry::new();

        registry
            .extension_versions
            .insert("mock_timeout".to_string(), "1.0.0".to_string());
        registry
            .register_grammar(MockGrammarExtension)
            .expect("grammar extension should register");

        // Test documentation generation
        let docs = registry.generate_docs();
        assert!(docs.contains("# Extension Documentation"));
        assert!(docs.contains("mock_timeout"));
        assert!(docs.contains("**Priority:** 100"));
        assert!(docs.contains("**Version:** 1.0.0"));

        assert_eq!(
            registry.extension_versions.get("mock_timeout"),
            Some(&"1.0.0".to_string())
        );
    }

    #[test]
    fn test_compose_grammar_is_stable_for_equal_priorities() {
        #[derive(Debug)]
        struct AlphaExt;
        impl GrammarExtension for AlphaExt {
            fn grammar_rules(&self) -> &'static str {
                "alpha_stmt = { \"alpha\" }"
            }
            fn statement_rules(&self) -> Vec<&'static str> {
                vec!["alpha_stmt"]
            }
            fn priority(&self) -> u32 {
                100
            }
            fn extension_id(&self) -> &'static str {
                "alpha_ext"
            }
        }

        #[derive(Debug)]
        struct BetaExt;
        impl GrammarExtension for BetaExt {
            fn grammar_rules(&self) -> &'static str {
                "beta_stmt = { \"beta\" }"
            }
            fn statement_rules(&self) -> Vec<&'static str> {
                vec!["beta_stmt"]
            }
            fn priority(&self) -> u32 {
                100
            }
            fn extension_id(&self) -> &'static str {
                "beta_ext"
            }
        }

        let mut registry = ExtensionRegistry::new();
        registry.register_grammar(BetaExt).unwrap();
        registry.register_grammar(AlphaExt).unwrap();

        let composed = registry.compose_grammar("base = { \"x\" }");
        let alpha_idx = composed.find("alpha_stmt").unwrap();
        let beta_idx = composed.find("beta_stmt").unwrap();
        assert!(alpha_idx < beta_idx);
    }

    #[test]
    fn test_parse_context() {
        use proc_macro2::Span;
        let roles = vec![
            Role::new(proc_macro2::Ident::new("Alice", Span::call_site())).unwrap(),
            Role::new(proc_macro2::Ident::new("Bob", Span::call_site())).unwrap(),
        ];

        let context = ParseContext {
            declared_roles: &roles,
            input: "test input",
        };

        assert_eq!(context.declared_roles.len(), 2);
        assert_eq!(context.input, "test input");
    }
}