5 helpers::pick_best_token,
6 search::{FileReference, ReferenceAccess, SearchScope},
10 ast::{self, LoopBodyOwner},
11 match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, WalkEvent, T,
14 use crate::{display::TryToNav, references, NavigationTarget};
16 pub struct HighlightedRange {
18 pub access: Option<ReferenceAccess>,
21 // Feature: Highlight Related
23 // Highlights constructs related to the thing under the cursor:
24 // - if on an identifier, highlights all references to that identifier in the current file
25 // - if on an `async` or `await token, highlights all yield points for that async context
26 // - if on a `return` token, `?` character or `->` return type arrow, highlights all exit points for that context
27 pub(crate) fn highlight_related(
28 sema: &Semantics<RootDatabase>,
29 position: FilePosition,
30 ) -> Option<Vec<HighlightedRange>> {
31 let _p = profile::span("highlight_related");
32 let syntax = sema.parse(position.file_id).syntax().clone();
34 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
35 T![?] => 2, // prefer `?` when the cursor is sandwiched like `await$0?`
36 T![await] | T![async] | T![return] | T![->] => 1,
41 T![return] | T![?] | T![->] => highlight_exit_points(sema, token),
42 T![await] | T![async] => highlight_yield_points(token),
43 _ => highlight_references(sema, &syntax, position),
47 fn highlight_references(
48 sema: &Semantics<RootDatabase>,
50 FilePosition { offset, file_id }: FilePosition,
51 ) -> Option<Vec<HighlightedRange>> {
52 let def = references::find_def(sema, syntax, offset)?;
53 let usages = def.usages(sema).set_scope(Some(SearchScope::single_file(file_id))).all();
55 let declaration = match def {
56 Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
57 Some(NavigationTarget::from_module_to_decl(sema.db, module))
59 def => def.try_to_nav(sema.db),
61 .filter(|decl| decl.file_id == file_id)
63 let range = decl.focus_range?;
64 let access = references::decl_access(&def, syntax, range);
65 Some(HighlightedRange { range, access })
68 let file_refs = usages.references.get(&file_id).map_or(&[][..], Vec::as_slice);
69 let mut res = Vec::with_capacity(file_refs.len() + 1);
70 res.extend(declaration);
74 .map(|&FileReference { access, range, .. }| HighlightedRange { range, access }),
79 fn highlight_exit_points(
80 sema: &Semantics<RootDatabase>,
82 ) -> Option<Vec<HighlightedRange>> {
84 sema: &Semantics<RootDatabase>,
85 body: Option<ast::Expr>,
86 ) -> Option<Vec<HighlightedRange>> {
87 let mut highlights = Vec::new();
89 walk(&body, &mut |expr| match expr {
90 ast::Expr::ReturnExpr(expr) => {
91 if let Some(token) = expr.return_token() {
92 highlights.push(HighlightedRange { access: None, range: token.text_range() });
95 ast::Expr::TryExpr(try_) => {
96 if let Some(token) = try_.question_mark_token() {
97 highlights.push(HighlightedRange { access: None, range: token.text_range() });
100 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
101 if sema.type_of_expr(&expr).map_or(false, |ty| ty.is_never()) {
103 .push(HighlightedRange { access: None, range: expr.syntax().text_range() });
108 let tail = match body {
109 ast::Expr::BlockExpr(b) => b.tail_expr(),
113 if let Some(tail) = tail {
114 for_each_inner_tail(&tail, &mut |tail| {
116 .push(HighlightedRange { access: None, range: tail.syntax().text_range() })
121 for anc in token.ancestors() {
124 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
125 ast::ClosureExpr(closure) => hl(sema, closure.body()),
126 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
127 hl(sema, effect.block_expr().map(ast::Expr::BlockExpr))
138 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
140 async_token: Option<SyntaxToken>,
141 body: Option<ast::Expr>,
142 ) -> Option<Vec<HighlightedRange>> {
143 let mut highlights = Vec::new();
144 highlights.push(HighlightedRange { access: None, range: async_token?.text_range() });
145 if let Some(body) = body {
146 walk(&body, &mut |expr| {
147 if let ast::Expr::AwaitExpr(expr) = expr {
148 if let Some(token) = expr.await_token() {
150 .push(HighlightedRange { access: None, range: token.text_range() });
157 for anc in token.ancestors() {
160 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
161 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr().map(ast::Expr::BlockExpr)),
162 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
170 /// Preorder walk all the expression's child expressions
171 fn walk(expr: &ast::Expr, cb: &mut dyn FnMut(ast::Expr)) {
172 let mut preorder = expr.syntax().preorder();
173 while let Some(event) = preorder.next() {
174 let node = match event {
175 WalkEvent::Enter(node) => node,
176 WalkEvent::Leave(_) => continue,
178 match ast::Stmt::cast(node.clone()) {
179 // recursively walk the initializer, skipping potential const pat expressions
180 // lets statements aren't usually nested too deeply so this is fine to recurse on
181 Some(ast::Stmt::LetStmt(l)) => {
182 if let Some(expr) = l.initializer() {
185 preorder.skip_subtree();
187 // Don't skip subtree since we want to process the expression child next
188 Some(ast::Stmt::ExprStmt(_)) => (),
189 // skip inner items which might have their own expressions
190 Some(ast::Stmt::Item(_)) => preorder.skip_subtree(),
192 if let Some(expr) = ast::Expr::cast(node) {
193 let is_different_context = match &expr {
194 ast::Expr::EffectExpr(effect) => {
197 ast::Effect::Async(_) | ast::Effect::Try(_) | ast::Effect::Const(_)
200 ast::Expr::ClosureExpr(__) => true,
204 if is_different_context {
205 preorder.skip_subtree();
208 preorder.skip_subtree();
215 // FIXME: doesn't account for labeled breaks in labeled blocks
216 fn for_each_inner_tail(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
218 ast::Expr::BlockExpr(b) => {
219 if let Some(e) = b.tail_expr() {
220 for_each_inner_tail(&e, cb);
223 ast::Expr::EffectExpr(e) => match e.effect() {
224 ast::Effect::Label(_) | ast::Effect::Unsafe(_) => {
225 if let Some(e) = e.block_expr().and_then(|b| b.tail_expr()) {
226 for_each_inner_tail(&e, cb);
229 ast::Effect::Async(_) | ast::Effect::Try(_) | ast::Effect::Const(_) => cb(expr),
231 ast::Expr::IfExpr(if_) => {
232 if_.blocks().for_each(|block| for_each_inner_tail(&ast::Expr::BlockExpr(block), cb))
234 ast::Expr::LoopExpr(l) => for_each_break(l, cb),
235 ast::Expr::MatchExpr(m) => {
236 if let Some(arms) = m.match_arm_list() {
237 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_inner_tail(&e, cb));
240 ast::Expr::ArrayExpr(_)
241 | ast::Expr::AwaitExpr(_)
242 | ast::Expr::BinExpr(_)
243 | ast::Expr::BoxExpr(_)
244 | ast::Expr::BreakExpr(_)
245 | ast::Expr::CallExpr(_)
246 | ast::Expr::CastExpr(_)
247 | ast::Expr::ClosureExpr(_)
248 | ast::Expr::ContinueExpr(_)
249 | ast::Expr::FieldExpr(_)
250 | ast::Expr::ForExpr(_)
251 | ast::Expr::IndexExpr(_)
252 | ast::Expr::Literal(_)
253 | ast::Expr::MacroCall(_)
254 | ast::Expr::MacroStmts(_)
255 | ast::Expr::MethodCallExpr(_)
256 | ast::Expr::ParenExpr(_)
257 | ast::Expr::PathExpr(_)
258 | ast::Expr::PrefixExpr(_)
259 | ast::Expr::RangeExpr(_)
260 | ast::Expr::RecordExpr(_)
261 | ast::Expr::RefExpr(_)
262 | ast::Expr::ReturnExpr(_)
263 | ast::Expr::TryExpr(_)
264 | ast::Expr::TupleExpr(_)
265 | ast::Expr::WhileExpr(_)
266 | ast::Expr::YieldExpr(_) => cb(expr),
270 fn for_each_break(l: &ast::LoopExpr, cb: &mut dyn FnMut(&ast::Expr)) {
271 let label = l.label().and_then(|lbl| lbl.lifetime());
273 if let Some(b) = l.loop_body() {
274 let preorder = &mut b.syntax().preorder();
275 let ev_as_expr = |ev| match ev {
276 WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
277 WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
279 let eq_label = |lt: Option<ast::Lifetime>| {
280 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
282 while let Some(node) = preorder.find_map(ev_as_expr) {
284 WalkEvent::Enter(expr) => match &expr {
285 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
288 ast::Expr::EffectExpr(e) if e.label().is_some() => depth += 1,
289 ast::Expr::BreakExpr(b) if depth == 0 || eq_label(b.lifetime()) => {
294 WalkEvent::Leave(expr) => match expr {
295 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
298 ast::Expr::EffectExpr(e) if e.label().is_some() => depth -= 1,
312 fn check(ra_fixture: &str) {
313 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
314 let hls = analysis.highlight_related(pos).unwrap().unwrap();
316 let mut expected = annotations
318 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
319 .collect::<Vec<_>>();
328 ReferenceAccess::Read => "read",
329 ReferenceAccess::Write => "write",
335 .collect::<Vec<_>>();
336 actual.sort_by_key(|(range, _)| range.start());
337 expected.sort_by_key(|(range, _)| range.start());
339 assert_eq!(expected, actual);
343 fn test_hl_module() {
356 fn test_hl_self_in_crate_root() {
365 fn test_hl_self_in_module() {
391 fn test_hl_yield_points() {
402 (async { 0.await }).await
410 fn test_hl_yield_points2() {
413 pub async$0 fn foo() {
421 (async { 0.await }).await
429 fn test_hl_yield_nested_fn() {
448 fn test_hl_yield_nested_async_blocks() {
465 fn test_hl_exit_points() {
484 fn test_hl_exit_points2() {
503 fn test_hl_prefer_ref_over_tail_exit() {
522 fn test_hl_never_call_is_exit_point() {
527 fn never(self) -> ! { loop {} }
532 fn never() -> ! { loop {} }
537 // FIXME sema doesn't give us types for macrocalls
550 fn test_hl_inner_tail_exit_points() {