5 helpers::{for_each_break_expr, for_each_tail_expr, pick_best_token},
6 search::{FileReference, ReferenceAccess, SearchScope},
10 ast::{self, LoopBodyOwner},
11 match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, 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 body.walk(&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_tail_expr(&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_expr(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 body.walk(&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 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
245 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
246 (Some(range), None) => Some(range),
247 (None, Some(range)) => Some(range),
248 (None, None) => None,
258 fn check(ra_fixture: &str) {
259 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
260 let hls = analysis.highlight_related(pos).unwrap().unwrap();
262 let mut expected = annotations
264 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
265 .collect::<Vec<_>>();
274 ReferenceAccess::Read => "read",
275 ReferenceAccess::Write => "write",
281 .collect::<Vec<_>>();
282 actual.sort_by_key(|(range, _)| range.start());
283 expected.sort_by_key(|(range, _)| range.start());
285 assert_eq!(expected, actual);
289 fn test_hl_module() {
302 fn test_hl_self_in_crate_root() {
311 fn test_hl_self_in_module() {
337 fn test_hl_yield_points() {
348 (async { 0.await }).await
356 fn test_hl_yield_points2() {
359 pub async$0 fn foo() {
367 (async { 0.await }).await
375 fn test_hl_yield_nested_fn() {
394 fn test_hl_yield_nested_async_blocks() {
411 fn test_hl_exit_points() {
430 fn test_hl_exit_points2() {
449 fn test_hl_prefer_ref_over_tail_exit() {
468 fn test_hl_never_call_is_exit_point() {
473 fn never(self) -> ! { loop {} }
478 fn never() -> ! { loop {} }
483 // FIXME sema doesn't give us types for macrocalls
496 fn test_hl_inner_tail_exit_points() {
534 fn test_hl_inner_tail_exit_points_labeled_block() {
555 fn test_hl_break_loop() {
583 fn test_hl_break_loop2() {
610 fn test_hl_break_for() {
614 'outer: for _ in () {
618 'inner: for _ in () {
620 'innermost: for _ in () {
638 fn test_hl_break_while() {
648 'innermost: while true {
666 fn test_hl_break_labeled_block() {
694 fn test_hl_break_unlabeled_loop() {
709 fn test_hl_break_unlabeled_block_in_loop() {