use super::token_tree::Edition;
use unicode_normalization::UnicodeNormalization;
pub(super) fn canonical_segment(segment: &str) -> &str {
segment.strip_prefix("r#").unwrap_or(segment)
}
pub(crate) fn canonical_module_path(path: &str) -> String {
let joined = path
.split("::")
.map(canonical_segment)
.collect::<Vec<_>>()
.join("::");
if joined.is_ascii() {
joined
} else {
joined.nfc().collect()
}
}
fn is_identifier(segment: &str) -> bool {
let (raw, name) = match segment.strip_prefix("r#") {
Some(name) => (true, name),
None => (false, segment),
};
let mut characters = name.chars();
let lexes = characters
.next()
.is_some_and(|first| first == '_' || unicode_ident::is_xid_start(first))
&& characters.all(unicode_ident::is_xid_continue);
lexes && !(raw && matches!(name, "crate" | "self" | "super" | "Self" | "_"))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Sysroot {
Prelude,
ProcMacro,
Test,
}
pub(crate) fn sysroot_crate(head: &str) -> Option<Sysroot> {
match head {
"std" | "core" | "alloc" => Some(Sysroot::Prelude),
"proc_macro" => Some(Sysroot::ProcMacro),
"test" => Some(Sysroot::Test),
_ => None,
}
}
fn is_canonical_spelling(written: &str) -> bool {
let mut segments = written.split("::");
segments.next() == Some("crate") && segments.all(is_identifier)
}
pub(crate) fn canonical_module_spelling(written: &str) -> Result<String, Option<String>> {
if is_canonical_spelling(written) {
return Ok(canonical_module_path(written));
}
let segments: Vec<&str> = written
.split("::")
.map(str::trim)
.filter(|segment| !segment.is_empty())
.collect();
let candidate = match segments.first().map(|head| canonical_segment(head)) {
None => return Err(Some("crate".to_string())),
Some("self" | "super") => return Err(None),
Some("crate") => std::iter::once("crate")
.chain(segments[1..].iter().copied())
.collect::<Vec<_>>()
.join("::"),
Some(_) => format!("crate::{}", segments.join("::")),
};
Err(is_canonical_spelling(&candidate).then_some(candidate))
}
fn is_disallowed_symbol_head(head: &str, is_global: bool) -> bool {
match head.strip_prefix("r#") {
Some(name) => matches!(name, "_" | "crate" | "self" | "super" | "Self"),
None => matches!(head, "_" | "self" | "super" | "Self") || (is_global && head == "crate"),
}
}
fn is_symbol_path_spelling(written: &str) -> bool {
let is_global = written.starts_with("::");
let raw = if is_global {
let after = &written[2..];
if after.is_empty() || after.starts_with(':') {
return false;
}
after
} else {
written
};
if raw.ends_with(':') {
return false;
}
let mut segments = raw.split("::");
let head = segments
.next()
.expect("`split` yields at least one segment");
let under_sysroot = sysroot_crate(canonical_segment(head)).is_some();
is_identifier(head)
&& !is_disallowed_symbol_head(head, is_global)
&& segments.all(|segment| {
is_identifier(segment) && segment != "_" && (!under_sysroot || segment.is_ascii())
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PrefixRoot {
Bare,
Global,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct SymbolPrefix {
pub path: String,
pub root: PrefixRoot,
}
impl SymbolPrefix {
pub(crate) fn of(written: &str) -> Self {
match written.strip_prefix("::") {
Some(rest) => SymbolPrefix {
path: canonical_module_path(rest),
root: PrefixRoot::Global,
},
None => SymbolPrefix {
path: canonical_module_path(written),
root: PrefixRoot::Bare,
},
}
}
}
pub(crate) fn canonical_symbol_path_spelling(
written: &str,
) -> Result<SymbolPrefix, Option<String>> {
if is_symbol_path_spelling(written) {
return Ok(SymbolPrefix::of(written));
}
let is_global = written.trim().starts_with("::");
let segments: Vec<&str> = written
.split("::")
.map(str::trim)
.filter(|segment| !segment.is_empty())
.collect();
if segments.is_empty() {
return Err(None);
}
let first = segments[0];
let head = canonical_segment(first);
if is_disallowed_symbol_head(head, is_global) {
return Err(None);
}
let candidate_path = segments
.iter()
.map(|segment| canonical_segment(segment))
.collect::<Vec<_>>()
.join("::");
let candidate = if is_global {
format!("::{candidate_path}")
} else {
candidate_path
};
Err(is_symbol_path_spelling(&candidate).then_some(candidate))
}
pub(crate) fn package_name_to_import_ident(name: &str) -> String {
name.replace('-', "_")
}
pub(crate) fn path_within(path: &str, prefix: &str) -> bool {
path == prefix || path.starts_with(&format!("{prefix}::"))
}
pub(super) fn block_segment(table: usize, id: u32) -> String {
format!("{{block#{table}.{id}}}")
}
pub(super) fn block_label(count: usize) -> String {
if count == 1 {
"{block}".to_string()
} else {
format!("{{block {count}}}")
}
}
pub(super) fn is_block_segment(segment: &str) -> bool {
segment.starts_with('{')
}
pub(super) fn readable_module(path: &str) -> String {
path.split("::")
.map(|segment| {
if segment.starts_with("{block#") {
"{block}"
} else {
segment
}
})
.collect::<Vec<_>>()
.join("::")
}
pub(super) fn identity_modules<'a>(
modules: impl IntoIterator<Item = &'a str>,
) -> std::collections::BTreeMap<String, String> {
let mut seen: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
let mut identities = std::collections::BTreeMap::new();
for module in modules {
if identities.contains_key(module) {
continue;
}
let readable = readable_module(module);
let count = seen.entry(readable.clone()).or_default();
*count += 1;
let identity = match readable.rfind("{block}") {
Some(at) if *count > 1 => {
format!(
"{}{{block {count}}}{}",
&readable[..at],
&readable[at + "{block}".len()..]
)
}
_ => readable,
};
identities.insert(module.to_string(), identity);
}
identities
}
pub(super) fn names_a_block_item(path: &str) -> bool {
path.split("::").any(is_block_segment)
}
pub(super) fn strip_block_segments(path: &str) -> &str {
let mut path = path;
while let Some((parent, last)) = path.rsplit_once("::") {
if !is_block_segment(last) {
break;
}
path = parent;
}
path
}
pub(super) fn fold_canonical_segments(segments: &[&str]) -> Option<String> {
let mut stack: Vec<&str> = Vec::new();
for &raw_seg in segments {
let seg = canonical_segment(raw_seg.trim());
if seg.is_empty() {
continue;
}
match seg {
"self" => continue,
"super" => {
if stack.last() == Some(&"crate") || stack.is_empty() {
return None;
}
stack.pop();
while stack
.last()
.is_some_and(|segment| is_block_segment(segment))
{
stack.pop();
}
}
other => stack.push(other),
}
}
if stack.first() == Some(&"crate") {
Some(stack.join("::"))
} else {
None
}
}
pub(super) fn resolve_self_super(current_module: &str, parts: &[&str]) -> Option<String> {
let first = parts.first().copied()?;
if first != "self" && first != "super" {
return None;
}
let mut full: Vec<&str> = current_module
.split("::")
.filter(|s| !s.is_empty())
.collect();
full.extend(parts);
fold_canonical_segments(&full)
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub(super) enum PathSite {
Use,
Expr,
}
#[derive(Debug, PartialEq, Eq)]
pub(super) enum WrittenRoot {
Crate(String),
Extern {
head: String,
rest: Vec<String>,
},
FromCrateRoot {
head: String,
rest: Vec<String>,
},
Bare {
head: String,
rest: Vec<String>,
},
Invalid,
}
pub(super) fn written_root(
written: &str,
module: &str,
site: PathSite,
edition: Edition,
) -> WrittenRoot {
let raw = written.trim();
let global = raw.starts_with("::");
let parts: Vec<String> = raw
.trim_start_matches("::")
.split("::")
.map(|s| canonical_module_path(s.trim()))
.filter(|s| !s.is_empty())
.collect();
let Some((head, rest)) = parts.split_first() else {
return if global && edition == Edition::Rust2015 {
WrittenRoot::Crate("crate".to_string())
} else {
WrittenRoot::Invalid
};
};
let parts_str: Vec<&str> = parts.iter().map(String::as_str).collect();
let (head, rest) = (head.clone(), rest.to_vec());
match head.as_str() {
"crate" => {
fold_canonical_segments(&parts_str).map_or(WrittenRoot::Invalid, WrittenRoot::Crate)
}
"self" | "super" | "Self" if global => WrittenRoot::Invalid,
"self" | "super" => {
resolve_self_super(module, &parts_str).map_or(WrittenRoot::Invalid, WrittenRoot::Crate)
}
_ if edition == Edition::Rust2015 && (global || site == PathSite::Use) => {
WrittenRoot::FromCrateRoot { head, rest }
}
_ if global => WrittenRoot::Extern { head, rest },
_ => WrittenRoot::Bare { head, rest },
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fold_canonical_segments_resolves_embedded_super_and_self() {
assert_eq!(
fold_canonical_segments(&["crate", "a", "b", "super", "c", "D"]),
Some("crate::a::c::D".to_string())
);
assert_eq!(
fold_canonical_segments(&["crate", "a", "self", "b", "C"]),
Some("crate::a::b::C".to_string())
);
assert_eq!(
fold_canonical_segments(&["crate", "a", "b", "super", "super", "secret"]),
Some("crate::secret".to_string())
);
}
#[test]
fn fold_canonical_segments_over_pop_returns_none() {
assert_eq!(
fold_canonical_segments(&["crate", "a", "super", "super"]),
None
);
assert_eq!(fold_canonical_segments(&["super", "a"]), None);
}
}