ryo-suggest 0.1.0

[experimental] Pattern-based suggestion engine for RYO
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
//! SpecGenerator - Generate code from Spec definitions
//!
//! This module provides Spec-first code generation, complementing the
//! problem-detection approach of Suggest.
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  Suggest (Problem Detection)    vs    SpecGenerator (Creation)  │
//! │  ────────────────────────────────────────────────────────────── │
//! │  Code → detect() → Problems       Spec → generate() → New Code  │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! # Usage
//!
//! ```ignore
//! use ryo_suggest::spec::{SpecGenerator, DomainSpecGenerator};
//!
//! let generator = DomainSpecGenerator::new();
//! let specs = generator.generate(&ctx, &spec_alias_data);
//! // specs: Vec<MutationSpec> containing AddField, AddMethod, etc.
//! ```

use ryo_analysis::context::AnalysisContext;
use ryo_analysis::query::SpecAliasData;
use ryo_analysis::{SymbolId, SymbolKind};
use ryo_executor::{SelfParam, Visibility};

use crate::MutationSpec;

/// Trait for generating code from Spec definitions
///
/// Unlike `Suggest` which detects problems in existing code,
/// `SpecGenerator` creates new code based on Spec definitions.
pub trait SpecGenerator: Send + Sync {
    /// Generator name for identification
    fn name(&self) -> &'static str;

    /// Description of what this generator creates
    fn description(&self) -> &str;

    /// Check if this generator applies to the given Spec
    fn matches(&self, spec: &SpecAliasData) -> bool;

    /// Generate MutationSpecs from a Spec definition
    ///
    /// Returns structured MutationSpecs (AddField, AddMethod, etc.)
    /// rather than raw code strings when possible.
    fn generate(&self, ctx: &AnalysisContext, spec: &SpecAliasData) -> Vec<MutationSpec>;
}

/// Options for code generation
#[derive(Debug, Clone, Default)]
pub struct GeneratorOptions {
    /// Generate accessor methods for relations
    pub generate_accessors: bool,
    /// Generate ID field for relations (e.g., order_id: OrderId)
    pub generate_id_fields: bool,
    /// Generate collection fields for relations (e.g., orders: Vec<Order>)
    pub generate_collection_fields: bool,
    /// Default derives to add
    pub default_derives: Vec<String>,
}

impl GeneratorOptions {
    pub fn new() -> Self {
        Self {
            generate_accessors: true,
            generate_id_fields: true,
            generate_collection_fields: false,
            default_derives: vec!["Debug".into(), "Clone".into()],
        }
    }

    pub fn with_accessors(mut self, enabled: bool) -> Self {
        self.generate_accessors = enabled;
        self
    }

    pub fn with_id_fields(mut self, enabled: bool) -> Self {
        self.generate_id_fields = enabled;
        self
    }

    pub fn with_collection_fields(mut self, enabled: bool) -> Self {
        self.generate_collection_fields = enabled;
        self
    }

    pub fn with_derives(mut self, derives: Vec<String>) -> Self {
        self.default_derives = derives;
        self
    }
}

/// Generator for domain model Specs
///
/// Generates struct fields and methods based on Spec relations.
///
/// # Generated Code
///
/// For `type UserSpec = Spec<DomainGroup, User, [DependsOn<Order>]>`:
///
/// - `AddField { field_name: "order_id", field_type: "OrderId" }`
/// - `AddMethod { method_name: "order_id", return_type: "&OrderId" }`
/// - `AddDerive { derives: ["Debug", "Clone"] }` (if not present)
pub struct DomainSpecGenerator {
    options: GeneratorOptions,
    /// Groups this generator applies to
    target_groups: Vec<String>,
}

impl DomainSpecGenerator {
    pub fn new() -> Self {
        Self {
            options: GeneratorOptions::new(),
            target_groups: vec!["DomainGroup".into()],
        }
    }

    pub fn with_options(mut self, options: GeneratorOptions) -> Self {
        self.options = options;
        self
    }

    pub fn with_groups(mut self, groups: Vec<String>) -> Self {
        self.target_groups = groups;
        self
    }

    /// Extract relation targets from a Spec (types it depends on)
    fn extract_relations(&self, ctx: &AnalysisContext, spec: &SpecAliasData) -> Vec<String> {
        use super::is_framework_type;

        let typeflow = ctx.typeflow_graph();
        let mut relations = Vec::new();

        let base_type = spec.wrapped_type_name.as_deref().unwrap_or("");

        for used_id in typeflow.types_used_by(spec.alias_id) {
            if let Some(path) = ctx.registry.path(used_id) {
                let kind = ctx.registry.kind(used_id);

                if !matches!(kind, Some(SymbolKind::Struct) | Some(SymbolKind::Enum)) {
                    continue;
                }

                let name = path.name();
                if is_framework_type(name) || name == base_type {
                    continue;
                }

                relations.push(name.to_string());
            }
        }

        relations
    }

    /// Check if struct has a field for the relation
    fn has_field_for(&self, ctx: &AnalysisContext, struct_id: SymbolId, target: &str) -> bool {
        let graph = ctx.code_graph();
        let target_lower = target.to_lowercase();

        for child_id in graph.children_of(struct_id) {
            if let Some(SymbolKind::Field) = ctx.registry.kind(child_id) {
                if let Some(path) = ctx.registry.path(child_id) {
                    if path.name().to_lowercase().contains(&target_lower) {
                        return true;
                    }
                }
            }
        }

        false
    }

    /// Check if struct has a method (simplified - checks children)
    fn has_method(&self, ctx: &AnalysisContext, struct_id: SymbolId, method_name: &str) -> bool {
        let graph = ctx.code_graph();

        // Check children (methods in impl blocks are children of the type)
        for child_id in graph.children_of(struct_id) {
            if let Some(SymbolKind::Method) = ctx.registry.kind(child_id) {
                if let Some(path) = ctx.registry.path(child_id) {
                    if path.name() == method_name {
                        return true;
                    }
                }
            }
        }

        false
    }

    /// Convert PascalCase to snake_case
    fn to_snake_case(&self, s: &str) -> String {
        let mut result = String::new();
        for (i, c) in s.chars().enumerate() {
            if c.is_uppercase() && i > 0 {
                result.push('_');
            }
            result.push(c.to_ascii_lowercase());
        }
        result
    }
}

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

impl SpecGenerator for DomainSpecGenerator {
    fn name(&self) -> &'static str {
        "domain-spec-generator"
    }

    fn description(&self) -> &str {
        "Generates struct fields and methods from domain Spec relations"
    }

    fn matches(&self, spec: &SpecAliasData) -> bool {
        // Check if spec belongs to one of our target groups
        // We need to get the group name, but SpecAliasData only has group_idx
        // For now, match all specs with wrapped types
        spec.wrapped_type_id.is_some()
    }

    fn generate(&self, ctx: &AnalysisContext, spec: &SpecAliasData) -> Vec<MutationSpec> {
        let mut mutations = Vec::new();

        // Get the wrapped struct
        let struct_id = match spec.wrapped_type_id {
            Some(id) => id,
            None => return mutations,
        };

        let _struct_name = match &spec.wrapped_type_name {
            Some(name) => name.clone(),
            None => return mutations,
        };

        // Extract relations
        let relations = self.extract_relations(ctx, spec);

        // Generate fields for each relation
        for relation in &relations {
            let field_name = format!("{}_id", self.to_snake_case(relation));
            let field_type = format!("{}Id", relation);

            // Check if field already exists
            if !self.has_field_for(ctx, struct_id, relation) && self.options.generate_id_fields {
                mutations.push(MutationSpec::AddField {
                    target: ryo_executor::MutationTargetSymbol::ById(struct_id),
                    field_name: field_name.clone(),
                    field_type: field_type.clone(),
                    visibility: Visibility::Pub,
                });
            }

            // Generate accessor method
            if self.options.generate_accessors && !self.has_method(ctx, struct_id, &field_name) {
                mutations.push(MutationSpec::AddMethod {
                    target: ryo_executor::MutationTargetSymbol::ById(struct_id),
                    method_name: field_name.clone(),
                    params: vec![],
                    return_type: Some(format!("&{}", field_type)),
                    body: format!("&self.{}", field_name),
                    is_pub: true,
                    self_param: Some(SelfParam::Ref),
                });
            }
        }

        // Add default derives if configured
        if !self.options.default_derives.is_empty() {
            // Check which derives are missing (simplified - always add for now)
            mutations.push(MutationSpec::AddDerive {
                target: ryo_executor::MutationTargetSymbol::ById(struct_id),
                derives: self.options.default_derives.clone(),
            });
        }

        mutations
    }
}

/// Registry for SpecGenerators
#[derive(Default)]
pub struct SpecGeneratorRegistry {
    generators: Vec<Box<dyn SpecGenerator>>,
}

impl SpecGeneratorRegistry {
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a generator
    pub fn register<G: SpecGenerator + 'static>(&mut self, generator: G) {
        self.generators.push(Box::new(generator));
    }

    /// Generate MutationSpecs for a Spec using all matching generators
    pub fn generate_for(&self, ctx: &AnalysisContext, spec: &SpecAliasData) -> Vec<MutationSpec> {
        let mut all_mutations = Vec::new();

        for generator in &self.generators {
            if generator.matches(spec) {
                let mutations = generator.generate(ctx, spec);
                all_mutations.extend(mutations);
            }
        }

        all_mutations
    }

    /// Generate MutationSpecs for all Specs in the context
    ///
    /// Iterates all TypeAliases matching Spec pattern and generates code.
    pub fn generate_all(&self, ctx: &AnalysisContext) -> Vec<(String, Vec<MutationSpec>)> {
        let mut results = Vec::new();

        // Find all TypeAliases that look like Specs
        for symbol_id in ctx.registry.iter_by_kind(SymbolKind::TypeAlias) {
            let path = match ctx.registry.path(symbol_id) {
                Some(p) => p,
                None => continue,
            };

            let alias_name = path.name();
            if !alias_name.ends_with("Spec") || alias_name == "Spec" {
                continue;
            }

            // Build SpecAliasData manually
            let base_type = &alias_name[..alias_name.len() - 4]; // Remove "Spec"
            let wrapped_type_id = self.find_struct_by_name(ctx, base_type);

            let spec_data = SpecAliasData {
                alias_id: symbol_id,
                alias_name: alias_name.to_string(),
                wrapped_type_id,
                wrapped_type_name: Some(base_type.to_string()),
                group_idx: 0, // Unknown
                source: ryo_analysis::query::SpecSource::TypeAlias,
            };

            let mutations = self.generate_for(ctx, &spec_data);
            if !mutations.is_empty() {
                results.push((alias_name.to_string(), mutations));
            }
        }

        results
    }

    /// Find struct by name
    fn find_struct_by_name(&self, ctx: &AnalysisContext, name: &str) -> Option<SymbolId> {
        for symbol_id in ctx.registry.iter_by_kind(SymbolKind::Struct) {
            if let Some(path) = ctx.registry.path(symbol_id) {
                if path.name() == name {
                    return Some(symbol_id);
                }
            }
        }
        None
    }
}

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

    #[test]
    fn test_to_snake_case() {
        let gen = DomainSpecGenerator::new();
        assert_eq!(gen.to_snake_case("Order"), "order");
        assert_eq!(gen.to_snake_case("OrderItem"), "order_item");
        assert_eq!(gen.to_snake_case("HTTPRequest"), "h_t_t_p_request");
    }

    #[test]
    fn test_generator_options() {
        let opts = GeneratorOptions::new()
            .with_accessors(false)
            .with_id_fields(true)
            .with_derives(vec!["Serialize".into()]);

        assert!(!opts.generate_accessors);
        assert!(opts.generate_id_fields);
        assert_eq!(opts.default_derives, vec!["Serialize"]);
    }

    #[test]
    fn test_domain_spec_generator_new() {
        let gen = DomainSpecGenerator::new();
        assert_eq!(gen.name(), "domain-spec-generator");
        assert!(gen.options.generate_accessors);
        assert!(gen.options.generate_id_fields);
    }
}