use syn::{Ident, Item, ItemType, ItemUse, Type};
use crate::types::unparen;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PathAnchor {
Crate,
SelfModule,
Relative,
Super(usize),
Unknown,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathQualifier {
pub anchor: PathAnchor,
pub segments: Vec<String>,
}
impl PathQualifier {
pub fn relative(segments: Vec<String>) -> Self {
PathQualifier {
anchor: PathAnchor::Relative,
segments,
}
}
pub fn is_uninformative(&self) -> bool {
self.anchor == PathAnchor::Unknown
|| (self.anchor == PathAnchor::Relative && self.segments.is_empty())
}
pub fn forbids_fallback(&self) -> bool {
matches!(self.anchor, PathAnchor::Super(_))
}
pub fn candidates(&self, module_path: &[String]) -> Vec<Vec<String>> {
let mut nested = module_path.to_vec();
nested.extend(self.segments.iter().cloned());
match self.anchor {
PathAnchor::Unknown => Vec::new(),
PathAnchor::Crate => vec![self.segments.clone()],
PathAnchor::SelfModule => vec![nested],
PathAnchor::Relative => vec![nested, self.segments.clone()],
PathAnchor::Super(levels) => {
if levels > module_path.len() {
return Vec::new();
}
let mut base = module_path[..module_path.len() - levels].to_vec();
base.extend(self.segments.iter().cloned());
vec![base]
}
}
}
pub fn macro_target_path(&self, symbol_path: &[String]) -> Vec<String> {
let below = |base: &[String]| {
let mut out = base.to_vec();
out.extend(self.segments.iter().cloned());
out
};
match self.anchor {
PathAnchor::Crate => self.segments.clone(),
PathAnchor::SelfModule | PathAnchor::Relative => below(symbol_path),
PathAnchor::Unknown => symbol_path.to_vec(),
PathAnchor::Super(levels) if levels <= symbol_path.len() => {
below(&symbol_path[..symbol_path.len() - levels])
}
PathAnchor::Super(_) => self.segments.clone(),
}
}
pub fn display_prefix(&self) -> String {
let mut parts: Vec<String> = match self.anchor {
PathAnchor::Crate => vec!["crate".to_string()],
PathAnchor::SelfModule => vec!["self".to_string()],
PathAnchor::Super(levels) => vec!["super".to_string(); levels],
PathAnchor::Relative | PathAnchor::Unknown => Vec::new(),
};
parts.extend(self.segments.iter().cloned());
if parts.is_empty() {
String::new()
} else {
format!("{}::", parts.join("::"))
}
}
}
pub fn type_path_qualifier(ty: &Type) -> PathQualifier {
let Type::Path(p) = unparen(ty) else {
return PathQualifier::relative(Vec::new());
};
if p.qself.is_some() {
return PathQualifier {
anchor: PathAnchor::Unknown,
segments: Vec::new(),
};
}
path_qualifier(p.path.segments.iter().map(|s| s.ident.to_string()))
}
pub fn path_qualifier(segments: impl IntoIterator<Item = String>) -> PathQualifier {
let all: Vec<String> = segments.into_iter().collect();
let mut anchor = PathAnchor::Relative;
let mut out = Vec::new();
let mut levels = 0usize;
let count = all.len();
for (i, name) in all.into_iter().enumerate() {
if i == 0 {
match name.as_str() {
"crate" => {
anchor = PathAnchor::Crate;
continue;
}
"self" => {
anchor = PathAnchor::SelfModule;
continue;
}
"super" => {
levels = 1;
anchor = PathAnchor::Super(levels);
continue;
}
_ => {}
}
} else if name == "super" {
if matches!(anchor, PathAnchor::Super(_)) && out.is_empty() {
levels += 1;
anchor = PathAnchor::Super(levels);
continue;
}
return PathQualifier {
anchor: PathAnchor::Unknown,
segments: Vec::new(),
};
}
if i + 1 < count {
out.push(name);
}
}
PathQualifier {
anchor,
segments: out,
}
}
#[derive(Debug, Clone)]
pub struct ScannedImport {
pub module_path: Vec<String>,
pub alias: String,
pub path: Vec<String>,
pub qualifier: PathQualifier,
pub glob: bool,
}
pub fn imports_of_use(item: &ItemUse, module_path: &[String]) -> Vec<ScannedImport> {
let mut bindings = Vec::new();
let mut prefix = Vec::new();
flatten_use_tree(&item.tree, &mut prefix, &mut bindings);
bindings
.into_iter()
.map(|(alias, anchored, glob)| {
let qualifier = if glob {
path_qualifier(
anchored
.iter()
.cloned()
.chain(std::iter::once("__rustcall_glob__".to_string())),
)
} else {
path_qualifier(anchored.iter().cloned())
};
let path: Vec<String> = anchored
.into_iter()
.filter(|s| s != "crate" && s != "self" && s != "super")
.collect();
ScannedImport {
module_path: module_path.to_vec(),
alias,
path,
qualifier,
glob,
}
})
.collect()
}
pub fn import_of_type_alias(
item: &ItemType,
module_path: &[String],
edition_2015: bool,
) -> Option<ScannedImport> {
let Type::Path(path) = unparen(&item.ty) else {
return None;
};
if path.path.leading_colon.is_some() && !edition_2015 {
return None;
}
path.qself.is_none().then(|| {
let anchored: Vec<String> = path
.path
.segments
.iter()
.map(|s| s.ident.to_string())
.collect();
let mut qualifier = path_qualifier(anchored.iter().cloned());
if path.path.leading_colon.is_some() {
qualifier.anchor = PathAnchor::Crate;
}
let path = anchored
.into_iter()
.filter(|s| s != "crate" && s != "self" && s != "super")
.collect();
ScannedImport {
module_path: module_path.to_vec(),
alias: item.ident.to_string(),
path,
qualifier,
glob: false,
}
})
}
fn flatten_use_tree(
tree: &syn::UseTree,
prefix: &mut Vec<String>,
out: &mut Vec<(String, Vec<String>, bool)>,
) {
match tree {
syn::UseTree::Path(path) => {
let segment = path.ident.to_string();
prefix.push(segment);
flatten_use_tree(&path.tree, prefix, out);
prefix.pop();
}
syn::UseTree::Name(name) => {
let mut full = prefix.clone();
let alias = if name.ident == "self" && !prefix.is_empty() {
prefix.last().unwrap().clone()
} else {
full.push(name.ident.to_string());
name.ident.to_string()
};
out.push((alias, full, false));
}
syn::UseTree::Rename(rename) => {
let mut full = prefix.clone();
if rename.ident != "self" || prefix.is_empty() {
full.push(rename.ident.to_string());
}
out.push((rename.rename.to_string(), full, false));
}
syn::UseTree::Group(group) => {
for item in &group.items {
flatten_use_tree(item, prefix, out);
}
}
syn::UseTree::Glob(_) => out.push(("*".to_string(), prefix.clone(), true)),
}
}
#[derive(Debug, Clone)]
pub struct ImplHeader {
pub target: Ident,
pub qualifier: PathQualifier,
pub module_path: Vec<String>,
}
impl ImplHeader {
pub fn of(item: &syn::ItemImpl, module_path: &[String]) -> Option<Self> {
if item.trait_.is_some() {
return None;
}
let target = crate::types::last_ident(&item.self_ty)?.clone();
Some(ImplHeader {
target,
qualifier: type_path_qualifier(&item.self_ty),
module_path: module_path.to_vec(),
})
}
pub fn display(&self) -> String {
format!("impl {}{}", self.qualifier.display_prefix(), self.target)
}
}
pub trait Located {
fn name(&self) -> &str;
fn module_path(&self) -> &[String];
fn visible_from(&self, _module_path: &[String]) -> bool {
true
}
}
pub fn visible_from(vis: &syn::Visibility, defined_in: &[String], from: &[String]) -> bool {
let restricted = match vis {
syn::Visibility::Public(_) => return true,
syn::Visibility::Inherited => return from.starts_with(defined_in),
syn::Visibility::Restricted(restricted) => restricted,
};
let parts: Vec<String> = restricted
.path
.segments
.iter()
.map(|s| s.ident.to_string())
.collect();
let (mut scope, consumed) = match parts.first().map(String::as_str) {
Some("crate") => (Vec::new(), 1),
Some("self") => (defined_in.to_vec(), 1),
Some("super") => {
let levels = parts.iter().take_while(|s| *s == "super").count();
if levels > defined_in.len() {
return false;
}
(defined_in[..defined_in.len() - levels].to_vec(), levels)
}
_ => (Vec::new(), 0),
};
scope.extend(parts.into_iter().skip(consumed));
from.starts_with(&scope)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unresolved {
NotFound,
Ambiguous(Vec<Vec<String>>),
}
pub fn locate<T: Located>(
structs: &[T],
header: &ImplHeader,
imports: &[ScannedImport],
) -> Result<usize, Unresolved> {
locate_with_fallback(structs, header, imports, true)
}
pub fn locate_type<T: Located>(
structs: &[T],
header: &ImplHeader,
imports: &[ScannedImport],
) -> Result<usize, Unresolved> {
locate_with_fallback(structs, header, imports, false)
}
fn locate_with_fallback<T: Located>(
structs: &[T],
header: &ImplHeader,
imports: &[ScannedImport],
allow_qualified_fallback: bool,
) -> Result<usize, Unresolved> {
let name = header.target.to_string();
let named = |s: &T| s.name() == name;
if !header.qualifier.is_uninformative() {
let alias_import = if header.qualifier.anchor == PathAnchor::Relative {
header.qualifier.segments.first().and_then(|alias| {
imports.iter().find(|import| {
import.module_path == header.module_path
&& !import.glob
&& import.alias == *alias
})
})
} else {
None
};
if let Some(import) = alias_import {
let mut segments = import.path.clone();
segments.extend(header.qualifier.segments.iter().skip(1).cloned());
let imported = PathQualifier {
anchor: import.qualifier.anchor,
segments,
};
for candidate in imported.candidates(&header.module_path) {
if let Some(i) = structs
.iter()
.position(|s| named(s) && s.module_path() == candidate.as_slice())
{
return Ok(i);
}
}
return Err(Unresolved::NotFound);
}
for candidate in header.qualifier.candidates(&header.module_path) {
if let Some(i) = structs
.iter()
.position(|s| named(s) && s.module_path() == candidate.as_slice())
{
return Ok(i);
}
}
if !allow_qualified_fallback || header.qualifier.forbids_fallback() {
return Err(Unresolved::NotFound);
}
}
if let Some(i) = structs
.iter()
.position(|s| named(s) && s.module_path() == header.module_path.as_slice())
{
return Ok(i);
}
for import in imports {
if import.module_path != header.module_path || import.alias != name {
continue;
}
let target = import.path.last().map(String::as_str).unwrap_or(&name);
for candidate in import.qualifier.candidates(&header.module_path) {
if let Some(i) = structs
.iter()
.position(|s| s.name() == target && s.module_path() == candidate.as_slice())
{
return Ok(i);
}
}
}
for import in imports {
if import.module_path != header.module_path || !import.glob {
continue;
}
for candidate in import.qualifier.candidates(&header.module_path) {
if let Some(i) = structs.iter().position(|s| {
named(s)
&& s.module_path() == candidate.as_slice()
&& s.visible_from(&header.module_path)
}) {
return Ok(i);
}
}
}
let matching: Vec<usize> = structs
.iter()
.enumerate()
.filter(|(_, s)| named(s))
.map(|(i, _)| i)
.collect();
match matching.as_slice() {
[one] => Ok(*one),
[] => Err(Unresolved::NotFound),
many => Err(Unresolved::Ambiguous(
many.iter()
.map(|&i| structs[i].module_path().to_vec())
.collect(),
)),
}
}
pub fn imports_in(items: &[Item], module_path: &[String]) -> Vec<ScannedImport> {
items
.iter()
.filter_map(|item| match item {
Item::Use(u) => Some(imports_of_use(u, module_path)),
_ => None,
})
.flatten()
.collect()
}