ast-bro 2.4.2

Fast, AST-based code-navigation: shape, public API, deps & call graphs, hybrid semantic search, structural rewrite, and log squeezing. MCP server included.
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
//! Hybrid entry-point discovery: file vs directory, manifest vs convention.
//!
//! Priority order when given a directory:
//!   1. `Cargo.toml` (workspace or single crate)
//!   2. `pyproject.toml` (Python package)
//!   3. `__init__.py` directly in the dir (Python package without manifest)
//!   4. Fallback: walk the dir and let the per-file visibility filter run.
//!
//! When given a file, dispatch by name/extension instead.

use crate::surface::manifest::{self, CargoManifest};
use crate::surface::options::{LangOverride, SurfaceError};
use std::collections::HashSet;
use std::path::{Path, PathBuf};

#[derive(Debug, Clone)]
pub enum EntryPoint {
    RustCrate {
        root_file: PathBuf,
        crate_name: String,
        #[allow(dead_code)]
        src_dir: PathBuf,
    },
    RustWorkspace {
        members: Vec<EntryPoint>,
    },
    PythonPackage {
        init: PathBuf,
        pkg_name: String,
    },
    /// TypeScript / JavaScript package — resolved entry plus the public
    /// name (the npm package name when `package.json` is present, else
    /// the directory basename).
    TsPackage {
        root_file: PathBuf,
        pkg_name: String,
    },
    /// Scala 3 package — for Scala there's no real "entry file"; the
    /// resolver scans every `.scala` file under `root` and stitches
    /// `export` clauses across them.
    ScalaPackage {
        root: PathBuf,
        #[allow(dead_code)]
        pkg_name: String,
    },
    /// Visibility-filtered walk for languages without re-exports.
    Fallback {
        paths: Vec<PathBuf>,
    },
}

pub fn discover(input: &Path) -> Result<EntryPoint, SurfaceError> {
    if input.is_file() {
        return discover_file(input);
    }
    discover_dir(input)
}

/// Force a particular resolver. Used when the user passes `--lang`.
pub fn discover_as(input: &Path, lang: LangOverride) -> Result<EntryPoint, SurfaceError> {
    match lang {
        LangOverride::Rust => discover_rust(input),
        LangOverride::Python => discover_python(input),
        LangOverride::TypeScript => discover_typescript(input),
        LangOverride::Scala => discover_scala(input),
        LangOverride::Fallback => Ok(EntryPoint::Fallback {
            paths: vec![input.to_path_buf()],
        }),
    }
}

fn discover_file(file: &Path) -> Result<EntryPoint, SurfaceError> {
    let name = file.file_name().and_then(|s| s.to_str()).unwrap_or("");
    let ext = file.extension().and_then(|s| s.to_str()).unwrap_or("");
    if name == "lib.rs" || name == "main.rs" {
        let src_dir = file.parent().unwrap_or(Path::new(".")).to_path_buf();
        let crate_name =
            _crate_name_from_cargo(&src_dir).unwrap_or_else(|| _dir_basename(&src_dir));
        return Ok(EntryPoint::RustCrate {
            root_file: file.to_path_buf(),
            crate_name,
            src_dir,
        });
    }
    if name == "__init__.py" {
        let dir = file.parent().unwrap_or(Path::new("."));
        return Ok(EntryPoint::PythonPackage {
            init: file.to_path_buf(),
            pkg_name: _dir_basename(dir),
        });
    }
    if name == "Cargo.toml" {
        return discover_rust(file.parent().unwrap_or(Path::new(".")));
    }
    if name == "pyproject.toml" {
        return discover_python(file.parent().unwrap_or(Path::new(".")));
    }
    if name == "package.json" {
        return discover_typescript(file.parent().unwrap_or(Path::new(".")));
    }
    if matches!(
        ext,
        "ts" | "tsx" | "mts" | "cts" | "js" | "jsx" | "mjs" | "cjs"
    ) {
        let dir = file.parent().unwrap_or(Path::new("."));
        let pkg_name = manifest::parse_package_json(&dir.join("package.json"))
            .and_then(|p| p.name)
            .unwrap_or_else(|| _dir_basename(dir));
        return Ok(EntryPoint::TsPackage {
            root_file: file.to_path_buf(),
            pkg_name,
        });
    }
    if ext == "scala" {
        let dir = file.parent().unwrap_or(Path::new("."));
        return Ok(EntryPoint::ScalaPackage {
            root: dir.to_path_buf(),
            pkg_name: _dir_basename(dir),
        });
    }
    // Last resort: fallback on this single file.
    Ok(EntryPoint::Fallback {
        paths: vec![file.to_path_buf()],
    })
}

fn discover_dir(dir: &Path) -> Result<EntryPoint, SurfaceError> {
    if dir.join("Cargo.toml").is_file() {
        return discover_rust(dir);
    }
    if dir.join("pyproject.toml").is_file() || dir.join("__init__.py").is_file() {
        return discover_python(dir);
    }
    if dir.join("package.json").is_file() {
        return discover_typescript(dir);
    }
    if _has_index_file(dir) {
        return discover_typescript(dir);
    }
    if _has_scala_file(dir) {
        return discover_scala(dir);
    }
    // PHP / Ruby / C++ have no `pub use`-style re-export semantics, so
    // there's no meaningful per-language surface resolver. Recognise their
    // manifests so we route to Fallback explicitly (and skip the deeper
    // probe below) rather than missing the dir entirely.
    if dir.join("composer.json").is_file()
        || dir.join("Gemfile").is_file()
        || dir.join("CMakeLists.txt").is_file()
    {
        return Ok(EntryPoint::Fallback {
            paths: vec![dir.to_path_buf()],
        });
    }
    // Probe one level down for a single-package layout
    // (e.g. a repo where the user is at the top and the crate is in `crates/foo`).
    if let Some(found) = _find_nearest_manifest(dir) {
        return discover(&found);
    }
    Ok(EntryPoint::Fallback {
        paths: vec![dir.to_path_buf()],
    })
}

fn _has_index_file(dir: &Path) -> bool {
    for stem in ["index", "main"] {
        for ext in ["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"] {
            if dir.join(format!("{}.{}", stem, ext)).is_file() {
                return true;
            }
        }
    }
    false
}

fn _has_scala_file(dir: &Path) -> bool {
    if let Ok(read) = std::fs::read_dir(dir) {
        for entry in read.flatten() {
            let p = entry.path();
            if p.extension().and_then(|s| s.to_str()) == Some("scala") {
                return true;
            }
        }
    }
    false
}

fn discover_rust(root: &Path) -> Result<EntryPoint, SurfaceError> {
    discover_rust_inner(root, &mut HashSet::new())
}

fn discover_rust_inner(
    root: &Path,
    seen: &mut HashSet<PathBuf>,
) -> Result<EntryPoint, SurfaceError> {
    let manifest_path = if root.join("Cargo.toml").is_file() {
        root.join("Cargo.toml")
    } else if root.is_file() && root.file_name().and_then(|s| s.to_str()) == Some("Cargo.toml") {
        root.to_path_buf()
    } else {
        return Err(SurfaceError::NoEntryPoint {
            path: root.to_path_buf(),
            hint: "no Cargo.toml here; pass `--lang fallback` or point at lib.rs/main.rs directly"
                .into(),
        });
    };

    let manifest = manifest::parse_cargo_toml(&manifest_path).ok_or_else(|| SurfaceError::Io {
        path: manifest_path.clone(),
        source: std::io::Error::other("cannot read Cargo.toml"),
    })?;
    let manifest_dir = manifest
        .manifest_dir
        .canonicalize()
        .unwrap_or_else(|_| manifest.manifest_dir.clone());
    if !seen.insert(manifest_dir) {
        return Err(SurfaceError::NoEntryPoint {
            path: manifest.manifest_dir.clone(),
            hint: "Cargo workspace member cycle detected".into(),
        });
    }

    // Workspace?
    if !manifest.workspace_members.is_empty() {
        let mut members = Vec::new();
        for member_root in manifest
            .workspace_members
            .iter()
            .flat_map(|m| _expand_workspace_member(&manifest.manifest_dir, m))
            .filter(|p| {
                !_workspace_member_excluded(&manifest.manifest_dir, p, &manifest.workspace_exclude)
            })
        {
            if let Ok(ep) = discover_rust_inner(&member_root, seen) {
                members.push(ep);
            }
        }
        if !members.is_empty() {
            return Ok(EntryPoint::RustWorkspace { members });
        }
    }

    let crate_name = manifest
        .package_name
        .clone()
        .unwrap_or_else(|| _dir_basename(&manifest.manifest_dir));

    let root_file = _resolve_rust_root(&manifest);
    if let Some(rf) = root_file {
        let src_dir = rf.parent().unwrap_or(&manifest.manifest_dir).to_path_buf();
        return Ok(EntryPoint::RustCrate {
            root_file: rf,
            crate_name,
            src_dir,
        });
    }
    Err(SurfaceError::NoEntryPoint {
        path: manifest.manifest_dir.clone(),
        hint: "Cargo.toml found but no lib.rs/main.rs and no [lib].path/[[bin]].path entry".into(),
    })
}

fn discover_python(root: &Path) -> Result<EntryPoint, SurfaceError> {
    // Direct __init__.py in the dir wins.
    let direct = root.join("__init__.py");
    if direct.is_file() {
        let pkg_name = manifest::parse_pyproject_toml(&root.join("pyproject.toml"))
            .and_then(|p| p.project_name)
            .unwrap_or_else(|| _dir_basename(root));
        return Ok(EntryPoint::PythonPackage {
            init: direct,
            pkg_name,
        });
    }
    // Otherwise look for a child dir that is a package (single-package layout).
    if let Ok(read) = std::fs::read_dir(root) {
        for entry in read.flatten() {
            let p = entry.path();
            if p.is_dir() && p.join("__init__.py").is_file() {
                let pkg_name = manifest::parse_pyproject_toml(&root.join("pyproject.toml"))
                    .and_then(|x| x.project_name)
                    .unwrap_or_else(|| _dir_basename(&p));
                return Ok(EntryPoint::PythonPackage {
                    init: p.join("__init__.py"),
                    pkg_name,
                });
            }
        }
    }
    Err(SurfaceError::NoEntryPoint {
        path: root.to_path_buf(),
        hint: "no __init__.py here or in any immediate subdirectory".into(),
    })
}

fn discover_typescript(root: &Path) -> Result<EntryPoint, SurfaceError> {
    let pkg_path = root.join("package.json");
    if pkg_path.is_file() {
        if let Some(pkg) = manifest::parse_package_json(&pkg_path) {
            if let Some(entry_file) = manifest::resolve_package_entry(&pkg) {
                let pkg_name = pkg
                    .name
                    .clone()
                    .unwrap_or_else(|| _dir_basename(&pkg.manifest_dir));
                return Ok(EntryPoint::TsPackage {
                    root_file: entry_file,
                    pkg_name,
                });
            }
        }
    }
    // No (or unresolvable) package.json — try index files at the root.
    for stem in ["index", "main", "src/index", "src/main"] {
        for ext in ["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"] {
            let cand = root.join(format!("{}.{}", stem, ext));
            if cand.is_file() {
                return Ok(EntryPoint::TsPackage {
                    root_file: cand,
                    pkg_name: _dir_basename(root),
                });
            }
        }
    }
    Err(SurfaceError::NoEntryPoint {
        path: root.to_path_buf(),
        hint: "no package.json with resolvable `exports`/`main`/`module`/`types`, and no index.* in the dir".into(),
    })
}

fn discover_scala(root: &Path) -> Result<EntryPoint, SurfaceError> {
    if !root.is_dir() {
        let dir = root.parent().unwrap_or(Path::new("."));
        return Ok(EntryPoint::ScalaPackage {
            root: dir.to_path_buf(),
            pkg_name: _dir_basename(dir),
        });
    }
    Ok(EntryPoint::ScalaPackage {
        root: root.to_path_buf(),
        pkg_name: _dir_basename(root),
    })
}

fn _expand_workspace_member(manifest_dir: &Path, member: &str) -> Vec<PathBuf> {
    crate::path_glob::expand_pattern(&manifest_dir.join(member))
        .into_iter()
        .filter(|p| p.join("Cargo.toml").is_file())
        .collect()
}

fn _workspace_member_excluded(
    manifest_dir: &Path,
    member_root: &Path,
    excludes: &[String],
) -> bool {
    excludes.iter().any(|exclude| {
        crate::path_glob::expand_pattern(&manifest_dir.join(exclude))
            .into_iter()
            .any(|p| _same_path(&p, member_root))
    })
}

fn _same_path(a: &Path, b: &Path) -> bool {
    let a = a.canonicalize().unwrap_or_else(|_| a.to_path_buf());
    let b = b.canonicalize().unwrap_or_else(|_| b.to_path_buf());
    a == b
}

fn _resolve_rust_root(m: &CargoManifest) -> Option<PathBuf> {
    if let Some(p) = &m.lib_path {
        let abs = m.manifest_dir.join(p);
        if abs.is_file() {
            return Some(abs);
        }
    }
    let default_lib = m.manifest_dir.join("src/lib.rs");
    if default_lib.is_file() {
        return Some(default_lib);
    }
    let default_main = m.manifest_dir.join("src/main.rs");
    if default_main.is_file() {
        return Some(default_main);
    }
    for b in &m.bins {
        if let Some(p) = &b.path {
            let abs = m.manifest_dir.join(p);
            if abs.is_file() {
                return Some(abs);
            }
        }
    }
    None
}

fn _find_nearest_manifest(dir: &Path) -> Option<PathBuf> {
    let read = std::fs::read_dir(dir).ok()?;
    for entry in read.flatten() {
        let p = entry.path();
        if !p.is_dir() {
            continue;
        }
        if p.join("Cargo.toml").is_file()
            || p.join("pyproject.toml").is_file()
            || p.join("__init__.py").is_file()
        {
            return Some(p);
        }
    }
    None
}

fn _crate_name_from_cargo(src_dir: &Path) -> Option<String> {
    // src_dir is e.g. .../mycrate/src ; manifest is one up.
    let parent = src_dir.parent()?;
    let manifest = parent.join("Cargo.toml");
    if !manifest.is_file() {
        return None;
    }
    manifest::parse_cargo_toml(&manifest).and_then(|m| m.package_name)
}

fn _dir_basename(p: &Path) -> String {
    p.file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("?")
        .to_string()
}