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)?;
64 .set_scope(Some(SearchScope::single_file(file_id)))
68 let declaration = match def {
69 Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
70 Some(NavigationTarget::from_module_to_decl(sema.db, module))
72 def => def.try_to_nav(sema.db),
74 .filter(|decl| decl.file_id == file_id)
76 let range = decl.focus_range?;
77 let access = references::decl_access(&def, syntax, range);
78 Some(HighlightedRange { range, access })
81 let file_refs = usages.references.get(&file_id).map_or(&[][..], Vec::as_slice);
82 let mut res = Vec::with_capacity(file_refs.len() + 1);
83 res.extend(declaration);
87 .map(|&FileReference { access, range, .. }| HighlightedRange { range, access }),
92 fn highlight_exit_points(
93 sema: &Semantics<RootDatabase>,
95 ) -> Option<Vec<HighlightedRange>> {
97 sema: &Semantics<RootDatabase>,
98 body: Option<ast::Expr>,
99 ) -> Option<Vec<HighlightedRange>> {
100 let mut highlights = Vec::new();
102 body.walk(&mut |expr| match expr {
103 ast::Expr::ReturnExpr(expr) => {
104 if let Some(token) = expr.return_token() {
105 highlights.push(HighlightedRange { access: None, range: token.text_range() });
108 ast::Expr::TryExpr(try_) => {
109 if let Some(token) = try_.question_mark_token() {
110 highlights.push(HighlightedRange { access: None, range: token.text_range() });
113 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
114 if sema.type_of_expr(&expr).map_or(false, |ty| ty.is_never()) {
116 .push(HighlightedRange { access: None, range: expr.syntax().text_range() });
121 let tail = match body {
122 ast::Expr::BlockExpr(b) => b.tail_expr(),
126 if let Some(tail) = tail {
127 for_each_tail_expr(&tail, &mut |tail| {
128 let range = match tail {
129 ast::Expr::BreakExpr(b) => b
131 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
132 _ => tail.syntax().text_range(),
134 highlights.push(HighlightedRange { access: None, range })
139 for anc in token.ancestors() {
142 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
143 ast::ClosureExpr(closure) => hl(sema, closure.body()),
144 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
145 hl(sema, effect.block_expr().map(ast::Expr::BlockExpr))
156 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
158 token: Option<SyntaxToken>,
159 label: Option<ast::Label>,
160 body: Option<ast::BlockExpr>,
161 ) -> Option<Vec<HighlightedRange>> {
162 let mut highlights = Vec::new();
163 let range = cover_range(
164 token.map(|tok| tok.text_range()),
165 label.as_ref().map(|it| it.syntax().text_range()),
167 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
168 for_each_break_expr(label, body, &mut |break_| {
169 let range = cover_range(
170 break_.break_token().map(|it| it.text_range()),
171 break_.lifetime().map(|it| it.syntax().text_range()),
173 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
177 let parent = token.parent()?;
178 let lbl = match_ast! {
180 ast::BreakExpr(b) => b.lifetime(),
181 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
182 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
183 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
184 ast::EffectExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
188 let lbl = lbl.as_ref();
189 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
191 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
195 for anc in token.ancestors().flat_map(ast::Expr::cast) {
197 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
198 hl(l.loop_token(), l.label(), l.loop_body())
200 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
201 hl(f.for_token(), f.label(), f.loop_body())
203 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
204 hl(w.while_token(), w.label(), w.loop_body())
206 ast::Expr::EffectExpr(e) if e.label().is_some() && label_matches(e.label()) => {
207 hl(None, e.label(), e.block_expr())
215 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
217 async_token: Option<SyntaxToken>,
218 body: Option<ast::Expr>,
219 ) -> Option<Vec<HighlightedRange>> {
221 vec![HighlightedRange { access: None, range: async_token?.text_range() }];
222 if let Some(body) = body {
223 body.walk(&mut |expr| {
224 if let ast::Expr::AwaitExpr(expr) = expr {
225 if let Some(token) = expr.await_token() {
227 .push(HighlightedRange { access: None, range: token.text_range() });
234 for anc in token.ancestors() {
237 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
238 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr().map(ast::Expr::BlockExpr)),
239 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
247 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
249 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
250 (Some(range), None) => Some(range),
251 (None, Some(range)) => Some(range),
252 (None, None) => None,
262 fn check(ra_fixture: &str) {
263 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
264 let hls = analysis.highlight_related(pos).unwrap().unwrap();
266 let mut expected = annotations
268 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
269 .collect::<Vec<_>>();
278 ReferenceAccess::Read => "read",
279 ReferenceAccess::Write => "write",
285 .collect::<Vec<_>>();
286 actual.sort_by_key(|(range, _)| range.start());
287 expected.sort_by_key(|(range, _)| range.start());
289 assert_eq!(expected, actual);
293 fn test_hl_module() {
306 fn test_hl_self_in_crate_root() {
315 fn test_hl_self_in_module() {
342 fn test_hl_yield_points() {
353 (async { 0.await }).await
361 fn test_hl_yield_points2() {
364 pub async$0 fn foo() {
372 (async { 0.await }).await
380 fn test_hl_yield_nested_fn() {
399 fn test_hl_yield_nested_async_blocks() {
416 fn test_hl_exit_points() {
435 fn test_hl_exit_points2() {
454 fn test_hl_prefer_ref_over_tail_exit() {
473 fn test_hl_never_call_is_exit_point() {
478 fn never(self) -> ! { loop {} }
483 fn never() -> ! { loop {} }
488 // FIXME sema doesn't give us types for macrocalls
501 fn test_hl_inner_tail_exit_points() {
539 fn test_hl_inner_tail_exit_points_labeled_block() {
560 fn test_hl_break_loop() {
588 fn test_hl_break_loop2() {
615 fn test_hl_break_for() {
619 'outer: for _ in () {
623 'inner: for _ in () {
625 'innermost: for _ in () {
643 fn test_hl_break_while() {
653 'innermost: while true {
671 fn test_hl_break_labeled_block() {
699 fn test_hl_break_unlabeled_loop() {
714 fn test_hl_break_unlabeled_block_in_loop() {