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 // - if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
28 pub(crate) fn highlight_related(
29 sema: &Semantics<RootDatabase>,
30 position: FilePosition,
31 ) -> Option<Vec<HighlightedRange>> {
32 let _p = profile::span("highlight_related");
33 let syntax = sema.parse(position.file_id).syntax().clone();
35 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
36 T![?] => 2, // prefer `?` when the cursor is sandwiched like `await$0?`
49 T![return] | T![?] | T![->] => highlight_exit_points(sema, token),
50 T![await] | T![async] => highlight_yield_points(token),
51 T![break] | T![loop] | T![for] | T![while] => highlight_break_points(token),
52 _ => highlight_references(sema, &syntax, position),
56 fn highlight_references(
57 sema: &Semantics<RootDatabase>,
59 FilePosition { offset, file_id }: FilePosition,
60 ) -> Option<Vec<HighlightedRange>> {
61 let def = references::find_def(sema, syntax, offset)?;
62 let usages = def.usages(sema).set_scope(Some(SearchScope::single_file(file_id))).all();
64 let declaration = match def {
65 Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
66 Some(NavigationTarget::from_module_to_decl(sema.db, module))
68 def => def.try_to_nav(sema.db),
70 .filter(|decl| decl.file_id == file_id)
72 let range = decl.focus_range?;
73 let access = references::decl_access(&def, syntax, range);
74 Some(HighlightedRange { range, access })
77 let file_refs = usages.references.get(&file_id).map_or(&[][..], Vec::as_slice);
78 let mut res = Vec::with_capacity(file_refs.len() + 1);
79 res.extend(declaration);
83 .map(|&FileReference { access, range, .. }| HighlightedRange { range, access }),
88 fn highlight_exit_points(
89 sema: &Semantics<RootDatabase>,
91 ) -> Option<Vec<HighlightedRange>> {
93 sema: &Semantics<RootDatabase>,
94 body: Option<ast::Expr>,
95 ) -> Option<Vec<HighlightedRange>> {
96 let mut highlights = Vec::new();
98 walk(&body, &mut |expr| match expr {
99 ast::Expr::ReturnExpr(expr) => {
100 if let Some(token) = expr.return_token() {
101 highlights.push(HighlightedRange { access: None, range: token.text_range() });
104 ast::Expr::TryExpr(try_) => {
105 if let Some(token) = try_.question_mark_token() {
106 highlights.push(HighlightedRange { access: None, range: token.text_range() });
109 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
110 if sema.type_of_expr(&expr).map_or(false, |ty| ty.is_never()) {
112 .push(HighlightedRange { access: None, range: expr.syntax().text_range() });
117 let tail = match body {
118 ast::Expr::BlockExpr(b) => b.tail_expr(),
122 if let Some(tail) = tail {
123 for_each_inner_tail(&tail, &mut |tail| {
124 let range = match tail {
125 ast::Expr::BreakExpr(b) => b
127 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
128 _ => tail.syntax().text_range(),
130 highlights.push(HighlightedRange { access: None, range })
135 for anc in token.ancestors() {
138 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
139 ast::ClosureExpr(closure) => hl(sema, closure.body()),
140 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
141 hl(sema, effect.block_expr().map(ast::Expr::BlockExpr))
152 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
154 token: Option<SyntaxToken>,
155 label: Option<ast::Label>,
156 body: Option<ast::BlockExpr>,
157 ) -> Option<Vec<HighlightedRange>> {
158 let mut highlights = Vec::new();
159 let range = cover_range(
160 token.map(|tok| tok.text_range()),
161 label.as_ref().map(|it| it.syntax().text_range()),
163 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
164 for_each_break(label, body, &mut |break_| {
165 let range = cover_range(
166 break_.break_token().map(|it| it.text_range()),
167 break_.lifetime().map(|it| it.syntax().text_range()),
169 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
173 let parent = token.parent()?;
174 let lbl = match_ast! {
176 ast::BreakExpr(b) => b.lifetime(),
177 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
178 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
179 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
180 ast::EffectExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
184 let lbl = lbl.as_ref();
185 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
187 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
191 for anc in token.ancestors().flat_map(ast::Expr::cast) {
193 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
194 hl(l.loop_token(), l.label(), l.loop_body())
196 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
197 hl(f.for_token(), f.label(), f.loop_body())
199 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
200 hl(w.while_token(), w.label(), w.loop_body())
202 ast::Expr::EffectExpr(e) if e.label().is_some() && label_matches(e.label()) => {
203 hl(None, e.label(), e.block_expr())
211 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
213 async_token: Option<SyntaxToken>,
214 body: Option<ast::Expr>,
215 ) -> Option<Vec<HighlightedRange>> {
216 let mut highlights = Vec::new();
217 highlights.push(HighlightedRange { access: None, range: async_token?.text_range() });
218 if let Some(body) = body {
219 walk(&body, &mut |expr| {
220 if let ast::Expr::AwaitExpr(expr) = expr {
221 if let Some(token) = expr.await_token() {
223 .push(HighlightedRange { access: None, range: token.text_range() });
230 for anc in token.ancestors() {
233 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
234 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr().map(ast::Expr::BlockExpr)),
235 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
243 /// Preorder walk all the expression's child expressions
244 fn walk(expr: &ast::Expr, cb: &mut dyn FnMut(ast::Expr)) {
245 let mut preorder = expr.syntax().preorder();
246 while let Some(event) = preorder.next() {
247 let node = match event {
248 WalkEvent::Enter(node) => node,
249 WalkEvent::Leave(_) => continue,
251 match ast::Stmt::cast(node.clone()) {
252 // recursively walk the initializer, skipping potential const pat expressions
253 // lets statements aren't usually nested too deeply so this is fine to recurse on
254 Some(ast::Stmt::LetStmt(l)) => {
255 if let Some(expr) = l.initializer() {
258 preorder.skip_subtree();
260 // Don't skip subtree since we want to process the expression child next
261 Some(ast::Stmt::ExprStmt(_)) => (),
262 // skip inner items which might have their own expressions
263 Some(ast::Stmt::Item(_)) => preorder.skip_subtree(),
265 if let Some(expr) = ast::Expr::cast(node) {
266 let is_different_context = match &expr {
267 ast::Expr::EffectExpr(effect) => {
270 ast::Effect::Async(_) | ast::Effect::Try(_) | ast::Effect::Const(_)
273 ast::Expr::ClosureExpr(__) => true,
277 if is_different_context {
278 preorder.skip_subtree();
281 preorder.skip_subtree();
288 // FIXME: doesn't account for labeled breaks in labeled blocks
289 fn for_each_inner_tail(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
291 ast::Expr::BlockExpr(b) => {
292 if let Some(e) = b.tail_expr() {
293 for_each_inner_tail(&e, cb);
296 ast::Expr::EffectExpr(e) => match e.effect() {
297 ast::Effect::Label(label) => {
298 for_each_break(Some(label), e.block_expr(), &mut |b| cb(&ast::Expr::BreakExpr(b)));
299 if let Some(b) = e.block_expr() {
300 for_each_inner_tail(&ast::Expr::BlockExpr(b), cb);
303 ast::Effect::Unsafe(_) => {
304 if let Some(e) = e.block_expr().and_then(|b| b.tail_expr()) {
305 for_each_inner_tail(&e, cb);
308 ast::Effect::Async(_) | ast::Effect::Try(_) | ast::Effect::Const(_) => cb(expr),
310 ast::Expr::IfExpr(if_) => {
311 if_.blocks().for_each(|block| for_each_inner_tail(&ast::Expr::BlockExpr(block), cb))
313 ast::Expr::LoopExpr(l) => {
314 for_each_break(l.label(), l.loop_body(), &mut |b| cb(&ast::Expr::BreakExpr(b)))
316 ast::Expr::MatchExpr(m) => {
317 if let Some(arms) = m.match_arm_list() {
318 arms.arms().filter_map(|arm| arm.expr()).for_each(|e| for_each_inner_tail(&e, cb));
321 ast::Expr::ArrayExpr(_)
322 | ast::Expr::AwaitExpr(_)
323 | ast::Expr::BinExpr(_)
324 | ast::Expr::BoxExpr(_)
325 | ast::Expr::BreakExpr(_)
326 | ast::Expr::CallExpr(_)
327 | ast::Expr::CastExpr(_)
328 | ast::Expr::ClosureExpr(_)
329 | ast::Expr::ContinueExpr(_)
330 | ast::Expr::FieldExpr(_)
331 | ast::Expr::ForExpr(_)
332 | ast::Expr::IndexExpr(_)
333 | ast::Expr::Literal(_)
334 | ast::Expr::MacroCall(_)
335 | ast::Expr::MacroStmts(_)
336 | ast::Expr::MethodCallExpr(_)
337 | ast::Expr::ParenExpr(_)
338 | ast::Expr::PathExpr(_)
339 | ast::Expr::PrefixExpr(_)
340 | ast::Expr::RangeExpr(_)
341 | ast::Expr::RecordExpr(_)
342 | ast::Expr::RefExpr(_)
343 | ast::Expr::ReturnExpr(_)
344 | ast::Expr::TryExpr(_)
345 | ast::Expr::TupleExpr(_)
346 | ast::Expr::WhileExpr(_)
347 | ast::Expr::YieldExpr(_) => cb(expr),
352 label: Option<ast::Label>,
353 body: Option<ast::BlockExpr>,
354 cb: &mut dyn FnMut(ast::BreakExpr),
356 let label = label.and_then(|lbl| lbl.lifetime());
358 if let Some(b) = body {
359 let preorder = &mut b.syntax().preorder();
360 let ev_as_expr = |ev| match ev {
361 WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)),
362 WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
364 let eq_label = |lt: Option<ast::Lifetime>| {
365 lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
367 while let Some(node) = preorder.find_map(ev_as_expr) {
369 WalkEvent::Enter(expr) => match expr {
370 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
373 ast::Expr::EffectExpr(e) if e.label().is_some() => depth += 1,
374 ast::Expr::BreakExpr(b) if depth == 0 || eq_label(b.lifetime()) => {
379 WalkEvent::Leave(expr) => match expr {
380 ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
383 ast::Expr::EffectExpr(e) if e.label().is_some() => depth -= 1,
391 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
393 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
394 (Some(range), None) => Some(range),
395 (None, Some(range)) => Some(range),
396 (None, None) => None,
406 fn check(ra_fixture: &str) {
407 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
408 let hls = analysis.highlight_related(pos).unwrap().unwrap();
410 let mut expected = annotations
412 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
413 .collect::<Vec<_>>();
422 ReferenceAccess::Read => "read",
423 ReferenceAccess::Write => "write",
429 .collect::<Vec<_>>();
430 actual.sort_by_key(|(range, _)| range.start());
431 expected.sort_by_key(|(range, _)| range.start());
433 assert_eq!(expected, actual);
437 fn test_hl_module() {
450 fn test_hl_self_in_crate_root() {
459 fn test_hl_self_in_module() {
485 fn test_hl_yield_points() {
496 (async { 0.await }).await
504 fn test_hl_yield_points2() {
507 pub async$0 fn foo() {
515 (async { 0.await }).await
523 fn test_hl_yield_nested_fn() {
542 fn test_hl_yield_nested_async_blocks() {
559 fn test_hl_exit_points() {
578 fn test_hl_exit_points2() {
597 fn test_hl_prefer_ref_over_tail_exit() {
616 fn test_hl_never_call_is_exit_point() {
621 fn never(self) -> ! { loop {} }
626 fn never() -> ! { loop {} }
631 // FIXME sema doesn't give us types for macrocalls
644 fn test_hl_inner_tail_exit_points() {
682 fn test_hl_inner_tail_exit_points_labeled_block() {
703 fn test_hl_break_loop() {
731 fn test_hl_break_for() {
735 'outer: for _ in () {
739 'inner: for _ in () {
741 'innermost: for _ in () {
759 fn test_hl_break_while() {
769 'innermost: while true {
787 fn test_hl_break_labeled_block() {
815 fn test_hl_break_unlabeled_loop() {
830 fn test_hl_break_unlabeled_block_in_loop() {