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 #[derive(Default, Clone)]
22 pub struct HighlightRelatedConfig {
24 pub exit_points: bool,
25 pub break_points: bool,
26 pub yield_points: bool,
29 // Feature: Highlight Related
31 // Highlights constructs related to the thing under the cursor:
32 // - if on an identifier, highlights all references to that identifier in the current file
33 // - if on an `async` or `await token, highlights all yield points for that async context
34 // - if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context
35 // - if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
37 // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor.
38 pub(crate) fn highlight_related(
39 sema: &Semantics<RootDatabase>,
40 config: HighlightRelatedConfig,
41 position: FilePosition,
42 ) -> Option<Vec<HighlightedRange>> {
43 let _p = profile::span("highlight_related");
44 let syntax = sema.parse(position.file_id).syntax().clone();
46 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
47 T![?] => 3, // prefer `?` when the cursor is sandwiched like in `await$0?`
49 kind if kind.is_keyword() => 1,
54 T![fn] | T![return] | T![?] | T![->] if config.exit_points => {
55 highlight_exit_points(sema, token)
57 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
58 T![break] | T![loop] | T![for] | T![while] if config.break_points => {
59 highlight_break_points(token)
61 _ if config.references => highlight_references(sema, &syntax, position),
66 fn highlight_references(
67 sema: &Semantics<RootDatabase>,
69 FilePosition { offset, file_id }: FilePosition,
70 ) -> Option<Vec<HighlightedRange>> {
71 let def = references::find_def(sema, syntax, offset)?;
74 .set_scope(Some(SearchScope::single_file(file_id)))
78 let declaration = match def {
79 Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
80 Some(NavigationTarget::from_module_to_decl(sema.db, module))
82 def => def.try_to_nav(sema.db),
84 .filter(|decl| decl.file_id == file_id)
86 let range = decl.focus_range?;
87 let access = references::decl_access(&def, syntax, range);
88 Some(HighlightedRange { range, access })
91 let file_refs = usages.references.get(&file_id).map_or(&[][..], Vec::as_slice);
92 let mut res = Vec::with_capacity(file_refs.len() + 1);
93 res.extend(declaration);
97 .map(|&FileReference { access, range, .. }| HighlightedRange { range, access }),
102 fn highlight_exit_points(
103 sema: &Semantics<RootDatabase>,
105 ) -> Option<Vec<HighlightedRange>> {
107 sema: &Semantics<RootDatabase>,
108 body: Option<ast::Expr>,
109 ) -> Option<Vec<HighlightedRange>> {
110 let mut highlights = Vec::new();
112 body.walk(&mut |expr| match expr {
113 ast::Expr::ReturnExpr(expr) => {
114 if let Some(token) = expr.return_token() {
115 highlights.push(HighlightedRange { access: None, range: token.text_range() });
118 ast::Expr::TryExpr(try_) => {
119 if let Some(token) = try_.question_mark_token() {
120 highlights.push(HighlightedRange { access: None, range: token.text_range() });
123 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
124 if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) {
126 .push(HighlightedRange { access: None, range: expr.syntax().text_range() });
131 let tail = match body {
132 ast::Expr::BlockExpr(b) => b.tail_expr(),
136 if let Some(tail) = tail {
137 for_each_tail_expr(&tail, &mut |tail| {
138 let range = match tail {
139 ast::Expr::BreakExpr(b) => b
141 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
142 _ => tail.syntax().text_range(),
144 highlights.push(HighlightedRange { access: None, range })
149 for anc in token.ancestors() {
152 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
153 ast::ClosureExpr(closure) => hl(sema, closure.body()),
154 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
155 hl(sema, effect.block_expr().map(ast::Expr::BlockExpr))
166 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
168 token: Option<SyntaxToken>,
169 label: Option<ast::Label>,
170 body: Option<ast::BlockExpr>,
171 ) -> Option<Vec<HighlightedRange>> {
172 let mut highlights = Vec::new();
173 let range = cover_range(
174 token.map(|tok| tok.text_range()),
175 label.as_ref().map(|it| it.syntax().text_range()),
177 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
178 for_each_break_expr(label, body, &mut |break_| {
179 let range = cover_range(
180 break_.break_token().map(|it| it.text_range()),
181 break_.lifetime().map(|it| it.syntax().text_range()),
183 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
187 let parent = token.parent()?;
188 let lbl = match_ast! {
190 ast::BreakExpr(b) => b.lifetime(),
191 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
192 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
193 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
194 ast::EffectExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
198 let lbl = lbl.as_ref();
199 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
201 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
205 for anc in token.ancestors().flat_map(ast::Expr::cast) {
207 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
208 hl(l.loop_token(), l.label(), l.loop_body())
210 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
211 hl(f.for_token(), f.label(), f.loop_body())
213 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
214 hl(w.while_token(), w.label(), w.loop_body())
216 ast::Expr::EffectExpr(e) if e.label().is_some() && label_matches(e.label()) => {
217 hl(None, e.label(), e.block_expr())
225 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
227 async_token: Option<SyntaxToken>,
228 body: Option<ast::Expr>,
229 ) -> Option<Vec<HighlightedRange>> {
231 vec![HighlightedRange { access: None, range: async_token?.text_range() }];
232 if let Some(body) = body {
233 body.walk(&mut |expr| {
234 if let ast::Expr::AwaitExpr(expr) = expr {
235 if let Some(token) = expr.await_token() {
237 .push(HighlightedRange { access: None, range: token.text_range() });
244 for anc in token.ancestors() {
247 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
248 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr().map(ast::Expr::BlockExpr)),
249 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
257 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
259 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
260 (Some(range), None) => Some(range),
261 (None, Some(range)) => Some(range),
262 (None, None) => None,
272 fn check(ra_fixture: &str) {
273 let config = HighlightRelatedConfig {
280 check_with_config(ra_fixture, config);
283 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
284 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
286 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or(Vec::default());
288 let mut expected = annotations
290 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
291 .collect::<Vec<_>>();
300 ReferenceAccess::Read => "read",
301 ReferenceAccess::Write => "write",
307 .collect::<Vec<_>>();
308 actual.sort_by_key(|(range, _)| range.start());
309 expected.sort_by_key(|(range, _)| range.start());
311 assert_eq!(expected, actual);
315 fn test_hl_module() {
328 fn test_hl_self_in_crate_root() {
337 fn test_hl_self_in_module() {
364 fn test_hl_yield_points() {
375 (async { 0.await }).await
383 fn test_hl_yield_points2() {
386 pub async$0 fn foo() {
394 (async { 0.await }).await
402 fn test_hl_yield_nested_fn() {
421 fn test_hl_yield_nested_async_blocks() {
438 fn test_hl_exit_points() {
457 fn test_hl_exit_points2() {
476 fn test_hl_exit_points3() {
495 fn test_hl_prefer_ref_over_tail_exit() {
514 fn test_hl_never_call_is_exit_point() {
519 fn never(self) -> ! { loop {} }
524 fn never() -> ! { loop {} }
529 // FIXME sema doesn't give us types for macrocalls
542 fn test_hl_inner_tail_exit_points() {
583 fn test_hl_inner_tail_exit_points_labeled_block() {
604 fn test_hl_break_loop() {
632 fn test_hl_break_loop2() {
659 fn test_hl_break_for() {
663 'outer: for _ in () {
667 'inner: for _ in () {
669 'innermost: for _ in () {
687 fn test_hl_break_while() {
697 'innermost: while true {
715 fn test_hl_break_labeled_block() {
743 fn test_hl_break_unlabeled_loop() {
758 fn test_hl_break_unlabeled_block_in_loop() {
775 fn test_hl_disabled_ref_local() {
776 let config = HighlightRelatedConfig {
789 check_with_config(ra_fixture, config);
793 fn test_hl_disabled_ref_local_preserved_break() {
794 let config = HighlightRelatedConfig {
811 check_with_config(ra_fixture, config.clone());
825 check_with_config(ra_fixture, config);
829 fn test_hl_disabled_ref_local_preserved_yield() {
830 let config = HighlightRelatedConfig {
845 check_with_config(ra_fixture, config.clone());
857 check_with_config(ra_fixture, config);
861 fn test_hl_disabled_ref_local_preserved_exit() {
862 let config = HighlightRelatedConfig {
881 check_with_config(ra_fixture, config.clone());
897 check_with_config(ra_fixture, config);
901 fn test_hl_disabled_break() {
902 let config = HighlightRelatedConfig {
916 check_with_config(ra_fixture, config);
920 fn test_hl_disabled_yield() {
921 let config = HighlightRelatedConfig {
933 check_with_config(ra_fixture, config);
937 fn test_hl_disabled_exit() {
938 let config = HighlightRelatedConfig {
954 check_with_config(ra_fixture, config);