Skip to main content

syster_cli/
lib.rs

1//! syster-cli library - Core analysis functionality
2//!
3//! This module provides the `run_analysis` function for parsing and analyzing
4//! SysML v2 and KerML files using the syster-base library.
5
6use serde::Serialize;
7use std::path::{Path, PathBuf};
8use syster::hir::{Severity, check_file};
9use syster::ide::AnalysisHost;
10use walkdir::WalkDir;
11
12/// Result of analyzing SysML/KerML files.
13#[derive(Debug, Serialize)]
14pub struct AnalysisResult {
15    /// Number of files analyzed.
16    pub file_count: usize,
17    /// Total number of symbols found.
18    pub symbol_count: usize,
19    /// Number of errors found.
20    pub error_count: usize,
21    /// Number of warnings found.
22    pub warning_count: usize,
23    /// All diagnostics collected.
24    pub diagnostics: Vec<DiagnosticInfo>,
25}
26
27/// A diagnostic message with location information.
28#[derive(Debug, Clone, Serialize)]
29pub struct DiagnosticInfo {
30    /// File path containing the diagnostic.
31    pub file: String,
32    /// Start line (1-indexed).
33    pub line: u32,
34    /// Start column (1-indexed).
35    pub col: u32,
36    /// End line (1-indexed).
37    pub end_line: u32,
38    /// End column (1-indexed).
39    pub end_col: u32,
40    /// The diagnostic message.
41    pub message: String,
42    /// Severity level.
43    #[serde(serialize_with = "serialize_severity")]
44    pub severity: Severity,
45    /// Optional error code.
46    pub code: Option<String>,
47}
48
49/// Serialize Severity as a string
50fn serialize_severity<S>(severity: &Severity, serializer: S) -> Result<S::Ok, S::Error>
51where
52    S: serde::Serializer,
53{
54    let s = match severity {
55        Severity::Error => "error",
56        Severity::Warning => "warning",
57        Severity::Info => "info",
58        Severity::Hint => "hint",
59    };
60    serializer.serialize_str(s)
61}
62
63/// Run analysis on input file or directory.
64///
65/// # Arguments
66/// * `input` - Path to a file or directory to analyze
67/// * `verbose` - Enable verbose output
68/// * `load_stdlib` - Whether to load the standard library
69/// * `stdlib_path` - Optional custom path to the standard library
70///
71/// # Returns
72/// An `AnalysisResult` with file count, symbol count, and diagnostics.
73pub fn run_analysis(
74    input: &Path,
75    verbose: bool,
76    load_stdlib: bool,
77    stdlib_path: Option<&Path>,
78) -> Result<AnalysisResult, String> {
79    let mut host = AnalysisHost::new();
80
81    // 1. Load stdlib if requested
82    if load_stdlib {
83        load_stdlib_files(&mut host, stdlib_path, verbose)?;
84    }
85
86    // 2. Load input file(s)
87    load_input(&mut host, input, verbose)?;
88
89    // 3. Trigger index rebuild and get analysis
90    let _analysis = host.analysis();
91
92    // 4. Collect diagnostics from all files
93    let diagnostics = collect_diagnostics(&host);
94
95    // 5. Build result
96    let error_count = diagnostics
97        .iter()
98        .filter(|d| matches!(d.severity, Severity::Error))
99        .count();
100    let warning_count = diagnostics
101        .iter()
102        .filter(|d| matches!(d.severity, Severity::Warning))
103        .count();
104
105    Ok(AnalysisResult {
106        file_count: host.file_count(),
107        symbol_count: host.symbol_index().all_symbols().count(),
108        error_count,
109        warning_count,
110        diagnostics,
111    })
112}
113
114/// Load input file or directory.
115fn load_input(host: &mut AnalysisHost, input: &Path, verbose: bool) -> Result<(), String> {
116    if input.is_file() {
117        load_file(host, input, verbose)
118    } else if input.is_dir() {
119        load_directory(host, input, verbose)
120    } else {
121        Err(format!("Path does not exist: {}", input.display()))
122    }
123}
124
125/// Load a single file into the analysis host.
126fn load_file(host: &mut AnalysisHost, path: &Path, verbose: bool) -> Result<(), String> {
127    if verbose {
128        println!("  Loading: {}", path.display());
129    }
130
131    let content = std::fs::read_to_string(path)
132        .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
133
134    let path_str = path.to_string_lossy();
135    let parse_errors = host.set_file_content(&path_str, &content);
136
137    // Parse errors are reported but don't fail the load
138    for err in parse_errors {
139        eprintln!(
140            "parse error: {}:{}:{}: {}",
141            path.display(),
142            err.position.line,
143            err.position.column,
144            err.message
145        );
146    }
147
148    Ok(())
149}
150
151/// Load all SysML/KerML files from a directory.
152fn load_directory(host: &mut AnalysisHost, dir: &Path, verbose: bool) -> Result<(), String> {
153    if verbose {
154        println!("Scanning directory: {}", dir.display());
155    }
156
157    for entry in WalkDir::new(dir).follow_links(true) {
158        let entry = entry.map_err(|e| format!("Walk error: {}", e))?;
159        let path = entry.path();
160
161        if is_sysml_file(path) {
162            load_file(host, path, verbose)?;
163        }
164    }
165
166    Ok(())
167}
168
169/// Check if a path is a SysML or KerML file.
170fn is_sysml_file(path: &Path) -> bool {
171    path.is_file()
172        && matches!(
173            path.extension().and_then(|e| e.to_str()),
174            Some("sysml") | Some("kerml")
175        )
176}
177
178/// Load standard library files.
179fn load_stdlib_files(
180    host: &mut AnalysisHost,
181    custom_path: Option<&Path>,
182    verbose: bool,
183) -> Result<(), String> {
184    if verbose {
185        println!("Loading standard library...");
186    }
187
188    // Try custom path first
189    if let Some(path) = custom_path {
190        if path.exists() {
191            return load_directory(host, path, verbose);
192        } else {
193            return Err(format!("Stdlib path does not exist: {}", path.display()));
194        }
195    }
196
197    // Try default locations
198    let default_paths = [
199        PathBuf::from("sysml.library"),
200        PathBuf::from("../sysml.library"),
201        PathBuf::from("../base/sysml.library"),
202    ];
203
204    for path in &default_paths {
205        if path.exists() {
206            return load_directory(host, path, verbose);
207        }
208    }
209
210    if verbose {
211        println!("  Warning: Standard library not found");
212    }
213
214    Ok(())
215}
216
217/// Collect diagnostics from all files in the host.
218fn collect_diagnostics(host: &AnalysisHost) -> Vec<DiagnosticInfo> {
219    let mut all_diagnostics = Vec::new();
220
221    for path in host.files().keys() {
222        if let Some(file_id) = host.get_file_id_for_path(path) {
223            let file_path = path.to_string_lossy().to_string();
224            let diagnostics = check_file(host.symbol_index(), file_id);
225
226            for diag in diagnostics {
227                all_diagnostics.push(DiagnosticInfo {
228                    file: file_path.clone(),
229                    line: diag.start_line + 1, // 1-indexed for display
230                    col: diag.start_col + 1,
231                    end_line: diag.end_line + 1,
232                    end_col: diag.end_col + 1,
233                    message: diag.message.to_string(),
234                    severity: diag.severity,
235                    code: diag.code.map(|c| c.to_string()),
236                });
237            }
238        }
239    }
240
241    // Sort by file, then line, then column
242    all_diagnostics.sort_by(|a, b| (&a.file, a.line, a.col).cmp(&(&b.file, b.line, b.col)));
243
244    all_diagnostics
245}
246
247// ============================================================================
248// EXPORT FUNCTIONS
249// ============================================================================
250
251/// A symbol for JSON export (simplified from HirSymbol).
252#[derive(Debug, Serialize)]
253pub struct ExportSymbol {
254    pub name: String,
255    pub qualified_name: String,
256    pub kind: String,
257    pub file: String,
258    pub start_line: u32,
259    pub start_col: u32,
260    pub end_line: u32,
261    pub end_col: u32,
262    #[serde(skip_serializing_if = "Option::is_none")]
263    pub doc: Option<String>,
264    #[serde(skip_serializing_if = "Vec::is_empty")]
265    pub supertypes: Vec<String>,
266}
267
268/// AST export result.
269#[derive(Debug, Serialize)]
270pub struct AstExport {
271    pub files: Vec<FileAst>,
272}
273
274/// AST for a single file.
275#[derive(Debug, Serialize)]
276pub struct FileAst {
277    pub path: String,
278    pub symbols: Vec<ExportSymbol>,
279}
280
281/// Export AST (symbols) for all files.
282pub fn export_ast(
283    input: &Path,
284    verbose: bool,
285    load_stdlib: bool,
286    stdlib_path: Option<&Path>,
287) -> Result<String, String> {
288    let mut host = AnalysisHost::new();
289
290    if load_stdlib {
291        load_stdlib_files(&mut host, stdlib_path, verbose)?;
292    }
293
294    load_input(&mut host, input, verbose)?;
295    let _analysis = host.analysis();
296
297    let mut files = Vec::new();
298
299    // Only export user files, not stdlib
300    for path in host.files().keys() {
301        let path_str = path.to_string_lossy().to_string();
302
303        // Skip stdlib files
304        if path_str.contains("sysml.library") {
305            continue;
306        }
307
308        if let Some(file_id) = host.get_file_id_for_path(path) {
309            let symbols: Vec<ExportSymbol> = host
310                .symbol_index()
311                .symbols_in_file(file_id)
312                .into_iter()
313                .map(|sym| ExportSymbol {
314                    name: sym.name.to_string(),
315                    qualified_name: sym.qualified_name.to_string(),
316                    kind: format!("{:?}", sym.kind),
317                    file: path_str.clone(),
318                    start_line: sym.start_line + 1,
319                    start_col: sym.start_col + 1,
320                    end_line: sym.end_line + 1,
321                    end_col: sym.end_col + 1,
322                    doc: sym.doc.as_ref().map(|d| d.to_string()),
323                    supertypes: sym.supertypes.iter().map(|s| s.to_string()).collect(),
324                })
325                .collect();
326
327            files.push(FileAst {
328                path: path_str,
329                symbols,
330            });
331        }
332    }
333
334    // Sort files by path for consistent output
335    files.sort_by(|a, b| a.path.cmp(&b.path));
336
337    let export = AstExport { files };
338    serde_json::to_string_pretty(&export).map_err(|e| format!("Failed to serialize AST: {}", e))
339}
340
341/// Export analysis result as JSON.
342pub fn export_json(result: &AnalysisResult) -> Result<String, String> {
343    serde_json::to_string_pretty(result).map_err(|e| format!("Failed to serialize result: {}", e))
344}
345
346// ============================================================================
347// INTERCHANGE EXPORT
348// ============================================================================
349
350/// Export a model to an interchange format.
351///
352/// Supported formats:
353/// - `xmi` - XML Model Interchange
354/// - `kpar` - Kernel Package Archive (ZIP)
355/// - `jsonld` - JSON-LD
356///
357/// # Arguments
358/// * `input` - Path to a file or directory to analyze
359/// * `format` - Output format (xmi, kpar, jsonld)
360/// * `verbose` - Enable verbose output
361/// * `load_stdlib` - Whether to load the standard library
362/// * `stdlib_path` - Optional custom path to the standard library
363///
364/// # Returns
365/// The serialized model as bytes.
366#[cfg(feature = "interchange")]
367pub fn export_model(
368    input: &Path,
369    format: &str,
370    verbose: bool,
371    load_stdlib: bool,
372    stdlib_path: Option<&Path>,
373) -> Result<Vec<u8>, String> {
374    use syster::interchange::{
375        JsonLd, Kpar, ModelFormat, Xmi, model_from_symbols, restore_ids_from_symbols,
376    };
377
378    let mut host = AnalysisHost::new();
379
380    // 1. Load stdlib if requested
381    if load_stdlib {
382        load_stdlib_files(&mut host, stdlib_path, verbose)?;
383    }
384
385    // 2. Load input file(s)
386    load_input(&mut host, input, verbose)?;
387
388    // 2.5. Load metadata if present (for ID preservation on round-trip)
389    #[cfg(feature = "interchange")]
390    {
391        use syster::project::WorkspaceLoader;
392        let loader = WorkspaceLoader::new();
393
394        // If input is a file, check for companion metadata
395        if input.is_file() {
396            let parent_dir = input.parent().unwrap_or(input);
397            if let Err(e) = loader.load_metadata_from_directory(parent_dir, &mut host) {
398                if verbose {
399                    eprintln!("Note: Could not load metadata: {}", e);
400                }
401            } else if verbose {
402                println!("Loaded metadata from {}", parent_dir.display());
403            }
404        } else if input.is_dir() {
405            // For directories, load metadata from that directory
406            if let Err(e) = loader.load_metadata_from_directory(input, &mut host) {
407                if verbose {
408                    eprintln!("Note: Could not load metadata: {}", e);
409                }
410            } else if verbose {
411                println!("Loaded metadata from {}", input.display());
412            }
413        }
414    }
415
416    // 3. Trigger index rebuild
417    let analysis = host.analysis();
418
419    // 4. Get all symbols from the index
420    let symbols: Vec<_> = analysis.symbol_index().all_symbols().cloned().collect();
421
422    // 5. Convert to interchange model
423    let mut model = model_from_symbols(&symbols);
424
425    // 6. Restore original element IDs from symbols (if they exist)
426    model = restore_ids_from_symbols(model, analysis.symbol_index());
427    if verbose {
428        println!("Restored element IDs from symbol database");
429    }
430
431    if verbose {
432        println!(
433            "Exported model: {} elements, {} relationships",
434            model.elements.len(),
435            model.relationships.len()
436        );
437    }
438
439    // 8. Serialize to requested format
440    match format.to_lowercase().as_str() {
441        "xmi" => Xmi.write(&model).map_err(|e| e.to_string()),
442        "kpar" => Kpar.write(&model).map_err(|e| e.to_string()),
443        "jsonld" | "json-ld" => JsonLd.write(&model).map_err(|e| e.to_string()),
444        _ => Err(format!(
445            "Unsupported format: {}. Use xmi, kpar, or jsonld.",
446            format
447        )),
448    }
449}
450
451/// Export model from an existing AnalysisHost to an interchange format.
452///
453/// This allows exporting from a pre-populated host (e.g., after import_model_into_host).
454/// Element IDs are preserved from the symbol database.
455#[cfg(feature = "interchange")]
456pub fn export_from_host(
457    host: &mut AnalysisHost,
458    format: &str,
459    verbose: bool,
460) -> Result<Vec<u8>, String> {
461    use syster::interchange::{
462        JsonLd, Kpar, ModelFormat, Xmi, model_from_symbols, restore_ids_from_symbols,
463    };
464
465    let analysis = host.analysis();
466    let symbols: Vec<_> = analysis.symbol_index().all_symbols().cloned().collect();
467
468    let mut model = model_from_symbols(&symbols);
469    model = restore_ids_from_symbols(model, analysis.symbol_index());
470
471    if verbose {
472        println!(
473            "Exported model: {} elements, {} relationships",
474            model.elements.len(),
475            model.relationships.len()
476        );
477    }
478
479    match format.to_lowercase().as_str() {
480        "xmi" => Xmi.write(&model).map_err(|e| e.to_string()),
481        "kpar" => Kpar.write(&model).map_err(|e| e.to_string()),
482        "jsonld" | "json-ld" => JsonLd.write(&model).map_err(|e| e.to_string()),
483        _ => Err(format!(
484            "Unsupported format: {}. Use xmi, kpar, or jsonld.",
485            format
486        )),
487    }
488}
489
490/// Result of importing a model from an interchange format.
491#[cfg(feature = "interchange")]
492#[derive(Debug)]
493pub struct ImportResult {
494    /// Number of elements imported.
495    pub element_count: usize,
496    /// Number of relationships imported.
497    pub relationship_count: usize,
498    /// Number of validation errors.
499    pub error_count: usize,
500    /// Validation messages.
501    pub messages: Vec<String>,
502}
503
504/// Import a model from an interchange format file (validation only).
505///
506/// This validates the model but doesn't load it into a workspace.
507/// For importing into a workspace, use `import_model_into_host()`.
508///
509/// Supported formats are detected from file extension:
510/// - `.xmi` - XML Model Interchange
511/// - `.kpar` - Kernel Package Archive (ZIP)
512/// - `.jsonld`, `.json` - JSON-LD
513///
514/// # Arguments
515/// * `input` - Path to the interchange file
516/// * `format` - Optional format override (otherwise detected from extension)
517/// * `verbose` - Enable verbose output
518///
519/// # Returns
520/// An `ImportResult` with element count and symbol info.
521#[cfg(feature = "interchange")]
522pub fn import_model_into_host(
523    host: &mut AnalysisHost,
524    input: &Path,
525    format: Option<&str>,
526    verbose: bool,
527) -> Result<ImportResult, String> {
528    use syster::interchange::{JsonLd, Kpar, ModelFormat, Xmi, detect_format, symbols_from_model};
529
530    // Read the input file
531    let bytes =
532        std::fs::read(input).map_err(|e| format!("Failed to read {}: {}", input.display(), e))?;
533
534    // Determine format
535    let format_str = format.map(String::from).unwrap_or_else(|| {
536        input
537            .extension()
538            .and_then(|e| e.to_str())
539            .unwrap_or("xmi")
540            .to_string()
541    });
542
543    if verbose {
544        println!(
545            "Importing {} as {} into workspace",
546            input.display(),
547            format_str
548        );
549    }
550
551    // Parse the model
552    let model = match format_str.to_lowercase().as_str() {
553        "xmi" | "sysmlx" | "kermlx" => Xmi.read(&bytes).map_err(|e| e.to_string())?,
554        "kpar" => Kpar.read(&bytes).map_err(|e| e.to_string())?,
555        "jsonld" | "json-ld" | "json" => JsonLd.read(&bytes).map_err(|e| e.to_string())?,
556        _ => {
557            // Try to detect from file extension
558            if let Some(format_impl) = detect_format(input) {
559                format_impl.read(&bytes).map_err(|e| e.to_string())?
560            } else {
561                return Err(format!(
562                    "Unknown format: {}. Use xmi, sysmlx, kermlx, kpar, or jsonld.",
563                    format_str
564                ));
565            }
566        }
567    };
568
569    // Convert model to symbols
570    let symbols = symbols_from_model(&model);
571    let symbol_count = symbols.len();
572
573    if verbose {
574        println!(
575            "Converted {} elements to {} symbols",
576            model.elements.len(),
577            symbol_count
578        );
579    }
580
581    // Add symbols to host
582    host.add_symbols_from_model(symbols);
583
584    if verbose {
585        println!("Loaded symbols into workspace with preserved element IDs");
586    }
587
588    Ok(ImportResult {
589        element_count: model.elements.len(),
590        relationship_count: model.relationships.len(),
591        error_count: 0,
592        messages: vec![format!("Successfully imported {} symbols", symbol_count)],
593    })
594}
595
596/// Import and validate a model from an interchange format (legacy version).
597///
598/// This validates the model but doesn't load it into a workspace.
599/// For importing into a workspace, use `import_model_into_host()`.
600///
601/// # Arguments
602/// * `input` - Path to the model file
603/// * `format` - Optional format override (xmi, kpar, jsonld)
604/// * `verbose` - Enable verbose output
605///
606/// # Returns
607/// An `ImportResult` with element count and validation info.
608#[cfg(feature = "interchange")]
609pub fn import_model(
610    input: &Path,
611    format: Option<&str>,
612    verbose: bool,
613) -> Result<ImportResult, String> {
614    use syster::interchange::{JsonLd, Kpar, ModelFormat, Xmi, detect_format};
615
616    // Read the input file
617    let bytes =
618        std::fs::read(input).map_err(|e| format!("Failed to read {}: {}", input.display(), e))?;
619
620    // Determine format
621    let format_str = format.map(String::from).unwrap_or_else(|| {
622        input
623            .extension()
624            .and_then(|e| e.to_str())
625            .unwrap_or("xmi")
626            .to_string()
627    });
628
629    if verbose {
630        println!("Importing {} as {}", input.display(), format_str);
631    }
632
633    // Parse the model
634    let model = match format_str.to_lowercase().as_str() {
635        "xmi" | "sysmlx" | "kermlx" => Xmi.read(&bytes).map_err(|e| e.to_string())?,
636        "kpar" => Kpar.read(&bytes).map_err(|e| e.to_string())?,
637        "jsonld" | "json-ld" | "json" => JsonLd.read(&bytes).map_err(|e| e.to_string())?,
638        _ => {
639            // Try to detect from file extension
640            if let Some(format_impl) = detect_format(input) {
641                format_impl.read(&bytes).map_err(|e| e.to_string())?
642            } else {
643                return Err(format!(
644                    "Unknown format: {}. Use xmi, sysmlx, kermlx, kpar, or jsonld.",
645                    format_str
646                ));
647            }
648        }
649    };
650
651    // Basic validation
652    let mut messages = Vec::new();
653    let mut error_count = 0;
654
655    // Check for orphan relationships (references to non-existent elements)
656    for rel in &model.relationships {
657        if model.elements.get(&rel.source).is_none() {
658            messages.push(format!(
659                "Warning: Relationship source '{}' not found",
660                rel.source
661            ));
662            error_count += 1;
663        }
664        if model.elements.get(&rel.target).is_none() {
665            messages.push(format!(
666                "Warning: Relationship target '{}' not found",
667                rel.target
668            ));
669            error_count += 1;
670        }
671    }
672
673    if verbose {
674        println!(
675            "Imported: {} elements, {} relationships, {} validation issues",
676            model.elements.len(),
677            model.relationships.len(),
678            error_count
679        );
680        for msg in &messages {
681            println!("  {}", msg);
682        }
683    }
684
685    Ok(ImportResult {
686        element_count: model.elements.len(),
687        relationship_count: model.relationships.len(),
688        error_count,
689        messages,
690    })
691}
692
693/// Result of decompiling a model to SysML files.
694#[cfg(feature = "interchange")]
695#[derive(Debug)]
696pub struct DecompileResult {
697    /// Generated SysML text.
698    pub sysml_text: String,
699    /// Metadata JSON for preserving element IDs.
700    pub metadata_json: String,
701    /// Number of elements decompiled.
702    pub element_count: usize,
703    /// Source file path.
704    pub source_path: String,
705}
706
707/// Decompile an interchange file to SysML text with metadata.
708///
709/// This function converts an XMI/KPAR/JSON-LD file to SysML text plus
710/// a companion metadata JSON file that preserves element IDs for
711/// lossless round-tripping.
712///
713/// # Arguments
714/// * `input` - Path to the interchange file
715/// * `format` - Optional format override (otherwise detected from extension)
716/// * `verbose` - Enable verbose output
717///
718/// # Returns
719/// A `DecompileResult` with SysML text and metadata JSON.
720#[cfg(feature = "interchange")]
721pub fn decompile_model(
722    input: &Path,
723    format: Option<&str>,
724    verbose: bool,
725) -> Result<DecompileResult, String> {
726    use syster::interchange::{
727        JsonLd, Kpar, ModelFormat, SourceInfo, Xmi, decompile_with_source, detect_format,
728    };
729
730    // Read the input file
731    let bytes =
732        std::fs::read(input).map_err(|e| format!("Failed to read {}: {}", input.display(), e))?;
733
734    // Determine format
735    let format_str = format.map(String::from).unwrap_or_else(|| {
736        input
737            .extension()
738            .and_then(|e| e.to_str())
739            .unwrap_or("xmi")
740            .to_string()
741    });
742
743    if verbose {
744        println!("Decompiling {} as {}", input.display(), format_str);
745    }
746
747    // Parse the model
748    let model = match format_str.to_lowercase().as_str() {
749        "xmi" | "sysmlx" | "kermlx" => Xmi.read(&bytes).map_err(|e| e.to_string())?,
750        "kpar" => Kpar.read(&bytes).map_err(|e| e.to_string())?,
751        "jsonld" | "json-ld" | "json" => JsonLd.read(&bytes).map_err(|e| e.to_string())?,
752        _ => {
753            if let Some(format_impl) = detect_format(input) {
754                format_impl.read(&bytes).map_err(|e| e.to_string())?
755            } else {
756                return Err(format!(
757                    "Unknown format: {}. Use xmi, sysmlx, kermlx, kpar, or jsonld.",
758                    format_str
759                ));
760            }
761        }
762    };
763
764    let element_count = model.elements.len();
765
766    // Create source info
767    let source = SourceInfo::from_path(input.to_string_lossy()).with_format(&format_str);
768
769    // Decompile to SysML
770    let result = decompile_with_source(&model, source);
771
772    if verbose {
773        println!(
774            "Decompiled: {} elements -> {} chars of SysML, {} metadata entries",
775            element_count,
776            result.text.len(),
777            result.metadata.elements.len()
778        );
779    }
780
781    // Serialize metadata to JSON
782    let metadata_json = serde_json::to_string_pretty(&result.metadata)
783        .map_err(|e| format!("Failed to serialize metadata: {}", e))?;
784
785    Ok(DecompileResult {
786        sysml_text: result.text,
787        metadata_json,
788        element_count,
789        source_path: input.to_string_lossy().to_string(),
790    })
791}