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
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
//! Rule and MatchResult types
//!
//! Lint rule definition and pattern matching results.

use crate::{BodyMatch, CodePattern, Relations};
use ryo_symbol::SymbolId;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Lint rule definition with optional fix
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct Rule {
    /// Unique identifier (e.g., "RL001")
    pub id: String,

    /// Human-readable name
    pub name: String,

    /// Severity level
    pub severity: Severity,

    /// Category for grouping
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub category: Option<String>,

    /// Detection query
    pub query: PatternQuery,

    /// Error message (supports variable interpolation)
    pub message: String,

    /// Suggestion text (human-readable hint, not executable)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub suggestion: Option<String>,

    /// Target code scopes where this rule applies.
    ///
    /// When non-empty, the rule only fires on symbols within the specified scopes.
    /// Valid values: "lib", "bin", "test".
    /// When empty (default), the rule applies to all scopes.
    ///
    /// ```yaml
    /// scope: [lib]           # Library code only
    /// scope: [lib, bin]      # Production code (lib + bin)
    /// ```
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scope: Vec<String>,

    /// Fix specification (Intent or MutationSpec as JSON)
    ///
    /// Default format is Intent (public DSL):
    /// ```yaml
    /// fix:
    ///   type: UnwrapToQuestion
    ///   target_fn: "$MATCH"
    /// ```
    ///
    /// For builtin rules, MutationSpec can be used with `_kind: mutation_spec`:
    /// ```yaml
    /// fix:
    ///   _kind: mutation_spec
    ///   type: UnwrapToQuestion
    ///   target: ...
    /// ```
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fix: Option<serde_json::Value>,
}

impl Rule {
    /// Create a new rule
    pub fn new(
        id: impl Into<String>,
        name: impl Into<String>,
        severity: Severity,
        query: PatternQuery,
        message: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            severity,
            category: None,
            query,
            message: message.into(),
            suggestion: None,
            scope: Vec::new(),
            fix: None,
        }
    }

    /// Set category
    pub fn with_category(mut self, category: impl Into<String>) -> Self {
        self.category = Some(category.into());
        self
    }

    /// Set suggestion
    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
        self.suggestion = Some(suggestion.into());
        self
    }

    /// Set fix specification (as JSON Value)
    pub fn with_fix(mut self, fix: serde_json::Value) -> Self {
        self.fix = Some(fix);
        self
    }
}

/// Query for pattern matching (extends RyoQL Query concept)
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct PatternQuery {
    /// Symbol kind to match (Function, Struct, etc.)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub kind: Option<SymbolKind>,

    /// Attribute matching conditions
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r#match: Option<MatchAttrs>,

    /// Body pattern matching
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub body: Option<BodyMatch>,

    /// Relation conditions
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub relations: Option<Relations>,

    /// Direct code pattern (for CodePattern-only queries)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern: Option<CodePattern>,
}

impl PatternQuery {
    /// Construct an empty `PatternQuery`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set symbol kind
    pub fn kind(mut self, kind: SymbolKind) -> Self {
        self.kind = Some(kind);
        self
    }

    /// Set match attributes
    pub fn with_match(mut self, attrs: MatchAttrs) -> Self {
        self.r#match = Some(attrs);
        self
    }

    /// Set body match
    pub fn with_body(mut self, body: BodyMatch) -> Self {
        self.body = Some(body);
        self
    }

    /// Set relations
    pub fn with_relations(mut self, relations: Relations) -> Self {
        self.relations = Some(relations);
        self
    }

    /// Set direct pattern
    pub fn with_pattern(mut self, pattern: CodePattern) -> Self {
        self.pattern = Some(pattern);
        self
    }
}

/// Symbol kind for query filtering
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum SymbolKind {
    /// `fn` item.
    Function,
    /// `struct` item.
    Struct,
    /// `enum` item.
    Enum,
    /// `trait` item.
    Trait,
    /// `impl` block.
    Impl,
    /// `mod` item.
    Mod,
    /// `const` item.
    Const,
    /// `static` item.
    Static,
    /// `type` alias.
    TypeAlias,
    /// Struct / enum field.
    Field,
    /// Enum variant.
    Variant,
    /// Match CodePattern directly
    CodePattern,
}

/// Match attributes for symbol filtering
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct MatchAttrs {
    /// Name pattern
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    /// Glob pattern for name
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pattern: Option<String>,

    /// Visibility
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vis: Option<Visibility>,

    /// Trait name (for Impl)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trait_name: Option<String>,

    /// Required attributes
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub attributes: Option<Vec<String>>,
}

impl MatchAttrs {
    /// Construct an empty `MatchAttrs`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the symbol name.
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the name glob pattern.
    pub fn pattern(mut self, pattern: impl Into<String>) -> Self {
        self.pattern = Some(pattern.into());
        self
    }

    /// Set the visibility filter.
    pub fn vis(mut self, vis: Visibility) -> Self {
        self.vis = Some(vis);
        self
    }
}

/// Visibility level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum Visibility {
    /// `pub`
    Public,
    /// `pub(crate)`
    Crate,
    /// `pub(super)`
    Super,
    /// 非公開 (modifier 無し)。
    Private,
}

/// Severity level
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum Severity {
    /// Must fix - blocks compilation or causes runtime errors
    Error,
    /// Should fix - code smell or potential issue
    Warning,
    /// Consider - style or convention suggestion
    Info,
    /// FYI - informational note
    Hint,
}

impl std::fmt::Display for Severity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Severity::Error => write!(f, "error"),
            Severity::Warning => write!(f, "warning"),
            Severity::Info => write!(f, "info"),
            Severity::Hint => write!(f, "hint"),
        }
    }
}

/// Result of pattern matching
#[derive(Debug, Clone)]
pub struct MatchResult {
    /// Whether the pattern matched
    pub matched: bool,

    /// Rule that matched (if from Rule evaluation)
    pub rule_id: Option<String>,

    /// Severity of the match
    pub severity: Option<Severity>,

    /// Interpolated message
    pub message: Option<String>,

    /// Suggestion text
    pub suggestion: Option<String>,

    /// Captured nodes (available for downstream mutation systems)
    pub captures: HashMap<String, CapturedNode>,
}

impl MatchResult {
    /// Create a non-matching result
    pub fn no_match() -> Self {
        Self {
            matched: false,
            rule_id: None,
            severity: None,
            message: None,
            suggestion: None,
            captures: HashMap::new(),
        }
    }

    /// Create a matching result
    pub fn matched() -> Self {
        Self {
            matched: true,
            rule_id: None,
            severity: None,
            message: None,
            suggestion: None,
            captures: HashMap::new(),
        }
    }

    /// Set rule info
    pub fn with_rule(mut self, rule: &Rule) -> Self {
        self.rule_id = Some(rule.id.clone());
        self.severity = Some(rule.severity);
        self.message = Some(rule.message.clone());
        self.suggestion = rule.suggestion.clone();
        self
    }

    /// Add a capture
    pub fn capture(mut self, var: impl Into<String>, node: CapturedNode) -> Self {
        self.captures.insert(var.into(), node);
        self
    }
}

/// A captured AST node from pattern matching
#[derive(Debug, Clone)]
pub struct CapturedNode {
    /// Symbol ID if the node corresponds to a known symbol
    pub symbol_id: Option<SymbolId>,

    /// Source location
    pub span: Span,

    /// Original source text
    pub text: String,
}

impl CapturedNode {
    /// Construct a `CapturedNode` from a span and source text.
    pub fn new(span: Span, text: impl Into<String>) -> Self {
        Self {
            symbol_id: None,
            span,
            text: text.into(),
        }
    }

    /// Attach a `SymbolId` to the captured node.
    pub fn with_symbol(mut self, id: SymbolId) -> Self {
        self.symbol_id = Some(id);
        self
    }
}

/// Source span (line/column based)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Span {
    /// Inclusive start position.
    pub start: Position,
    /// Exclusive end position.
    pub end: Position,
}

impl Span {
    /// Construct a span from start / end positions.
    pub fn new(start: Position, end: Position) -> Self {
        Self { start, end }
    }

    /// Construct a zero-width span at `(line, column)`.
    pub fn point(line: u32, column: u32) -> Self {
        let pos = Position { line, column };
        Self {
            start: pos,
            end: pos,
        }
    }
}

/// Position in source code
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Position {
    /// 1-based line number.
    pub line: u32,
    /// 0-based column.
    pub column: u32,
}

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

    #[test]
    fn test_rule_builder() {
        let query = PatternQuery::new().kind(SymbolKind::Function).with_match(
            MatchAttrs::new()
                .vis(Visibility::Public)
                .pattern("process_*"),
        );

        let rule = Rule::new(
            "RL001",
            "no-unwrap",
            Severity::Warning,
            query,
            "Avoid unwrap()",
        )
        .with_category("error-handling")
        .with_suggestion("Use ? operator instead");

        assert_eq!(rule.id, "RL001");
        assert_eq!(rule.severity, Severity::Warning);
        assert!(rule.category.is_some());
        assert!(rule.suggestion.is_some());
    }

    #[test]
    fn test_match_result() {
        let result = MatchResult::matched().capture(
            "$UNWRAP",
            CapturedNode::new(Span::point(42, 10), "result.unwrap()"),
        );

        assert!(result.matched);
        assert!(result.captures.contains_key("$UNWRAP"));
    }

    #[test]
    fn test_pattern_query_with_body() {
        let query = PatternQuery::new()
            .kind(SymbolKind::Function)
            .with_body(BodyMatch::new().contains(CodePattern::new(NodeKind::MethodCall)));

        assert!(query.kind.is_some());
        assert!(query.body.is_some());
    }
}