ryo-pattern 0.1.0

RyoPattern - AST pattern matching and lint rules 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
//! Generator Template Loading
//!
//! Loads generator templates from YAML configuration files.
//! Generator templates define parameterized code generation patterns.
//!
//! # Example YAML
//! ```yaml
//! generator:
//!   id: GEN001
//!   name: domain_struct
//!   description: Generate a domain struct with common derives
//!   category: domain
//!
//! params:
//!   - name: name
//!     description: Struct name (e.g., Order)
//!     required: true
//!   - name: module
//!     description: Target module path
//!     required: false
//!     default: src/lib.rs
//!
//! template:
//!   code: |
//!     #[derive(Debug, Clone, PartialEq, Eq)]
//!     pub struct {{name}} {
//!         pub id: String,
//!     }
//! ```

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;
use thiserror::Error;

// ============================================================================
// Types
// ============================================================================

/// A generator template loaded from YAML
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct GeneratorTemplate {
    /// Generator metadata
    pub generator: GeneratorMeta,

    /// Parameter definitions
    #[serde(default)]
    pub params: Vec<ParamSpec>,

    /// Code template
    pub template: TemplateSpec,
}

/// Generator metadata
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct GeneratorMeta {
    /// Unique identifier (e.g., "GEN001")
    pub id: String,

    /// Human-readable name (used as suggest name)
    pub name: String,

    /// Description of what this generator does
    pub description: String,

    /// Category for grouping (e.g., "domain", "api", "test")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,
}

/// Parameter specification
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ParamSpec {
    /// Parameter name (used in template as {{name}})
    pub name: String,

    /// Description for LLM/user consumption
    pub description: String,

    /// Whether this parameter is required
    #[serde(default)]
    pub required: bool,

    /// Default value if not provided
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,

    /// Example value for documentation
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub example: Option<String>,
}

/// Code template specification
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TemplateSpec {
    /// The code template with {{param}} placeholders
    pub code: String,

    /// Target file path template (default: "src/lib.rs")
    #[serde(default = "default_target_file")]
    pub target_file: String,

    /// Position hint for insertion
    #[serde(default)]
    pub position: InsertPosition,
}

fn default_target_file() -> String {
    "src/lib.rs".to_string()
}

/// Where to insert the generated code
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum InsertPosition {
    /// At the top of the file (after use statements)
    Top,
    /// At the bottom of the file
    #[default]
    Bottom,
    /// After a specific pattern (e.g., "mod tests")
    After(String),
    /// Before a specific pattern
    Before(String),
}

// ============================================================================
// Errors
// ============================================================================

/// Errors from generator loading
#[derive(Debug, Error)]
pub enum GeneratorLoadError {
    /// IO failure while reading generator file.
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    /// YAML parse failure.
    #[error("YAML parse error: {0}")]
    Yaml(#[from] serde_yaml::Error),

    /// JSON parse failure.
    #[error("JSON parse error: {0}")]
    Json(#[from] serde_json::Error),
}

/// Errors during template rendering
#[derive(Debug, Clone, Error)]
pub enum RenderError {
    /// Required parameters are missing
    #[error("missing required parameters: {}", .0.join(", "))]
    MissingParams(Vec<String>),
}

// ============================================================================
// GeneratorTemplate Implementation
// ============================================================================

impl GeneratorTemplate {
    /// Get the generator ID
    pub fn id(&self) -> &str {
        &self.generator.id
    }

    /// Get the generator name
    pub fn name(&self) -> &str {
        &self.generator.name
    }

    /// Get the description
    pub fn description(&self) -> &str {
        &self.generator.description
    }

    /// Get category
    pub fn category(&self) -> Option<&str> {
        self.generator.category.as_deref()
    }

    /// Check if a parameter is required
    pub fn is_param_required(&self, name: &str) -> bool {
        self.params
            .iter()
            .find(|p| p.name == name)
            .map(|p| p.required)
            .unwrap_or(false)
    }

    /// Get default value for a parameter
    pub fn get_param_default(&self, name: &str) -> Option<&str> {
        self.params
            .iter()
            .find(|p| p.name == name)
            .and_then(|p| p.default.as_deref())
    }

    /// Validate that all required parameters are provided
    pub fn validate_params(&self, params: &HashMap<String, String>) -> Result<(), Vec<String>> {
        let missing: Vec<String> = self
            .params
            .iter()
            .filter(|p| p.required && !params.contains_key(&p.name) && p.default.is_none())
            .map(|p| p.name.clone())
            .collect();

        if missing.is_empty() {
            Ok(())
        } else {
            Err(missing)
        }
    }

    /// Render the template with given parameters
    pub fn render(&self, params: &HashMap<String, String>) -> Result<String, RenderError> {
        // Validate required params
        if let Err(missing) = self.validate_params(params) {
            return Err(RenderError::MissingParams(missing));
        }

        // Build complete params with defaults
        let mut complete_params = HashMap::new();
        for spec in &self.params {
            if let Some(value) = params.get(&spec.name) {
                complete_params.insert(spec.name.clone(), value.clone());
            } else if let Some(default) = &spec.default {
                complete_params.insert(spec.name.clone(), default.clone());
            }
        }

        // Simple template substitution ({{param}} -> value)
        let mut result = self.template.code.clone();
        for (key, value) in &complete_params {
            let placeholder = format!("{{{{{}}}}}", key);
            result = result.replace(&placeholder, value);
        }

        Ok(result)
    }

    /// Render target file path with parameters
    pub fn render_target_file(&self, params: &HashMap<String, String>) -> String {
        let mut result = self.template.target_file.clone();
        for (key, value) in params {
            let placeholder = format!("{{{{{}}}}}", key);
            result = result.replace(&placeholder, value);
        }
        result
    }
}

// ============================================================================
// GeneratorLoader
// ============================================================================

/// Generator template loader
pub struct GeneratorLoader;

impl GeneratorLoader {
    /// Load generator from a file (auto-detect format)
    pub fn load_file(path: impl AsRef<Path>) -> Result<GeneratorTemplate, GeneratorLoadError> {
        let path = path.as_ref();
        let content = std::fs::read_to_string(path)?;
        Self::load_from_str(&content, path)
    }

    /// Load generator from string with path hint for format detection
    pub fn load_from_str(
        content: &str,
        path: impl AsRef<Path>,
    ) -> Result<GeneratorTemplate, GeneratorLoadError> {
        let path = path.as_ref();
        let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");

        match ext {
            "yaml" | "yml" => Self::from_yaml(content),
            "json" => Self::from_json(content),
            _ => {
                // Try YAML first, then JSON
                Self::from_yaml(content).or_else(|_| Self::from_json(content))
            }
        }
    }

    /// Load from YAML string
    pub fn from_yaml(yaml: &str) -> Result<GeneratorTemplate, GeneratorLoadError> {
        Ok(serde_yaml::from_str(yaml)?)
    }

    /// Load from JSON string
    pub fn from_json(json: &str) -> Result<GeneratorTemplate, GeneratorLoadError> {
        Ok(serde_json::from_str(json)?)
    }

    /// Load all generators from a directory
    pub fn load_dir(dir: impl AsRef<Path>) -> Result<Vec<GeneratorTemplate>, GeneratorLoadError> {
        let dir = dir.as_ref();
        let mut templates = Vec::new();

        if !dir.exists() {
            return Ok(templates);
        }

        for entry in std::fs::read_dir(dir)? {
            let entry = entry?;
            let path = entry.path();

            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            if matches!(ext, "yaml" | "yml" | "json") {
                match Self::load_file(&path) {
                    Ok(template) => templates.push(template),
                    Err(e) => {
                        eprintln!(
                            "Warning: Failed to load generator from {}: {}",
                            path.display(),
                            e
                        );
                    }
                }
            }
        }

        Ok(templates)
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    const EXAMPLE_YAML: &str = r#"
generator:
  id: GEN001
  name: domain_struct
  description: Generate a domain struct
  category: domain

params:
  - name: name
    description: Struct name
    required: true
  - name: module
    description: Target module
    required: false
    default: src/lib.rs

template:
  code: |
    #[derive(Debug, Clone)]
    pub struct {{name}} {
        pub id: String,
    }
"#;

    #[test]
    fn test_parse_template() {
        let template = GeneratorLoader::from_yaml(EXAMPLE_YAML).unwrap();
        assert_eq!(template.id(), "GEN001");
        assert_eq!(template.name(), "domain_struct");
        assert_eq!(template.params.len(), 2);
        assert!(template.is_param_required("name"));
        assert!(!template.is_param_required("module"));
    }

    #[test]
    fn test_render_template() {
        let template = GeneratorLoader::from_yaml(EXAMPLE_YAML).unwrap();
        let mut params = HashMap::new();
        params.insert("name".to_string(), "Order".to_string());

        let rendered = template.render(&params).unwrap();
        assert!(rendered.contains("pub struct Order"));
    }

    #[test]
    fn test_missing_required_param() {
        let template = GeneratorLoader::from_yaml(EXAMPLE_YAML).unwrap();
        let params = HashMap::new(); // Missing "name"

        let result = template.render(&params);
        assert!(result.is_err());
    }

    #[test]
    fn test_validate_params() {
        let template = GeneratorLoader::from_yaml(EXAMPLE_YAML).unwrap();

        // Missing required param
        let params = HashMap::new();
        assert!(template.validate_params(&params).is_err());

        // All required params present
        let mut params = HashMap::new();
        params.insert("name".to_string(), "Test".to_string());
        assert!(template.validate_params(&params).is_ok());
    }

    #[test]
    fn test_json_format() {
        let json = r#"{
            "generator": {
                "id": "GEN002",
                "name": "api_endpoint",
                "description": "Generate API endpoint"
            },
            "params": [
                {"name": "resource", "description": "Resource name", "required": true}
            ],
            "template": {
                "code": "pub fn get_{{resource}}() {}"
            }
        }"#;

        let template = GeneratorLoader::from_json(json).unwrap();
        assert_eq!(template.id(), "GEN002");
    }
}