telltale-language 7.0.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
//! Extension Discovery and Registration System
//!
//! This module provides utilities for discovering and registering extensions
//! in a clean, composable way. It supports extension versioning, dependency
//! management, and compatibility checking.

use super::{ExtensionRegistry, GrammarExtension, ParseError};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

/// Extension metadata for discovery and versioning
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtensionMetadata {
    pub name: String,
    pub version: String,
    pub description: String,
    pub author: String,
    pub dependencies: Vec<String>,
    pub required_telltale_version: Option<String>,
    pub priority: Option<u32>,
    /// Documentation fields
    pub overview: Option<String>,
    pub syntax_guide: Option<String>,
    pub use_cases: Option<Vec<String>>,
    pub keywords: Option<Vec<String>>,
}

/// Extension package containing metadata and implementation
#[derive(Debug)]
pub struct ExtensionPackage {
    pub metadata: ExtensionMetadata,
    pub extension: Box<dyn GrammarExtension>,
    pub source_path: Option<PathBuf>,
}

/// Registry for extension discovery and management
#[derive(Debug, Default)]
pub struct ExtensionDiscovery {
    discovered_extensions: BTreeMap<String, ExtensionPackage>,
    search_paths: Vec<PathBuf>,
}

impl ExtensionDiscovery {
    /// Create a new extension discovery manager
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a search path for extensions
    pub fn add_search_path<P: AsRef<Path>>(&mut self, path: P) {
        self.search_paths.push(path.as_ref().to_path_buf());
    }

    /// Manually register an extension with metadata
    pub fn register_extension(
        &mut self,
        metadata: ExtensionMetadata,
        extension: Box<dyn GrammarExtension>,
    ) -> Result<(), ParseError> {
        // Validate metadata
        if metadata.name.is_empty() {
            return Err(ParseError::InvalidSyntax {
                details: "Extension name cannot be empty".to_string(),
            });
        }

        // Check for conflicts
        if self.discovered_extensions.contains_key(&metadata.name) {
            return Err(ParseError::RegistrationFailed {
                extension: metadata.name.clone(),
                rule: "discovery".to_string(),
                details: format!(
                    "Extension '{}' is already registered in discovery system",
                    metadata.name
                ),
            });
        }

        let package = ExtensionPackage {
            metadata,
            extension,
            source_path: None,
        };

        self.discovered_extensions
            .insert(package.metadata.name.clone(), package);
        Ok(())
    }

    /// Get all discovered extensions
    pub fn get_extensions(&self) -> &BTreeMap<String, ExtensionPackage> {
        &self.discovered_extensions
    }

    /// Check if an extension is available
    pub fn has_extension(&self, name: &str) -> bool {
        self.discovered_extensions.contains_key(name)
    }

    /// Get extension metadata by name
    pub fn get_metadata(&self, name: &str) -> Option<&ExtensionMetadata> {
        self.discovered_extensions
            .get(name)
            .map(|pkg| &pkg.metadata)
    }

    /// Resolve extension dependencies using topological sort
    ///
    /// Returns extensions in dependency order (dependencies before dependents)
    pub fn resolve_dependencies(
        &self,
        extension_names: &[String],
    ) -> Result<Vec<String>, ParseError> {
        let mut resolved = Vec::new();
        let mut visited = BTreeSet::new();
        let mut visiting = BTreeSet::new(); // For cycle detection

        // Helper function for DFS topological sort
        fn visit(
            name: &str,
            extensions: &BTreeMap<String, ExtensionPackage>,
            visited: &mut BTreeSet<String>,
            visiting: &mut BTreeSet<String>,
            resolved: &mut Vec<String>,
        ) -> Result<(), ParseError> {
            if visited.contains(name) {
                return Ok(());
            }

            if visiting.contains(name) {
                return Err(ParseError::Conflict {
                    message: format!("Circular dependency detected involving '{}'", name),
                });
            }

            visiting.insert(name.to_string());

            if let Some(package) = extensions.get(name) {
                // Process dependencies first
                for dep in &package.metadata.dependencies {
                    visit(dep, extensions, visited, visiting, resolved)?;
                }
            } else {
                return Err(ParseError::MissingDependency {
                    extension: "dependency_resolution".to_string(),
                    dependency: name.to_string(),
                });
            }

            visiting.remove(name);
            visited.insert(name.to_string());
            resolved.push(name.to_string());

            Ok(())
        }

        // Visit all requested extensions
        for ext_name in extension_names {
            visit(
                ext_name,
                &self.discovered_extensions,
                &mut visited,
                &mut visiting,
                &mut resolved,
            )?;
        }

        Ok(resolved)
    }

    /// Create a configured extension registry
    pub fn create_registry(
        &self,
        extension_names: &[String],
    ) -> Result<ExtensionRegistry, ParseError> {
        let resolved = self.resolve_dependencies(extension_names)?;
        let mut registry = ExtensionRegistry::new();

        // Register extensions in dependency order
        for ext_name in resolved {
            if let Some(package) = self.discovered_extensions.get(&ext_name) {
                // Clone the extension (this requires extensions to be cloneable or
                // we need a different approach for ownership)
                registry.register_grammar(ClonableExtensionWrapper::new(
                    &*package.extension,
                    &package.metadata,
                ))?;

                // Add dependencies to registry
                for dep in &package.metadata.dependencies {
                    registry.add_dependency(&ext_name, dep);
                }
            }
        }

        // Note: We skip validate_dependencies() here because:
        // 1. Dependencies were already resolved and validated by resolve_dependencies()
        // 2. ClonableExtensionWrapper has a limitation where extension_id() returns
        //    a static string, not the dynamic name, so registry validation would fail
        //
        // The dependency ordering is guaranteed by the topological sort above.

        Ok(registry)
    }

    /// Validate extension compatibility
    pub fn check_compatibility(&self, extension_names: &[String]) -> Result<(), ParseError> {
        let resolved = self.resolve_dependencies(extension_names)?;

        // Check version compatibility
        for ext_name in &resolved {
            if let Some(package) = self.discovered_extensions.get(ext_name) {
                if let Some(required_version) = &package.metadata.required_telltale_version {
                    // Compare against baseline 0.5.0 (could use env!("CARGO_PKG_VERSION"))
                    if required_version != "0.5.0" {
                        return Err(ParseError::IncompatibleExtensions {
                            details: format!(
                                "Extension '{}' requires telltale version '{}', but current version is '0.5.0'. Please update the extension or telltale to compatible versions.",
                                ext_name, required_version
                            ),
                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Load extension from a directory or file.
    ///
    /// **Note**: This method loads extension metadata from TOML files but creates
    /// a `MetadataOnlyExtension` that does not provide actual grammar rules.
    /// For production use, prefer static registration via `register_extension()`
    /// with a concrete `GrammarExtension` implementation.
    ///
    /// This is primarily useful for:
    /// - Testing extension discovery and dependency resolution
    /// - Development workflows where grammar rules aren't needed
    /// - Future integration with dynamic loading (not currently implemented)
    pub fn load_from_path<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ParseError> {
        let path = path.as_ref();

        // Look for extension metadata file
        let metadata_path = path.join("extension.toml");
        if metadata_path.exists() {
            let metadata_str =
                std::fs::read_to_string(&metadata_path).map_err(|e| ParseError::InvalidSyntax {
                    details: format!("Failed to read extension metadata: {}", e),
                })?;

            let metadata: ExtensionMetadata =
                toml::from_str(&metadata_str).map_err(|e| ParseError::InvalidSyntax {
                    details: format!("Invalid extension metadata: {}", e),
                })?;

            // Dynamic library loading not supported; create metadata-only extension
            let extension = Box::new(MetadataOnlyExtension::new(&metadata));

            let package = ExtensionPackage {
                metadata: metadata.clone(),
                extension,
                source_path: Some(path.to_path_buf()),
            };

            self.discovered_extensions.insert(metadata.name, package);
        }

        Ok(())
    }

    /// Create a registry with commonly used extensions
    pub fn with_common_extensions() -> Result<ExtensionRegistry, ParseError> {
        let mut discovery = Self::new();

        // Register built-in extensions
        discovery.register_extension(
            ExtensionMetadata {
                name: "timeout".to_string(),
                version: "0.5.0".to_string(),
                description: "Timeout support for choreographic protocols".to_string(),
                author: "Telltale Team".to_string(),
                dependencies: vec![],
                required_telltale_version: Some("0.5.0".to_string()),
                priority: Some(100),
                overview: Some("Adds timeout semantics to choreographic protocols".to_string()),
                syntax_guide: Some("Use `timeout(duration) { ... }` syntax".to_string()),
                use_cases: Some(vec![
                    "Network protocols".to_string(),
                    "Real-time systems".to_string(),
                ]),
                keywords: Some(vec!["timeout".to_string(), "timing".to_string()]),
            },
            Box::new(super::timeout::TimeoutGrammarExtension),
        )?;

        discovery.register_extension(
            ExtensionMetadata {
                name: "aura_annotations".to_string(),
                version: "0.1.0".to_string(),
                description: "Aura-style annotations for capability tracking".to_string(),
                author: "Aura Project".to_string(),
                dependencies: vec![],
                required_telltale_version: Some("0.5.0".to_string()),
                priority: Some(110),
                overview: Some(
                    "Adds Aura-specific annotations for capabilities and flow control".to_string(),
                ),
                syntax_guide: Some(
                    "Use Role[annotation=value] syntax in communications".to_string(),
                ),
                use_cases: Some(vec![
                    "Capability verification".to_string(),
                    "Flow control".to_string(),
                ]),
                keywords: Some(vec![
                    "aura".to_string(),
                    "capabilities".to_string(),
                    "annotations".to_string(),
                ]),
            },
            Box::new(AuraAnnotationExtension),
        )?;

        discovery.create_registry(&["timeout".to_string(), "aura_annotations".to_string()])
    }

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

    /// Helper to register built-in telltale extensions
    pub fn with_builtin_only() -> Result<ExtensionRegistry, ParseError> {
        let mut discovery = Self::new();

        discovery.register_extension(
            ExtensionMetadata {
                name: "timeout".to_string(),
                version: "0.5.0".to_string(),
                description: "Timeout support for choreographic protocols".to_string(),
                author: "Telltale Team".to_string(),
                dependencies: vec![],
                required_telltale_version: Some("0.5.0".to_string()),
                priority: Some(100),
                overview: Some("Adds timeout semantics to choreographic protocols".to_string()),
                syntax_guide: Some("Use `timeout(duration) { ... }` syntax".to_string()),
                use_cases: Some(vec![
                    "Network protocols".to_string(),
                    "Real-time systems".to_string(),
                ]),
                keywords: Some(vec!["timeout".to_string(), "timing".to_string()]),
            },
            Box::new(super::timeout::TimeoutGrammarExtension),
        )?;

        discovery.create_registry(&["timeout".to_string()])
    }

    /// Helper to validate extension metadata before registration
    pub fn validate_metadata(metadata: &ExtensionMetadata) -> Result<(), ParseError> {
        if metadata.name.is_empty() {
            return Err(ParseError::InvalidSyntax {
                details: "Extension name cannot be empty".to_string(),
            });
        }

        if metadata.version.is_empty() {
            return Err(ParseError::InvalidSyntax {
                details: "Extension version cannot be empty".to_string(),
            });
        }

        if metadata.name.contains(' ') {
            return Err(ParseError::InvalidSyntax {
                details: "Extension name cannot contain spaces".to_string(),
            });
        }

        Ok(())
    }

    /// List all available extensions with their metadata
    pub fn list_extensions(&self) -> Vec<&ExtensionMetadata> {
        self.discovered_extensions
            .values()
            .map(|pkg| &pkg.metadata)
            .collect()
    }

    /// Find extensions by author
    pub fn find_by_author(&self, author: &str) -> Vec<&ExtensionMetadata> {
        self.discovered_extensions
            .values()
            .filter_map(|pkg| {
                if pkg.metadata.author == author {
                    Some(&pkg.metadata)
                } else {
                    None
                }
            })
            .collect()
    }
}

/// Wrapper to make extensions cloneable for registry management
///
/// Note: Some fields are stored for future use when dynamic grammar injection
/// is fully implemented. Currently only `priority` is used.
#[derive(Debug, Clone)]
struct ClonableExtensionWrapper {
    #[allow(dead_code)] // Stored for future dynamic grammar support
    id: String,
    #[allow(dead_code)] // Stored for future dynamic grammar support
    rules: Vec<String>,
    #[allow(dead_code)] // Stored for future dynamic grammar support
    grammar: String,
    priority: u32,
}

impl ClonableExtensionWrapper {
    fn new(extension: &dyn GrammarExtension, metadata: &ExtensionMetadata) -> Self {
        Self {
            id: metadata.name.clone(),
            rules: extension
                .statement_rules()
                .iter()
                .map(|s| (*s).to_string())
                .collect(),
            grammar: extension.grammar_rules().to_string(),
            priority: metadata.priority.unwrap_or(extension.priority()),
        }
    }
}

impl GrammarExtension for ClonableExtensionWrapper {
    fn grammar_rules(&self) -> &'static str {
        // Wrapper cannot provide dynamic rules; returns empty (use inner extension directly)
        ""
    }

    fn statement_rules(&self) -> Vec<&'static str> {
        // Wrapper cannot provide dynamic rules; returns empty
        vec![]
    }

    fn priority(&self) -> u32 {
        self.priority
    }

    fn extension_id(&self) -> &'static str {
        // This needs a different approach for dynamic extensions
        "cloneable_wrapper"
    }
}

/// Metadata-only extension loaded from configuration files.
///
/// Does not provide grammar rules - exists for testing extension discovery
/// and dependency resolution. Dynamic library loading is not supported.
///
/// **For production use**, implement `GrammarExtension` directly and
/// register via `ExtensionDiscovery::register_extension()`.
#[derive(Debug, Clone)]
struct MetadataOnlyExtension {
    #[allow(dead_code)] // Stored for error messages and debugging
    name: String,
    priority: u32,
}

impl MetadataOnlyExtension {
    fn new(metadata: &ExtensionMetadata) -> Self {
        Self {
            name: metadata.name.clone(),
            priority: metadata.priority.unwrap_or(100),
        }
    }
}

impl GrammarExtension for MetadataOnlyExtension {
    fn grammar_rules(&self) -> &'static str {
        ""
    }

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

    fn priority(&self) -> u32 {
        self.priority
    }

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

/// Aura annotation extension implementation
#[derive(Debug, Clone)]
struct AuraAnnotationExtension;

impl GrammarExtension for AuraAnnotationExtension {
    fn grammar_rules(&self) -> &'static str {
        r#"
aura_annotation_stmt = { role_ref ~ "[" ~ aura_annotation_list ~ "]" ~ "->" ~ role_ref ~ ":" ~ message ~ ";" }
aura_annotation_list = { aura_annotation_item ~ ("," ~ aura_annotation_item)* }
aura_annotation_item = { ident ~ "=" ~ annotation_value }
"#
    }

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

    fn priority(&self) -> u32 {
        110
    }

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

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

    #[test]
    fn test_extension_discovery() {
        let mut discovery = ExtensionDiscovery::new();

        let metadata = ExtensionMetadata {
            name: "test_ext".to_string(),
            version: "1.0.0".to_string(),
            description: "Test extension".to_string(),
            author: "Test Author".to_string(),
            dependencies: vec![],
            required_telltale_version: Some("0.5.0".to_string()),
            priority: Some(100),
            overview: None,
            syntax_guide: None,
            use_cases: None,
            keywords: None,
        };

        let extension = Box::new(MetadataOnlyExtension::new(&metadata));
        assert!(discovery.register_extension(metadata, extension).is_ok());
        assert!(discovery.has_extension("test_ext"));
    }

    #[test]
    fn test_dependency_resolution() {
        let mut discovery = ExtensionDiscovery::new();

        // Add base extension
        let base_metadata = ExtensionMetadata {
            name: "base".to_string(),
            version: "1.0.0".to_string(),
            description: "Base extension".to_string(),
            author: "Test".to_string(),
            dependencies: vec![],
            required_telltale_version: Some("0.5.0".to_string()),
            priority: Some(100),
            overview: None,
            syntax_guide: None,
            use_cases: None,
            keywords: None,
        };
        discovery
            .register_extension(
                base_metadata.clone(),
                Box::new(MetadataOnlyExtension::new(&base_metadata)),
            )
            .unwrap();

        // Add dependent extension
        let dep_metadata = ExtensionMetadata {
            name: "dependent".to_string(),
            version: "1.0.0".to_string(),
            description: "Dependent extension".to_string(),
            author: "Test".to_string(),
            dependencies: vec!["base".to_string()],
            required_telltale_version: Some("0.5.0".to_string()),
            priority: Some(100),
            overview: None,
            syntax_guide: None,
            use_cases: None,
            keywords: None,
        };
        discovery
            .register_extension(
                dep_metadata.clone(),
                Box::new(MetadataOnlyExtension::new(&dep_metadata)),
            )
            .unwrap();

        let resolved = discovery
            .resolve_dependencies(&["dependent".to_string()])
            .unwrap();
        assert!(resolved.contains(&"base".to_string()));
        assert!(resolved.contains(&"dependent".to_string()));
    }
}