Skip to main content

ggen_core/reverse_sync/
ast_extractor.rs

1//! Code to RDF extraction - Parse Rust, Elixir, and Go services into RDF format
2//!
3//! This module provides AST extraction functionality that converts source code definitions
4//! into ServiceDef structures, and then into RDF/Turtle format for integration with the
5//! ggen ontology system.
6//!
7//! # Example
8//!
9//! ```rust,no_run
10//! use crate::reverse_sync::ast_extractor::{extract_rust_service, convert_to_rdf, Language};
11//!
12//! # fn main() -> crate::utils::error::Result<()> {
13//! let services = extract_rust_service("src/lib.rs")?;
14//! let rdf = convert_to_rdf(&services)?;
15//! println!("{}", rdf);
16//! # Ok(())
17//! # }
18//! ```
19
20use crate::utils::error::{Error, Result};
21use regex::Regex;
22use std::fs;
23
24/// Programming language identifier
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26pub enum Language {
27    Rust,
28    Elixir,
29    Go,
30}
31
32impl Language {
33    fn as_str(&self) -> &'static str {
34        match self {
35            Language::Rust => "rust",
36            Language::Elixir => "elixir",
37            Language::Go => "go",
38        }
39    }
40}
41
42/// Kind of code construct a [`ServiceDef`] represents.
43///
44/// Regex-based extraction recovers structs, enums, and traits from Rust source.
45/// Elixir/Go extraction continues to use [`ServiceKind::Struct`] (the historical
46/// default) since those extractors model modules/structs as services.
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum ServiceKind {
49    Struct,
50    Enum,
51    Trait,
52}
53
54impl ServiceKind {
55    /// RDF class name (under the `code:` namespace) for this kind.
56    fn rdf_class(&self) -> &'static str {
57        match self {
58            ServiceKind::Struct => "Service",
59            ServiceKind::Enum => "Enum",
60            ServiceKind::Trait => "Trait",
61        }
62    }
63}
64
65/// Represents a field in a struct/type
66#[derive(Debug, Clone)]
67pub struct Field {
68    pub name: String,
69    pub field_type: String,
70}
71
72/// Represents a method or callback
73#[derive(Debug, Clone)]
74pub struct Method {
75    pub name: String,
76    pub params: Vec<String>,
77    pub return_type: Option<String>,
78}
79
80/// Represents an enum variant.
81///
82/// Captures variant name and optional payload information (tuple or struct fields).
83/// Payloads are stored as raw strings without full parsing.
84#[derive(Debug, Clone)]
85pub struct Variant {
86    pub name: String,
87    /// Optional payload: `"(u32, String)"` for tuple variants, `"{ field: Type, ... }"` for struct variants
88    pub payload: Option<String>,
89}
90
91/// Complete service definition extracted from source code
92#[derive(Debug, Clone)]
93pub struct ServiceDef {
94    pub name: String,
95    pub language: Language,
96    /// Whether this definition is a struct, enum, or trait. Defaults to
97    /// [`ServiceKind::Struct`] for backwards compatibility.
98    pub kind: ServiceKind,
99    pub fields: Vec<Field>,
100    pub methods: Vec<Method>,
101    /// Enum variants (empty for non-enum kinds).
102    pub variants: Vec<Variant>,
103    /// Generic type parameters captured as raw strings (e.g. `T`, `K`, `V`).
104    /// Bounds and lifetimes are not separated out.
105    pub type_params: Vec<String>,
106    /// Trait bounds mapped from type parameter to list of bounds.
107    /// E.g. { "T" => ["Clone", "Send"], "U" => ["Default"] }
108    pub trait_bounds: std::collections::HashMap<String, Vec<String>>,
109}
110
111/// Extract Rust struct definitions from a file
112///
113/// Parses `pub struct Name { field: Type, ... }` patterns and returns
114/// ServiceDef structs with field information.
115///
116/// # Example
117///
118/// ```rust,no_run
119/// # use crate::reverse_sync::ast_extractor::extract_rust_service;
120/// let services = extract_rust_service("src/service.rs")?;
121/// assert!(!services.is_empty());
122/// # Ok::<(), crate::utils::error::Error>(())
123/// # }
124/// ```
125pub fn extract_rust_service(file_path: &str) -> Result<Vec<ServiceDef>> {
126    let content = fs::read_to_string(file_path)
127        .map_err(|e| Error::new(&format!("Failed to read {}: {}", file_path, e)))?;
128
129    extract_rust_service_from_str(&content)
130}
131
132/// Extract Rust definitions from an in-memory source string.
133///
134/// Captures (regex-based headers + balanced-brace body scan):
135/// - `pub struct Name<...> { ... }` — name, generics, fields
136/// - `pub enum Name<...> { Variant, ... }` — name, generics, variant names
137/// - `pub trait Name<...> { fn ... }` — name, generics, required method signatures
138/// - `impl<...> Name<...> { fn ... }` (inherent and trait impls) — method signatures
139///   attached back to the matching struct/enum `ServiceDef`.
140///
141/// Block bodies are delimited with a brace-depth scan ([`balanced_block_body`])
142/// rather than a naive `{...}` regex, so nested braces (method bodies inside an
143/// `impl`, struct-variant payloads inside an `enum`) do not truncate the capture.
144///
145/// This is the workhorse behind [`extract_rust_service`]; it is separated so the
146/// extraction logic can be exercised without touching the filesystem.
147pub fn extract_rust_service_from_str(content: &str) -> Result<Vec<ServiceDef>> {
148    let mut services: Vec<ServiceDef> = Vec::new();
149
150    // --- Structs: pub struct Name<generics> { fields } ---
151    // The generics group is optional and non-greedy so it does not swallow the
152    // body. The body itself is captured with a balanced-brace scan so nested
153    // braces (rare in struct fields, common in struct-variant enums below) do
154    // not truncate the capture at the first `}`.
155    let struct_header_re =
156        Regex::new(r"pub\s+struct\s+(\w+)\s*(?:<([^>]*)>)?\s*(?:where\s+([^{]*))?\{")
157            .map_err(|e| Error::new(&format!("Failed to compile struct header regex: {}", e)))?;
158
159    for cap in struct_header_re.captures_iter(content) {
160        let name = cap_str(&cap, 1);
161        let type_params = cap
162            .get(2)
163            .map(|m| parse_type_params(m.as_str()))
164            .unwrap_or_default();
165
166        let open_brace_idx = match cap.get(0) {
167            Some(m) => m.end() - 1,
168            None => continue,
169        };
170        let body = balanced_block_body(content, open_brace_idx).unwrap_or("");
171
172        let fields = parse_struct_fields(body)?;
173
174        let mut trait_bounds =
175            extract_bounds_from_type_params(cap.get(2).map(|m| m.as_str()).unwrap_or(""));
176        if let Some(where_clause) = cap.get(3) {
177            trait_bounds.extend(extract_bounds_from_type_params(where_clause.as_str()));
178        }
179
180        services.push(ServiceDef {
181            name,
182            language: Language::Rust,
183            kind: ServiceKind::Struct,
184            fields,
185            methods: Vec::new(),
186            variants: Vec::new(),
187            type_params,
188            trait_bounds,
189        });
190    }
191
192    // --- Enums: pub enum Name<generics> { Variant, ... } ---
193    let enum_header_re =
194        Regex::new(r"pub\s+enum\s+(\w+)\s*(?:<([^>]*)>)?\s*(?:where\s+([^{]*))?\{")
195            .map_err(|e| Error::new(&format!("Failed to compile enum header regex: {}", e)))?;
196
197    for cap in enum_header_re.captures_iter(content) {
198        let name = cap_str(&cap, 1);
199        let type_params = cap
200            .get(2)
201            .map(|m| parse_type_params(m.as_str()))
202            .unwrap_or_default();
203
204        let open_brace_idx = match cap.get(0) {
205            Some(m) => m.end() - 1,
206            None => continue,
207        };
208        let body = balanced_block_body(content, open_brace_idx).unwrap_or("");
209
210        let variants = parse_enum_variants(body)?;
211        let mut trait_bounds =
212            extract_bounds_from_type_params(cap.get(2).map(|m| m.as_str()).unwrap_or(""));
213        if let Some(where_clause) = cap.get(3) {
214            trait_bounds.extend(extract_bounds_from_type_params(where_clause.as_str()));
215        }
216
217        services.push(ServiceDef {
218            name,
219            language: Language::Rust,
220            kind: ServiceKind::Enum,
221            fields: Vec::new(),
222            methods: Vec::new(),
223            variants,
224            type_params,
225            trait_bounds,
226        });
227    }
228
229    // --- Traits: pub trait Name<generics> [: bounds] { fn ...; } ---
230    // The trait header is matched with a regex, but the body is extracted with a
231    // balanced-brace scan so that default-method bodies (with their own `{ }`)
232    // and multiple methods are all captured — not just up to the first `}`.
233    let trait_header_re =
234        Regex::new(r"pub\s+trait\s+(\w+)\s*(?:<([^>]*)>)?\s*(?::[^{]*)?\s*(?:where\s+([^{]*))?\{")
235            .map_err(|e| Error::new(&format!("Failed to compile trait header regex: {}", e)))?;
236
237    for cap in trait_header_re.captures_iter(content) {
238        let name = cap_str(&cap, 1);
239        let type_params = cap
240            .get(2)
241            .map(|m| parse_type_params(m.as_str()))
242            .unwrap_or_default();
243
244        // The full match ends at the opening `{`; scan from there for the body.
245        let open_brace_idx = match cap.get(0) {
246            Some(m) => m.end() - 1,
247            None => continue,
248        };
249        let body = balanced_block_body(content, open_brace_idx).unwrap_or("");
250
251        let methods = parse_rust_fn_signatures(body)?;
252        let mut trait_bounds =
253            extract_bounds_from_type_params(cap.get(2).map(|m| m.as_str()).unwrap_or(""));
254        if let Some(where_clause) = cap.get(3) {
255            trait_bounds.extend(extract_bounds_from_type_params(where_clause.as_str()));
256        }
257
258        services.push(ServiceDef {
259            name,
260            language: Language::Rust,
261            kind: ServiceKind::Trait,
262            fields: Vec::new(),
263            methods,
264            variants: Vec::new(),
265            type_params,
266            trait_bounds,
267        });
268    }
269
270    // --- impl blocks: attach inherent/trait-impl methods to their type ---
271    // Matches `impl<...> Type<...> {` and `impl<...> Trait for Type<...> {`.
272    // The captured type name (group 1) is the receiver type in both inherent and
273    // `impl Trait for Type` forms. The body is extracted with a balanced-brace
274    // scan so method bodies do not truncate the capture at the first `}`.
275    let impl_header_re = Regex::new(
276        r"impl(?:<[^>]*>)?\s+(?:[\w:]+(?:<[^>]*>)?\s+for\s+)?(\w+)(?:<[^>]*>)?\s*(?:where\s+[^{]*)?\{",
277    )
278    .map_err(|e| Error::new(&format!("Failed to compile impl header regex: {}", e)))?;
279
280    for cap in impl_header_re.captures_iter(content) {
281        let type_name = cap_str(&cap, 1);
282
283        let open_brace_idx = match cap.get(0) {
284            Some(m) => m.end() - 1,
285            None => continue,
286        };
287        let body = balanced_block_body(content, open_brace_idx).unwrap_or("");
288
289        let methods = parse_rust_fn_signatures(body)?;
290        if methods.is_empty() {
291            continue;
292        }
293
294        // Attach to an existing struct/enum of the same name if present,
295        // otherwise record a stand-alone struct-kind ServiceDef so the methods
296        // are not lost (e.g. impl on a type defined in another file).
297        if let Some(existing) = services.iter_mut().find(|s| s.name == type_name) {
298            existing.methods.extend(methods);
299        } else {
300            services.push(ServiceDef {
301                name: type_name,
302                language: Language::Rust,
303                kind: ServiceKind::Struct,
304                fields: Vec::new(),
305                methods,
306                variants: Vec::new(),
307                type_params: Vec::new(),
308                trait_bounds: std::collections::HashMap::new(),
309            });
310        }
311    }
312
313    Ok(services)
314}
315
316/// Safely extract a capture group as an owned `String`, returning an empty
317/// string when the group is absent (avoids `unwrap` on optional captures).
318fn cap_str(cap: &regex::Captures<'_>, idx: usize) -> String {
319    cap.get(idx)
320        .map(|m| m.as_str().to_string())
321        .unwrap_or_default()
322}
323
324/// Given a byte index pointing at an opening `{` in `content`, return the inner
325/// body slice between that brace and its matching `}` (exclusive of both braces).
326///
327/// Uses a depth counter so nested braces (e.g. method bodies inside an `impl`
328/// block) are spanned correctly. Returns `None` if `open_idx` is not `{` or if
329/// no matching close brace is found. String/char-literal braces are NOT handled;
330/// this is a deliberate simplification of the regex-based extractor.
331fn balanced_block_body(content: &str, open_idx: usize) -> Option<&str> {
332    let bytes = content.as_bytes();
333    if open_idx >= bytes.len() || bytes[open_idx] != b'{' {
334        return None;
335    }
336
337    let mut depth = 0usize;
338    let body_start = open_idx + 1;
339    let mut i = open_idx;
340    while i < bytes.len() {
341        match bytes[i] {
342            b'{' => depth += 1,
343            b'}' => {
344                depth -= 1;
345                if depth == 0 {
346                    // body is everything between the opening and this closing brace
347                    return content.get(body_start..i);
348                }
349            }
350            _ => {}
351        }
352        i += 1;
353    }
354
355    None
356}
357
358/// Parse a comma-separated generic parameter list (the text between `<` and `>`).
359///
360/// Each parameter is kept as a raw string with any bound stripped to the
361/// leading identifier (`T: Clone + Send` -> `T`). Lifetimes (`'a`) and const
362/// generics are returned verbatim. This is intentionally shallow.
363fn parse_type_params(raw: &str) -> Vec<String> {
364    raw.split(',')
365        .map(|p| {
366            // Take the portion before any bound (`:`) and trim.
367            let head = p.split(':').next().unwrap_or(p).trim();
368            head.to_string()
369        })
370        .filter(|p| !p.is_empty())
371        .collect()
372}
373
374/// Extract trait bounds from a raw type parameter string.
375///
376/// Given `T: Clone + Send, U, V: Default`, returns a HashMap:
377/// - "T" => ["Clone", "Send"]
378/// - "V" => ["Default"]
379/// (U has no bounds, so it is not included in the map)
380pub fn extract_bounds_from_type_params(
381    raw: &str,
382) -> std::collections::HashMap<String, Vec<String>> {
383    use std::collections::HashMap;
384    let mut bounds_map: HashMap<String, Vec<String>> = HashMap::new();
385
386    for param_spec in raw.split(',') {
387        let param_spec = param_spec.trim();
388        if param_spec.is_empty() {
389            continue;
390        }
391
392        // Split on `:` to separate param name from bounds
393        let parts: Vec<&str> = param_spec.split(':').collect();
394        if parts.len() < 2 {
395            // No bounds for this param
396            continue;
397        }
398
399        let param_name = parts[0].trim().to_string();
400        let bounds_str = parts[1..].join(":"); // Rejoin in case of nested `:` (rare)
401
402        // Split bounds on `+` and collect as strings
403        let bounds: Vec<String> = bounds_str
404            .split('+')
405            .map(|b| b.trim().to_string())
406            .filter(|b| !b.is_empty())
407            .collect();
408
409        if !bounds.is_empty() {
410            bounds_map.insert(param_name, bounds);
411        }
412    }
413
414    bounds_map
415}
416
417/// Parse enum variant names and payloads from an enum body.
418///
419/// Splits the body on top-level commas (commas at brace/paren/angle depth 0) so
420/// payloads do not introduce spurious separators, then extracts the leading
421/// identifier and any payload. Handles `Variant`, `Variant(T)`,
422/// `Variant { .. }`, and `Variant = 1` forms on one line or many. Tuple/struct
423/// payloads are captured as raw strings; explicit discriminants are ignored.
424fn parse_enum_variants(body: &str) -> Result<Vec<Variant>> {
425    let mut variants = Vec::new();
426
427    // Leading identifier of a segment, allowing leading whitespace, attributes,
428    // and doc comments to be skipped by the trim below.
429    let ident_re = Regex::new(r"^\s*(?:#\[[^\]]*\]\s*)*(\w+)(.*)")
430        .map_err(|e| Error::new(&format!("Failed to compile variant ident regex: {}", e)))?;
431
432    for segment in split_top_level_commas(body) {
433        let segment = segment.trim();
434        if segment.is_empty() {
435            continue;
436        }
437        if let Some(cap) = ident_re.captures(segment) {
438            let name = cap_str(&cap, 1);
439            // Skip lines that are clearly not variants (e.g. a stray attribute word).
440            if !name.is_empty() {
441                let rest = cap.get(2).map(|m| m.as_str()).unwrap_or("").trim();
442                // Extract payload if present (before `=` for explicit discriminant)
443                let payload = if rest.starts_with('(') || rest.starts_with('{') {
444                    let payload_end = rest.find('=').unwrap_or(rest.len());
445                    let raw = rest[..payload_end].trim();
446                    if raw.is_empty() {
447                        None
448                    } else {
449                        Some(raw.to_string())
450                    }
451                } else {
452                    None
453                };
454                variants.push(Variant { name, payload });
455            }
456        }
457    }
458
459    Ok(variants)
460}
461
462/// Split a string on commas that are at the top nesting level — i.e. not inside
463/// `()`, `[]`, `{}`, or `<>`. Used to separate enum variants without breaking on
464/// commas inside payloads like `Variant(A, B)` or `Variant { x: u8, y: u8 }`.
465fn split_top_level_commas(input: &str) -> Vec<&str> {
466    let bytes = input.as_bytes();
467    let mut segments = Vec::new();
468    let mut depth: i32 = 0;
469    let mut start = 0usize;
470
471    for (i, &b) in bytes.iter().enumerate() {
472        match b {
473            b'(' | b'[' | b'{' | b'<' => depth += 1,
474            b')' | b']' | b'}' | b'>' => {
475                if depth > 0 {
476                    depth -= 1;
477                }
478            }
479            b',' if depth == 0 => {
480                if let Some(seg) = input.get(start..i) {
481                    segments.push(seg);
482                }
483                start = i + 1;
484            }
485            _ => {}
486        }
487    }
488
489    if let Some(seg) = input.get(start..) {
490        segments.push(seg);
491    }
492
493    segments
494}
495
496/// Parse Rust function signatures from a trait body or impl block body.
497///
498/// Matches `fn name(params) -> ReturnType` and `fn name(params)` (with optional
499/// leading `pub`/`async`/`const`/`unsafe` qualifiers, which are simply not
500/// captured). The return type is taken lazily up to the first `{`, `;`, or
501/// `where`. Generic params on the fn and `where` clauses are not separately
502/// modeled. The body passed in is expected to already be the full balanced block
503/// (see [`balanced_block_body`]), so every method in a multi-method impl/trait is
504/// visited — not just the first. Method *bodies* themselves are not parsed; only
505/// signatures are recovered. A param whose type contains a top-level `,` (e.g.
506/// `cb: fn(a, b)`) will be split into multiple raw param strings — a known
507/// limitation of the comma-split param parsing.
508fn parse_rust_fn_signatures(body: &str) -> Result<Vec<Method>> {
509    let mut methods = Vec::new();
510
511    // Qualifiers are optional and order-tolerant enough for common cases.
512    // Return type captured up to `{`, `;`, or `where`.
513    let fn_re = Regex::new(
514        r"fn\s+(\w+)\s*(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?:->\s*([^{;]+?))?\s*(?:where|\{|;)",
515    )
516    .map_err(|e| Error::new(&format!("Failed to compile fn regex: {}", e)))?;
517
518    for cap in fn_re.captures_iter(body) {
519        let name = cap_str(&cap, 1);
520        let params_str = cap.get(2).map(|m| m.as_str()).unwrap_or("");
521
522        let params: Vec<String> = params_str
523            .split(',')
524            .map(|p| p.trim().to_string())
525            .filter(|p| !p.is_empty())
526            .collect();
527
528        let return_type = cap
529            .get(3)
530            .map(|m| m.as_str().trim().to_string())
531            .filter(|s| !s.is_empty());
532
533        methods.push(Method {
534            name,
535            params,
536            return_type,
537        });
538    }
539
540    Ok(methods)
541}
542
543/// Extract Elixir GenServer definitions from a file
544///
545/// Parses `defmodule Name do ... use GenServer` patterns and extracts
546/// callback methods (init, handle_call, handle_cast, etc.)
547///
548/// # Example
549///
550/// ```rust,no_run
551/// # use crate::reverse_sync::ast_extractor::extract_elixir_genserver;
552/// let services = extract_elixir_genserver("lib/processor.ex")?;
553/// assert!(!services.is_empty());
554/// # Ok::<(), crate::utils::error::Error>(())
555/// # }
556/// ```
557pub fn extract_elixir_genserver(file_path: &str) -> Result<Vec<ServiceDef>> {
558    let content = fs::read_to_string(file_path)
559        .map_err(|e| Error::new(&format!("Failed to read {}: {}", file_path, e)))?;
560
561    let mut services = Vec::new();
562
563    // Regex to match: defmodule Name do ... end
564    let module_re = Regex::new(r"defmodule\s+(\w+)\s+do")
565        .map_err(|e| Error::new(&format!("Failed to compile module regex: {}", e)))?;
566
567    // Check if file contains GenServer pattern
568    let has_genserver = content.contains("use GenServer");
569
570    for cap in module_re.captures_iter(&content) {
571        let name = cap.get(1).unwrap().as_str().to_string();
572
573        let methods = if has_genserver {
574            extract_elixir_callbacks(&content)?
575        } else {
576            Vec::new()
577        };
578
579        services.push(ServiceDef {
580            name,
581            language: Language::Elixir,
582            kind: ServiceKind::Struct,
583            fields: Vec::new(),
584            methods,
585            variants: Vec::new(),
586            type_params: Vec::new(),
587            trait_bounds: std::collections::HashMap::new(),
588        });
589    }
590
591    Ok(services)
592}
593
594/// Extract callback method names from Elixir code
595fn extract_elixir_callbacks(content: &str) -> Result<Vec<Method>> {
596    let mut methods = Vec::new();
597
598    // Match: def callback_name(...) do ... end
599    let callback_re =
600        Regex::new(r"def\s+(init|handle_call|handle_cast|handle_info|terminate)\s*\(([^)]*)\)")
601            .map_err(|e| Error::new(&format!("Failed to compile callback regex: {}", e)))?;
602
603    for cap in callback_re.captures_iter(content) {
604        let name = cap.get(1).unwrap().as_str().to_string();
605        let params_str = cap.get(2).unwrap().as_str();
606
607        // Simple param parsing (split by comma, trim)
608        let params: Vec<String> = params_str
609            .split(',')
610            .map(|p| p.trim().to_string())
611            .filter(|p| !p.is_empty())
612            .collect();
613
614        methods.push(Method {
615            name,
616            params,
617            return_type: Some("tuple".to_string()), // Elixir callbacks return tuples
618        });
619    }
620
621    Ok(methods)
622}
623
624/// Extract Go struct definitions and their methods from a file
625///
626/// Parses `type Name struct { ... }` patterns and associated methods
627/// `func (s *Name) MethodName(...) ReturnType`
628///
629/// # Example
630///
631/// ```rust,no_run
632/// # use crate::reverse_sync::ast_extractor::extract_go_service;
633/// let services = extract_go_service("service.go")?;
634/// assert!(!services.is_empty());
635/// # Ok::<(), crate::utils::error::Error>(())
636/// # }
637/// ```
638pub fn extract_go_service(file_path: &str) -> Result<Vec<ServiceDef>> {
639    let content = fs::read_to_string(file_path)
640        .map_err(|e| Error::new(&format!("Failed to read {}: {}", file_path, e)))?;
641
642    let mut services = Vec::new();
643
644    // Regex to match: type Name struct { ... }
645    let struct_re = Regex::new(r"type\s+(\w+)\s+struct\s*\{([^}]*)\}")
646        .map_err(|e| Error::new(&format!("Failed to compile Go struct regex: {}", e)))?;
647
648    for cap in struct_re.captures_iter(&content) {
649        let name = cap.get(1).unwrap().as_str().to_string();
650        let body = cap.get(2).unwrap().as_str();
651
652        let fields = parse_go_struct_fields(body)?;
653        let methods = extract_go_methods(&content, &name)?;
654
655        services.push(ServiceDef {
656            name,
657            language: Language::Go,
658            kind: ServiceKind::Struct,
659            fields,
660            methods,
661            variants: Vec::new(),
662            type_params: Vec::new(),
663            trait_bounds: std::collections::HashMap::new(),
664        });
665    }
666
667    Ok(services)
668}
669
670/// Parse struct fields from Go struct body
671fn parse_go_struct_fields(body: &str) -> Result<Vec<Field>> {
672    let mut fields = Vec::new();
673
674    // Match: FieldName FieldType
675    let field_re = Regex::new(r"(\w+)\s+(\w+(?:\s*\[\])?(?:\s*\*)?)")
676        .map_err(|e| Error::new(&format!("Failed to compile field regex: {}", e)))?;
677
678    for cap in field_re.captures_iter(body) {
679        let field_name = cap.get(1).unwrap().as_str().to_string();
680        let field_type = cap.get(2).unwrap().as_str().to_string();
681
682        fields.push(Field {
683            name: field_name,
684            field_type,
685        });
686    }
687
688    Ok(fields)
689}
690
691/// Extract receiver methods for a Go struct
692fn extract_go_methods(content: &str, struct_name: &str) -> Result<Vec<Method>> {
693    let mut methods = Vec::new();
694
695    // Match: func (s *StructName) MethodName(...) ReturnType
696    let method_pattern = format!(
697        r"func\s*\(\s*\w+\s*\*{}\s*\)\s*(\w+)\s*\(([^)]*)\)\s*(\w+)?",
698        struct_name
699    );
700    let method_re = Regex::new(&method_pattern)
701        .map_err(|e| Error::new(&format!("Failed to compile Go method regex: {}", e)))?;
702
703    for cap in method_re.captures_iter(content) {
704        let method_name = cap.get(1).unwrap().as_str().to_string();
705        let params_str = cap.get(2).unwrap().as_str();
706
707        let params: Vec<String> = params_str
708            .split(',')
709            .map(|p| p.trim().to_string())
710            .filter(|p| !p.is_empty())
711            .collect();
712
713        let return_type = cap.get(3).map(|m| m.as_str().to_string());
714
715        methods.push(Method {
716            name: method_name,
717            params,
718            return_type,
719        });
720    }
721
722    Ok(methods)
723}
724
725/// Parse struct field definitions from Rust/Elixir struct body
726fn parse_struct_fields(body: &str) -> Result<Vec<Field>> {
727    let mut fields = Vec::new();
728
729    // Match: field_name: Type or field_name: Type,
730    let field_re = Regex::new(r"(\w+)\s*:\s*([^,}]+)")
731        .map_err(|e| Error::new(&format!("Failed to compile field regex: {}", e)))?;
732
733    for cap in field_re.captures_iter(body) {
734        let field_name = cap.get(1).unwrap().as_str().to_string();
735        let field_type = cap.get(2).unwrap().as_str().trim().to_string();
736
737        fields.push(Field {
738            name: field_name,
739            field_type,
740        });
741    }
742
743    Ok(fields)
744}
745
746/// Convert ServiceDef structures into RDF/Turtle format
747///
748/// Generates RDF triples describing services and their properties.
749/// Uses the `https://ggen.io/code#` namespace for code-related predicates.
750///
751/// # Example
752///
753/// ```rust,no_run
754/// # use crate::reverse_sync::ast_extractor::{extract_rust_service, convert_to_rdf};
755/// let services = extract_rust_service("src/lib.rs")?;
756/// let rdf = convert_to_rdf(&services)?;
757/// println!("{}", rdf);
758/// # Ok::<(), crate::utils::error::Error>(())
759/// # }
760/// ```
761pub fn convert_to_rdf(services: &[ServiceDef]) -> Result<String> {
762    let mut turtle = String::from(
763        "@prefix code: <https://ggen.io/code#> .\n\
764         @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n\
765         @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n\n",
766    );
767
768    for service in services {
769        let safe_name = sanitize_iri(&service.name);
770        let resource_id = format!("code:{}", safe_name);
771
772        // Construct type (struct=Service / enum=Enum / trait=Trait) and language.
773        turtle.push_str(&format!(
774            "{} a code:{} ;\n    code:language \"{}\" ;\n",
775            resource_id,
776            service.kind.rdf_class(),
777            service.language.as_str()
778        ));
779
780        // Generic type parameters (captured as raw identifiers).
781        if !service.type_params.is_empty() {
782            for tp in &service.type_params {
783                turtle.push_str(&format!("    code:typeParam \"{}\" ;\n", tp));
784                // Emit trait bounds for this parameter if present
785                if let Some(bounds) = service.trait_bounds.get(tp) {
786                    for bound in bounds {
787                        turtle.push_str(&format!("    code:traitBound \"{}\" ;\n", bound));
788                    }
789                }
790            }
791        }
792
793        // Add fields as properties
794        if !service.fields.is_empty() {
795            for field in &service.fields {
796                turtle.push_str(&format!(
797                    "    code:hasField [ a code:Field ; code:fieldName \"{}\" ; code:fieldType \"{}\" ] ;\n",
798                    field.name, field.field_type
799                ));
800            }
801        }
802
803        // Add enum variants
804        if !service.variants.is_empty() {
805            for variant in &service.variants {
806                turtle.push_str(&format!(
807                    "    code:hasVariant [ a code:Variant ; code:variantName \"{}\"",
808                    variant.name
809                ));
810                if let Some(payload) = &variant.payload {
811                    turtle.push_str(&format!("; code:variantPayload \"{}\"", payload));
812                }
813                turtle.push_str(" ] ;\n");
814            }
815        }
816
817        // Add methods
818        if !service.methods.is_empty() {
819            for method in &service.methods {
820                turtle.push_str(&format!(
821                    "    code:hasMethod [ a code:Method ; code:methodName \"{}\"",
822                    method.name
823                ));
824
825                if !method.params.is_empty() {
826                    let params_str = method.params.join(", ");
827                    turtle.push_str(&format!("; code:methodParams \"{}\"", params_str));
828                }
829
830                if let Some(return_type) = &method.return_type {
831                    turtle.push_str(&format!("; code:returnType \"{}\"", return_type));
832                }
833
834                turtle.push_str(" ] ;\n");
835            }
836        }
837
838        // Close resource (remove trailing semicolon from last property)
839        if turtle.ends_with(";\n") {
840            turtle.pop();
841            turtle.pop();
842            turtle.push_str(" .\n");
843        }
844
845        turtle.push('\n');
846    }
847
848    Ok(turtle)
849}
850
851/// Sanitize strings for use in IRIs
852///
853/// Removes or replaces special characters that are not valid in IRIs.
854fn sanitize_iri(input: &str) -> String {
855    input
856        .chars()
857        .map(|c| match c {
858            'a'..='z' | 'A'..='Z' | '0'..='9' | '_' => c,
859            _ => '_',
860        })
861        .collect()
862}
863
864#[cfg(test)]
865mod tests {
866    use super::*;
867
868    #[test]
869    fn test_sanitize_iri() {
870        assert_eq!(sanitize_iri("MyService"), "MyService");
871        assert_eq!(sanitize_iri("My-Service"), "My_Service");
872        assert_eq!(sanitize_iri("service.type"), "service_type");
873    }
874
875    #[test]
876    fn test_convert_to_rdf_empty() {
877        let services: Vec<ServiceDef> = vec![];
878        let rdf = convert_to_rdf(&services).unwrap();
879        assert!(rdf.contains("@prefix code:"));
880    }
881
882    #[test]
883    fn test_convert_to_rdf_with_service() {
884        let service = ServiceDef {
885            name: "MyService".to_string(),
886            language: Language::Rust,
887            kind: ServiceKind::Struct,
888            fields: vec![Field {
889                name: "id".to_string(),
890                field_type: "u64".to_string(),
891            }],
892            methods: vec![],
893            variants: vec![],
894            type_params: vec![],
895            trait_bounds: std::collections::HashMap::new(),
896        };
897
898        let rdf = convert_to_rdf(&[service]).unwrap();
899        assert!(rdf.contains("code:MyService"));
900        assert!(rdf.contains("code:Service"));
901        assert!(rdf.contains("\"rust\""));
902        assert!(rdf.contains("\"id\""));
903        assert!(rdf.contains("\"u64\""));
904    }
905
906    #[test]
907    fn test_convert_to_rdf_with_method() {
908        let service = ServiceDef {
909            name: "Handler".to_string(),
910            language: Language::Elixir,
911            kind: ServiceKind::Struct,
912            fields: vec![],
913            methods: vec![Method {
914                name: "handle_call".to_string(),
915                params: vec!["msg".to_string(), "from".to_string()],
916                return_type: Some("tuple".to_string()),
917            }],
918            variants: vec![],
919            type_params: vec![],
920            trait_bounds: std::collections::HashMap::new(),
921        };
922
923        let rdf = convert_to_rdf(&[service]).unwrap();
924        assert!(rdf.contains("code:Handler"));
925        assert!(rdf.contains("code:Method"));
926        assert!(rdf.contains("\"handle_call\""));
927        assert!(rdf.contains("code:methodParams"));
928        assert!(rdf.contains("code:returnType"));
929    }
930
931    #[test]
932    fn test_parse_struct_fields() {
933        let body = "id: u64, name: String, active: bool";
934        let fields = parse_struct_fields(body).unwrap();
935
936        assert_eq!(fields.len(), 3);
937        assert_eq!(fields[0].name, "id");
938        assert_eq!(fields[0].field_type, "u64");
939        assert_eq!(fields[1].name, "name");
940        assert_eq!(fields[1].field_type, "String");
941    }
942
943    #[test]
944    fn test_extract_elixir_callbacks() {
945        let content = r#"
946            defmodule MyHandler do
947              use GenServer
948
949              def init(args) do
950                {:ok, args}
951              end
952
953              def handle_call(msg, from, state) do
954                {:reply, msg, state}
955              end
956            end
957        "#;
958
959        let methods = extract_elixir_callbacks(content).unwrap();
960        assert!(methods.iter().any(|m| m.name == "init"));
961        assert!(methods.iter().any(|m| m.name == "handle_call"));
962    }
963
964    #[test]
965    fn test_parse_type_params_strips_bounds() {
966        let params = parse_type_params("T: Clone + Send, U, V: Default");
967        assert_eq!(
968            params,
969            vec!["T".to_string(), "U".to_string(), "V".to_string()]
970        );
971    }
972
973    #[test]
974    fn test_parse_enum_variants() {
975        let body = "Active,\n    Inactive,\n    Pending(u32),\n    Custom { code: u16 },\n";
976        let variants = parse_enum_variants(body).unwrap();
977        let names: Vec<&str> = variants.iter().map(|v| v.name.as_str()).collect();
978        assert!(names.contains(&"Active"));
979        assert!(names.contains(&"Inactive"));
980        assert!(names.contains(&"Pending"));
981        assert!(names.contains(&"Custom"));
982
983        // Verify payloads are captured
984        let pending = variants
985            .iter()
986            .find(|v| v.name == "Pending")
987            .expect("Pending variant");
988        assert!(pending.payload.is_some());
989        assert!(pending.payload.as_ref().unwrap().contains("u32"));
990
991        let custom = variants
992            .iter()
993            .find(|v| v.name == "Custom")
994            .expect("Custom variant");
995        assert!(custom.payload.is_some());
996        assert!(custom.payload.as_ref().unwrap().contains("code"));
997    }
998
999    #[test]
1000    fn test_parse_rust_fn_signatures() {
1001        let body = "fn start(&self) -> bool { true }\n    fn stop(&mut self, force: bool) { }\n";
1002        let methods = parse_rust_fn_signatures(body).unwrap();
1003        let start = methods
1004            .iter()
1005            .find(|m| m.name == "start")
1006            .expect("start fn");
1007        assert_eq!(start.return_type.as_deref(), Some("bool"));
1008        let stop = methods.iter().find(|m| m.name == "stop").expect("stop fn");
1009        assert!(stop.params.iter().any(|p| p.contains("force")));
1010    }
1011
1012    #[test]
1013    fn test_extract_rust_struct_with_generics() {
1014        let src = "pub struct Container<T> { item: T, count: usize }";
1015        let services = extract_rust_service_from_str(src).unwrap();
1016        let c = services
1017            .iter()
1018            .find(|s| s.name == "Container")
1019            .expect("Container");
1020        assert_eq!(c.kind, ServiceKind::Struct);
1021        assert!(c.type_params.contains(&"T".to_string()));
1022        assert!(c.fields.iter().any(|f| f.name == "item"));
1023    }
1024
1025    #[test]
1026    fn test_extract_rust_enum() {
1027        let src = "pub enum Status { Ok, Err, Pending }";
1028        let services = extract_rust_service_from_str(src).unwrap();
1029        let e = services
1030            .iter()
1031            .find(|s| s.name == "Status")
1032            .expect("Status enum");
1033        assert_eq!(e.kind, ServiceKind::Enum);
1034        let names: Vec<&str> = e.variants.iter().map(|v| v.name.as_str()).collect();
1035        assert!(names.contains(&"Ok"));
1036        assert!(names.contains(&"Err"));
1037        assert!(names.contains(&"Pending"));
1038    }
1039
1040    #[test]
1041    fn test_extract_rust_trait() {
1042        let src = "pub trait Runnable { fn run(&self) -> i32; fn name(&self) -> String; }";
1043        let services = extract_rust_service_from_str(src).unwrap();
1044        let t = services
1045            .iter()
1046            .find(|s| s.name == "Runnable")
1047            .expect("Runnable trait");
1048        assert_eq!(t.kind, ServiceKind::Trait);
1049        assert!(t.methods.iter().any(|m| m.name == "run"));
1050        assert!(t.methods.iter().any(|m| m.name == "name"));
1051    }
1052
1053    #[test]
1054    fn test_impl_methods_attached_to_struct() {
1055        let src = "pub struct Worker { id: u32 }\n\
1056                   impl Worker { fn process(&self) -> bool { true } fn reset(&mut self) { } }";
1057        let services = extract_rust_service_from_str(src).unwrap();
1058        let w = services
1059            .iter()
1060            .find(|s| s.name == "Worker")
1061            .expect("Worker");
1062        assert_eq!(w.kind, ServiceKind::Struct);
1063        assert!(w.methods.iter().any(|m| m.name == "process"));
1064        assert!(w.methods.iter().any(|m| m.name == "reset"));
1065    }
1066}