ggen-core 26.6.11

Core graph-aware code generation engine
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
//! Code graph operations
//!
//! Converts SPARQL query results into strongly-typed code graph entities
//! that can be rendered by Tera templates.

use crate::utils::error::{Error, Result};
use serde::Serialize;
use std::collections::BTreeMap;

/// Builder for code graph entities from SPARQL results
pub struct CodeGraphBuilder {
    /// Parsed structs
    structs: Vec<CodeStruct>,
    /// Parsed traits
    traits: Vec<CodeTrait>,
    /// Parsed impls
    impls: Vec<CodeImpl>,
    /// Parsed enums
    enums: Vec<CodeEnum>,
}

impl CodeGraphBuilder {
    /// Create a new code graph builder
    pub fn new() -> Self {
        Self {
            structs: Vec::new(),
            traits: Vec::new(),
            impls: Vec::new(),
            enums: Vec::new(),
        }
    }

    /// Parse SPARQL SELECT results into CodeStruct objects
    ///
    /// # Arguments
    /// * `results` - SPARQL query results as maps of variable bindings
    ///
    /// # Returns
    /// * `Ok(Vec<CodeStruct>)` - Parsed structs
    /// * `Err(Error)` - Parse error
    pub fn from_sparql_results(results: &[BTreeMap<String, String>]) -> Result<Vec<CodeStruct>> {
        let mut structs = Vec::new();

        for row in results {
            let name = row
                .get("name")
                .ok_or_else(|| Error::new("SPARQL result missing 'name' binding"))?;

            let iri = row.get("iri").cloned().unwrap_or_default();

            let struct_def = CodeStruct {
                iri,
                name: name.clone(),
                visibility: row
                    .get("visibility")
                    .cloned()
                    .unwrap_or_else(|| "pub".to_string()),
                derives: Self::parse_derives(row.get("derives")),
                generics: row.get("generics").cloned(),
                fields: Vec::new(), // Populated by separate query
                docstring: row.get("docstring").cloned(),
                attributes: Vec::new(),
                source_iri: row.get("source_iri").cloned(),
            };

            structs.push(struct_def);
        }

        Ok(structs)
    }

    /// Parse comma-separated derives into Vec
    fn parse_derives(derives: Option<&String>) -> Vec<String> {
        derives
            .map(|d| d.split(',').map(|s| s.trim().to_string()).collect())
            .unwrap_or_default()
    }

    /// Convert code graph entities to Tera context
    pub fn to_tera_context(&self) -> tera::Context {
        let mut ctx = tera::Context::new();
        ctx.insert("structs", &self.structs);
        ctx.insert("traits", &self.traits);
        ctx.insert("impls", &self.impls);
        ctx.insert("enums", &self.enums);
        ctx
    }

    /// Add a struct to the code graph
    pub fn add_struct(&mut self, s: CodeStruct) {
        self.structs.push(s);
    }

    /// Add a trait to the code graph
    pub fn add_trait(&mut self, t: CodeTrait) {
        self.traits.push(t);
    }

    /// Add an impl to the code graph
    pub fn add_impl(&mut self, i: CodeImpl) {
        self.impls.push(i);
    }

    /// Build an impl block from a relationship definition
    ///
    /// # Arguments
    /// * `source` - Source entity name (e.g., "User")
    /// * `rel_type` - Relationship type (e.g., "has_many")
    /// * `target` - Target entity name (e.g., "Order")
    pub fn build_impl_from_relationship(source: &str, rel_type: &str, target: &str) -> CodeImpl {
        let method_name = match rel_type {
            "has_many" => format!("get_{}s", target.to_lowercase()),
            "has_one" | "belongs_to" => format!("get_{}", target.to_lowercase()),
            _ => format!("get_{}", target.to_lowercase()),
        };

        let return_type = match rel_type {
            "has_many" => format!("Vec<{}>", target),
            _ => target.to_string(),
        };

        CodeImpl {
            iri: String::new(),
            for_type: source.to_string(),
            trait_name: None,
            generics: None,
            methods: vec![CodeMethod {
                iri: String::new(),
                name: method_name,
                visibility: "pub".to_string(),
                is_async: false,
                self_param: Some("&self".to_string()),
                params: Vec::new(),
                return_type: Some(return_type.clone()),
                body: Some(if return_type.starts_with("Vec<") {
                    "Vec::new()".to_string()
                } else if return_type.starts_with("Option<") {
                    "None".to_string()
                } else if return_type.starts_with("Result<") {
                    "Err(crate::utils::error::Error::new(\"Not implemented\"))".to_string()
                } else {
                    "Default::default()".to_string()
                }),
                docstring: Some(format!(
                    "Get {} {}(s)",
                    rel_type.replace('_', " "),
                    target.to_lowercase()
                )),
            }],
        }
    }
}

impl Default for CodeGraphBuilder {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Code Graph Entity Types
// ============================================================================

/// Represents a Rust module
#[derive(Debug, Clone, Serialize)]
pub struct CodeModule {
    /// IRI identifying this module
    pub iri: String,
    /// Module name (e.g., "models")
    pub name: String,
    /// Visibility ("pub", "pub(crate)", "")
    #[serde(default)]
    pub visibility: String,
    /// Use statements
    #[serde(default)]
    pub imports: Vec<CodeImport>,
    /// Module items (structs, traits, impls)
    #[serde(default)]
    pub items: Vec<CodeItem>,
    /// Module-level attributes
    #[serde(default)]
    pub attributes: Vec<String>,
}

/// A code item (struct, trait, impl, or enum)
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub enum CodeItem {
    /// Rust struct
    Struct(CodeStruct),
    /// Rust trait
    Trait(CodeTrait),
    /// Rust impl block
    Impl(CodeImpl),
    /// Rust enum
    Enum(CodeEnum),
}

/// Represents a Rust struct
#[derive(Debug, Clone, Serialize)]
pub struct CodeStruct {
    /// IRI from code graph
    pub iri: String,
    /// Struct name (PascalCase)
    pub name: String,
    /// Visibility
    #[serde(default)]
    pub visibility: String,
    /// Derive macros
    #[serde(default)]
    pub derives: Vec<String>,
    /// Generic parameters
    #[serde(default)]
    pub generics: Option<String>,
    /// Struct fields (ordered)
    #[serde(default)]
    pub fields: Vec<CodeField>,
    /// Documentation string
    #[serde(default)]
    pub docstring: Option<String>,
    /// Additional attributes
    #[serde(default)]
    pub attributes: Vec<String>,
    /// Source traceability
    #[serde(default)]
    pub source_iri: Option<String>,
}

/// Represents a struct field
#[derive(Debug, Clone, Serialize)]
pub struct CodeField {
    /// IRI from code graph
    pub iri: String,
    /// Field name (snake_case)
    pub name: String,
    /// Rust type
    pub field_type: String,
    /// Visibility
    #[serde(default)]
    pub visibility: String,
    /// Documentation
    #[serde(default)]
    pub docstring: Option<String>,
    /// Field attributes
    #[serde(default)]
    pub attributes: Vec<String>,
    /// Default value expression
    #[serde(default)]
    pub default: Option<String>,
}

/// Represents a Rust trait
#[derive(Debug, Clone, Serialize)]
pub struct CodeTrait {
    /// IRI from code graph
    pub iri: String,
    /// Trait name
    pub name: String,
    /// Visibility
    #[serde(default)]
    pub visibility: String,
    /// Trait bounds
    #[serde(default)]
    pub bounds: Option<String>,
    /// Trait methods
    #[serde(default)]
    pub methods: Vec<CodeMethod>,
    /// Whether trait has async methods
    #[serde(default)]
    pub is_async: bool,
    /// Documentation
    #[serde(default)]
    pub docstring: Option<String>,
}

/// Represents a method signature or implementation
#[derive(Debug, Clone, Serialize)]
pub struct CodeMethod {
    /// IRI from code graph
    pub iri: String,
    /// Method name
    pub name: String,
    /// Visibility
    #[serde(default)]
    pub visibility: String,
    /// Whether method is async
    #[serde(default)]
    pub is_async: bool,
    /// Self parameter ("&self", "&mut self", "self", None)
    #[serde(default)]
    pub self_param: Option<String>,
    /// Method parameters
    #[serde(default)]
    pub params: Vec<CodeParam>,
    /// Return type
    #[serde(default)]
    pub return_type: Option<String>,
    /// Method body (for impls)
    #[serde(default)]
    pub body: Option<String>,
    /// Documentation
    #[serde(default)]
    pub docstring: Option<String>,
}

/// Represents a method parameter
#[derive(Debug, Clone, Serialize)]
pub struct CodeParam {
    /// Parameter name
    pub name: String,
    /// Parameter type
    pub param_type: String,
}

/// Represents a Rust impl block
#[derive(Debug, Clone, Serialize)]
pub struct CodeImpl {
    /// IRI from code graph
    pub iri: String,
    /// Type being implemented for
    pub for_type: String,
    /// Trait being implemented (if any)
    #[serde(default)]
    pub trait_name: Option<String>,
    /// Generic parameters
    #[serde(default)]
    pub generics: Option<String>,
    /// Implemented methods
    #[serde(default)]
    pub methods: Vec<CodeMethod>,
}

/// Represents a Rust enum
#[derive(Debug, Clone, Serialize)]
pub struct CodeEnum {
    /// IRI from code graph
    pub iri: String,
    /// Enum name
    pub name: String,
    /// Visibility
    #[serde(default)]
    pub visibility: String,
    /// Derive macros
    #[serde(default)]
    pub derives: Vec<String>,
    /// Enum variants
    #[serde(default)]
    pub variants: Vec<CodeVariant>,
    /// Documentation
    #[serde(default)]
    pub docstring: Option<String>,
}

/// Represents an enum variant
#[derive(Debug, Clone, Serialize)]
pub struct CodeVariant {
    /// Variant name
    pub name: String,
    /// Variant fields (for tuple/struct variants)
    #[serde(default)]
    pub fields: Vec<CodeField>,
    /// Documentation
    #[serde(default)]
    pub docstring: Option<String>,
}

/// Represents a use/import statement
#[derive(Debug, Clone, Serialize)]
pub struct CodeImport {
    /// Import path
    pub path: String,
    /// Optional alias
    #[serde(default)]
    pub alias: Option<String>,
}

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

    #[test]
    fn test_parse_derives() {
        let derives = Some("Debug, Clone, Serialize".to_string());
        let result = CodeGraphBuilder::parse_derives(derives.as_ref());
        assert_eq!(result, vec!["Debug", "Clone", "Serialize"]);
    }

    #[test]
    fn test_build_impl_has_many() {
        let impl_block =
            CodeGraphBuilder::build_impl_from_relationship("User", "has_many", "Order");
        assert_eq!(impl_block.for_type, "User");
        assert_eq!(impl_block.methods.len(), 1);
        assert_eq!(impl_block.methods[0].name, "get_orders");
        assert_eq!(
            impl_block.methods[0].return_type,
            Some("Vec<Order>".to_string())
        );
    }

    #[test]
    fn test_build_impl_belongs_to() {
        let impl_block =
            CodeGraphBuilder::build_impl_from_relationship("Order", "belongs_to", "User");
        assert_eq!(impl_block.methods[0].name, "get_user");
        assert_eq!(impl_block.methods[0].return_type, Some("User".to_string()));
    }

    #[test]
    fn test_from_sparql_results() {
        let mut row = BTreeMap::new();
        row.insert("name".to_string(), "User".to_string());
        row.insert("iri".to_string(), "http://example.org/User".to_string());
        row.insert("derives".to_string(), "Debug, Clone".to_string());
        row.insert("docstring".to_string(), "A user entity".to_string());

        let results = CodeGraphBuilder::from_sparql_results(&[row]).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "User");
        assert_eq!(results[0].derives, vec!["Debug", "Clone"]);
    }
}