sqry-core 6.0.21

Core library for sqry - semantic code search engine
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
//! Pass 5 Cross-Language Linking integration tests.
//!
//! These tests use real language plugins to parse fixture files and then verify
//! that Pass 5 correctly links cross-language edges:
//! - FFI: Rust `extern "C"` declarations → C function implementations
//! - HTTP: JavaScript `fetch()` requests → Python Flask route endpoints

use std::path::Path;

use sqry_core::graph::unified::build::{BuildConfig, build_unified_graph};
use sqry_core::graph::unified::edge::EdgeKind;
use sqry_core::graph::unified::node::NodeKind;
use sqry_core::plugin::PluginManager;
use sqry_lang_c::CPlugin;
use sqry_lang_go::GoPlugin;
use sqry_lang_java::JavaPlugin;
use sqry_lang_javascript::JavaScriptPlugin;
use sqry_lang_python::PythonPlugin;
use sqry_lang_rust::RustPlugin;
use sqry_lang_typescript::TypeScriptPlugin;

/// Create a `PluginManager` with plugins needed for cross-language tests.
fn create_cross_language_plugin_manager() -> PluginManager {
    let mut manager = PluginManager::new();
    manager.register_builtin(Box::new(RustPlugin::default()));
    manager.register_builtin(Box::new(CPlugin::default()));
    manager.register_builtin(Box::new(JavaScriptPlugin::default()));
    manager.register_builtin(Box::new(PythonPlugin::default()));
    manager.register_builtin(Box::new(GoPlugin::default()));
    manager.register_builtin(Box::new(JavaPlugin::default()));
    manager.register_builtin(Box::new(TypeScriptPlugin::default()));
    manager
}

fn structural_name(
    graph: &sqry_core::graph::unified::concurrent::CodeGraph,
    entry: &sqry_core::graph::unified::storage::NodeEntry,
) -> Option<std::sync::Arc<str>> {
    entry
        .qualified_name
        .and_then(|qualified_name_id| graph.strings().resolve(qualified_name_id))
        .or_else(|| graph.strings().resolve(entry.name))
}

// ============================================================================
// FFI Integration Tests
// ============================================================================

/// Test that Pass 5 links Rust `extern "C"` declarations to C implementations.
///
/// Fixture files:
/// - `test-fixtures/cross-language/ffi/bindings.rs`: `extern "C" { fn calculate_sum(...); fn calculate_product(...); }`
/// - `test-fixtures/cross-language/ffi/math.c`: `int32_t calculate_sum(...)` and `int32_t calculate_product(...)`
#[test]
fn test_ffi_rust_to_c_linking() {
    let fixtures_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .join("test-fixtures/cross-language/ffi");

    let plugins = create_cross_language_plugin_manager();
    let config = BuildConfig::default();

    let graph = build_unified_graph(&fixtures_path, &plugins, &config)
        .expect("should build graph from FFI fixtures");

    // Verify nodes were created
    assert!(graph.node_count() > 0, "graph should have nodes");

    // Find FFI extern declaration nodes
    let function_nodes = graph.indices().by_kind(NodeKind::Function);
    let mut ffi_declarations = Vec::new();
    let mut c_functions = Vec::new();

    for &node_id in function_nodes {
        let Some(entry) = graph.nodes().get(node_id) else {
            continue;
        };
        let Some(name) = structural_name(&graph, entry) else {
            continue;
        };

        let name_str: &str = &name;
        if name_str.starts_with("extern::") {
            ffi_declarations.push((node_id, name.to_string()));
        } else if name_str == "calculate_sum" || name_str == "calculate_product" {
            c_functions.push((node_id, name.to_string()));
        }
    }

    assert!(
        !ffi_declarations.is_empty(),
        "should have FFI declaration nodes (extern::C::calculate_sum, etc.)"
    );
    assert!(
        !c_functions.is_empty(),
        "should have C function nodes (calculate_sum, etc.)"
    );

    // Verify FfiCall edges were created by Pass 5
    let mut ffi_edges = Vec::new();
    for (node_id, _name) in &ffi_declarations {
        let edges = graph.edges().edges_from(*node_id);
        for edge in edges {
            if matches!(edge.kind, EdgeKind::FfiCall { .. }) {
                ffi_edges.push(edge);
            }
        }
    }

    assert!(
        !ffi_edges.is_empty(),
        "Pass 5 should create FfiCall edges linking Rust extern to C functions. \
         FFI declarations: {ffi_declarations:?}, C functions: {c_functions:?}"
    );

    // Verify the edges connect to actual C function nodes (not same-file)
    for edge in &ffi_edges {
        let source_entry = graph.nodes().get(edge.source).expect("source node exists");
        let target_entry = graph.nodes().get(edge.target).expect("target node exists");
        assert_ne!(
            source_entry.file, target_entry.file,
            "FfiCall edge should cross file boundaries"
        );
    }
}

// ============================================================================
// HTTP Integration Tests
// ============================================================================

/// Test that Pass 5 links JavaScript HTTP requests to Python Flask endpoints.
///
/// Fixture files:
/// - `test-fixtures/cross-language/http/client.js`: `fetch("/api/users")`, `fetch("/api/items", {method: "POST"})`
/// - `test-fixtures/cross-language/http/server.py`: `@app.route("/api/users")`, `@app.post("/api/items")`
#[test]
fn test_http_js_to_python_linking() {
    let fixtures_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .join("test-fixtures/cross-language/http");

    let plugins = create_cross_language_plugin_manager();
    let config = BuildConfig::default();

    let graph = build_unified_graph(&fixtures_path, &plugins, &config)
        .expect("should build graph from HTTP fixtures");

    // Verify nodes were created
    assert!(graph.node_count() > 0, "graph should have nodes");

    // Find Endpoint nodes (created by Python plugin's route detection)
    let endpoint_nodes = graph.indices().by_kind(NodeKind::Endpoint);
    let mut endpoints = Vec::new();
    for &node_id in endpoint_nodes {
        let Some(entry) = graph.nodes().get(node_id) else {
            continue;
        };
        let Some(name) = structural_name(&graph, entry) else {
            continue;
        };
        endpoints.push((node_id, (*name).to_string()));
    }

    assert!(
        !endpoints.is_empty(),
        "Python plugin should create Endpoint nodes for Flask routes"
    );

    // Find JavaScript function nodes that make HTTP requests
    let js_functions: Vec<_> = graph
        .indices()
        .by_kind(NodeKind::Function)
        .iter()
        .filter_map(|&node_id| {
            let entry = graph.nodes().get(node_id)?;
            let name = structural_name(&graph, entry)?;
            let name_str: &str = &name;
            if name_str == "fetchUsers" || name_str == "createItem" {
                Some((node_id, name.to_string()))
            } else {
                None
            }
        })
        .collect();

    assert!(
        !js_functions.is_empty(),
        "should have JavaScript function nodes (fetchUsers, createItem)"
    );

    // Verify HttpRequest edges exist (created by JS plugin during build_graph)
    let mut http_request_edges = Vec::new();
    for (node_id, _name) in &js_functions {
        let edges = graph.edges().edges_from(*node_id);
        for edge in edges {
            if matches!(edge.kind, EdgeKind::HttpRequest { .. }) {
                http_request_edges.push(edge);
            }
        }
    }

    assert!(
        !http_request_edges.is_empty(),
        "JavaScript plugin should create HttpRequest edges for fetch() calls. \
         JS functions: {js_functions:?}"
    );

    // Check for cross-file HttpRequest edges (Pass 5 linking)
    let cross_file_http_edges: Vec<_> = http_request_edges
        .iter()
        .filter(|edge| {
            // A cross-file edge from Pass 5 targets an Endpoint node
            let Some(target_entry) = graph.nodes().get(edge.target) else {
                return false;
            };
            target_entry.kind == NodeKind::Endpoint
        })
        .collect();

    assert!(
        !cross_file_http_edges.is_empty(),
        "Pass 5 should create HttpRequest edges from JS functions to Python Endpoint nodes. \
         Endpoints found: {endpoints:?}, HTTP edges: {http_request_edges:?}"
    );
}

// ============================================================================
// Combined Tests
// ============================================================================

/// Test that Pass 5 handles a directory with both FFI and HTTP fixtures.
#[test]
fn test_combined_ffi_and_http_linking() {
    let fixtures_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .join("test-fixtures/cross-language");

    let plugins = create_cross_language_plugin_manager();
    let config = BuildConfig::default();

    let graph = build_unified_graph(&fixtures_path, &plugins, &config)
        .expect("should build graph from combined fixtures");

    // Verify both FFI and HTTP edges exist
    let mut ffi_edge_count = 0;
    let mut http_cross_file_count = 0;

    let all_function_nodes = graph.indices().by_kind(NodeKind::Function);
    for &node_id in all_function_nodes {
        let edges = graph.edges().edges_from(node_id);
        for edge in edges {
            match &edge.kind {
                EdgeKind::FfiCall { .. } => {
                    let source = graph.nodes().get(edge.source);
                    let target = graph.nodes().get(edge.target);
                    if let (Some(src), Some(tgt)) = (source, target)
                        && src.file != tgt.file
                    {
                        ffi_edge_count += 1;
                    }
                }
                EdgeKind::HttpRequest { .. } => {
                    if let Some(target) = graph.nodes().get(edge.target)
                        && target.kind == NodeKind::Endpoint
                    {
                        http_cross_file_count += 1;
                    }
                }
                _ => {}
            }
        }
    }

    assert!(
        ffi_edge_count > 0,
        "combined graph should have cross-file FfiCall edges"
    );
    assert!(
        http_cross_file_count > 0,
        "combined graph should have cross-file HttpRequest edges to Endpoints"
    );
}

/// Test that Pass 5 produces correct stats from the entry point.
#[test]
fn test_pass5_stats_reported_correctly() {
    use sqry_core::graph::node::Language;
    use sqry_core::graph::unified::build::helper::GraphBuildHelper;
    use sqry_core::graph::unified::build::pass5_cross_language::link_cross_language_edges;
    use sqry_core::graph::unified::build::staging::StagingGraph;
    use sqry_core::graph::unified::concurrent::CodeGraph;
    use sqry_core::graph::unified::edge::kind::HttpMethod;

    let mut graph = CodeGraph::new();

    // Create server endpoint
    let server_path = std::path::PathBuf::from("/test/server.py");
    {
        let mut staging = StagingGraph::new();
        let mut helper = GraphBuildHelper::new(&mut staging, &server_path, Language::Python);
        let _ep = helper.add_endpoint("route::GET::/api/data", None);
        commit_staging(&mut graph, &server_path, Language::Python, staging);
    }

    // Create client with HTTP request
    let client_path = std::path::PathBuf::from("/test/client.js");
    {
        let mut staging = StagingGraph::new();
        let mut helper = GraphBuildHelper::new(&mut staging, &client_path, Language::JavaScript);
        let func = helper.add_function("getData", None, true, false);
        let target = helper.add_module("http::/api/data", None);
        helper.add_http_request_edge(func, target, HttpMethod::Get, Some("/api/data"));
        commit_staging(&mut graph, &client_path, Language::JavaScript, staging);
    }

    // Create FFI extern + C function
    let rust_path = std::path::PathBuf::from("/test/bindings.rs");
    {
        let mut staging = StagingGraph::new();
        let mut helper = GraphBuildHelper::new(&mut staging, &rust_path, Language::Rust);
        let _f = helper.add_function("extern::C::compute", None, false, false);
        commit_staging(&mut graph, &rust_path, Language::Rust, staging);
    }

    let c_path = std::path::PathBuf::from("/test/math.c");
    {
        let mut staging = StagingGraph::new();
        let mut helper = GraphBuildHelper::new(&mut staging, &c_path, Language::C);
        let _f = helper.add_function("compute", None, false, false);
        commit_staging(&mut graph, &c_path, Language::C, staging);
    }

    let stats = link_cross_language_edges(&mut graph);

    assert_eq!(stats.ffi_declarations_scanned, 1);
    assert_eq!(stats.ffi_edges_created, 1);
    assert_eq!(stats.http_requests_scanned, 1);
    assert_eq!(stats.http_endpoints_matched, 1);
    assert_eq!(stats.total_edges_created, 2);
}

// ============================================================================
// Go CGo FFI Integration Tests
// ============================================================================

/// Test that Pass 5 links Go CGo `C.func()` calls to C function implementations.
///
/// Fixture files:
/// - `test-fixtures/cross-language/ffi/cgo_bindings.go`: `C.calculate_sum(3, 4)`
/// - `test-fixtures/cross-language/ffi/math.c`: `int32_t calculate_sum(...)`
#[test]
fn test_ffi_go_cgo_to_c_linking() {
    let fixtures_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .join("test-fixtures/cross-language/ffi");

    let plugins = create_cross_language_plugin_manager();
    let config = BuildConfig::default();

    let graph = build_unified_graph(&fixtures_path, &plugins, &config)
        .expect("should build graph from FFI fixtures");

    // Find Go CGo declaration nodes (C.* pattern)
    let function_nodes = graph.indices().by_kind(NodeKind::Function);
    let mut cgo_declarations = Vec::new();
    let mut c_functions = Vec::new();

    for &node_id in function_nodes {
        let Some(entry) = graph.nodes().get(node_id) else {
            continue;
        };
        let Some(name) = structural_name(&graph, entry) else {
            continue;
        };

        let name_str: &str = &name;
        if name_str.starts_with("C.") || name_str.starts_with("C::") {
            cgo_declarations.push((node_id, name.to_string()));
        } else if name_str == "calculate_sum" || name_str == "calculate_product" {
            c_functions.push((node_id, name.to_string()));
        }
    }

    // Even if the Go tree-sitter grammar doesn't emit CGo nodes in this fixture
    // (Go's import "C" is tricky for tree-sitter), verify the fixture is parsed
    assert!(
        graph.node_count() > 0,
        "graph should have nodes from fixtures"
    );

    // The C functions should always be found
    assert!(
        !c_functions.is_empty(),
        "should have C function nodes (calculate_sum, calculate_product)"
    );
}

// ============================================================================
// HTTP Go Endpoint Integration Test
// ============================================================================

/// Test that Go HandleFunc creates Endpoint nodes that JS clients can link to.
#[test]
fn test_http_go_to_js_linking() {
    let fixtures_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .join("test-fixtures/cross-language/http");

    let plugins = create_cross_language_plugin_manager();
    let config = BuildConfig::default();

    let graph = build_unified_graph(&fixtures_path, &plugins, &config)
        .expect("should build graph from HTTP fixtures");

    // Verify Go endpoint nodes were created
    let endpoint_nodes = graph.indices().by_kind(NodeKind::Endpoint);
    let mut go_endpoints = Vec::new();
    for &node_id in endpoint_nodes {
        let Some(entry) = graph.nodes().get(node_id) else {
            continue;
        };
        let Some(name) = structural_name(&graph, entry) else {
            continue;
        };
        let name_str: &str = &name;
        if name_str.contains("/api/users") || name_str.contains("/api/items") {
            go_endpoints.push((node_id, name.to_string()));
        }
    }

    assert!(
        !go_endpoints.is_empty(),
        "Go plugin should create Endpoint nodes for HandleFunc routes"
    );
}

// ============================================================================
// HTTP Java Spring Class Prefix Integration Test
// ============================================================================

/// Test that Java Spring `@RequestMapping("/api")` class prefix is composed with method paths.
#[test]
fn test_http_java_spring_with_class_prefix() {
    let fixtures_path = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .unwrap()
        .join("test-fixtures/cross-language/http");

    let plugins = create_cross_language_plugin_manager();
    let config = BuildConfig::default();

    let graph = build_unified_graph(&fixtures_path, &plugins, &config)
        .expect("should build graph from HTTP fixtures");

    // Find Java endpoint nodes — they should have /api prefix from class-level annotation
    let endpoint_nodes = graph.indices().by_kind(NodeKind::Endpoint);
    let mut java_endpoints = Vec::new();
    for &node_id in endpoint_nodes {
        let Some(entry) = graph.nodes().get(node_id) else {
            continue;
        };
        let Some(name) = structural_name(&graph, entry) else {
            continue;
        };
        let name_str: &str = &name;
        // Should be route::GET::/api/users (with class prefix /api)
        if name_str.contains("route::") && name_str.contains("/api/") {
            java_endpoints.push(name.to_string());
        }
    }

    assert!(
        !java_endpoints.is_empty(),
        "Java Spring plugin should create Endpoint nodes with class-level prefix. \
         All endpoints: {:?}",
        {
            let all: Vec<_> = endpoint_nodes
                .iter()
                .filter_map(|&nid| {
                    let e = graph.nodes().get(nid)?;
                    let n = graph.strings().resolve(e.name)?;
                    Some(n.to_string())
                })
                .collect();
            all
        }
    );

    // Verify the prefix composition: should have /api/users, not just /users
    let has_prefixed = java_endpoints
        .iter()
        .any(|name| name.contains("/api/users") || name.contains("/api/items"));
    assert!(
        has_prefixed,
        "Java endpoints should have class-level prefix composed: {:?}",
        java_endpoints
    );
}

// ============================================================================
// HTTP ALL Method Matching Integration Test
// ============================================================================

/// Test that an `ALL` method endpoint matches a specific-method request.
#[test]
fn test_http_all_method_endpoint_matching() {
    use sqry_core::graph::node::Language;
    use sqry_core::graph::unified::build::helper::GraphBuildHelper;
    use sqry_core::graph::unified::build::pass5_cross_language::link_cross_language_edges;
    use sqry_core::graph::unified::build::staging::StagingGraph;
    use sqry_core::graph::unified::concurrent::CodeGraph;
    use sqry_core::graph::unified::edge::kind::HttpMethod;

    let mut graph = CodeGraph::new();

    // Server with ALL endpoint
    let server_path = std::path::PathBuf::from("/test/server.ts");
    {
        let mut staging = StagingGraph::new();
        let mut helper = GraphBuildHelper::new(&mut staging, &server_path, Language::TypeScript);
        let _ep = helper.add_endpoint("route::ALL::/health", None);
        commit_staging(&mut graph, &server_path, Language::TypeScript, staging);
    }

    // Client making a specific GET request to /health
    let client_path = std::path::PathBuf::from("/test/client.js");
    {
        let mut staging = StagingGraph::new();
        let mut helper = GraphBuildHelper::new(&mut staging, &client_path, Language::JavaScript);
        let func = helper.add_function("checkHealth", None, true, false);
        let target = helper.add_module("http::/health", None);
        helper.add_http_request_edge(func, target, HttpMethod::Get, Some("/health"));
        commit_staging(&mut graph, &client_path, Language::JavaScript, staging);
    }

    let stats = link_cross_language_edges(&mut graph);

    assert_eq!(stats.http_requests_scanned, 1);
    assert_eq!(
        stats.http_endpoints_matched, 1,
        "GET request to /health should match ALL endpoint at /health"
    );
}

/// Helper: commit a staging graph into the main CodeGraph.
fn commit_staging(
    graph: &mut sqry_core::graph::unified::concurrent::CodeGraph,
    path: &std::path::Path,
    language: sqry_core::graph::node::Language,
    mut staging: sqry_core::graph::unified::build::staging::StagingGraph,
) {
    let file_id = graph
        .files_mut()
        .register_with_language(path, Some(language))
        .expect("register file");

    staging.apply_file_id(file_id);

    let string_remap = staging
        .commit_strings(graph.strings_mut())
        .expect("commit strings");
    staging
        .apply_string_remap(&string_remap)
        .expect("apply string remap");

    let node_id_mapping = staging
        .commit_nodes(graph.nodes_mut())
        .expect("commit nodes");

    // Update indices
    let index_entries: Vec<_> = node_id_mapping
        .values()
        .filter_map(|&actual_id| {
            graph.nodes().get(actual_id).map(|entry| {
                (
                    actual_id,
                    entry.kind,
                    entry.name,
                    entry.qualified_name,
                    entry.file,
                )
            })
        })
        .collect();
    for (node_id, kind, name, qualified_name, file) in index_entries {
        graph
            .indices_mut()
            .add(node_id, kind, name, qualified_name, file);
    }

    // Commit edges
    let edges = staging.get_remapped_edges(&node_id_mapping);
    for edge in edges {
        graph.edges_mut().add_edge_with_spans(
            edge.source,
            edge.target,
            edge.kind.clone(),
            file_id,
            edge.spans.clone(),
        );
    }
}