3 base_db::{FileId, FilePosition},
4 defs::{Definition, IdentClass},
5 helpers::pick_best_token,
6 search::{FileReference, ReferenceCategory, SearchScope},
7 syntax_helpers::node_ext::{for_each_break_and_continue_expr, for_each_tail_expr, walk_expr},
8 FxHashSet, RootDatabase,
11 ast::{self, HasLoopBody},
13 SyntaxKind::{self, IDENT, INT_NUMBER},
14 SyntaxNode, SyntaxToken, TextRange, T,
17 use crate::{references, NavigationTarget, TryToNav};
19 #[derive(PartialEq, Eq, Hash)]
20 pub struct HighlightedRange {
22 // FIXME: This needs to be more precise. Reference category makes sense only
23 // for references, but we also have defs. And things like exit points are
25 pub category: Option<ReferenceCategory>,
28 #[derive(Default, Clone)]
29 pub struct HighlightRelatedConfig {
31 pub exit_points: bool,
32 pub break_points: bool,
33 pub yield_points: bool,
36 // Feature: Highlight Related
38 // Highlights constructs related to the thing under the cursor:
40 // . if on an identifier, highlights all references to that identifier in the current file
41 // . if on an `async` or `await token, highlights all yield points for that async context
42 // . if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context
43 // . if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
45 // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor.
46 pub(crate) fn highlight_related(
47 sema: &Semantics<RootDatabase>,
48 config: HighlightRelatedConfig,
49 FilePosition { offset, file_id }: FilePosition,
50 ) -> Option<Vec<HighlightedRange>> {
51 let _p = profile::span("highlight_related");
52 let syntax = sema.parse(file_id).syntax().clone();
54 let token = pick_best_token(syntax.token_at_offset(offset), |kind| match kind {
55 T![?] => 4, // prefer `?` when the cursor is sandwiched like in `await$0?`
57 kind if kind.is_keyword() => 2,
58 IDENT | INT_NUMBER => 1,
62 T![?] if config.exit_points && token.parent().and_then(ast::TryExpr::cast).is_some() => {
63 highlight_exit_points(sema, token)
65 T![fn] | T![return] | T![->] if config.exit_points => highlight_exit_points(sema, token),
66 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
67 T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => {
68 highlight_break_points(token)
70 T![break] | T![loop] | T![while] | T![continue] if config.break_points => {
71 highlight_break_points(token)
73 _ if config.references => highlight_references(sema, &syntax, token, file_id),
78 fn highlight_references(
79 sema: &Semantics<RootDatabase>,
83 ) -> Option<Vec<HighlightedRange>> {
84 let defs = find_defs(sema, token);
89 .set_scope(Some(SearchScope::single_file(file_id)))
96 .map(|FileReference { category: access, range, .. }| HighlightedRange {
100 let mut res = FxHashSet::default();
102 let mut def_to_hl_range = |def| {
103 let hl_range = match def {
104 Definition::Module(module) => {
105 Some(NavigationTarget::from_module_to_decl(sema.db, module))
107 def => def.try_to_nav(sema.db),
109 .filter(|decl| decl.file_id == file_id)
110 .and_then(|decl| decl.focus_range)
113 references::decl_mutability(&def, node, range).then(|| ReferenceCategory::Write);
114 HighlightedRange { range, category }
116 if let Some(hl_range) = hl_range {
117 res.insert(hl_range);
122 Definition::Local(local) => local
123 .associated_locals(sema.db)
125 .for_each(|&local| def_to_hl_range(Definition::Local(local))),
126 def => def_to_hl_range(def),
134 Some(res.into_iter().collect())
138 fn highlight_exit_points(
139 sema: &Semantics<RootDatabase>,
141 ) -> Option<Vec<HighlightedRange>> {
143 sema: &Semantics<RootDatabase>,
144 body: Option<ast::Expr>,
145 ) -> Option<Vec<HighlightedRange>> {
146 let mut highlights = Vec::new();
148 walk_expr(&body, &mut |expr| match expr {
149 ast::Expr::ReturnExpr(expr) => {
150 if let Some(token) = expr.return_token() {
151 highlights.push(HighlightedRange { category: None, range: token.text_range() });
154 ast::Expr::TryExpr(try_) => {
155 if let Some(token) = try_.question_mark_token() {
156 highlights.push(HighlightedRange { category: None, range: token.text_range() });
159 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroExpr(_) => {
160 if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) {
161 highlights.push(HighlightedRange {
163 range: expr.syntax().text_range(),
169 let tail = match body {
170 ast::Expr::BlockExpr(b) => b.tail_expr(),
174 if let Some(tail) = tail {
175 for_each_tail_expr(&tail, &mut |tail| {
176 let range = match tail {
177 ast::Expr::BreakExpr(b) => b
179 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
180 _ => tail.syntax().text_range(),
182 highlights.push(HighlightedRange { category: None, range })
187 for anc in token.parent_ancestors() {
190 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
191 ast::ClosureExpr(closure) => hl(sema, closure.body()),
192 ast::BlockExpr(block_expr) => if matches!(block_expr.modifier(), Some(ast::BlockModifier::Async(_) | ast::BlockModifier::Try(_)| ast::BlockModifier::Const(_))) {
193 hl(sema, Some(block_expr.into()))
204 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
206 cursor_token_kind: SyntaxKind,
207 token: Option<SyntaxToken>,
208 label: Option<ast::Label>,
209 body: Option<ast::StmtList>,
210 ) -> Option<Vec<HighlightedRange>> {
211 let mut highlights = Vec::new();
212 let range = cover_range(
213 token.map(|tok| tok.text_range()),
214 label.as_ref().map(|it| it.syntax().text_range()),
216 highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
217 for_each_break_and_continue_expr(label, body, &mut |expr| {
218 let range: Option<TextRange> = match (cursor_token_kind, expr) {
219 (T![for] | T![while] | T![loop] | T![break], ast::Expr::BreakExpr(break_)) => {
221 break_.break_token().map(|it| it.text_range()),
222 break_.lifetime().map(|it| it.syntax().text_range()),
226 T![for] | T![while] | T![loop] | T![continue],
227 ast::Expr::ContinueExpr(continue_),
229 continue_.continue_token().map(|it| it.text_range()),
230 continue_.lifetime().map(|it| it.syntax().text_range()),
234 highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
238 let parent = token.parent()?;
239 let lbl = match_ast! {
241 ast::BreakExpr(b) => b.lifetime(),
242 ast::ContinueExpr(c) => c.lifetime(),
243 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
244 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
245 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
246 ast::BlockExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
250 let lbl = lbl.as_ref();
251 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
253 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
257 let token_kind = token.kind();
258 for anc in token.parent_ancestors().flat_map(ast::Expr::cast) {
260 ast::Expr::LoopExpr(l) if label_matches(l.label()) => hl(
264 l.loop_body().and_then(|it| it.stmt_list()),
266 ast::Expr::ForExpr(f) if label_matches(f.label()) => hl(
270 f.loop_body().and_then(|it| it.stmt_list()),
272 ast::Expr::WhileExpr(w) if label_matches(w.label()) => hl(
276 w.loop_body().and_then(|it| it.stmt_list()),
278 ast::Expr::BlockExpr(e) if e.label().is_some() && label_matches(e.label()) => {
279 hl(token_kind, None, e.label(), e.stmt_list())
287 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
289 async_token: Option<SyntaxToken>,
290 body: Option<ast::Expr>,
291 ) -> Option<Vec<HighlightedRange>> {
293 vec![HighlightedRange { category: None, range: async_token?.text_range() }];
294 if let Some(body) = body {
295 walk_expr(&body, &mut |expr| {
296 if let ast::Expr::AwaitExpr(expr) = expr {
297 if let Some(token) = expr.await_token() {
299 .push(HighlightedRange { category: None, range: token.text_range() });
306 for anc in token.parent_ancestors() {
309 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
310 ast::BlockExpr(block_expr) => {
311 if block_expr.async_token().is_none() {
314 hl(block_expr.async_token(), Some(block_expr.into()))
316 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
324 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
326 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
327 (Some(range), None) => Some(range),
328 (None, Some(range)) => Some(range),
329 (None, None) => None,
333 fn find_defs(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> FxHashSet<Definition> {
334 sema.descend_into_macros(token)
336 .filter_map(|token| IdentClass::classify_token(sema, &token).map(IdentClass::definitions))
348 fn check(ra_fixture: &str) {
349 let config = HighlightRelatedConfig {
356 check_with_config(ra_fixture, config);
360 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
361 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
363 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or_default();
365 let mut expected = annotations
367 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
368 .collect::<Vec<_>>();
375 hl.category.map(|it| {
377 ReferenceCategory::Read => "read",
378 ReferenceCategory::Write => "write",
384 .collect::<Vec<_>>();
385 actual.sort_by_key(|(range, _)| range.start());
386 expected.sort_by_key(|(range, _)| range.start());
388 assert_eq!(expected, actual);
392 fn test_hl_tuple_fields() {
395 struct Tuple(u32, u32);
408 fn test_hl_module() {
421 fn test_hl_self_in_crate_root() {
436 //- /main.rs crate:main deps:lib
439 //- /lib.rs crate:lib
445 fn test_hl_self_in_module() {
472 fn test_hl_local_in_attr() {
475 //- proc_macros: identity
476 #[proc_macros::identity]
488 fn test_multi_macro_usage() {
493 fn $ident() -> $ident { loop {} }
501 let bar: bar = bar();
511 fn $ident() -> $ident { loop {} }
519 let bar: bar$0 = bar();
527 fn test_hl_yield_points() {
538 (async { 0.await }).await
546 fn test_hl_yield_points2() {
549 pub async$0 fn foo() {
557 (async { 0.await }).await
565 fn test_hl_yield_nested_fn() {
584 fn test_hl_yield_nested_async_blocks() {
601 fn test_hl_exit_points() {
620 fn test_hl_exit_points2() {
639 fn test_hl_exit_points3() {
658 fn test_hl_prefer_ref_over_tail_exit() {
677 fn test_hl_never_call_is_exit_point() {
682 fn never(self) -> ! { loop {} }
687 fn never() -> ! { loop {} }
705 fn test_hl_inner_tail_exit_points() {
746 fn test_hl_inner_tail_exit_points_labeled_block() {
767 fn test_hl_break_loop() {
795 fn test_hl_break_loop2() {
822 fn test_hl_break_for() {
826 'outer: for _ in () {
830 'inner: for _ in () {
832 'innermost: for _ in () {
850 fn test_hl_break_for_but_not_continue() {
854 'outer: for _ in () {
859 'inner: for _ in () {
862 'innermost: for _ in () {
885 fn test_hl_continue_for_but_not_break() {
889 'outer: for _ in () {
894 'inner: for _ in () {
897 'innermost: for _ in () {
920 fn test_hl_break_and_continue() {
924 'outer: fo$0r _ in () {
930 'inner: for _ in () {
933 'innermost: for _ in () {
959 fn test_hl_break_while() {
969 'innermost: while true {
987 fn test_hl_break_labeled_block() {
1015 fn test_hl_break_unlabeled_loop() {
1030 fn test_hl_break_unlabeled_block_in_loop() {
1047 fn test_hl_field_shorthand() {
1050 struct Struct { field: u32 }
1052 fn function(field: u32) {
1062 fn test_hl_disabled_ref_local() {
1063 let config = HighlightRelatedConfig {
1082 fn test_hl_disabled_ref_local_preserved_break() {
1083 let config = HighlightRelatedConfig {
1122 fn test_hl_disabled_ref_local_preserved_yield() {
1123 let config = HighlightRelatedConfig {
1158 fn test_hl_disabled_ref_local_preserved_exit() {
1159 let config = HighlightRelatedConfig {
1201 fn test_hl_disabled_break() {
1202 let config = HighlightRelatedConfig {
1204 break_points: false,
1222 fn test_hl_disabled_yield() {
1223 let config = HighlightRelatedConfig {
1227 yield_points: false,
1241 fn test_hl_disabled_exit() {
1242 let config = HighlightRelatedConfig {
1263 fn test_hl_multi_local() {
1315 fn test_hl_trait_impl_methods() {