use std::iter;
use kartta_lang::path::{base, dir, join};
use kartta_lang::{
Extraction, ImportRef, IncludeRef, RawExtraction, Repository, Resolver, SymbolFlags,
};
use crate::walk::IMPORT_FORM;
pub(crate) struct Modules<'r> {
repository: &'r dyn Repository,
}
impl<'r> Modules<'r> {
pub(crate) const fn new(repository: &'r dyn Repository) -> Self {
Self { repository }
}
}
impl Resolver for Modules<'_> {
fn resolve(&self, raw: RawExtraction, path: &str) -> Extraction {
let (mut extraction, directives) = raw.into_extraction(path);
let module = module_name(path);
let flags = SymbolFlags::empty()
.with_test(is_test_file(path))
.with_generated(is_generated_path(path));
for symbol in &mut extraction.symbols {
if !module.is_empty() {
symbol.qualified_name = format!("{module}.{}", symbol.qualified_name);
}
symbol.flags = symbol.flags.union(flags);
}
let mut imports = Imports {
repository: self.repository,
path,
includes: Vec::new(),
};
for directive in directives {
let found = imports.includes.len();
if directive.form == IMPORT_FORM {
imports.resolve(&directive.spec, &directive.names);
}
if imports.includes.len() > found {
continue;
}
extraction.imports.push(ImportRef {
module: directive.spec,
names: directive.names,
line: directive.line,
});
}
extraction.includes = imports.includes;
extraction
}
}
struct Imports<'a> {
repository: &'a dyn Repository,
path: &'a str,
includes: Vec<IncludeRef>,
}
impl Imports<'_> {
fn resolve(&mut self, spec: &str, names: &[String]) {
if spec.starts_with('.') {
self.relative(spec, names);
return;
}
let module = dotted_path(spec);
if module.is_empty() {
return;
}
match self.absolute(&module) {
Found::Package(package) => self.submodules(&package, names),
Found::Module => {}
Found::Nowhere => self.namespace(&module, names),
}
}
fn absolute(&mut self, module: &str) -> Found {
for anchor in anchors(self.path) {
if let Some((target, package)) = self.probe(&anchor_join(anchor, module)) {
self.includes.push(IncludeRef { target });
return package.map_or(Found::Module, Found::Package);
}
}
Found::Nowhere
}
fn namespace(&mut self, module: &str, names: &[String]) {
if names.is_empty() {
return;
}
for anchor in anchors(self.path) {
let found = self.includes.len();
self.submodules(&anchor_join(anchor, module), names);
if self.includes.len() > found {
return;
}
}
}
fn relative(&mut self, spec: &str, names: &[String]) {
let dots = spec.bytes().take_while(|&byte| byte == b'.').count();
let Some(climbed) = join(dir(self.path), &"../".repeat(dots - 1)) else {
return;
};
let package = anchor_join(&climbed, &dotted_path(&spec[dots..]));
let mut plain_module = false;
if let Some((target, as_package)) = self.probe(&package) {
plain_module = as_package.is_none();
self.includes.push(IncludeRef { target });
}
if !plain_module {
self.submodules(&package, names);
}
}
fn submodules(&mut self, package: &str, names: &[String]) {
for name in names {
if let Some((target, _)) = self.probe(&anchor_join(package, name)) {
self.includes.push(IncludeRef { target });
}
}
}
fn probe(&self, module: &str) -> Option<(String, Option<String>)> {
for (extension, initializer) in [(".py", "__init__.py"), (".pyi", "__init__.pyi")] {
let file = format!("{module}{extension}");
if self.repository.contains(&file) {
return Some((file, None));
}
let init = anchor_join(module, initializer);
if self.repository.contains(&init) {
return Some((init, Some(module.to_owned())));
}
}
None
}
}
enum Found {
Module,
Package(String),
Nowhere,
}
fn anchors(path: &str) -> impl Iterator<Item = &str> {
let around = iter::successors(Some(dir(path)).filter(|from| *from != "."), |from| {
from.rsplit_once('/').map(|(parent, _)| parent)
});
iter::once("").chain(around)
}
fn dotted_path(dotted: &str) -> String {
let mut path = String::with_capacity(dotted.len());
for segment in dotted.split('.').filter(|segment| !segment.is_empty()) {
if !path.is_empty() {
path.push('/');
}
path.push_str(segment);
}
path
}
fn anchor_join(anchor: &str, piece: &str) -> String {
match (anchor.is_empty(), piece.is_empty()) {
(true, _) => piece.to_owned(),
(false, true) => anchor.to_owned(),
(false, false) => format!("{anchor}/{piece}"),
}
}
fn stem(name: &str) -> &str {
name.rsplit_once('.')
.filter(|(_, extension)| {
extension.eq_ignore_ascii_case("py") || extension.eq_ignore_ascii_case("pyi")
})
.map_or(name, |(stem, _)| stem)
}
fn module_name(path: &str) -> String {
let module = stem(path);
let module = match module.strip_suffix("__init__") {
Some("") => "",
Some(package) => package.strip_suffix('/').unwrap_or(module),
None => module,
};
module.replace('/', ".")
}
fn is_test_file(path: &str) -> bool {
let stem = stem(base(path));
stem == "conftest"
|| stem.ends_with("_test")
|| stem.starts_with("test_")
|| path
.split('/')
.any(|component| matches!(component, "test" | "tests"))
}
fn is_generated_path(path: &str) -> bool {
let stem = stem(base(path));
stem.ends_with("_pb2") || stem.ends_with("_pb2_grpc")
}