Fully remove old macro descension API

This commit is contained in:
Lukas Wirth 2024-08-22 16:18:01 +02:00
parent 495118015e
commit 64064907ce
13 changed files with 66 additions and 103 deletions

View file

@ -93,8 +93,7 @@ pub use crate::{
diagnostics::*, diagnostics::*,
has_source::HasSource, has_source::HasSource,
semantics::{ semantics::{
DescendPreference, PathResolution, Semantics, SemanticsImpl, SemanticsScope, TypeInfo, PathResolution, Semantics, SemanticsImpl, SemanticsScope, TypeInfo, VisibleTraits,
VisibleTraits,
}, },
}; };
pub use hir_ty::method_resolution::TyFingerprint; pub use hir_ty::method_resolution::TyFingerprint;

View file

@ -51,10 +51,6 @@ use crate::{
const CONTINUE_NO_BREAKS: ControlFlow<Infallible, ()> = ControlFlow::Continue(()); const CONTINUE_NO_BREAKS: ControlFlow<Infallible, ()> = ControlFlow::Continue(());
pub enum DescendPreference {
None,
}
#[derive(Debug, Copy, Clone, PartialEq, Eq)] #[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum PathResolution { pub enum PathResolution {
/// An item /// An item
@ -183,6 +179,7 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
/// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*, /// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*,
/// descend it and find again /// descend it and find again
// FIXME: Rethink this API
pub fn find_node_at_offset_with_descend<N: AstNode>( pub fn find_node_at_offset_with_descend<N: AstNode>(
&self, &self,
node: &SyntaxNode, node: &SyntaxNode,
@ -191,8 +188,9 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast) self.imp.descend_node_at_offset(node, offset).flatten().find_map(N::cast)
} }
/// Find an AstNode by offset inside SyntaxNode, if it is inside *MacroCall*, /// Find an AstNode by offset inside SyntaxNode, if it is inside an attribte macro call,
/// descend it and find again /// descend it and find again
// FIXME: Rethink this API
pub fn find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>( pub fn find_nodes_at_offset_with_descend<'slf, N: AstNode + 'slf>(
&'slf self, &'slf self,
node: &SyntaxNode, node: &SyntaxNode,
@ -666,38 +664,6 @@ impl<'db> SemanticsImpl<'db> {
res res
} }
/// Descend the token into its macro call if it is part of one, returning the tokens in the
/// expansion that it is associated with.
pub fn descend_into_macros(
&self,
mode: DescendPreference,
token: SyntaxToken,
) -> SmallVec<[SyntaxToken; 1]> {
enum Dp {
None,
}
let mode = match mode {
DescendPreference::None => Dp::None,
};
let mut res = smallvec![];
self.descend_into_macros_impl::<Infallible>(
token.clone(),
&mut |InFile { value, .. }| {
let is_a_match = match mode {
Dp::None => true,
};
if is_a_match {
res.push(value);
}
ControlFlow::Continue(())
},
);
if res.is_empty() {
res.push(token);
}
res
}
pub fn descend_into_macros_ng( pub fn descend_into_macros_ng(
&self, &self,
token: SyntaxToken, token: SyntaxToken,
@ -709,6 +675,18 @@ impl<'db> SemanticsImpl<'db> {
}); });
} }
pub fn descend_into_macros_ng_v(&self, token: SyntaxToken) -> SmallVec<[SyntaxToken; 1]> {
let mut res = smallvec![];
self.descend_into_macros_impl(token.clone(), &mut |t| {
res.push(t.value);
CONTINUE_NO_BREAKS
});
if res.is_empty() {
res.push(token);
}
res
}
pub fn descend_into_macros_ng_b<T>( pub fn descend_into_macros_ng_b<T>(
&self, &self,
token: SyntaxToken, token: SyntaxToken,
@ -1003,7 +981,7 @@ impl<'db> SemanticsImpl<'db> {
offset: TextSize, offset: TextSize,
) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ { ) -> impl Iterator<Item = impl Iterator<Item = SyntaxNode> + '_> + '_ {
node.token_at_offset(offset) node.token_at_offset(offset)
.map(move |token| self.descend_into_macros(DescendPreference::None, token)) .map(move |token| self.descend_into_macros_exact(token))
.map(|descendants| { .map(|descendants| {
descendants.into_iter().map(move |it| self.token_ancestors_with_macros(it)) descendants.into_iter().map(move |it| self.token_ancestors_with_macros(it))
}) })

View file

@ -3,8 +3,8 @@ use std::{iter, ops::RangeInclusive};
use ast::make; use ast::make;
use either::Either; use either::Either;
use hir::{ use hir::{
DescendPreference, HasSource, HirDisplay, InFile, Local, LocalSource, ModuleDef, HasSource, HirDisplay, InFile, Local, LocalSource, ModuleDef, PathResolution, Semantics,
PathResolution, Semantics, TypeInfo, TypeParam, TypeInfo, TypeParam,
}; };
use ide_db::{ use ide_db::{
defs::{Definition, NameRefClass}, defs::{Definition, NameRefClass},
@ -834,7 +834,7 @@ impl FunctionBody {
.descendants_with_tokens() .descendants_with_tokens()
.filter_map(SyntaxElement::into_token) .filter_map(SyntaxElement::into_token)
.filter(|it| matches!(it.kind(), SyntaxKind::IDENT | T![self])) .filter(|it| matches!(it.kind(), SyntaxKind::IDENT | T![self]))
.flat_map(|t| sema.descend_into_macros(DescendPreference::None, t)) .flat_map(|t| sema.descend_into_macros_exact(t))
.for_each(|t| add_name_if_local(t.parent().and_then(ast::NameRef::cast))); .for_each(|t| add_name_if_local(t.parent().and_then(ast::NameRef::cast)));
} }
} }

View file

@ -3,7 +3,7 @@
use std::collections::VecDeque; use std::collections::VecDeque;
use base_db::SourceRootDatabase; use base_db::SourceRootDatabase;
use hir::{Crate, DescendPreference, ItemInNs, ModuleDef, Name, Semantics}; use hir::{Crate, ItemInNs, ModuleDef, Name, Semantics};
use span::{Edition, FileId}; use span::{Edition, FileId};
use syntax::{ use syntax::{
ast::{self, make}, ast::{self, make},
@ -112,11 +112,12 @@ pub fn is_editable_crate(krate: Crate, db: &RootDatabase) -> bool {
!db.source_root(source_root_id).is_library !db.source_root(source_root_id).is_library
} }
// FIXME: This is a weird function
pub fn get_definition( pub fn get_definition(
sema: &Semantics<'_, RootDatabase>, sema: &Semantics<'_, RootDatabase>,
token: SyntaxToken, token: SyntaxToken,
) -> Option<Definition> { ) -> Option<Definition> {
for token in sema.descend_into_macros(DescendPreference::None, token) { for token in sema.descend_into_macros_exact(token) {
let def = IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops); let def = IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops);
if let Some(&[x]) = def.as_deref() { if let Some(&[x]) = def.as_deref() {
return Some(x); return Some(x);

View file

@ -9,8 +9,8 @@ use std::mem;
use base_db::{salsa::Database, SourceDatabase, SourceRootDatabase}; use base_db::{salsa::Database, SourceDatabase, SourceRootDatabase};
use hir::{ use hir::{
sym, AsAssocItem, DefWithBody, DescendPreference, FileRange, HasAttrs, HasSource, HirFileIdExt, sym, AsAssocItem, DefWithBody, FileRange, HasAttrs, HasSource, HirFileIdExt, InFile,
InFile, InRealFile, ModuleSource, PathResolution, Semantics, Visibility, InRealFile, ModuleSource, PathResolution, Semantics, Visibility,
}; };
use memchr::memmem::Finder; use memchr::memmem::Finder;
use parser::SyntaxKind; use parser::SyntaxKind;
@ -549,9 +549,7 @@ impl<'a> FindUsages<'a> {
// every textual hit. That function is notoriously // every textual hit. That function is notoriously
// expensive even for things that do not get down mapped // expensive even for things that do not get down mapped
// into macros. // into macros.
sema.descend_into_macros(DescendPreference::None, token) sema.descend_into_macros_exact(token).into_iter().filter_map(|it| it.parent())
.into_iter()
.filter_map(|it| it.parent())
}) })
}; };

View file

@ -2,7 +2,7 @@
use std::iter; use std::iter;
use hir::{DescendPreference, Semantics}; use hir::Semantics;
use ide_db::{ use ide_db::{
defs::{Definition, NameClass, NameRefClass}, defs::{Definition, NameClass, NameRefClass},
helpers::pick_best_token, helpers::pick_best_token,
@ -86,7 +86,7 @@ pub(crate) fn outgoing_calls(
})?; })?;
let mut calls = CallLocations::default(); let mut calls = CallLocations::default();
sema.descend_into_macros(DescendPreference::None, token) sema.descend_into_macros_exact(token)
.into_iter() .into_iter()
.filter_map(|it| it.parent_ancestors().nth(1).and_then(ast::Item::cast)) .filter_map(|it| it.parent_ancestors().nth(1).and_then(ast::Item::cast))
.filter_map(|item| match item { .filter_map(|item| match item {

View file

@ -10,10 +10,7 @@ use pulldown_cmark_to_cmark::{cmark_resume_with_options, Options as CMarkOptions
use stdx::format_to; use stdx::format_to;
use url::Url; use url::Url;
use hir::{ use hir::{db::HirDatabase, sym, Adt, AsAssocItem, AssocItem, AssocItemContainer, HasAttrs};
db::HirDatabase, sym, Adt, AsAssocItem, AssocItem, AssocItemContainer, DescendPreference,
HasAttrs,
};
use ide_db::{ use ide_db::{
base_db::{CrateOrigin, LangCrateOrigin, ReleaseChannel, SourceDatabase}, base_db::{CrateOrigin, LangCrateOrigin, ReleaseChannel, SourceDatabase},
defs::{Definition, NameClass, NameRefClass}, defs::{Definition, NameClass, NameRefClass},
@ -289,7 +286,7 @@ impl DocCommentToken {
let original_start = doc_token.text_range().start(); let original_start = doc_token.text_range().start();
let relative_comment_offset = offset - original_start - prefix_len; let relative_comment_offset = offset - original_start - prefix_len;
sema.descend_into_macros(DescendPreference::None, doc_token).into_iter().find_map(|t| { sema.descend_into_macros_ng_v(doc_token).into_iter().find_map(|t| {
let (node, descended_prefix_len) = match_ast! { let (node, descended_prefix_len) = match_ast! {
match t { match t {
ast::Comment(comment) => (t.parent()?, TextSize::try_from(comment.prefix().len()).ok()?), ast::Comment(comment) => (t.parent()?, TextSize::try_from(comment.prefix().len()).ok()?),

View file

@ -1,4 +1,4 @@
use hir::{DescendPreference, InFile, MacroFileIdExt, Semantics}; use hir::{InFile, MacroFileIdExt, Semantics};
use ide_db::{ use ide_db::{
helpers::pick_best_token, syntax_helpers::insert_whitespace_into_node::insert_ws_into, FileId, helpers::pick_best_token, syntax_helpers::insert_whitespace_into_node::insert_ws_into, FileId,
RootDatabase, RootDatabase,
@ -41,37 +41,30 @@ pub(crate) fn expand_macro(db: &RootDatabase, position: FilePosition) -> Option<
// struct Bar; // struct Bar;
// ``` // ```
let derive = sema let derive = sema.descend_into_macros_exact(tok.clone()).into_iter().find_map(|descended| {
.descend_into_macros(DescendPreference::None, tok.clone()) let macro_file = sema.hir_file_for(&descended.parent()?).macro_file()?;
.into_iter() if !macro_file.is_derive_attr_pseudo_expansion(db) {
.find_map(|descended| { return None;
let macro_file = sema.hir_file_for(&descended.parent()?).macro_file()?; }
if !macro_file.is_derive_attr_pseudo_expansion(db) {
return None;
}
let name = descended.parent_ancestors().filter_map(ast::Path::cast).last()?.to_string(); let name = descended.parent_ancestors().filter_map(ast::Path::cast).last()?.to_string();
// up map out of the #[derive] expansion // up map out of the #[derive] expansion
let InFile { file_id, value: tokens } = let InFile { file_id, value: tokens } =
hir::InMacroFile::new(macro_file, descended).upmap_once(db); hir::InMacroFile::new(macro_file, descended).upmap_once(db);
let token = sema.parse_or_expand(file_id).covering_element(tokens[0]).into_token()?; let token = sema.parse_or_expand(file_id).covering_element(tokens[0]).into_token()?;
let attr = token.parent_ancestors().find_map(ast::Attr::cast)?; let attr = token.parent_ancestors().find_map(ast::Attr::cast)?;
let expansions = sema.expand_derive_macro(&attr)?; let expansions = sema.expand_derive_macro(&attr)?;
let idx = attr let idx = attr
.token_tree()? .token_tree()?
.token_trees_and_tokens() .token_trees_and_tokens()
.filter_map(NodeOrToken::into_token) .filter_map(NodeOrToken::into_token)
.take_while(|it| it != &token) .take_while(|it| it != &token)
.filter(|it| it.kind() == T![,]) .filter(|it| it.kind() == T![,])
.count(); .count();
let expansion = format( let expansion =
db, format(db, SyntaxKind::MACRO_ITEMS, position.file_id, expansions.get(idx).cloned()?);
SyntaxKind::MACRO_ITEMS, Some(ExpandedMacro { name, expansion })
position.file_id, });
expansions.get(idx).cloned()?,
);
Some(ExpandedMacro { name, expansion })
});
if derive.is_some() { if derive.is_some() {
return derive; return derive;

View file

@ -1,4 +1,4 @@
use hir::{AsAssocItem, DescendPreference, Semantics}; use hir::{AsAssocItem, Semantics};
use ide_db::{ use ide_db::{
defs::{Definition, NameClass, NameRefClass}, defs::{Definition, NameClass, NameRefClass},
RootDatabase, RootDatabase,
@ -29,7 +29,7 @@ pub(crate) fn goto_declaration(
.find(|it| matches!(it.kind(), IDENT | T![self] | T![super] | T![crate] | T![Self]))?; .find(|it| matches!(it.kind(), IDENT | T![self] | T![super] | T![crate] | T![Self]))?;
let range = original_token.text_range(); let range = original_token.text_range();
let info: Vec<NavigationTarget> = sema let info: Vec<NavigationTarget> = sema
.descend_into_macros(DescendPreference::None, original_token) .descend_into_macros_ng_v(original_token)
.iter() .iter()
.filter_map(|token| { .filter_map(|token| {
let parent = token.parent()?; let parent = token.parent()?;

View file

@ -5,10 +5,7 @@ use crate::{
navigation_target::{self, ToNav}, navigation_target::{self, ToNav},
FilePosition, NavigationTarget, RangeInfo, TryToNav, UpmappingResult, FilePosition, NavigationTarget, RangeInfo, TryToNav, UpmappingResult,
}; };
use hir::{ use hir::{AsAssocItem, AssocItem, FileRange, InFile, MacroFileIdExt, ModuleDef, Semantics};
AsAssocItem, AssocItem, DescendPreference, FileRange, InFile, MacroFileIdExt, ModuleDef,
Semantics,
};
use ide_db::{ use ide_db::{
base_db::{AnchoredPath, FileLoader, SourceDatabase}, base_db::{AnchoredPath, FileLoader, SourceDatabase},
defs::{Definition, IdentClass}, defs::{Definition, IdentClass},
@ -86,7 +83,7 @@ pub(crate) fn goto_definition(
} }
let navs = sema let navs = sema
.descend_into_macros(DescendPreference::None, original_token.clone()) .descend_into_macros_ng_v(original_token.clone())
.into_iter() .into_iter()
.filter_map(|token| { .filter_map(|token| {
let parent = token.parent()?; let parent = token.parent()?;
@ -251,7 +248,7 @@ pub(crate) fn find_fn_or_blocks(
None None
}; };
sema.descend_into_macros(DescendPreference::None, token.clone()) sema.descend_into_macros_ng_v(token.clone())
.into_iter() .into_iter()
.filter_map(find_ancestors) .filter_map(find_ancestors)
.collect_vec() .collect_vec()
@ -369,7 +366,7 @@ pub(crate) fn find_loops(
None None
}; };
sema.descend_into_macros(DescendPreference::None, token.clone()) sema.descend_into_macros_ng_v(token.clone())
.into_iter() .into_iter()
.filter_map(find_ancestors) .filter_map(find_ancestors)
.collect_vec() .collect_vec()

View file

@ -1,4 +1,4 @@
use hir::{DescendPreference, GenericParam}; use hir::GenericParam;
use ide_db::{base_db::Upcast, defs::Definition, helpers::pick_best_token, RootDatabase}; use ide_db::{base_db::Upcast, defs::Definition, helpers::pick_best_token, RootDatabase};
use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, T}; use syntax::{ast, match_ast, AstNode, SyntaxKind::*, SyntaxToken, T};
@ -69,7 +69,7 @@ pub(crate) fn goto_type_definition(
} }
let range = token.text_range(); let range = token.text_range();
sema.descend_into_macros(DescendPreference::None, token) sema.descend_into_macros_ng_v(token)
.into_iter() .into_iter()
.filter_map(|token| { .filter_map(|token| {
let ty = sema let ty = sema

View file

@ -1,6 +1,6 @@
use std::iter; use std::iter;
use hir::{db, DescendPreference, FilePosition, FileRange, HirFileId, InFile, Semantics}; use hir::{db, FilePosition, FileRange, HirFileId, InFile, Semantics};
use ide_db::{ use ide_db::{
defs::{Definition, IdentClass}, defs::{Definition, IdentClass},
helpers::pick_best_token, helpers::pick_best_token,
@ -542,7 +542,7 @@ fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange
} }
fn find_defs(sema: &Semantics<'_, RootDatabase>, token: SyntaxToken) -> FxHashSet<Definition> { fn find_defs(sema: &Semantics<'_, RootDatabase>, token: SyntaxToken) -> FxHashSet<Definition> {
sema.descend_into_macros(DescendPreference::None, token) sema.descend_into_macros_exact(token)
.into_iter() .into_iter()
.filter_map(|token| IdentClass::classify_token(sema, &token)) .filter_map(|token| IdentClass::classify_token(sema, &token))
.flat_map(IdentClass::definitions_no_ops) .flat_map(IdentClass::definitions_no_ops)

View file

@ -3,7 +3,7 @@
use core::fmt; use core::fmt;
use hir::{Adt, AsAssocItem, AssocItemContainer, Crate, DescendPreference, MacroKind, Semantics}; use hir::{Adt, AsAssocItem, AssocItemContainer, Crate, MacroKind, Semantics};
use ide_db::{ use ide_db::{
base_db::{CrateOrigin, LangCrateOrigin}, base_db::{CrateOrigin, LangCrateOrigin},
defs::{Definition, IdentClass}, defs::{Definition, IdentClass},
@ -154,7 +154,7 @@ pub(crate) fn moniker(
}); });
} }
let navs = sema let navs = sema
.descend_into_macros(DescendPreference::None, original_token.clone()) .descend_into_macros_exact(original_token.clone())
.into_iter() .into_iter()
.filter_map(|token| { .filter_map(|token| {
IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops).map(|it| { IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops).map(|it| {