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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Parameterized Suggest implementations for code generation.
//!
//! These suggestions accept external parameters to generate code from patterns.
//! LLMs can discover available patterns via `SuggestService::list_parameterized()`.

use ryo_analysis::context::AnalysisContext;
use ryo_analysis::{SymbolId, SymbolPath};

use crate::suggest::{
    MutationSpec, OpportunityContext, OpportunityId, ParamDef, SafetyLevel, Suggest,
    SuggestCategory, SuggestLocation, SuggestOpportunity, SuggestParams, SuggestResult,
};

// =============================================================================
// Helper Functions
// =============================================================================

/// Create a SuggestLocation for generated code (not from existing source).
fn create_generation_location(name: &str) -> SuggestLocation {
    // Use a dummy SymbolId for generated code
    let symbol_id = SymbolId::parse("0v1").expect("valid dummy SymbolId");

    let symbol_path = SymbolPath::builder("generated")
        .push(name)
        .build()
        .unwrap_or_else(|_| SymbolPath::builder("generated").build().expect("path"));

    SuggestLocation::new(symbol_id, symbol_path, "(generated)")
}

// =============================================================================
// DomainStructSuggest - Generate domain struct from pattern
// =============================================================================

/// Generates a domain struct with common patterns.
///
/// # Parameters
/// - `name` (required): Struct name (e.g., "Order")
/// - `fields` (optional): Comma-separated field definitions (e.g., "id:u64,name:String")
///
/// # Generated Code
/// ```ignore
/// #[derive(Debug, Clone)]
/// pub struct Order {
///     pub id: u64,
///     pub name: String,
/// }
/// ```
pub struct DomainStructSuggest {
    default_derives: Vec<String>,
}

impl DomainStructSuggest {
    pub fn new() -> Self {
        Self {
            default_derives: vec!["Debug".into(), "Clone".into()],
        }
    }

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

    /// Parse fields from comma-separated string.
    /// Format: "name:Type,other:OtherType"
    fn parse_fields(&self, fields_str: &str) -> Vec<(String, String)> {
        if fields_str.is_empty() {
            return vec![];
        }

        fields_str
            .split(',')
            .filter_map(|field| {
                let parts: Vec<&str> = field.trim().split(':').collect();
                if parts.len() == 2 {
                    Some((parts[0].trim().to_string(), parts[1].trim().to_string()))
                } else {
                    None
                }
            })
            .collect()
    }
}

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

impl Suggest for DomainStructSuggest {
    fn name(&self) -> &'static str {
        "domain-struct"
    }

    fn description(&self) -> &str {
        "Generate a domain struct with derives and fields"
    }

    fn category(&self) -> SuggestCategory {
        SuggestCategory::Pattern
    }

    fn safety_level(&self) -> SafetyLevel {
        SafetyLevel::Confirm
    }

    fn rule_id(&self) -> Option<&str> {
        Some("RG001")
    }

    fn accepts_params(&self) -> bool {
        true
    }

    fn param_schema(&self) -> Vec<ParamDef> {
        vec![
            ParamDef::required("name", "Struct name (e.g., Order, User, Product)"),
            ParamDef::optional(
                "fields",
                "Comma-separated fields (e.g., id:u64,name:String)",
            ),
            ParamDef::optional("derives", "Comma-separated derives (default: Debug,Clone)"),
        ]
    }

    fn detect_with_params(
        &self,
        _ctx: &AnalysisContext,
        _symbols: &[SymbolId],
        params: &SuggestParams,
    ) -> Vec<SuggestOpportunity> {
        let Some(name) = params.get("name") else {
            return vec![];
        };

        let fields = params
            .get("fields")
            .map(|s| self.parse_fields(s))
            .unwrap_or_default();

        let derives = params
            .get("derives")
            .map(|s| s.split(',').map(|d| d.trim().to_string()).collect())
            .unwrap_or_else(|| self.default_derives.clone());

        let message = format!(
            "Generate struct `{}` with {} fields and derives {:?}",
            name,
            fields.len(),
            derives
        );

        // Create a dummy location since this is generation, not detection
        let location = create_generation_location(name);

        vec![SuggestOpportunity::new(
            OpportunityId::new(0),
            vec![],
            location,
            message,
            1.0,
            OpportunityContext::Generation {
                pattern: "domain-struct".to_string(),
                params: params.clone(),
            },
        )]
    }

    fn detect(&self, _ctx: &AnalysisContext, _symbols: &[SymbolId]) -> Vec<SuggestOpportunity> {
        // This is a generation-only suggest, no detection
        vec![]
    }

    fn to_mutation_specs(
        &self,
        _ctx: &AnalysisContext,
        opportunity: &SuggestOpportunity,
    ) -> SuggestResult<Vec<MutationSpec>> {
        let OpportunityContext::Generation { params, .. } = &opportunity.context else {
            return Ok(vec![]);
        };

        let Some(name) = params.get("name") else {
            return Ok(vec![]);
        };

        let fields = params
            .get("fields")
            .map(|s| self.parse_fields(s))
            .unwrap_or_default();

        let derives = params
            .get("derives")
            .map(|s| s.split(',').map(|d| d.trim().to_string()).collect())
            .unwrap_or_else(|| self.default_derives.clone());

        // Build struct code
        let mut code = String::new();

        // Add derives
        if !derives.is_empty() {
            code.push_str(&format!("#[derive({})]\n", derives.join(", ")));
        }

        // Add struct definition
        code.push_str(&format!("pub struct {} {{\n", name));
        for (field_name, field_type) in &fields {
            code.push_str(&format!("    pub {}: {},\n", field_name, field_type));
        }
        code.push('}');

        // Use AddItem to add the struct
        let target = SymbolPath::parse("crate")
            .unwrap_or_else(|_| SymbolPath::builder("crate").build().expect("crate path"));

        Ok(vec![MutationSpec::AddItem {
            target: ryo_executor::MutationTargetSymbol::ByPath(Box::new(target)),
            content: code,
            position: ryo_executor::InsertPosition::Bottom,
        }])
    }
}

// =============================================================================
// ApiPatternSuggest - Generate API struct with CRUD methods
// =============================================================================

/// Generates an API struct with common CRUD methods.
///
/// # Parameters
/// - `name` (required): API name prefix (e.g., "Order" -> OrderAPI)
/// - `entity` (optional): Entity type (default: same as name)
///
/// # Generated Code
/// ```ignore
/// pub struct OrderAPI {
///     // ...
/// }
///
/// impl OrderAPI {
///     pub fn new() -> Self { ... }
///     pub fn get(&self, id: OrderId) -> Result<Order, Error> { ... }
///     pub fn list(&self) -> Result<Vec<Order>, Error> { ... }
///     pub fn create(&self, entity: Order) -> Result<Order, Error> { ... }
///     pub fn update(&self, id: OrderId, entity: Order) -> Result<Order, Error> { ... }
///     pub fn delete(&self, id: OrderId) -> Result<(), Error> { ... }
/// }
/// ```
pub struct ApiPatternSuggest {
    methods: Vec<ApiMethod>,
}

#[derive(Clone)]
struct ApiMethod {
    name: &'static str,
    has_id_param: bool,
    has_entity_param: bool,
    returns_entity: bool,
}

impl ApiPatternSuggest {
    pub fn new() -> Self {
        Self {
            methods: vec![
                ApiMethod {
                    name: "get",
                    has_id_param: true,
                    has_entity_param: false,
                    returns_entity: true,
                },
                ApiMethod {
                    name: "list",
                    has_id_param: false,
                    has_entity_param: false,
                    returns_entity: true,
                },
                ApiMethod {
                    name: "create",
                    has_id_param: false,
                    has_entity_param: true,
                    returns_entity: true,
                },
                ApiMethod {
                    name: "update",
                    has_id_param: true,
                    has_entity_param: true,
                    returns_entity: true,
                },
                ApiMethod {
                    name: "delete",
                    has_id_param: true,
                    has_entity_param: false,
                    returns_entity: false,
                },
            ],
        }
    }
}

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

impl Suggest for ApiPatternSuggest {
    fn name(&self) -> &'static str {
        "api-pattern"
    }

    fn description(&self) -> &str {
        "Generate API struct with CRUD methods (get, list, create, update, delete)"
    }

    fn category(&self) -> SuggestCategory {
        SuggestCategory::Pattern
    }

    fn safety_level(&self) -> SafetyLevel {
        SafetyLevel::Confirm
    }

    fn rule_id(&self) -> Option<&str> {
        Some("RG002")
    }

    fn accepts_params(&self) -> bool {
        true
    }

    fn param_schema(&self) -> Vec<ParamDef> {
        vec![
            ParamDef::required("name", "API name prefix (e.g., Order -> OrderAPI)"),
            ParamDef::optional("entity", "Entity type name (default: same as name)"),
            ParamDef::optional(
                "methods",
                "Comma-separated methods to generate (default: get,list,create,update,delete)",
            ),
        ]
    }

    fn detect_with_params(
        &self,
        _ctx: &AnalysisContext,
        _symbols: &[SymbolId],
        params: &SuggestParams,
    ) -> Vec<SuggestOpportunity> {
        let Some(name) = params.get("name") else {
            return vec![];
        };

        let api_name = format!("{}API", name);
        let entity = params
            .get("entity")
            .cloned()
            .unwrap_or_else(|| name.clone());

        let method_names: Vec<&str> = params
            .get("methods")
            .map(|s| s.split(',').map(|m| m.trim()).collect())
            .unwrap_or_else(|| vec!["get", "list", "create", "update", "delete"]);

        let message = format!(
            "Generate `{}` with methods: {} for entity `{}`",
            api_name,
            method_names.join(", "),
            entity
        );

        let location = create_generation_location(&api_name);

        vec![SuggestOpportunity::new(
            OpportunityId::new(0),
            vec![],
            location,
            message,
            1.0,
            OpportunityContext::Generation {
                pattern: "api-pattern".to_string(),
                params: params.clone(),
            },
        )]
    }

    fn detect(&self, _ctx: &AnalysisContext, _symbols: &[SymbolId]) -> Vec<SuggestOpportunity> {
        vec![]
    }

    fn to_mutation_specs(
        &self,
        _ctx: &AnalysisContext,
        opportunity: &SuggestOpportunity,
    ) -> SuggestResult<Vec<MutationSpec>> {
        let OpportunityContext::Generation { params, .. } = &opportunity.context else {
            return Ok(vec![]);
        };

        let Some(name) = params.get("name") else {
            return Ok(vec![]);
        };

        let api_name = format!("{}API", name);
        let entity = params
            .get("entity")
            .cloned()
            .unwrap_or_else(|| name.clone());
        let id_type = format!("{}Id", entity);

        let method_filter: Option<Vec<&str>> = params
            .get("methods")
            .map(|s| s.split(',').map(|m| m.trim()).collect());

        let mut specs = Vec::new();

        // Generate API struct using AddItem
        let struct_code = format!("pub struct {} {{}}", api_name);
        let target = SymbolPath::parse("crate")
            .unwrap_or_else(|_| SymbolPath::builder("crate").build().expect("crate path"));

        specs.push(MutationSpec::AddItem {
            target: ryo_executor::MutationTargetSymbol::ByPath(Box::new(target)),
            content: struct_code,
            position: ryo_executor::InsertPosition::Bottom,
        });

        // Generate methods
        for method in &self.methods {
            if let Some(ref filter) = method_filter {
                if !filter.contains(&method.name) {
                    continue;
                }
            }

            let mut method_params: Vec<(String, String)> = vec![];
            if method.has_id_param {
                method_params.push(("id".to_string(), id_type.clone()));
            }
            if method.has_entity_param {
                method_params.push(("entity".to_string(), entity.clone()));
            }

            let return_type = if method.returns_entity {
                if method.name == "list" {
                    format!("Result<Vec<{}>, Error>", entity)
                } else {
                    format!("Result<{}, Error>", entity)
                }
            } else {
                "Result<(), Error>".to_string()
            };

            let body = "todo!()".to_string();

            specs.push(MutationSpec::AddMethod {
                target: ryo_executor::MutationTargetSymbol::ByKindAndName(
                    ryo_executor::ItemKind::Struct,
                    api_name.clone(),
                ),
                method_name: method.name.to_string(),
                params: method_params,
                return_type: Some(return_type),
                body,
                is_pub: true,
                self_param: Some(ryo_executor::SelfParam::Ref),
            });
        }

        Ok(specs)
    }
}

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

    #[test]
    fn test_domain_struct_param_schema() {
        let suggest = DomainStructSuggest::new();
        assert!(suggest.accepts_params());
        assert_eq!(suggest.param_schema().len(), 3);
    }

    #[test]
    fn test_domain_struct_parse_fields() {
        let suggest = DomainStructSuggest::new();
        let fields = suggest.parse_fields("id:u64,name:String,active:bool");
        assert_eq!(fields.len(), 3);
        assert_eq!(fields[0], ("id".to_string(), "u64".to_string()));
        assert_eq!(fields[1], ("name".to_string(), "String".to_string()));
        assert_eq!(fields[2], ("active".to_string(), "bool".to_string()));
    }

    #[test]
    fn test_api_pattern_param_schema() {
        let suggest = ApiPatternSuggest::new();
        assert!(suggest.accepts_params());
        assert_eq!(suggest.param_schema().len(), 3);
    }

    #[test]
    fn test_api_pattern_name() {
        let suggest = ApiPatternSuggest::new();
        assert_eq!(suggest.name(), "api-pattern");
        assert_eq!(suggest.rule_id(), Some("RG002"));
    }
}