use std::sync::Arc;
use super::body_ribs::RibStack;
use super::body_walk::FileResolver;
use super::crate_snapshot::CrateSnapshot;
use super::db::{FileId, GlobalDefId, ItemDb, ItemKind, ModuleId, SourceDb};
use super::db_impls::ImplTargetKey;
use super::def_map::CrateDefMap;
use super::ext_scope::ExtScopeCache;
use super::mod_tree::ModuleTree;
use super::per_ns::{LocalItemId, PrimTy};
use crate::parser::parse;
use crate::tree::{NodeId, SyntaxTree};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct LocalBindId(pub u32);
impl LocalBindId {
pub const NONE: Self = Self(u32::MAX);
#[inline]
pub const fn is_some(self) -> bool {
self.0 != u32::MAX
}
}
impl Default for LocalBindId {
#[inline]
fn default() -> Self {
Self::NONE
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericBindId(pub u32);
impl GenericBindId {
pub const NONE: Self = Self(u32::MAX);
#[inline]
pub const fn is_some(self) -> bool {
self.0 != u32::MAX
}
}
impl Default for GenericBindId {
#[inline]
fn default() -> Self {
Self::NONE
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct LocalBindData {
pub id: LocalBindId,
pub decl_node: NodeId,
pub name_start: u32,
pub name_end: u32,
pub is_self: bool,
pub is_mut: bool,
}
impl LocalBindData {
#[inline]
pub fn name<'s>(&self, src: &'s str) -> &'s str {
&src[self.name_start as usize..self.name_end as usize]
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct GenericBindData {
pub id: GenericBindId,
pub def: GlobalDefId,
pub owner_node: NodeId,
pub owner_def: GlobalDefId,
pub decl_node: NodeId,
pub name_start: u32,
pub name_end: u32,
pub index: u16,
pub is_const: bool,
}
impl GenericBindData {
#[inline]
pub fn name<'s>(&self, src: &'s str) -> &'s str {
&src[self.name_start as usize..self.name_end as usize]
}
}
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PathCtx {
Expr = 0,
RecordExpr = 1,
Type = 2,
TypeArg = 3,
TypeBound = 4,
PatValue = 5,
PatRecord = 6,
UseTree = 7,
MacroCall = 8,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ResTarget {
Def { def: GlobalDefId, local: LocalItemId, kind: ItemKind },
Local(LocalBindId),
Generic(GenericBindId),
SelfTy { target: ImplTargetKey, trait_def: GlobalDefId },
Prim(PrimTy),
}
impl ResTarget {
#[inline]
pub const fn effective_def_id(self) -> Option<GlobalDefId> {
match self {
Self::Def { def, .. } if def.is_some() => Some(def),
Self::SelfTy { target: ImplTargetKey::Adt(adt_def), .. } if adt_def.is_some() => Some(adt_def),
_ => None,
}
}
#[inline]
pub fn effective_def_id_in(self, file_res: &FileNameRes) -> Option<GlobalDefId> {
match self {
Self::Generic(gid) => {
let d = file_res.generic_data(gid).def;
d.is_some().then_some(d)
}
other => other.effective_def_id(),
}
}
#[inline]
pub const fn is_local(self) -> bool {
matches!(self, Self::Local(_))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ResolvedRef {
pub start: u32,
pub end: u32,
pub path_node: NodeId,
pub target: ResTarget,
pub ctx: PathCtx,
pub is_segment_tail: bool,
}
#[derive(Clone, Debug, Default)]
pub struct FileNameRes {
pub file: FileId,
pub refs: Vec<ResolvedRef>,
pub locals: Vec<LocalBindData>,
pub generics: Vec<GenericBindData>,
pub prelude_traits: Arc<[GlobalDefId]>,
pub mod_trait_scopes: Vec<(NodeId, NodeId, Arc<[GlobalDefId]>, bool)>,
pub block_trait_imports: Vec<(NodeId, NodeId, GlobalDefId)>,
pub self_trait_scopes: Vec<(NodeId, NodeId, GlobalDefId)>,
pub param_trait_bounds: Vec<(GenericBindId, GlobalDefId)>,
pub(super) ribs: RibStack,
}
impl FileNameRes {
pub fn new() -> Self {
Self::default()
}
#[inline]
pub fn swap_scratch(&mut self, other: &mut Self) {
core::mem::swap(&mut self.ribs, &mut other.ribs);
}
#[inline]
pub fn clear(&mut self) {
self.file = FileId::NONE;
self.refs.clear();
self.locals.clear();
self.generics.clear();
self.mod_trait_scopes.clear();
self.block_trait_imports.clear();
self.self_trait_scopes.clear();
self.param_trait_bounds.clear();
self.ribs.clear();
}
pub fn collect_traits_in_scope_at(&self, node: NodeId, out: &mut Vec<GlobalDefId>) {
out.clear();
for &(s, e, tdef) in &self.self_trait_scopes {
if node.0 >= s.0 && node.0 < e.0 && tdef.is_some() && !out.contains(&tdef) {
out.push(tdef);
}
}
for &(s, e, tdef) in self.block_trait_imports.iter().rev() {
if node.0 >= s.0 && node.0 < e.0 && tdef.is_some() && !out.contains(&tdef) {
out.push(tdef);
}
}
let mut include_prelude = true;
if let Some((_, _, vis, inc)) = self.mod_trait_scopes.iter().rfind(|&&(s, e, _, _)| node.0 >= s.0 && node.0 < e.0) {
include_prelude = *inc;
for &tdef in vis.iter() {
if tdef.is_some() && !out.contains(&tdef) {
out.push(tdef);
}
}
}
if include_prelude {
for &tdef in self.prelude_traits.iter() {
if tdef.is_some() && !out.contains(&tdef) {
out.push(tdef);
}
}
}
}
#[inline]
pub fn has_inner_trait_scopes(&self, start: NodeId, end: u32) -> bool {
let s0 = start.0;
self.block_trait_imports.iter().any(|&(s, e, _)| (s.0 > s0 && s.0 < end) || (e.0 > s0 && e.0 < end))
|| self.self_trait_scopes.iter().any(|&(s, e, _)| (s.0 > s0 && s.0 < end) || (e.0 > s0 && e.0 < end))
|| self.mod_trait_scopes.iter().any(|(s, e, _, _)| (s.0 > s0 && s.0 < end) || (e.0 > s0 && e.0 < end))
}
pub(super) fn finalize(&mut self) {
self.refs.sort_unstable_by_key(|a| (a.start, a.end, a.target, !a.is_segment_tail, a.path_node.0, a.ctx));
self.refs.dedup_by(|b, a| a.start == b.start && a.end == b.end && a.target == b.target);
}
pub fn ref_at_offset(&self, byte_offset: u32) -> Option<&ResolvedRef> {
let idx = self.refs.partition_point(|r| r.start <= byte_offset);
self.refs[..idx].iter().rfind(|r| byte_offset < r.end)
}
pub fn refs_at_span(&self, start: u32, end: u32) -> &[ResolvedRef] {
let lo = self.refs.partition_point(|r| (r.start, r.end) < (start, end));
let hi = self.refs[lo..].partition_point(|r| r.start == start && r.end == end);
&self.refs[lo..lo + hi]
}
pub fn path_tail_ref(&self, path_node: NodeId) -> Option<&ResolvedRef> {
self.refs.iter().find(|r| r.path_node == path_node && r.is_segment_tail)
}
#[inline]
pub fn path_tail_ref_in_st(&self, st: &SyntaxTree<'_>, path_node: NodeId) -> Option<&ResolvedRef> {
let nr = st.range(path_node);
let lo = self.refs.partition_point(|r| r.start < nr.start as u32);
let hi = lo + self.refs[lo..].partition_point(|r| r.start <= nr.end as u32);
self.refs[lo..hi].iter().find(|r| r.path_node == path_node && r.is_segment_tail).or_else(|| {
let te = st.children(path_node).filter(|&c| st.kind(c) == crate::syntax_kind::SyntaxKind::PathSegment).last().map_or(nr.end as u32, |s| st.range(s).end as u32);
self.refs[lo..hi].iter().rfind(|r| r.path_node == NodeId(u32::MAX) && r.is_segment_tail && r.end == te)
})
}
#[inline]
pub fn refs_starting_in(&self, start: u32, end: u32) -> &[ResolvedRef] {
let lo = self.refs.partition_point(|r| r.start < start);
let hi = lo + self.refs[lo..].partition_point(|r| r.start <= end);
&self.refs[lo..hi]
}
#[inline]
pub fn local_data(&self, id: LocalBindId) -> &LocalBindData {
&self.locals[id.0 as usize]
}
#[inline]
pub fn generic_data(&self, id: GenericBindId) -> &GenericBindData {
&self.generics[id.0 as usize]
}
pub fn local_uses(&self, local_id: LocalBindId) -> impl Iterator<Item = &ResolvedRef> {
self.refs.iter().filter(move |r| r.target == ResTarget::Local(local_id))
}
}
impl CrateDefMap {
pub fn resolve_file_paths(&self, db: &dyn ItemDb, sources: &dyn SourceDb, mod_tree: &ModuleTree, file: FileId) -> FileNameRes {
let st = parse(sources.file_text(file));
let mut ext_cache = ExtScopeCache::new();
let mut out = FileNameRes::new();
self.resolve_file_paths_into(db, mod_tree, &mut ext_cache, file, &st, &mut out);
out
}
pub fn resolve_file_paths_into(&self, db: &dyn ItemDb, mod_tree: &ModuleTree, ext_cache: &mut ExtScopeCache, file: FileId, st: &SyntaxTree<'_>, out: &mut FileNameRes) {
out.clear();
out.file = file;
let ribs = std::mem::take(&mut out.ribs);
let mut resolver = FileResolver::new(self, db, mod_tree, ext_cache, file, st, out, ribs);
resolver.walk_file();
let ribs = resolver.ribs;
out.ribs = ribs;
out.finalize();
}
#[allow(clippy::too_many_arguments)]
pub fn resolve_fn_paths_into(
&self,
db: &dyn ItemDb,
mod_tree: &ModuleTree,
ext_cache: &mut ExtScopeCache,
file: FileId,
st: &SyntaxTree<'_>,
target_fn: NodeId,
out: &mut FileNameRes,
) {
out.clear();
out.file = file;
let ribs = std::mem::take(&mut out.ribs);
let mut resolver = FileResolver::new(self, db, mod_tree, ext_cache, file, st, out, ribs);
resolver.target_range = Some((target_fn.0, st.node(target_fn).subtree_end));
resolver.walk_file();
let ribs = resolver.ribs;
out.ribs = ribs;
out.finalize();
}
pub(crate) fn resolve_module_snippet_into(&self, db: &dyn ItemDb, module: ModuleId, file: FileId, st: &SyntaxTree<'_>, out: &mut FileNameRes) {
out.clear();
out.file = file;
let mut ext_cache = ExtScopeCache::new();
let ribs = std::mem::take(&mut out.ribs);
let mut resolver = FileResolver::new(self, db, &self.mod_tree, &mut ext_cache, file, st, out, ribs);
resolver.cur_mod = module;
resolver.walk_file();
out.ribs = resolver.ribs;
out.finalize();
}
}
impl CrateSnapshot {
pub fn resolve_file_paths_into(&self, db: &dyn ItemDb, file: FileId, st: &SyntaxTree<'_>, out: &mut FileNameRes) {
let mut ext_c = self.ext_cache.borrow_mut();
self.clean_def_map.resolve_file_paths_into(db, &self.mod_tree, &mut ext_c, file, st, out);
}
pub fn resolve_fn_paths_into(&self, db: &dyn ItemDb, file: FileId, st: &SyntaxTree<'_>, target_fn: NodeId, out: &mut FileNameRes) {
let mut ext_c = self.ext_cache.borrow_mut();
self.clean_def_map.resolve_fn_paths_into(db, &self.mod_tree, &mut ext_c, file, st, target_fn, out);
}
pub fn resolve_dirty_file_paths_into(
&self,
db: &dyn ItemDb,
new_mod_tree: Option<&ModuleTree>,
def_map: &CrateDefMap,
file: FileId,
st: &SyntaxTree<'_>,
out: &mut FileNameRes,
) {
let mut ext_c = self.ext_cache.borrow_mut();
def_map.resolve_file_paths_into(db, new_mod_tree.unwrap_or(&self.mod_tree), &mut ext_c, file, st, out);
}
}