heddle-semantic 0.15.0

An AI-native version control system
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
// SPDX-License-Identifier: Apache-2.0
use super::*;

fn nested_rust_modules(depth: usize, inner: &str) -> String {
    let mut source = String::new();
    for level in 0..depth {
        source.push_str(&format!("mod layer_{level} {{\n"));
    }
    source.push_str(inner);
    source.push('\n');
    for _ in 0..depth {
        source.push_str("}\n");
    }
    source
}

#[test]
fn test_language_from_path() {
    assert_eq!(
        Language::from_path(std::path::Path::new("foo.rs")),
        Language::Rust
    );
    assert_eq!(
        Language::from_path(std::path::Path::new("foo.py")),
        Language::Python
    );
    assert_eq!(
        Language::from_path(std::path::Path::new("foo.zig")),
        Language::Zig
    );
    assert_eq!(
        Language::from_path(std::path::Path::new("foo.txt")),
        Language::Unknown
    );
}

#[test]
fn test_parse_rust_function() {
    let source = r#"
fn hello_world() -> String {
    "Hello".to_string()
}

fn add(a: i32, b: i32) -> i32 {
    a + b
}
"#;

    let parsed = ParsedFile::parse(source, Language::Rust).expect("Should parse");
    let functions = parsed.extract_functions();

    assert_eq!(functions.len(), 2);
    assert_eq!(functions[0].name, "hello_world");
    assert_eq!(functions[1].name, "add");
    assert!(functions[1].signature.contains("a"));
    assert!(functions[1].signature.contains("b"));
}

#[cfg(all(
    feature = "lang-rust",
    feature = "lang-python",
    feature = "lang-javascript",
    feature = "lang-typescript"
))]
#[test]
fn test_parse_common_language_functions_and_imports() {
    let cases = [
        (
            Language::Rust,
            r#"
use std::collections::HashMap;

pub async fn load_map() -> HashMap<String, usize> {
    HashMap::new()
}
"#,
            "load_map",
            "std::collections",
        ),
        (
            Language::Python,
            r#"
from pathlib import Path

@pytest.mark.slow
async def load_path(root: Path) -> Path:
    return root / "file.txt"
"#,
            "load_path",
            "pathlib",
        ),
        (
            Language::JavaScript,
            r#"
import fs from "node:fs";

export const readConfig = async (path) => {
    return fs.readFileSync(path, "utf8");
};
"#,
            "readConfig",
            "node:fs",
        ),
        (
            Language::TypeScript,
            r#"
import type { Request } from "./types";

export const handleRequest = (request: Request): string => {
    return request.id;
};
"#,
            "handleRequest",
            "./types",
        ),
    ];

    for (language, source, function_name, import_text) in cases {
        let parsed = ParsedFile::parse(source, language)
            .unwrap_or_else(|| panic!("{language:?} should parse"));
        let functions = parsed.extract_functions();
        assert!(
            functions
                .iter()
                .any(|function| function.name == function_name),
            "{language:?} should extract {function_name}: {functions:?}"
        );
        let imports = parsed.extract_imports();
        assert!(
            imports
                .iter()
                .any(|import| import.raw.contains(import_text)),
            "{language:?} should extract import containing {import_text}: {imports:?}"
        );
    }
}

#[cfg(all(
    feature = "lang-c",
    feature = "lang-cpp",
    feature = "lang-go",
    feature = "lang-java"
))]
#[test]
fn test_parse_extended_language_functions_and_imports() {
    let cases = [
        (
            Language::Go,
            r#"
package main

import "context"

func Serve(ctx context.Context) error {
    return nil
}
"#,
            "Serve",
            "context",
        ),
        (
            Language::Java,
            r#"
import java.util.List;

class Handler {
    public String handle(List<String> values) {
        return values.get(0);
    }
}
"#,
            "handle",
            "java.util.List",
        ),
        (
            Language::C,
            r#"
#include <stdio.h>

int add(int left, int right) {
    return left + right;
}
"#,
            "add",
            "",
        ),
        (
            Language::Cpp,
            r#"
#include <vector>

int sum(std::vector<int> values) {
    return values.size();
}
"#,
            "sum",
            "",
        ),
    ];

    for (language, source, function_name, import_text) in cases {
        let parsed = ParsedFile::parse(source, language)
            .unwrap_or_else(|| panic!("{language:?} should parse"));
        let functions = parsed.extract_functions();
        assert!(
            functions
                .iter()
                .any(|function| function.name == function_name),
            "{language:?} should extract {function_name}: {functions:?}"
        );
        if !import_text.is_empty() {
            let imports = parsed.extract_imports();
            assert!(
                imports
                    .iter()
                    .any(|import| import.raw.contains(import_text)),
                "{language:?} should extract import containing {import_text}: {imports:?}"
            );
        }
    }
}

#[test]
fn test_extract_rust_imports() {
    let source = r#"
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
extern crate anyhow;

fn main() {}
"#;

    let parsed = ParsedFile::parse(source, Language::Rust).expect("Should parse");
    let imports = parsed.extract_imports();

    assert_eq!(imports.len(), 3);
    assert!(imports.iter().any(|i| i.raw.contains("std")));
    assert!(imports.iter().any(|i| i.raw.contains("serde")));
    assert!(imports.iter().any(|i| i.raw.contains("anyhow")));
}

#[test]
fn test_extract_functions_handles_deeply_nested_modules() {
    let source = nested_rust_modules(512, "fn deeply_nested() -> i32 { 42 }");

    let parsed = ParsedFile::parse(source, Language::Rust).expect("Should parse");
    let functions = parsed.extract_functions();

    assert_eq!(functions.len(), 1);
    assert_eq!(functions[0].name, "deeply_nested");
}

#[test]
fn extract_functions_qualifies_impl_methods_by_container() {
    let source = r#"
impl Foo {
    fn run() { 1 }
}
impl Bar {
    fn run() { 2 }
}
"#;
    let parsed = ParsedFile::parse(source, Language::Rust).expect("Should parse");
    let functions = parsed.extract_functions();
    let identities: Vec<String> = functions.iter().map(|f| f.symbol_identity()).collect();
    assert!(
        identities
            .iter()
            .any(|id| id.contains("Foo") && id.contains("run")),
        "Foo::run must be qualified: {identities:?}"
    );
    assert!(
        identities
            .iter()
            .any(|id| id.contains("Bar") && id.contains("run")),
        "Bar::run must be qualified: {identities:?}"
    );
    assert_ne!(
        functions[0].symbol_identity(),
        functions[1].symbol_identity()
    );
}

#[test]
fn extract_functions_qualifies_nested_mod_impl_methods() {
    let source = r#"
mod a {
    impl Foo {
        fn run() { 1 }
    }
}
mod b {
    impl Foo {
        fn run() { 2 }
    }
}
"#;
    let parsed = ParsedFile::parse(source, Language::Rust).expect("Should parse");
    let functions = parsed.extract_functions();
    let identities: Vec<String> = functions.iter().map(|f| f.symbol_identity()).collect();
    assert!(
        identities
            .iter()
            .any(|id| id.contains("a") && id.contains("Foo") && id.contains("run")),
        "a::Foo::run must be qualified: {identities:?}"
    );
    assert!(
        identities
            .iter()
            .any(|id| id.contains("b") && id.contains("Foo") && id.contains("run")),
        "b::Foo::run must be qualified: {identities:?}"
    );
    assert_ne!(
        functions[0].symbol_identity(),
        functions[1].symbol_identity()
    );
}

#[test]
fn extract_functions_includes_javascript_object_literal_methods() {
    let source = r#"
export const handlers = {
    save: async () => {
        await persist();
    },
    load: function () {
        return fetchItem();
    },
};
"#;
    let parsed = ParsedFile::parse(source, Language::JavaScript).expect("Should parse");
    let functions = parsed.extract_functions();
    let names: Vec<&str> = functions.iter().map(|f| f.name.as_str()).collect();
    assert!(
        names.contains(&"save"),
        "object-literal arrow method must extract: {names:?}"
    );
    assert!(
        names.contains(&"load"),
        "object-literal function method must extract: {names:?}"
    );
}

#[test]
fn extract_calls_includes_python_call_nodes() {
    let source = r#"
def target():
    return 1

def test_target():
    target()
"#;
    let parsed = ParsedFile::parse(source, Language::Python).expect("Should parse");
    let calls = parsed.extract_calls();
    assert!(
        calls
            .iter()
            .any(|call| call.name == "target" && call.qualifier.is_empty()),
        "python call nodes must be extracted: {calls:?}"
    );
}

#[test]
fn extract_own_calls_excludes_nested_function_and_closure() {
    let rust = r#"
fn test_x() {
    fn unused() {
        target();
    }
    let unused_closure = || {
        other();
    };
}
"#;
    let parsed = ParsedFile::parse(rust, Language::Rust).expect("Should parse");
    let own = parsed.extract_own_calls();
    assert!(
        own.iter()
            .all(|call| call.name != "target" && call.name != "other"),
        "nested rust calls must not leak to the outer function: {own:?}"
    );

    let js = r#"
function test_x() {
    function unused() {
        target();
    }
    const unused_arrow = () => {
        other();
    };
}
"#;
    let parsed = ParsedFile::parse(js, Language::JavaScript).expect("Should parse");
    let own = parsed.extract_own_calls();
    assert!(
        own.iter()
            .all(|call| call.name != "target" && call.name != "other"),
        "nested js calls must not leak to the outer function: {own:?}"
    );
}

#[test]
fn extract_calls_uses_tree_not_comment_or_string_substrings() {
    let source = r#"
fn test_it() {
    Bar::run();
    foo.run();
    covered();
    // TODO: call orphan()
    let _ = "orphan()";
}
"#;
    let parsed = ParsedFile::parse(source, Language::Rust).expect("Should parse");
    let calls = parsed.extract_calls();
    assert!(
        calls
            .iter()
            .any(|call| call.name == "run" && call.qualifier == ["Bar"]),
        "path call Bar::run: {calls:?}"
    );
    assert!(
        calls
            .iter()
            .any(|call| call.name == "run" && call.qualifier == ["foo"]),
        "receiver call foo.run: {calls:?}"
    );
    assert!(
        calls
            .iter()
            .any(|call| call.name == "covered" && call.qualifier.is_empty()),
        "bare call covered: {calls:?}"
    );
    assert!(
        calls.iter().all(|call| call.name != "orphan"),
        "comment/string must not create call edges: {calls:?}"
    );
}

#[cfg(feature = "lang-cpp")]
#[test]
fn test_cpp_templated_qualified_function_names() {
    // For `void Foo<U>::bar()` the declarator subtree's first
    // identifier in DFS order is the scope's `type_identifier` ("Foo"),
    // so a plain DFS walk reports every method on the same templated
    // scope as "Foo" and collides them. The fix walks the declarator's
    // `declarator` field and recurses into `qualified_identifier` /
    // `template_function`'s `name` field — see heddle#114 commit
    // dc37af8 for the proven pattern (mirrored from
    // `merge_driver::items::c_function_name`).
    let source = r#"
template <typename U>
struct Foo {
    void bar();
    void baz();
};

template <typename U>
void Foo<U>::bar() {}

template <typename U>
void Foo<U>::baz() {}
"#;

    let parsed = ParsedFile::parse(source, Language::Cpp).expect("Should parse");
    let functions = parsed.extract_functions();
    let names: Vec<&str> = functions.iter().map(|f| f.name.as_str()).collect();

    assert!(
        names.contains(&"bar"),
        "expected templated qualified def to resolve as `bar`, got {names:?}"
    );
    assert!(
        names.contains(&"baz"),
        "expected templated qualified def to resolve as `baz`, got {names:?}"
    );
    let foo_count = names.iter().filter(|n| **n == "Foo").count();
    assert_eq!(
        foo_count, 0,
        "templated qualified method defs should not resolve to scope name `Foo`: {names:?}"
    );
}