use sealmap_model::{Descriptor, Package, SymbolId, SymbolKind};
pub fn package(manager: &str, name: &str) -> Package {
Package::current(manager, name).unwrap_or_else(|_| {
let cleaned: String = name.chars().filter(|c| !c.is_control()).collect::<String>().trim().to_owned();
let cleaned = if cleaned.is_empty() || cleaned == "." { "_".to_owned() } else { cleaned };
Package::current(manager, cleaned)
.or_else(|_| Package::current("unknown", "_"))
.expect("`unknown _ .` is a valid package")
})
}
pub fn module_id(package: &Package, modules: &[String]) -> SymbolId {
SymbolId::global(package.clone(), modules.iter().map(|m| SymbolKind::Module.descriptor(m.as_str())).collect())
}
pub fn item_id(scope: &SymbolId, kind: SymbolKind, name: &str) -> SymbolId {
scope.child(kind.descriptor(name)).unwrap_or_else(|| scope.extend_path(name))
}
pub fn method_id(owner: &SymbolId, trait_: Option<&str>, name: &str) -> SymbolId {
let scoped = match trait_ {
Some(t) => owner.child(Descriptor::type_parameter(t)),
None => Some(owner.clone()),
};
scoped.and_then(|s| s.child(Descriptor::method(name))).unwrap_or_else(|| owner.extend_path(name))
}
pub fn impl_method_id(
module: &SymbolId,
owner: &SymbolId,
self_ty: &str,
trait_: Option<&str>,
name: &str,
) -> SymbolId {
if owner.is_global() {
return method_id(owner, trait_, name);
}
let mut d = vec![Descriptor::r#type("impl"), Descriptor::type_parameter(self_ty)];
if let Some(t) = trait_ {
d.push(Descriptor::type_parameter(t));
}
d.push(Descriptor::method(name));
d.into_iter().try_fold(module.clone(), |id, d| id.child(d)).unwrap_or_else(|| module.extend_path(name))
}
pub fn path_id(segments: &[String]) -> Option<SymbolId> {
SymbolId::path(segments.iter().cloned()).ok()
}
pub fn unresolved_method_id(name: &str) -> SymbolId {
SymbolId::unresolved(name)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids() {
let pkg = package("cargo", "app");
let root = module_id(&pkg, &[]);
assert_eq!(root.to_string(), "sym:cargo app .");
let a = module_id(&pkg, &["a".into(), "b".into()]);
assert_eq!(a.parent().unwrap().to_string(), "sym:cargo app . a/");
let f = item_id(&a, SymbolKind::Function, "go");
assert_eq!(f.to_string(), "sym:cargo app . a/b/go().");
assert_eq!(item_id(&a, SymbolKind::Module, "go").to_string(), "sym:cargo app . a/b/go/");
assert_eq!(unresolved_method_id("go").to_string(), "sym:? go");
assert!(path_id(&[]).is_none());
let ext = path_id(&["dep".into(), "T".into()]).unwrap();
assert_eq!(method_id(&ext, Some("X"), "m").to_string(), "sym:extern dep::T::m");
assert_eq!(item_id(&ext, SymbolKind::Function, "f").to_string(), "sym:extern dep::T::f");
}
#[test]
fn package_names_are_repaired_not_rejected() {
assert_eq!(package("cargo", "").name(), "_");
assert_eq!(package("cargo", " a\n").name(), "a");
assert_eq!(package("Cargo", "a").manager(), "unknown");
}
}