5 helpers::pick_best_token,
6 search::{FileReference, ReferenceAccess, SearchScope},
10 ast, match_ast, AstNode,
11 SyntaxKind::{ASYNC_KW, AWAIT_KW, QUESTION, RETURN_KW, THIN_ARROW},
12 SyntaxNode, SyntaxToken, TextRange, WalkEvent,
15 use crate::{display::TryToNav, references, NavigationTarget};
17 pub struct DocumentHighlight {
19 pub access: Option<ReferenceAccess>,
22 // Feature: Highlight related
24 // Highlights exit points, yield points or the definition and all references of the item at the cursor location in the current file.
25 pub(crate) fn highlight_related(
26 sema: &Semantics<RootDatabase>,
27 position: FilePosition,
28 ) -> Option<Vec<DocumentHighlight>> {
29 let _p = profile::span("document_highlight");
30 let syntax = sema.parse(position.file_id).syntax().clone();
32 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
33 QUESTION => 2, // prefer `?` when the cursor is sandwiched like `await$0?`
34 AWAIT_KW | ASYNC_KW | THIN_ARROW | RETURN_KW => 1,
39 QUESTION | RETURN_KW | THIN_ARROW => highlight_exit_points(token),
40 AWAIT_KW | ASYNC_KW => highlight_yield_points(token),
41 _ => highlight_references(sema, &syntax, position),
45 fn highlight_exit_points(_token: SyntaxToken) -> Option<Vec<DocumentHighlight>> {
49 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<DocumentHighlight>> {
51 async_token: Option<SyntaxToken>,
52 body: Option<ast::BlockExpr>,
53 ) -> Option<Vec<DocumentHighlight>> {
54 let mut highlights = Vec::new();
55 highlights.push(DocumentHighlight { access: None, range: async_token?.text_range() });
56 if let Some(body) = body {
57 let mut preorder = body.syntax().preorder();
58 while let Some(event) = preorder.next() {
59 let node = match event {
60 WalkEvent::Enter(node) => node,
61 WalkEvent::Leave(_) => continue,
65 ast::AwaitExpr(expr) => if let Some(token) = expr.await_token() {
66 highlights.push(DocumentHighlight {
68 range: token.text_range(),
71 ast::EffectExpr(__) => preorder.skip_subtree(),
72 ast::ClosureExpr(__) => preorder.skip_subtree(),
73 ast::Item(__) => preorder.skip_subtree(),
74 ast::Path(__) => preorder.skip_subtree(),
82 for anc in token.ancestors() {
85 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body()),
86 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr()),
87 ast::ClosureExpr(__) => None,
95 fn highlight_references(
96 sema: &Semantics<RootDatabase>,
98 FilePosition { offset, file_id }: FilePosition,
99 ) -> Option<Vec<DocumentHighlight>> {
100 let def = references::find_def(sema, syntax, offset)?;
101 let usages = def.usages(sema).set_scope(Some(SearchScope::single_file(file_id))).all();
103 let declaration = match def {
104 Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
105 Some(NavigationTarget::from_module_to_decl(sema.db, module))
107 def => def.try_to_nav(sema.db),
109 .filter(|decl| decl.file_id == file_id)
111 let range = decl.focus_range?;
112 let access = references::decl_access(&def, syntax, range);
113 Some(DocumentHighlight { range, access })
116 let file_refs = usages.references.get(&file_id).map_or(&[][..], Vec::as_slice);
117 let mut res = Vec::with_capacity(file_refs.len() + 1);
118 res.extend(declaration);
122 .map(|&FileReference { access, range, .. }| DocumentHighlight { range, access }),
133 fn check(ra_fixture: &str) {
134 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
135 let hls = analysis.highlight_related(pos).unwrap().unwrap();
137 let mut expected = annotations
139 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
140 .collect::<Vec<_>>();
149 ReferenceAccess::Read => "read",
150 ReferenceAccess::Write => "write",
156 .collect::<Vec<_>>();
157 actual.sort_by_key(|(range, _)| range.start());
158 expected.sort_by_key(|(range, _)| range.start());
160 assert_eq!(expected, actual);
164 fn test_hl_module() {
177 fn test_hl_self_in_crate_root() {
186 fn test_hl_self_in_module() {
212 fn test_hl_yield_points() {
223 (async { 0.await }).await
231 fn test_hl_yield_points2() {
234 pub async$0 fn foo() {
242 (async { 0.await }).await
250 fn test_hl_yield_nested_fn() {
269 fn test_hl_yield_nested_async_blocks() {