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
//! RyoQL Executor - クエリ実行オーケストレーション
//!
//! RyoQLクエリをDiscoveryEngineで実行し、結果を変換して返す。
//!
//! ## 責務
//! 1. Query → DiscoveryQuery変換
//! 2. DiscoveryEngine実行
//! 3. 後処理フィルタ適用
//! 4. 結果をQueryResponseに変換
//! 5. on_emptyリカバリー

use std::time::Instant;

use crate::converter::{CompositeOp, ConversionResult, QueryConverter};
use crate::schema::{
    MatchResult, Query, QueryMetadata, QueryResponse, QueryStatus, ResolveConfig, ResolveKind,
    ResolveStatus, Suggestion, SuggestionKind, ViewMode,
};
use ryo_analysis::{AnalysisContext, DiscoveredSymbol, DiscoveryEngine, SymbolId, SymbolKind};
use thiserror::Error;

/// 実行エラー
#[derive(Debug, Error)]
pub enum ExecuteError {
    /// クエリ変換段階の失敗。
    #[error("conversion error: {0}")]
    Conversion(#[from] crate::converter::ConvertError),

    /// `DiscoveryEngine` 呼び出し失敗。
    #[error("discovery error: {0}")]
    Discovery(String),

    /// 後処理フィルタ適用失敗。
    #[error("post-filter error: {0}")]
    PostFilter(String),
}

/// クエリ実行器
pub struct QueryExecutor<'a> {
    ctx: &'a AnalysisContext,
    view_mode: ViewMode,
}

impl<'a> QueryExecutor<'a> {
    /// 新しいExecutorを作成
    pub fn new(ctx: &'a AnalysisContext) -> Self {
        Self {
            ctx,
            view_mode: ViewMode::default(),
        }
    }

    /// ViewModeを設定
    pub fn with_view_mode(mut self, mode: ViewMode) -> Self {
        self.view_mode = mode;
        self
    }

    /// クエリを実行
    pub fn execute(&self, query: &Query) -> Result<QueryResponse, ExecuteError> {
        let start = Instant::now();
        let view_mode = query.view.unwrap_or(self.view_mode);

        // 1. 変換
        let conversion = QueryConverter::to_discovery_query(query)?;

        // 2. 実行
        let (results, status) = self.execute_conversion(&conversion)?;

        // 3. 後処理フィルタ
        let filter_processor = crate::filter::PostFilterProcessor::new(self.ctx);
        let filtered = filter_processor.apply(results, &conversion.post_filters);

        // 4. Resolve処理(指定されている場合)
        let (resolved, resolve_status) = if let Some(ref resolve_config) = query.resolve {
            self.execute_resolve(&filtered, resolve_config)?
        } else {
            (filtered, None)
        };

        // 5. ViewMode適用してMatchResultに変換
        let match_results: Vec<MatchResult> = resolved
            .iter()
            .map(|s| self.to_match_result(s, view_mode))
            .collect();

        // 6. on_emptyリカバリー
        let (final_results, suggestions, final_status) = if match_results.is_empty() {
            self.try_recovery(query, &conversion)?
        } else {
            (match_results, vec![], status)
        };

        // 7. limit適用
        let limited: Vec<MatchResult> = if let Some(limit) = query.limit {
            final_results.into_iter().take(limit).collect()
        } else {
            final_results
        };

        let total = limited.len();
        let elapsed = start.elapsed();

        Ok(QueryResponse {
            status: final_status,
            results: limited,
            suggestions,
            metadata: QueryMetadata {
                elapsed_ms: elapsed.as_millis() as u32,
                total_matches: total,
                resolve_status,
            },
        })
    }

    /// ConversionResultを実行
    fn execute_conversion(
        &self,
        conversion: &ConversionResult,
    ) -> Result<(Vec<DiscoveredSymbol>, QueryStatus), ExecuteError> {
        // 複合クエリの場合
        if let Some(ref composite) = conversion.composite {
            let mut all_results: Vec<DiscoveredSymbol> = Vec::new();

            for sub in &composite.queries {
                let (results, _) = self.execute_conversion(sub)?;
                match composite.op {
                    CompositeOp::Or => {
                        // Or: マージ(重複排除)
                        for r in results {
                            if !all_results.iter().any(|existing| existing.path == r.path) {
                                all_results.push(r);
                            }
                        }
                    }
                    CompositeOp::And => {
                        if all_results.is_empty() {
                            all_results = results;
                        } else {
                            // And: intersection
                            all_results
                                .retain(|existing| results.iter().any(|r| r.path == existing.path));
                        }
                    }
                }
            }

            let status = if all_results.is_empty() {
                QueryStatus::NotFound
            } else {
                QueryStatus::Found
            };

            return Ok((all_results, status));
        }

        // 単純クエリの場合
        if let Some(ref dq) = conversion.discovery_query {
            // TypeFlowGraphがあれば使用
            let engine = DiscoveryEngine::new(&self.ctx.code_graph, &self.ctx.registry, None)
                .set_typeflow(&self.ctx.typeflow_graph);
            let result = engine.execute(dq);

            let status = if result.symbols.is_empty() {
                QueryStatus::NotFound
            } else {
                QueryStatus::Found
            };

            Ok((result.symbols, status))
        } else {
            Ok((vec![], QueryStatus::NotFound))
        }
    }

    /// Resolveクエリを実行
    ///
    /// 初期結果の各シンボルに対して、指定された関係のシンボルを検索する。
    fn execute_resolve(
        &self,
        symbols: &[DiscoveredSymbol],
        config: &ResolveConfig,
    ) -> Result<(Vec<DiscoveredSymbol>, Option<ResolveStatus>), ExecuteError> {
        let mut resolved_ids: Vec<SymbolId> = Vec::new();
        let depth = config.depth.unwrap_or(1);

        // 各シンボルに対してresolve
        for symbol in symbols {
            let related = self.resolve_single(symbol.id, config.kind, depth);
            for id in related {
                if !resolved_ids.contains(&id) {
                    resolved_ids.push(id);
                }
            }
        }

        // SymbolIdをDiscoveredSymbolに変換
        let resolved_symbols: Vec<DiscoveredSymbol> = resolved_ids
            .into_iter()
            .filter_map(|id| self.symbol_id_to_discovered(id))
            .collect();

        Ok((resolved_symbols, Some(ResolveStatus::Complete)))
    }

    /// 単一シンボルのresolve
    fn resolve_single(&self, id: SymbolId, kind: ResolveKind, depth: usize) -> Vec<SymbolId> {
        if depth == 0 {
            return vec![];
        }

        let direct: Vec<SymbolId> = match kind {
            ResolveKind::Callers => self.ctx.code_graph.callers_of(id).collect(),
            ResolveKind::Callees => self.ctx.code_graph.callees_of(id).collect(),
            ResolveKind::Uses => self.ctx.typeflow_graph.types_used_by(id).collect(),
            ResolveKind::UsedBy => self.ctx.typeflow_graph.type_users(id).collect(),
            ResolveKind::Implementations => self.ctx.code_graph.implementors_of(id).collect(),
            ResolveKind::References => {
                // References = 参照箇所 = callers + type users
                self.ctx
                    .code_graph
                    .callers_of(id)
                    .chain(self.ctx.typeflow_graph.type_users(id))
                    .collect()
            }
            ResolveKind::Definition => {
                // Definition = 定義元(id自身、または継承元など)
                // 現時点では元のシンボルを返す
                vec![id]
            }
        };

        // depth > 1 の場合は再帰的に探索
        if depth > 1 {
            let mut all = direct.clone();
            for child_id in &direct {
                let deeper = self.resolve_single(*child_id, kind, depth - 1);
                for d in deeper {
                    if !all.contains(&d) {
                        all.push(d);
                    }
                }
            }
            all
        } else {
            direct
        }
    }

    /// SymbolId → DiscoveredSymbol 変換
    fn symbol_id_to_discovered(&self, id: SymbolId) -> Option<DiscoveredSymbol> {
        let path = self.ctx.registry.resolve(id)?;
        let kind = self.ctx.registry.kind(id).unwrap_or(SymbolKind::Other);
        let span = self.ctx.registry.span(id).cloned();
        let visibility = self.ctx.registry.visibility(id).cloned();

        let mut symbol = DiscoveredSymbol::new(id, path.clone(), kind);
        if let Some(s) = span {
            symbol = symbol.with_span(s);
        }
        if let Some(v) = visibility {
            symbol = symbol.with_visibility(v);
        }

        Some(symbol)
    }

    /// on_emptyリカバリーを試行
    ///
    /// デフォルトでsuggestが有効(UX向上のため)
    fn try_recovery(
        &self,
        query: &Query,
        _conversion: &ConversionResult,
    ) -> Result<(Vec<MatchResult>, Vec<Suggestion>, QueryStatus), ExecuteError> {
        // デフォルトでsuggestを有効にする(UX向上)
        let default_recovery = crate::schema::RecoveryStrategy {
            fuzzy: Some(crate::schema::FuzzyConfig { max_distance: 2 }),
            split_words: None,
            enumerate_scope: Some(10),
        };

        let on_empty = query.r#match.as_ref().and_then(|m| m.on_empty.as_ref());
        let recovery = on_empty.unwrap_or(&default_recovery);
        let mut suggestions = Vec::new();

        // fuzzy検索(未実装 - ryo-fuzzy-parserのdistance.rsを使って実装予定)
        if recovery.fuzzy.is_some() {
            suggestions.push(Suggestion {
                kind: SuggestionKind::Typo,
                name: "[未実装] fuzzy検索は現在利用できません".to_string(),
                distance: None,
                confidence: 0.0,
            });
        }

        // enumerate_scope(未実装 - スコープ内シンボル列挙)
        if recovery.enumerate_scope.is_some() {
            suggestions.push(Suggestion {
                kind: SuggestionKind::InScope,
                name: "[未実装] スコープ内シンボル列挙は現在利用できません".to_string(),
                distance: None,
                confidence: 0.0,
            });
        }

        let status = if suggestions.is_empty() {
            QueryStatus::NotFound
        } else {
            QueryStatus::Partial
        };

        Ok((vec![], suggestions, status))
    }

    /// DiscoveredSymbol → MatchResult 変換 (公開API)
    ///
    /// CLI等から直接呼び出せるように公開。パターン検索結果を任意のViewModeで
    /// MatchResultに変換する。
    pub fn to_match_result(&self, symbol: &DiscoveredSymbol, mode: ViewMode) -> MatchResult {
        use crate::schema::MatchView;

        // SymbolId: slotmapのキー形式
        let symbol_id = format!("{:?}", symbol.id);

        // ViewMode別のデータを構築
        let view = match mode {
            ViewMode::Snippet => {
                // TODO: ソースコードスニペットを取得
                let text = format!("// {} at {}", symbol.path.name(), symbol.path);
                MatchView::Snippet { text }
            }
            ViewMode::Precise => MatchView::Precise,
            ViewMode::Count => {
                // CountモードではMatchResult自体を生成しないはずだが、フォールバック
                MatchView::Precise
            }
            ViewMode::Def => {
                let (module_path, definition, doc) = self.get_def_info(symbol);
                MatchView::Def {
                    module_path: module_path.unwrap_or_else(|| symbol.path.module_path()),
                    definition: definition.unwrap_or_else(|| format!("{:?}", symbol.kind)),
                    doc,
                }
            }
            ViewMode::Full => {
                let (module_path, definition, doc) = self.get_def_info(symbol);
                let body = self
                    .get_full_source(symbol)
                    .unwrap_or_else(|| "// source not available".to_string());
                MatchView::Full {
                    module_path: module_path.unwrap_or_else(|| symbol.path.module_path()),
                    definition: definition.unwrap_or_else(|| format!("{:?}", symbol.kind)),
                    body,
                    doc,
                }
            }
        };

        MatchResult {
            id: symbol_id,
            uuid: symbol.uuid.map(|u| u.to_string()),
            path: symbol.path.to_string(),
            node_kind: format!("{:?}", symbol.kind),
            name: symbol.path.name().to_string(),
            view,
        }
    }

    /// Defモード用: 定義詳細情報を取得(公開API)
    pub fn get_def_info_for_symbol(
        &self,
        symbol: &DiscoveredSymbol,
    ) -> (Option<String>, Option<String>, Option<String>) {
        self.get_def_info(symbol)
    }

    /// Defモード用: 定義詳細情報を取得
    ///
    /// ASTRegistry から SymbolId で O(1) 直接取得。
    /// 全ファイル走査や名前マッチは行わない。
    fn get_def_info(
        &self,
        symbol: &DiscoveredSymbol,
    ) -> (Option<String>, Option<String>, Option<String>) {
        use crate::formatter::SourceFormatter;
        use ryo_source::pure::PureItem;

        let module_path = Some(symbol.path.module_path());

        // ASTRegistry: SymbolId → PureItem (O(1))
        if let Some(item) = self.ctx.ast_registry.get(symbol.id) {
            let fmt_or_err =
                |r: Result<String, _>| r.unwrap_or_else(|e| format!("<format error: {}>", e));
            let (def, doc) = match item {
                PureItem::Fn(f) => (
                    fmt_or_err(SourceFormatter::format_fn_signature(f)),
                    SourceFormatter::extract_doc_and_spec(&f.attrs),
                ),
                PureItem::Struct(s) => (
                    fmt_or_err(SourceFormatter::format_struct(s)),
                    SourceFormatter::extract_doc_and_spec(&s.attrs),
                ),
                PureItem::Enum(e) => (
                    fmt_or_err(SourceFormatter::format_enum(e)),
                    SourceFormatter::extract_doc_and_spec(&e.attrs),
                ),
                PureItem::Trait(t) => (
                    fmt_or_err(SourceFormatter::format_trait(t)),
                    SourceFormatter::extract_doc_and_spec(&t.attrs),
                ),
                PureItem::Mod(_) => {
                    let def = self.format_module_contents(symbol);
                    return (module_path, Some(def), None);
                }
                PureItem::Type(t) => (
                    fmt_or_err(SourceFormatter::format_item_source(item)),
                    SourceFormatter::extract_doc_and_spec(&t.attrs),
                ),
                PureItem::Const(c) => (
                    fmt_or_err(SourceFormatter::format_item_source(item)),
                    SourceFormatter::extract_doc_and_spec(&c.attrs),
                ),
                PureItem::Static(s) => (
                    fmt_or_err(SourceFormatter::format_item_source(item)),
                    SourceFormatter::extract_doc_and_spec(&s.attrs),
                ),
                _ => {
                    // Impl, Use, etc. — use DetailStore fallback
                    let definition = self.get_definition_from_detail_store(symbol);
                    return (module_path, definition, None);
                }
            };
            return (module_path, Some(def), doc);
        }

        // フォールバック: DetailStoreから取得
        let definition = self.get_definition_from_detail_store(symbol);
        (module_path, definition, None)
    }

    /// DetailStoreから定義を取得(フォールバック)
    fn get_definition_from_detail_store(&self, symbol: &DiscoveredSymbol) -> Option<String> {
        match symbol.kind {
            SymbolKind::Function | SymbolKind::Method => {
                self.ctx.detail_store.function(symbol.id).map(|d| {
                    let params: Vec<_> = d
                        .params
                        .iter()
                        .map(|p| format!("{}: {}", p.name, p.ty))
                        .collect();
                    let ret = d
                        .return_type
                        .as_ref()
                        .map(|t| format!(" -> {}", t))
                        .unwrap_or_default();
                    let async_kw = if d.is_async { "async " } else { "" };
                    format!(
                        "{}fn {}({}){}",
                        async_kw,
                        symbol.path.name(),
                        params.join(", "),
                        ret
                    )
                })
            }
            SymbolKind::Struct => self.ctx.detail_store.struct_(symbol.id).map(|d| {
                let fields: Vec<_> = d
                    .fields
                    .iter()
                    .map(|f| format!("    {}: {},", f.name, f.ty))
                    .collect();
                if fields.is_empty() {
                    format!("struct {}", symbol.path.name())
                } else {
                    format!(
                        "struct {} {{\n{}\n}}",
                        symbol.path.name(),
                        fields.join("\n")
                    )
                }
            }),
            SymbolKind::Enum => self.ctx.detail_store.enum_(symbol.id).map(|d| {
                let variants: Vec<_> = d
                    .variants
                    .iter()
                    .map(|v| format!("    {},", v.name))
                    .collect();
                format!(
                    "enum {} {{\n{}\n}}",
                    symbol.path.name(),
                    variants.join("\n")
                )
            }),
            SymbolKind::Trait => self
                .ctx
                .detail_store
                .trait_(symbol.id)
                .map(|_| format!("trait {} {{ ... }}", symbol.path.name())),
            SymbolKind::Mod => {
                // モジュール内のアイテム一覧を表示
                Some(self.format_module_contents(symbol))
            }
            _ => None,
        }
    }

    /// モジュール内のアイテムを一覧表示
    fn format_module_contents(&self, symbol: &DiscoveredSymbol) -> String {
        use std::fmt::Write;

        let mut items_by_kind: std::collections::BTreeMap<&'static str, Vec<String>> =
            std::collections::BTreeMap::new();

        // このモジュールのパスプレフィックス
        let mod_path_str = symbol.path.to_string();
        let depth = symbol.path.depth();

        // レジストリから直接の子シンボルを取得
        for (child_id, child_path) in self.ctx.registry.iter() {
            // 直接の子かチェック(パスの深さが1つだけ深い && プレフィックスが一致)
            if child_path.depth() == depth + 1 {
                let child_path_str = child_path.to_string();
                if child_path_str.starts_with(&mod_path_str) {
                    let kind = self.ctx.registry.kind(child_id).unwrap_or(SymbolKind::Any);
                    let kind_str = match kind {
                        SymbolKind::Function => "fn",
                        SymbolKind::Method => "fn",
                        SymbolKind::Struct => "struct",
                        SymbolKind::Enum => "enum",
                        SymbolKind::Trait => "trait",
                        SymbolKind::Impl => continue, // implは省略
                        SymbolKind::Const => "const",
                        SymbolKind::Static => "static",
                        SymbolKind::TypeAlias => "type",
                        SymbolKind::Mod => "mod",
                        _ => continue,
                    };
                    items_by_kind
                        .entry(kind_str)
                        .or_default()
                        .push(child_path.name().to_string());
                }
            }
        }

        let mut output = format!("mod {} {{\n", symbol.path.name());
        for (kind, names) in items_by_kind {
            for name in names.iter().take(10) {
                writeln!(output, "    {} {};", kind, name).unwrap();
            }
            if names.len() > 10 {
                writeln!(output, "    // ... +{} more {}", names.len() - 10, kind).unwrap();
            }
        }
        output.push('}');
        output
    }

    /// Full: 関数bodyを含む完全なソースを取得
    ///
    /// ASTRegistry から SymbolId で O(1) 直接取得。
    /// 外部モジュールのみ registry.span() → files lookup で取得。
    fn get_full_source(&self, symbol: &DiscoveredSymbol) -> Option<String> {
        use crate::formatter::SourceFormatter;
        use ryo_source::pure::PureItem;

        // ASTRegistry: SymbolId → PureItem (O(1))
        if let Some(item) = self.ctx.ast_registry.get(symbol.id) {
            let fmt_or_err =
                |r: Result<String, _>| r.unwrap_or_else(|e| format!("<format error: {}>", e));
            return match item {
                PureItem::Fn(f) => Some(fmt_or_err(SourceFormatter::format_fn_full(f))),
                PureItem::Struct(s) => Some(fmt_or_err(SourceFormatter::format_struct(s))),
                PureItem::Enum(e) => Some(fmt_or_err(SourceFormatter::format_enum(e))),
                PureItem::Trait(t) => Some(fmt_or_err(SourceFormatter::format_trait(t))),
                PureItem::Mod(m) => {
                    if !m.items.is_empty() {
                        // Inline module: format from AST
                        SourceFormatter::format_item_source(item).ok()
                    } else {
                        // External module (mod foo;): find source file
                        self.get_external_module_source(symbol)
                    }
                }
                _ => SourceFormatter::format_item_source(item).ok(),
            };
        }

        // ASTRegistry に未登録の場合: 外部モジュールの可能性
        if symbol.kind == SymbolKind::Mod {
            return self.get_external_module_source(symbol);
        }

        None
    }

    /// Get source for external module (mod foo;) by finding the corresponding file.
    ///
    /// SymbolId → registry.span() → FileSpan.file でファイル特定を試み、
    /// 該当しない場合のみモジュール名ベースのフォールバックを行う。
    fn get_external_module_source(&self, symbol: &DiscoveredSymbol) -> Option<String> {
        use crate::formatter::SourceFormatter;

        // 1. span → file で O(1) 特定を試みる
        //    ただし mod 宣言の span は宣言側ファイルを指すため、
        //    module_children 経由で子シンボルのファイルを探す。
        if let Some(children) = self.ctx.ast_registry.get_module_children(symbol.id) {
            if let Some(&first_child) = children.first() {
                if let Some(child_span) = self.ctx.registry.span(first_child) {
                    if let Some(file) = self.ctx.files.get(&child_span.file) {
                        let mut output = String::new();
                        for item in &file.items {
                            if let Ok(formatted) = SourceFormatter::format_item_source(item) {
                                if !output.is_empty() {
                                    output.push_str("\n\n");
                                }
                                output.push_str(&formatted);
                            }
                        }
                        if !output.is_empty() {
                            return Some(output);
                        }
                    }
                }
            }
        }

        // 2. フォールバック: モジュール名ベースでファイル検索
        let module_path = symbol.path.module_path();
        let module_name = symbol.path.name();

        for (file_path, file) in self.ctx.files.iter() {
            let path_str = file_path.as_relative().to_string_lossy();

            let is_match = path_str.ends_with(&format!("{}.rs", module_name))
                || path_str.ends_with(&format!("{}/mod.rs", module_name));

            let crate_name = module_path.split("::").next().unwrap_or("");
            let file_crate = file_path.crate_name().as_str();
            let crate_matches = crate_name == file_crate
                || crate_name.replace('_', "-") == file_crate
                || crate_name.replace('-', "_") == file_crate;

            if is_match && crate_matches {
                let mut output = String::new();
                for item in &file.items {
                    if let Ok(formatted) = SourceFormatter::format_item_source(item) {
                        if !output.is_empty() {
                            output.push_str("\n\n");
                        }
                        output.push_str(&formatted);
                    }
                }
                if !output.is_empty() {
                    return Some(output);
                }
            }
        }
        None
    }
}

/// 簡易実行関数
///
/// AnalysisContextがある場合に、クエリを直接実行する。
pub fn execute_query(ctx: &AnalysisContext, query: &Query) -> Result<QueryResponse, ExecuteError> {
    QueryExecutor::new(ctx).execute(query)
}

/// YAMLからクエリを実行
pub fn execute_yaml(ctx: &AnalysisContext, yaml: &str) -> Result<QueryResponse, ExecuteError> {
    let query = crate::parser::QueryParser::from_yaml(yaml)
        .map_err(|e| ExecuteError::Discovery(e.to_string()))?;
    execute_query(ctx, &query)
}

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

    // Note: 実際のテストにはAnalysisContextが必要
    // ここでは変換〜実行フローの型チェックのみ

    #[test]
    fn test_query_response_structure() {
        let response = QueryResponse {
            status: QueryStatus::Found,
            results: vec![MatchResult {
                id: "SymbolId(1v1)".to_string(),
                uuid: None,
                path: "test::foo".to_string(),
                node_kind: "Function".to_string(),
                name: "foo".to_string(),
                view: MatchView::Snippet {
                    text: "fn foo() {}".to_string(),
                },
            }],
            suggestions: vec![],
            metadata: QueryMetadata {
                elapsed_ms: 5,
                total_matches: 1,
                resolve_status: None,
            },
        };

        assert_eq!(response.status, QueryStatus::Found);
        assert_eq!(response.results.len(), 1);
        assert_eq!(response.results[0].name, "foo");
    }

    #[test]
    fn test_match_view_variants() {
        // Snippet
        let snippet = MatchView::Snippet {
            text: "fn example() {}".to_string(),
        };
        assert!(matches!(snippet, MatchView::Snippet { .. }));

        // Def
        let def = MatchView::Def {
            module_path: "mylib::handlers".to_string(),
            definition: "pub fn handle() -> Result<()>".to_string(),
            doc: Some("Handles requests".to_string()),
        };
        assert!(matches!(def, MatchView::Def { .. }));

        // Full
        let full = MatchView::Full {
            module_path: "mylib::handlers".to_string(),
            definition: "pub fn handle() -> Result<()>".to_string(),
            body: "{ Ok(()) }".to_string(),
            doc: None,
        };
        assert!(matches!(full, MatchView::Full { .. }));
    }
}