ryo-query-language 0.1.0

RyoQL - Structured code query language for AI agents
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
//! RyoQL Query → DiscoveryQuery 変換層
//!
//! RyoQLのYAML/JSON形式クエリを、ryo-analysisの内部クエリ形式に変換する。

use crate::schema::{
    GenericsMatch, MatchAttrs, NameMatcher, NameMatcherDetailed, Query, QueryKind, ReceiverKind,
    Scope, Visibility,
};
use ryo_analysis::{DiscoveryQuery, Pattern, SymbolKind, TypeFilter};
use thiserror::Error;

/// 変換エラー
#[derive(Debug, Error)]
pub enum ConvertError {
    /// 正規表現パターンが invalid。
    #[error("invalid regex pattern: {0}")]
    InvalidRegex(String),

    /// `DiscoveryQuery` に変換できない `QueryKind`。
    #[error("unsupported query kind for conversion: {kind:?}")]
    UnsupportedKind {
        /// 変換対象の `QueryKind`。
        kind: QueryKind,
    },

    /// Pattern クエリに `name` field が無い。
    #[error("Pattern query requires 'name' field")]
    PatternNameRequired,

    /// Or/And クエリに `queries` field が無い。
    #[error("Or/And query requires 'queries' field")]
    QueriesRequired,
}

/// クエリ変換器
pub struct QueryConverter;

impl QueryConverter {
    /// RyoQL Query → DiscoveryQuery 変換
    ///
    /// # Note
    /// 以下の機能はDiscoveryQueryでは未対応のため、後処理が必要:
    /// - `inner` 条件 (ReturnType, Parameter, Field等)
    /// - `match.is_async`, `match.is_unsafe` 等の詳細フィルタ
    /// - `match.receiver` (ReceiverKind)
    /// - `match.attributes`
    /// - `match.generics`
    /// - `scope.path`, `scope.exclude_path` (ファイルパスフィルタ)
    /// - `resolve` (LSP連携)
    pub fn to_discovery_query(query: &Query) -> Result<ConversionResult, ConvertError> {
        match query.kind {
            QueryKind::Or | QueryKind::And => {
                // Or/Andは個別クエリに分解して返す
                if query.queries.is_empty() {
                    return Err(ConvertError::QueriesRequired);
                }
                let sub_results: Result<Vec<_>, _> =
                    query.queries.iter().map(Self::to_discovery_query).collect();
                Ok(ConversionResult {
                    discovery_query: None,
                    composite: Some(CompositeQuery {
                        op: if query.kind == QueryKind::Or {
                            CompositeOp::Or
                        } else {
                            CompositeOp::And
                        },
                        queries: sub_results?,
                    }),
                    post_filters: vec![],
                    unsupported: vec![],
                })
            }
            QueryKind::Pattern => {
                // TODO: Pattern検索はryo-analysisのPattern機能と連携
                // 現状は名前でパターン検索
                let name = query
                    .name
                    .as_ref()
                    .ok_or(ConvertError::PatternNameRequired)?;
                Ok(ConversionResult {
                    discovery_query: Some(DiscoveryQuery::exact(name)),
                    composite: None,
                    post_filters: vec![PostFilter::PatternSearch(name.clone())],
                    unsupported: vec!["Pattern search (requires pattern registry)".to_string()],
                })
            }
            _ => Self::convert_simple_query(query),
        }
    }

    /// シンプルなクエリの変換
    fn convert_simple_query(query: &Query) -> Result<ConversionResult, ConvertError> {
        let mut unsupported = Vec::new();
        let mut post_filters = Vec::new();

        // Pattern変換
        let pattern = Self::convert_name_matcher(query.r#match.as_ref())?;

        // DiscoveryQuery構築
        let mut dq = match pattern {
            Some(p) => DiscoveryQuery::symbol(p.as_str()),
            None => DiscoveryQuery::symbol("*"),
        };

        // Kind変換
        if let Some(kinds) = Self::convert_kind(query.kind) {
            dq = dq.kinds(kinds);
        }

        // Scope変換
        if let Some(ref scope) = query.scope {
            dq = Self::apply_scope(dq, scope, &mut post_filters, &mut unsupported);
        }

        // Limit
        if let Some(limit) = query.limit {
            dq = dq.limit(limit);
        }

        // Inner conditions: convert to PostFilters for DetailStore-based filtering
        // (TypeFilter is for TypeFlowGraph, PostFilter is for DetailStore)
        if !query.inner.is_empty() {
            Self::collect_inner_post_filters(&query.inner, &mut post_filters)?;
        }

        // TypeFilter構築(generics.bounds のみ)
        // Note: inner条件はPostFilterで処理するため、TypeFilterからは除外
        let mut type_filter: Option<TypeFilter> = None;

        // generics.bounds → TypeFilter.has_bound
        if let Some(ref attrs) = query.r#match {
            if let Some(ref generics) = attrs.generics {
                if let Some(ref bounds) = generics.bounds {
                    if let Some(bound_pattern) = Self::convert_bounds_to_pattern(bounds)? {
                        let filter = type_filter.get_or_insert_with(TypeFilter::default);
                        filter.has_bound = Some(bound_pattern);
                    }
                }
            }
        }

        // TypeFilterをDiscoveryQueryに設定
        if let Some(filter) = type_filter {
            dq = dq.with_type_filter(filter);
        }

        // MatchAttrs の詳細フィルタ(DiscoveryQuery未対応 → 後処理)
        if let Some(ref attrs) = query.r#match {
            Self::collect_post_filters(attrs, &mut post_filters, &mut unsupported);
        }

        // Body pattern matching: 後処理フィルタとして追加
        if let Some(ref body) = query.body {
            post_filters.push(PostFilter::BodyMatch(body.clone()));
        }

        // Relations filter: 後処理フィルタとして追加
        if let Some(ref relations) = query.relations {
            if !relations.is_empty() {
                post_filters.push(PostFilter::Relations(relations.clone()));
            }
        }

        // resolve: Executor側で処理(CodeGraph使用)
        // converter では何もしない

        Ok(ConversionResult {
            discovery_query: Some(dq),
            composite: None,
            post_filters,
            unsupported,
        })
    }

    /// NameMatcher → Pattern 変換
    fn convert_name_matcher(attrs: Option<&MatchAttrs>) -> Result<Option<Pattern>, ConvertError> {
        let attrs = match attrs {
            Some(a) => a,
            None => return Ok(None),
        };

        // name が指定されている場合はそれを優先
        if let Some(ref name) = attrs.name {
            let pattern = match name {
                NameMatcher::Exact(s) => Pattern::exact(s),
                NameMatcher::Detailed(d) => Self::convert_detailed_matcher(d)?,
            };
            return Ok(Some(pattern));
        }

        // name がない場合、pattern をショートハンドとして使用
        if let Some(ref pattern_str) = attrs.pattern {
            return Ok(Some(Pattern::glob(pattern_str)));
        }

        Ok(None)
    }

    /// 詳細NameMatcher → Pattern 変換
    fn convert_detailed_matcher(d: &NameMatcherDetailed) -> Result<Pattern, ConvertError> {
        // 優先順位: regex > glob > contains > starts_with > ends_with
        if let Some(ref regex) = d.regex {
            return Pattern::regex(regex).map_err(|e| ConvertError::InvalidRegex(e.to_string()));
        }

        if let Some(ref glob) = d.glob {
            return Ok(Pattern::glob(glob));
        }

        if let Some(ref contains) = d.contains {
            return Ok(Pattern::glob(format!("*{}*", contains)));
        }

        if let Some(ref starts) = d.starts_with {
            return Ok(Pattern::glob(format!("{}*", starts)));
        }

        if let Some(ref ends) = d.ends_with {
            return Ok(Pattern::glob(format!("*{}", ends)));
        }

        // 全部Noneの場合
        Ok(Pattern::glob("*"))
    }

    /// QueryKind → SymbolKind 変換
    fn convert_kind(kind: QueryKind) -> Option<Vec<SymbolKind>> {
        match kind {
            // Any: 全種類を検索
            QueryKind::Any => None,
            QueryKind::Function => Some(vec![SymbolKind::Function]),
            QueryKind::Struct => Some(vec![SymbolKind::Struct]),
            QueryKind::Enum => Some(vec![SymbolKind::Enum]),
            QueryKind::Trait => Some(vec![SymbolKind::Trait]),
            QueryKind::Impl => Some(vec![SymbolKind::Impl]),
            QueryKind::Mod => Some(vec![SymbolKind::Mod]),
            QueryKind::Const => Some(vec![SymbolKind::Const]),
            QueryKind::Static => Some(vec![SymbolKind::Static]),
            QueryKind::TypeAlias => Some(vec![SymbolKind::TypeAlias]),
            // inner用/複合は単体では変換しない
            QueryKind::ReturnType
            | QueryKind::Parameter
            | QueryKind::Field
            | QueryKind::Variant
            | QueryKind::Or
            | QueryKind::And
            | QueryKind::Pattern => None,
            // Literalは特殊クエリ(シンボル検索ではない)
            QueryKind::Literal => None,
        }
    }

    /// Scope適用
    fn apply_scope(
        mut dq: DiscoveryQuery,
        scope: &Scope,
        post_filters: &mut Vec<PostFilter>,
        _unsupported: &mut Vec<String>,
    ) -> DiscoveryQuery {
        // module → DiscoveryQuery.in_module
        if let Some(ref module) = scope.module {
            dq = dq.in_module(module);
        }

        // path, exclude_path → 後処理フィルタ
        // Note: ファイルパスベースのフィルタは scope.module (SymbolPathベース) で代替可能。
        // 互換性のため残すが、module の使用を推奨。
        if let Some(ref path) = scope.path {
            post_filters.push(PostFilter::PathInclude(path.clone()));
        }

        if let Some(ref exclude) = scope.exclude_path {
            post_filters.push(PostFilter::PathExclude(exclude.clone()));
        }

        dq
    }

    /// Generics.bounds → Pattern 変換
    ///
    /// 複数のboundsがある場合は最初の一つを使用(将来的にはOR検索に対応)
    fn convert_bounds_to_pattern(bounds: &[NameMatcher]) -> Result<Option<Pattern>, ConvertError> {
        if bounds.is_empty() {
            return Ok(None);
        }

        // 最初のbound matc herをPatternに変換
        let first = &bounds[0];
        let pattern = match first {
            NameMatcher::Exact(s) => Pattern::exact(s),
            NameMatcher::Detailed(d) => Self::convert_detailed_matcher(d)?,
        };

        Ok(Some(pattern))
    }

    /// Inner条件 → PostFilter 変換
    ///
    /// inner条件のQueryKindに応じてPostFilterを収集する:
    /// - ReturnType → PostFilter::ReturnType (DetailStore.function().return_type で処理)
    /// - Parameter → PostFilter::ParamType (DetailStore.function().params で処理)
    /// - Field → PostFilter::FieldType (DetailStore.struct_().fields で処理)
    fn collect_inner_post_filters(
        inner: &[Query],
        post_filters: &mut Vec<PostFilter>,
    ) -> Result<(), ConvertError> {
        for q in inner {
            // Get the pattern string from match.name
            let pattern_str = if let Some(ref attrs) = q.r#match {
                if let Some(ref name) = attrs.name {
                    Self::name_matcher_to_pattern_str(name)
                } else {
                    continue;
                }
            } else {
                continue;
            };

            match q.kind {
                QueryKind::ReturnType => {
                    post_filters.push(PostFilter::ReturnType(pattern_str));
                }
                QueryKind::Parameter => {
                    post_filters.push(PostFilter::ParamType(pattern_str));
                }
                QueryKind::Field => {
                    post_filters.push(PostFilter::FieldType(pattern_str));
                }
                QueryKind::Variant => {
                    // Variantもfield_typeとして扱う
                    post_filters.push(PostFilter::FieldType(pattern_str));
                }
                _ => {
                    // 他のQueryKindはinner条件として無効
                }
            }
        }

        Ok(())
    }

    /// NameMatcher → パターン文字列変換
    fn name_matcher_to_pattern_str(name: &NameMatcher) -> String {
        match name {
            NameMatcher::Exact(s) => s.clone(),
            NameMatcher::Detailed(d) => {
                // Priority: glob > regex > contains > starts_with > ends_with
                if let Some(ref glob) = d.glob {
                    glob.clone()
                } else if let Some(ref regex) = d.regex {
                    format!("regex:{}", regex)
                } else if let Some(ref contains) = d.contains {
                    format!("*{}*", contains)
                } else if let Some(ref starts_with) = d.starts_with {
                    format!("{}*", starts_with)
                } else if let Some(ref ends_with) = d.ends_with {
                    format!("*{}", ends_with)
                } else {
                    "*".to_string()
                }
            }
        }
    }

    /// Inner条件 → TypeFilter 変換 (deprecated, kept for backward compatibility)
    #[allow(dead_code)]
    fn convert_inner_to_type_filter(inner: &[Query]) -> Result<Option<TypeFilter>, ConvertError> {
        let mut filter = TypeFilter::default();
        let mut has_filter = false;

        for q in inner {
            let pattern = Self::convert_name_matcher(q.r#match.as_ref())?;
            let Some(pattern) = pattern else {
                continue;
            };

            match q.kind {
                QueryKind::ReturnType => {
                    filter.return_type = Some(pattern);
                    has_filter = true;
                }
                QueryKind::Parameter => {
                    filter.param_type = Some(pattern);
                    has_filter = true;
                }
                QueryKind::Field => {
                    filter.field_type = Some(pattern);
                    has_filter = true;
                }
                QueryKind::Variant => {
                    // Variantもfield_typeとして扱う(VariantFieldコンテキストで処理)
                    filter.field_type = Some(pattern);
                    has_filter = true;
                }
                _ => {
                    // 他のQueryKindはinner条件として無効
                }
            }
        }

        if has_filter {
            Ok(Some(filter))
        } else {
            Ok(None)
        }
    }

    /// MatchAttrsから後処理フィルタを収集
    fn collect_post_filters(
        attrs: &MatchAttrs,
        post_filters: &mut Vec<PostFilter>,
        unsupported: &mut Vec<String>,
    ) {
        // TODO: これらのフィルタはDiscoveryQueryで直接サポートすべき
        // 現状は後処理で対応

        if let Some(ref sid) = attrs.symbol_id {
            post_filters.push(PostFilter::SymbolId(sid.clone()));
        }

        if let Some(is_async) = attrs.is_async {
            post_filters.push(PostFilter::IsAsync(is_async));
            unsupported.push(format!("is_async: {}", is_async));
        }

        if let Some(is_unsafe) = attrs.is_unsafe {
            post_filters.push(PostFilter::IsUnsafe(is_unsafe));
            unsupported.push(format!("is_unsafe: {}", is_unsafe));
        }

        if let Some(ref vis) = attrs.vis {
            post_filters.push(PostFilter::Visibility(vis.clone()));
            unsupported.push(format!("visibility: {:?}", vis));
        }

        if let Some(ref receiver) = attrs.receiver {
            post_filters.push(PostFilter::Receiver(*receiver));
            unsupported.push(format!("receiver: {:?}", receiver));
        }

        if let Some(ref attributes) = attrs.attributes {
            post_filters.push(PostFilter::Attributes(attributes.clone()));
            unsupported.push(format!("attributes: {:?}", attributes));
        }

        if let Some(ref generics) = attrs.generics {
            // bounds はTypeFilter.has_boundで処理するため除外
            // params と lifetimes のみを PostFilter で処理
            let has_params = generics.params.as_ref().is_some_and(|p| !p.is_empty());
            let has_lifetimes = generics.lifetimes.as_ref().is_some_and(|l| !l.is_empty());

            if has_params || has_lifetimes {
                let filtered_generics = GenericsMatch {
                    params: generics.params.clone(),
                    bounds: None, // boundsはTypeFilterで処理
                    lifetimes: generics.lifetimes.clone(),
                };
                post_filters.push(PostFilter::Generics(filtered_generics));
                unsupported.push(format!(
                    "generics (params/lifetimes): params={:?}, lifetimes={:?}",
                    generics.params, generics.lifetimes
                ));
            }
        }

        // on_empty は executor で処理
        if attrs.on_empty.is_some() {
            post_filters.push(PostFilter::OnEmpty);
        }

        // parent フィルタ(Variant, Field, Method用)
        if let Some(ref parent) = attrs.parent {
            let pattern = match parent {
                NameMatcher::Exact(s) => Pattern::exact(s),
                NameMatcher::Detailed(d) => {
                    // 優先順位: regex > glob > contains > starts_with > ends_with
                    if let Some(ref regex) = d.regex {
                        Pattern::regex(regex).unwrap_or_else(|_| Pattern::glob(regex))
                    } else if let Some(ref glob) = d.glob {
                        Pattern::glob(glob)
                    } else if let Some(ref contains) = d.contains {
                        Pattern::glob(format!("*{}*", contains))
                    } else if let Some(ref starts) = d.starts_with {
                        Pattern::glob(format!("{}*", starts))
                    } else if let Some(ref ends) = d.ends_with {
                        Pattern::glob(format!("*{}", ends))
                    } else {
                        Pattern::glob("*")
                    }
                }
            };
            post_filters.push(PostFilter::Parent(pattern));
        }
    }
}

/// 変換結果
#[derive(Debug, Clone)]
pub struct ConversionResult {
    /// 変換されたDiscoveryQuery(Or/Andの場合はNone)
    pub discovery_query: Option<DiscoveryQuery>,

    /// 複合クエリ(Or/And)
    pub composite: Option<CompositeQuery>,

    /// 後処理が必要なフィルタ
    pub post_filters: Vec<PostFilter>,

    /// DiscoveryQuery未対応の機能リスト(警告用)
    pub unsupported: Vec<String>,
}

/// 複合クエリ
#[derive(Debug, Clone)]
pub struct CompositeQuery {
    /// 子クエリ群を結合する演算子。
    pub op: CompositeOp,
    /// 結合対象の子変換結果。
    pub queries: Vec<ConversionResult>,
}

/// 複合演算子
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CompositeOp {
    /// 和集合 (いずれかにマッチ)。
    Or,
    /// 積集合 (すべてにマッチ)。
    And,
}

/// 後処理フィルタ
///
/// DiscoveryQueryでは表現できない条件。
/// Executorで結果に対して後処理を行う。
#[derive(Debug, Clone)]
pub enum PostFilter {
    /// async関数フィルタ
    IsAsync(bool),
    /// unsafe関数フィルタ
    IsUnsafe(bool),
    /// 可視性フィルタ
    Visibility(Visibility),
    /// レシーバーフィルタ
    Receiver(ReceiverKind),
    /// アトリビュートフィルタ
    Attributes(Vec<String>),
    /// ジェネリクスフィルタ
    Generics(GenericsMatch),
    /// パスincludeフィルタ
    PathInclude(String),
    /// パスexcludeフィルタ
    PathExclude(String),
    /// パターン検索
    PatternSearch(String),
    /// on_emptyリカバリー(executor処理)
    OnEmpty,
    /// 戻り値型フィルタ (inner: ReturnType)
    ReturnType(String),
    /// パラメータ型フィルタ (inner: Parameter)
    ParamType(String),
    /// フィールド型フィルタ (inner: Field)
    FieldType(String),
    /// 親シンボルフィルタ (Variant, Field, Method用)
    Parent(Pattern),
    /// SymbolId直接指定フィルタ
    SymbolId(String),
    /// Body パターンマッチフィルタ
    BodyMatch(ryo_pattern::BodyMatch),
    /// Relations フィルタ (any/all/none)
    Relations(ryo_pattern::Relations),
}

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

    #[test]
    fn test_convert_simple_function_query() {
        let yaml = r#"
kind: Function
match:
  name: "process"
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        assert!(result.discovery_query.is_some());
        assert!(result.composite.is_none());
    }

    #[test]
    fn test_convert_glob_pattern() {
        let yaml = r#"
kind: Struct
match:
  name: { glob: "*Config" }
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        let dq = result.discovery_query.unwrap();
        assert!(dq.pattern.matches("AppConfig"));
        assert!(dq.pattern.matches("Config"));
        assert!(!dq.pattern.matches("ConfigManager"));
    }

    #[test]
    fn test_convert_contains_to_glob() {
        let yaml = r#"
kind: Function
match:
  name: { contains: "process" }
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        let dq = result.discovery_query.unwrap();
        // contains: "process" → glob: "*process*"
        assert!(dq.pattern.matches("process"));
        assert!(dq.pattern.matches("process_event"));
        assert!(dq.pattern.matches("do_process"));
    }

    #[test]
    fn test_convert_with_post_filters() {
        let yaml = r#"
kind: Function
match:
  name: "handler"
  is_async: true
  vis: Public
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        // is_async, visはpost_filtersに入る
        assert!(result
            .post_filters
            .iter()
            .any(|f| matches!(f, PostFilter::IsAsync(true))));
        assert!(result
            .post_filters
            .iter()
            .any(|f| matches!(f, PostFilter::Visibility(_))));
        assert!(!result.unsupported.is_empty());
    }

    #[test]
    fn test_convert_or_query() {
        let yaml = r#"
kind: Or
queries:
  - kind: Struct
    match:
      name: { contains: "Error" }
  - kind: Enum
    match:
      name: { contains: "Error" }
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        assert!(result.discovery_query.is_none());
        assert!(result.composite.is_some());

        let composite = result.composite.unwrap();
        assert_eq!(composite.op, CompositeOp::Or);
        assert_eq!(composite.queries.len(), 2);
    }

    #[test]
    fn test_convert_with_scope() {
        let yaml = r#"
kind: Function
match:
  name: "*"
scope:
  module: "handlers"
  path: "src/**"
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        let dq = result.discovery_query.unwrap();
        assert_eq!(dq.in_module, Some("handlers".to_string()));

        // path は後処理
        assert!(result
            .post_filters
            .iter()
            .any(|f| matches!(f, PostFilter::PathInclude(_))));
    }

    #[test]
    fn test_convert_with_inner() {
        let yaml = r#"
kind: Function
match:
  name: { starts_with: "process_" }
inner:
  - kind: ReturnType
    match:
      name: "Result"
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        // inner条件はPostFilterに変換される
        assert!(result
            .post_filters
            .iter()
            .any(|f| matches!(f, PostFilter::ReturnType(_))));
    }

    #[test]
    fn test_convert_with_multiple_inner() {
        let yaml = r#"
kind: Function
match:
  name: "*"
inner:
  - kind: ReturnType
    match:
      name: { contains: "Result" }
  - kind: Parameter
    match:
      name: { contains: "Config" }
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        // inner条件はPostFilterに変換される
        assert!(result
            .post_filters
            .iter()
            .any(|f| matches!(f, PostFilter::ReturnType(_))));
        assert!(result
            .post_filters
            .iter()
            .any(|f| matches!(f, PostFilter::ParamType(_))));
    }

    #[test]
    fn test_convert_field_inner() {
        let yaml = r#"
kind: Struct
match:
  name: "*"
inner:
  - kind: Field
    match:
      name: "String"
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        // inner条件はPostFilterに変換される
        assert!(result
            .post_filters
            .iter()
            .any(|f| matches!(f, PostFilter::FieldType(_))));
    }

    #[test]
    fn test_convert_kind_function_excludes_method() {
        // BUG#2 regression: QueryKind::Function must map to SymbolKind::Function only
        let kinds = QueryConverter::convert_kind(QueryKind::Function).unwrap();
        assert_eq!(kinds, vec![SymbolKind::Function]);
        assert!(!kinds.contains(&SymbolKind::Method));
    }

    #[test]
    fn test_convert_kind_struct_single() {
        let kinds = QueryConverter::convert_kind(QueryKind::Struct).unwrap();
        assert_eq!(kinds, vec![SymbolKind::Struct]);
    }

    #[test]
    fn test_convert_generics_bounds_to_type_filter() {
        let yaml = r#"
kind: Function
match:
  name: "*"
  generics:
    bounds: ["Clone"]
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        // bounds は TypeFilter.has_bound に変換される
        let dq = result.discovery_query.unwrap();
        assert!(dq.type_filter.is_some());

        let type_filter = dq.type_filter.unwrap();
        assert!(type_filter.has_bound.is_some());
        assert!(type_filter.has_bound.unwrap().matches("Clone"));
    }

    #[test]
    fn test_convert_generics_params_to_post_filter() {
        let yaml = r#"
kind: Function
match:
  name: "*"
  generics:
    params: ["T", "E"]
    lifetimes: ["'a"]
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        // params/lifetimes は PostFilter::Generics に残る
        assert!(result.post_filters.iter().any(|f| {
            matches!(f, PostFilter::Generics(g) if g.params.is_some() && g.bounds.is_none())
        }));
    }

    #[test]
    fn test_convert_generics_mixed_bounds_and_params() {
        let yaml = r#"
kind: Struct
match:
  name: "*"
  generics:
    params: ["T"]
    bounds: [{ glob: "*Send*" }]
"#;
        let query = QueryParser::from_yaml(yaml).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        // bounds は TypeFilter へ
        let dq = result.discovery_query.unwrap();
        let type_filter = dq.type_filter.unwrap();
        assert!(type_filter.has_bound.is_some());
        assert!(type_filter.has_bound.unwrap().matches("MySendTrait"));

        // params は PostFilter へ
        assert!(result.post_filters.iter().any(|f| {
            matches!(f, PostFilter::Generics(g) if g.params.is_some() && g.bounds.is_none())
        }));
    }

    #[test]
    fn test_convert_symbol_id_filter() {
        let json = r#"{"kind":"Function","match":{"symbol_id":"2421v1"}}"#;
        let query = QueryParser::from_json(json).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        assert!(
            result
                .post_filters
                .iter()
                .any(|f| matches!(f, PostFilter::SymbolId(ref s) if s == "2421v1")),
            "symbol_id must be converted to PostFilter::SymbolId"
        );
    }

    #[test]
    fn test_convert_symbol_id_with_prefix() {
        let json = r#"{"kind":"Any","match":{"symbol_id":"SymbolId(165v1)"}}"#;
        let query = QueryParser::from_json(json).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        assert!(
            result
                .post_filters
                .iter()
                .any(|f| matches!(f, PostFilter::SymbolId(ref s) if s == "SymbolId(165v1)")),
            "SymbolId(xxx) format must also be preserved in PostFilter"
        );
    }

    #[test]
    fn test_convert_body_contains_filter() {
        let json = r#"{
            "kind": "Function",
            "body": {
                "contains": [
                    {"node": "MethodCall"}
                ]
            }
        }"#;
        let query = QueryParser::from_json(json).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        assert!(
            result
                .post_filters
                .iter()
                .any(|f| matches!(f, PostFilter::BodyMatch(_))),
            "body.contains must be converted to PostFilter::BodyMatch"
        );
    }

    #[test]
    fn test_convert_body_not_contains_filter() {
        let json = r#"{
            "kind": "Function",
            "body": {
                "not_contains": [
                    {"node": "MethodCall", "children": {"method": {"name": "unwrap"}}}
                ]
            }
        }"#;
        let query = QueryParser::from_json(json).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        assert!(
            result
                .post_filters
                .iter()
                .any(|f| matches!(f, PostFilter::BodyMatch(bm) if bm.not_contains.is_some())),
            "body.not_contains must be preserved in PostFilter::BodyMatch"
        );
    }

    #[test]
    fn test_convert_relations_any_filter() {
        let json = r#"{
            "kind": "Function",
            "relations": {
                "any": [
                    {"kind": "Calls", "target": {"kind": "Function", "match": {"name": "serve"}}}
                ]
            }
        }"#;
        let query = QueryParser::from_json(json).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        assert!(
            result
                .post_filters
                .iter()
                .any(|f| matches!(f, PostFilter::Relations(r) if r.any.is_some())),
            "relations.any must be converted to PostFilter::Relations"
        );
    }

    #[test]
    fn test_convert_relations_none_filter() {
        let json = r#"{
            "kind": "Trait",
            "relations": {
                "none": [
                    {"kind": "ImplementedBy", "target": {"kind": "Struct", "match": {"name": "Router"}}}
                ]
            }
        }"#;
        let query = QueryParser::from_json(json).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        assert!(
            result
                .post_filters
                .iter()
                .any(|f| matches!(f, PostFilter::Relations(r) if r.none.is_some())),
            "relations.none must be converted to PostFilter::Relations"
        );
    }

    #[test]
    fn test_convert_empty_relations_skipped() {
        let json = r#"{"kind": "Function", "relations": {}}"#;
        let query = QueryParser::from_json(json).unwrap();
        let result = QueryConverter::to_discovery_query(&query).unwrap();

        assert!(
            !result
                .post_filters
                .iter()
                .any(|f| matches!(f, PostFilter::Relations(_))),
            "empty relations must not produce PostFilter"
        );
    }
}