loctree 0.13.1

Structural code intelligence for AI agents. Scan once, query everything.
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
//! Lightweight Swift (.swift) analyzer.
//!
//! Regex-based parser that extracts public declarations (`class`, `struct`, `enum`, `protocol`, `func`, `var`, `let`, `extension`),
//! `@import` / `import` statements, and symbol usages.

use once_cell::sync::Lazy;
use regex::Regex;

use crate::types::{
    ExportSymbol, FileAnalysis, ImportEntry, ImportKind, ImportResolutionKind, SymbolUsage,
};

// Public declarations:   public final class NAME / struct NAME / func NAME / protocol NAME / extension NAME
static RE_SWIFT_DECL: Lazy<Regex> = Lazy::new(|| {
    Regex::new(
        r"^\s*(?:@objc\s*(?:\([^)]+\)\s*)?)?(?:(?:public|internal|private|fileprivate|open|final|override|static|class|mutating|nonmutating|lazy|weak|unowned)\s+)*(class|struct|enum|protocol|extension|func|var|let)\s+([A-Za-z_][A-Za-z0-9_]*)",
    )
    .expect("valid swift decl regex")
});

// `import Foundation`, `@testable import MyApp`
static RE_IMPORT: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^\s*(?:@testable\s+)?import\s+(?:class\s+|struct\s+|enum\s+|protocol\s+|func\s+|var\s+|let\s+)?([A-Za-z0-9_.]+)")
        .expect("valid swift import regex")
});

// Regex to capture potential symbol usages (CamelCase or known patterns)
static RE_WORD: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"\b([A-Z][A-Za-z0-9_]*|[a-z][A-Za-z0-9_]*)\b").expect("valid swift word regex")
});

pub fn analyze_swift_file(content: &str, relative: String) -> FileAnalysis {
    let mut analysis = FileAnalysis::new(relative);
    analysis.imports = parse_imports(content);
    analysis.exports = parse_exports(content);
    analysis.symbol_usages = parse_symbol_usages(content, &analysis.exports);
    analysis.local_uses = parse_local_uses(content, &analysis.exports);
    apply_runtime_dispatch_signals(content, &mut analysis);
    credit_uniffi_generated_glue(content, &mut analysis);
    analysis
}

/// A UniFFI-generated Swift bridge file is saturated with `FfiConverter*` glue;
/// a hand-written file almost never carries more than one or two. Two
/// independent corroborating signals (this density AND the autogenerated header)
/// keep the detection precise so a hand-written `*_ffi.swift` is not fenced.
const UNIFFI_FFICONVERTER_DENSITY_THRESHOLD: usize = 4;

/// Recognize a UniFFI-generated Swift bridge file and credit ALL of its exports
/// as `local_uses` so they are not flagged HIGH-confidence dead.
///
/// loctree-fail.md (2026-06-26): `loct dead --full` flagged ~50 symbols in
/// `*_ffi.swift` (`FfiConverterType*_lift/_lower`, `UNIFFI_CALLBACK_*`,
/// `uniffiTraitInterface*`, …) as HIGH dead. These are machine-written FFI glue
/// whose ONLY consumers live across the FFI boundary (C / Rust) — exactly the
/// `pub extern "C" fn` blind spot, on the Swift side. They have 0 in-Swift
/// references yet are 100% live.
///
/// Detection is deliberately narrow (the prior hak warned against overreaching
/// generated-file detection): the canonical UniFFI autogenerated header OR a
/// high `FfiConverter` density. Crediting can only REMOVE a dead flag, never add
/// one, and only fires on a recognized generated bridge, so genuine dead code in
/// a hand-written file stays detectable.
fn credit_uniffi_generated_glue(content: &str, analysis: &mut FileAnalysis) {
    if !is_uniffi_generated_bridge(content) {
        return;
    }
    let existing: std::collections::HashSet<&str> =
        analysis.local_uses.iter().map(|u| u.as_str()).collect();
    let credited: Vec<String> = analysis
        .exports
        .iter()
        .map(|e| e.name.clone())
        .filter(|name| !existing.contains(name.as_str()))
        .collect();
    // Dedup credited names (an export may appear twice with different kinds).
    let mut seen = std::collections::HashSet::new();
    for name in credited {
        if seen.insert(name.clone()) {
            analysis.local_uses.push(name);
        }
    }
}

/// True when the content looks like a UniFFI-generated Swift binding:
/// 1. the autogenerated header (`autogenerated` + `hand-written` in the head), or
/// 2. `FfiConverter` density at/above [`UNIFFI_FFICONVERTER_DENSITY_THRESHOLD`].
fn is_uniffi_generated_bridge(content: &str) -> bool {
    let head: String = content
        .lines()
        .take(12)
        .collect::<Vec<_>>()
        .join("\n")
        .to_ascii_lowercase();
    let has_autogen_header = head.contains("autogenerated") && head.contains("hand-written");
    if has_autogen_header {
        return true;
    }
    content.matches("FfiConverter").count() >= UNIFFI_FFICONVERTER_DENSITY_THRESHOLD
}

/// AppKit/UIKit lifecycle methods invoked by the framework, never "called by
/// identifier" in user code. They conform to NSApplicationDelegate /
/// UIApplicationDelegate / scene protocols, so an import-graph dead scan sees
/// 0 references and (before this) flagged them HIGH-confidence dead
/// (loctree-fail.md, 2026-06-16). Curated, not exhaustive — `override` and
/// `@objc` cover the rest.
const SWIFT_FRAMEWORK_DISPATCH_METHODS: &[&str] = &[
    // NSApplicationDelegate
    "applicationDidFinishLaunching",
    "applicationWillFinishLaunching",
    "applicationWillTerminate",
    "applicationShouldTerminateAfterLastWindowClosed",
    "applicationShouldTerminate",
    "applicationSupportsSecureRestorableState",
    "applicationDidBecomeActive",
    "applicationWillBecomeActive",
    "applicationDidResignActive",
    "applicationWillResignActive",
    "applicationDidHide",
    "applicationDidUnhide",
    "applicationShouldHandleReopen",
    "applicationDockMenu",
    "applicationOpenUntitledFile",
    "applicationShouldOpenUntitledFile",
    "applicationDidChangeScreenParameters",
    // UIApplicationDelegate / scene lifecycle (method base name)
    "application",
    "sceneDidDisconnect",
    "sceneWillEnterForeground",
    "sceneDidEnterBackground",
    "sceneWillResignActive",
    "sceneDidBecomeActive",
    // NSObject KVO / NSWindowDelegate (common)
    "observeValue",
    "windowWillClose",
    "windowDidResize",
    "windowShouldClose",
];

/// Detect Swift runtime reachability the import graph cannot see:
/// 1. Entry points — `@main` / `@NSApplicationMain` / `@UIApplicationMain`
///    attributes, or a top-level `NSApplicationMain(` / `UIApplicationMain(`
///    call — recorded in `entry_points` so the dead pipeline fences the file.
/// 2. Framework-dispatched methods — `override func`, `@objc func`, and known
///    AppKit/UIKit lifecycle methods — credited into `local_uses` so they are
///    not false dead. Crediting can only REMOVE a dead flag, never add one, so
///    genuine dead code stays detectable.
fn apply_runtime_dispatch_signals(content: &str, analysis: &mut FileAnalysis) {
    let mut is_entry = false;
    // `@objc` can sit on the line above the `func`; carry it forward one decl.
    let mut pending_objc = false;

    for raw_line in content.lines() {
        let line = strip_line_comment(raw_line);
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }

        // Entry-point attributes / top-level executable bootstrap.
        if trimmed.starts_with("@main")
            || trimmed.starts_with("@NSApplicationMain")
            || trimmed.starts_with("@UIApplicationMain")
            || trimmed.contains("NSApplicationMain(")
            || trimmed.contains("UIApplicationMain(")
        {
            is_entry = true;
        }

        if trimmed.starts_with("@objc") {
            pending_objc = true;
        }

        // Framework-dispatched method crediting.
        if let Some(caps) = RE_SWIFT_DECL.captures(line) {
            let is_func = caps.get(1).map(|m| m.as_str()) == Some("func");
            if is_func && let Some(name) = caps.get(2).map(|m| m.as_str()) {
                let has_override = trimmed.contains("override ");
                let has_objc = trimmed.contains("@objc") || pending_objc;
                let is_lifecycle = SWIFT_FRAMEWORK_DISPATCH_METHODS.contains(&name);
                if (has_override || has_objc || is_lifecycle)
                    && !analysis.local_uses.iter().any(|u| u == name)
                {
                    analysis.local_uses.push(name.to_string());
                }
            }
            // A declaration consumes any pending attribute carry.
            pending_objc = false;
        }
    }

    if is_entry && !analysis.entry_points.iter().any(|e| e == "swift-main") {
        analysis.entry_points.push("swift-main".to_string());
    }
}

/// Same-file uses of this file's OWN declarations. `parse_symbol_usages`
/// deliberately drops own-export names, so without this a Swift symbol read
/// only within its defining file (a property used by a sibling method, a
/// file-private helper) looks unused. We credit an export name that appears as
/// an identifier on any line OTHER than its declaration line — the declaration
/// occurrence itself never counts as a use. Dead detection consumes this via
/// `local_uses` exactly like the Go/Dart analyzers do.
fn parse_local_uses(content: &str, exports: &[ExportSymbol]) -> Vec<String> {
    use std::collections::{HashMap, HashSet};

    if exports.is_empty() {
        return Vec::new();
    }

    // export name -> the line(s) it is declared on (1-based); used to skip the
    // declaration occurrence so a never-referenced symbol stays a candidate.
    let mut decl_lines: HashMap<&str, HashSet<usize>> = HashMap::new();
    for e in exports {
        if let Some(line) = e.line {
            decl_lines.entry(e.name.as_str()).or_default().insert(line);
        }
    }
    let export_names: HashSet<&str> = exports.iter().map(|e| e.name.as_str()).collect();

    let mut used: Vec<String> = Vec::new();
    let mut seen: HashSet<String> = HashSet::new();
    for (idx, line) in content.lines().enumerate() {
        let effective = strip_line_comment(line);
        if effective.trim().is_empty() {
            continue;
        }
        let lineno = idx + 1;
        for caps in RE_WORD.captures_iter(effective) {
            let Some(m) = caps.get(1) else { continue };
            let word = m.as_str();
            if !export_names.contains(word) {
                continue;
            }
            // Skip the declaration line for this exact symbol.
            if decl_lines
                .get(word)
                .is_some_and(|lines| lines.contains(&lineno))
            {
                continue;
            }
            if seen.insert(word.to_string()) {
                used.push(word.to_string());
            }
        }
    }
    used
}

fn parse_imports(content: &str) -> Vec<ImportEntry> {
    let mut imports: Vec<ImportEntry> = Vec::new();
    for (idx, line) in content.lines().enumerate() {
        let effective = strip_line_comment(line);
        if let Some(caps) = RE_IMPORT.captures(effective)
            && let Some(m) = caps.get(1)
        {
            let path = m.as_str().trim();
            if path.is_empty() {
                continue;
            }
            if imports.iter().any(|i| i.source == path) {
                continue;
            }
            let mut entry = ImportEntry::new(path.to_string(), ImportKind::Static);
            entry.line = Some(idx + 1);
            entry.resolution = ImportResolutionKind::Unknown;
            imports.push(entry);
        }
    }
    imports
}

fn parse_exports(content: &str) -> Vec<ExportSymbol> {
    let mut out: Vec<ExportSymbol> = Vec::new();
    for (idx, line) in content.lines().enumerate() {
        let effective = strip_line_comment(line);
        if let Some(caps) = RE_SWIFT_DECL.captures(effective) {
            let keyword = caps.get(1).map(|m| m.as_str()).unwrap_or("");
            let name = caps.get(2).map(|m| m.as_str()).unwrap_or("").to_string();
            if name.is_empty() {
                continue;
            }
            if !out.iter().any(|e| e.name == name && e.kind == keyword) {
                out.push(ExportSymbol::new(name, keyword, "named", Some(idx + 1)));
            }
        }
    }
    out
}

fn parse_symbol_usages(content: &str, exports: &[ExportSymbol]) -> Vec<SymbolUsage> {
    let mut out: Vec<SymbolUsage> = Vec::new();
    let export_names: std::collections::HashSet<&str> =
        exports.iter().map(|e| e.name.as_str()).collect();

    for (idx, line) in content.lines().enumerate() {
        let effective = strip_line_comment(line);
        if effective.trim().is_empty() {
            continue;
        }
        for caps in RE_WORD.captures_iter(effective) {
            if let Some(m) = caps.get(1) {
                let word = m.as_str();
                // Avoid self-references (exports) or basic keywords
                if word.is_empty() || is_swift_keyword(word) || export_names.contains(word) {
                    continue;
                }
                // Cap to a reasonable number to avoid noise
                if out.len() >= 1500 {
                    return out;
                }
                out.push(SymbolUsage {
                    name: word.to_string(),
                    line: idx + 1,
                    context: effective.trim().to_string(),
                });
            }
        }
    }
    // Deduplicate symbol usages
    out.sort_by(|a, b| a.name.cmp(&b.name).then(a.line.cmp(&b.line)));
    out.dedup_by(|a, b| a.name == b.name && a.line == b.line);
    out
}

fn strip_line_comment(line: &str) -> &str {
    let mut in_str = false;
    let bytes = line.as_bytes();
    let mut idx = 0;
    while idx + 1 < bytes.len() {
        let ch = bytes[idx] as char;
        match ch {
            '\\' => {
                idx += 2;
                continue;
            }
            '"' => in_str = !in_str,
            '/' if !in_str && bytes[idx + 1] == b'/' => {
                return &line[..idx];
            }
            _ => {}
        }
        idx += 1;
    }
    line
}

fn is_swift_keyword(word: &str) -> bool {
    matches!(
        word,
        "import"
            | "struct"
            | "class"
            | "enum"
            | "protocol"
            | "extension"
            | "func"
            | "var"
            | "let"
            | "public"
            | "internal"
            | "private"
            | "fileprivate"
            | "open"
            | "final"
            | "override"
            | "static"
            | "mutating"
            | "nonmutating"
            | "lazy"
            | "weak"
            | "unowned"
            | "if"
            | "else"
            | "guard"
            | "switch"
            | "case"
            | "default"
            | "for"
            | "in"
            | "while"
            | "repeat"
            | "do"
            | "catch"
            | "throw"
            | "throws"
            | "rethrows"
            | "try"
            | "return"
            | "break"
            | "continue"
            | "fallthrough"
            | "defer"
            | "true"
            | "false"
            | "nil"
            | "self"
            | "super"
            | "init"
            | "deinit"
            | "subscript"
            | "typealias"
            | "associatedtype"
            | "String"
            | "Int"
            | "Bool"
            | "Double"
            | "Float"
            | "Optional"
            | "Array"
            | "Dictionary"
            | "Set"
    )
}

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

    #[test]
    fn parses_swift_decls() {
        let src = r#"
import Foundation

public final class WorkspaceCacheStore {
    let id: String
    private var data: [String: Any]
    
    init() {}
}

struct DocumentRecord {}
protocol Searchable {}
extension WorkspaceCacheStore: Searchable {}
"#;
        let analysis = analyze_swift_file(src, "main.swift".to_string());

        let classes: Vec<_> = analysis
            .exports
            .iter()
            .filter(|e| e.kind == "class")
            .map(|e| e.name.clone())
            .collect();
        assert!(classes.contains(&"WorkspaceCacheStore".to_string()));

        let structs: Vec<_> = analysis
            .exports
            .iter()
            .filter(|e| e.kind == "struct")
            .map(|e| e.name.clone())
            .collect();
        assert!(structs.contains(&"DocumentRecord".to_string()));

        let extensions: Vec<_> = analysis
            .exports
            .iter()
            .filter(|e| e.kind == "extension")
            .map(|e| e.name.clone())
            .collect();
        assert!(extensions.contains(&"WorkspaceCacheStore".to_string()));
    }

    #[test]
    fn marks_nsapplicationmain_file_as_entry_point() {
        // loctree-fail.md (2026-06-16): main.swift drives the app via
        // NSApplicationMain; it is a runtime entry point, not dead.
        let src = "import AppKit\n\nlet delegate = AppDelegate()\nNSApplication.shared.delegate = delegate\n_ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)\n";
        let analysis = analyze_swift_file(src, "main.swift".to_string());
        assert!(
            !analysis.entry_points.is_empty(),
            "a file calling NSApplicationMain must be a runtime entry point"
        );
    }

    #[test]
    fn marks_main_attribute_file_as_entry_point() {
        let src = "import SwiftUI\n\n@main\nstruct MyApp: App {\n    var body: some Scene { WindowGroup {} }\n}\n";
        let analysis = analyze_swift_file(src, "MyApp.swift".to_string());
        assert!(
            !analysis.entry_points.is_empty(),
            "a @main type must mark its file as an entry point"
        );
    }

    #[test]
    fn credits_appkit_lifecycle_and_override_methods_as_used() {
        // loctree-fail.md (2026-06-16): NSApplicationDelegate protocol methods
        // and `override`/`@objc` self-dispatched helpers are framework-invoked,
        // never "called by identifier" — they were FALSE HIGH-confidence dead.
        // Crediting them as local_uses removes the FP (can only ADD a use,
        // never mask genuine dead code).
        let src = "import AppKit\n\n@MainActor\nclass AppDelegate: NSObject, NSApplicationDelegate {\n    func applicationDidFinishLaunching(_ notification: Notification) {}\n    func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool { true }\n    override func observeValue(forKeyPath keyPath: String?) {}\n    @objc func handleClick() {}\n    private func internalHelper() {}\n}\n";
        let analysis = analyze_swift_file(src, "AppDelegate.swift".to_string());

        for invoked in [
            "applicationDidFinishLaunching",
            "applicationSupportsSecureRestorableState",
            "observeValue",
            "handleClick",
        ] {
            assert!(
                analysis.local_uses.iter().any(|u| u == invoked),
                "framework-dispatched method `{invoked}` must be credited as used"
            );
        }
        // A plain private helper with no dispatch signal is NOT auto-credited
        // (so genuine dead code is still detectable).
        assert!(
            !analysis.local_uses.iter().any(|u| u == "internalHelper"),
            "plain private helper must not be force-credited"
        );
    }

    #[test]
    fn credits_uniffi_generated_glue_via_header() {
        // loctree-fail.md (2026-06-26): UniFFI-generated bridge glue is reached
        // only across the FFI boundary (C/Rust), has 0 in-Swift references, and
        // was flagged HIGH-confidence dead. The autogenerated header marks the
        // whole file as generated → every export is credited as used.
        let src = "// This file was autogenerated by some hand-written code.\n// Trust me, you don't want to mess with it!\nimport Foundation\n\npublic func uniffiTraitInterfaceCallWithError() {}\npublic let UNIFFI_CALLBACK_SUCCESS = 0\npublic struct FfiConverterTypeFoo {}\n";
        let analysis = analyze_swift_file(src, "vibecrafted_shell_ffi.swift".to_string());
        for credited in [
            "uniffiTraitInterfaceCallWithError",
            "UNIFFI_CALLBACK_SUCCESS",
            "FfiConverterTypeFoo",
        ] {
            assert!(
                analysis.local_uses.iter().any(|u| u == credited),
                "UniFFI generated symbol `{credited}` must be credited as used"
            );
        }
    }

    #[test]
    fn credits_uniffi_generated_glue_via_ffi_converter_density() {
        // Header stripped, but FfiConverter density alone is a precise UniFFI
        // signature (hand-written code virtually never reaches the threshold).
        let src = "import Foundation\n\npublic struct FfiConverterUInt8 {}\npublic struct FfiConverterString {}\npublic struct FfiConverterData {}\npublic struct FfiConverterBool {}\npublic func lift() {}\n";
        let analysis = analyze_swift_file(src, "bindings.swift".to_string());
        assert!(
            analysis.local_uses.iter().any(|u| u == "lift"),
            "a high-FfiConverter-density file must credit its exports as used"
        );
    }

    #[test]
    fn does_not_credit_hand_written_ffi_named_file() {
        // A hand-written file that merely sits at *_ffi.swift, with no UniFFI
        // header and no FfiConverter density, must NOT be fenced — genuine dead
        // code stays detectable (no overreaching generated-file detection).
        let src = "import Foundation\n\npublic func myHandWrittenHelper() {}\npublic struct FfiBridge {}\n";
        let analysis = analyze_swift_file(src, "custom_ffi.swift".to_string());
        assert!(
            !analysis
                .local_uses
                .iter()
                .any(|u| u == "myHandWrittenHelper"),
            "hand-written *_ffi.swift must not be force-credited as generated"
        );
    }

    #[test]
    fn parses_swift_imports() {
        let src = r#"
import Foundation
@testable import MyApp
import struct Module.MyStruct
"#;
        let analysis = analyze_swift_file(src, "main.swift".to_string());
        let imports: Vec<_> = analysis.imports.iter().map(|i| i.source.clone()).collect();
        assert!(imports.contains(&"Foundation".to_string()));
        assert!(imports.contains(&"MyApp".to_string()));
        assert!(imports.contains(&"Module.MyStruct".to_string()));
    }
}