3 base_db::{FileId, FilePosition},
4 defs::{Definition, IdentClass},
5 helpers::{for_each_break_expr, for_each_tail_expr, node_ext::walk_expr, pick_best_token},
6 search::{FileReference, ReferenceCategory, SearchScope},
9 use rustc_hash::FxHashSet;
11 ast::{self, HasLoopBody},
13 SyntaxKind::{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:
39 // - if on an identifier, highlights all references to that identifier in the current file
40 // - if on an `async` or `await token, highlights all yield points for that async context
41 // - if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context
42 // - if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
44 // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor.
45 pub(crate) fn highlight_related(
46 sema: &Semantics<RootDatabase>,
47 config: HighlightRelatedConfig,
48 FilePosition { offset, file_id }: FilePosition,
49 ) -> Option<Vec<HighlightedRange>> {
50 let _p = profile::span("highlight_related");
51 let syntax = sema.parse(file_id).syntax().clone();
53 let token = pick_best_token(syntax.token_at_offset(offset), |kind| match kind {
54 T![?] => 4, // prefer `?` when the cursor is sandwiched like in `await$0?`
56 kind if kind.is_keyword() => 2,
57 IDENT | INT_NUMBER => 1,
61 T![?] if config.exit_points && token.parent().and_then(ast::TryExpr::cast).is_some() => {
62 highlight_exit_points(sema, token)
64 T![fn] | T![return] | T![->] if config.exit_points => highlight_exit_points(sema, token),
65 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
66 T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => {
67 highlight_break_points(token)
69 T![break] | T![loop] | T![while] if config.break_points => highlight_break_points(token),
70 _ if config.references => highlight_references(sema, &syntax, token, file_id),
75 fn highlight_references(
76 sema: &Semantics<RootDatabase>,
80 ) -> Option<Vec<HighlightedRange>> {
81 let defs = find_defs(sema, token);
86 .set_scope(Some(SearchScope::single_file(file_id)))
93 .map(|FileReference { category: access, range, .. }| HighlightedRange {
98 let declarations = defs.iter().flat_map(|def| {
100 &Definition::Module(module) => {
101 Some(NavigationTarget::from_module_to_decl(sema.db, module))
103 def => def.try_to_nav(sema.db),
105 .filter(|decl| decl.file_id == file_id)
107 let range = decl.focus_range?;
109 references::decl_mutability(&def, node, range).then(|| ReferenceCategory::Write);
110 Some(HighlightedRange { range, category })
114 let res: FxHashSet<_> = declarations.chain(usages).collect();
118 Some(res.into_iter().collect())
122 fn highlight_exit_points(
123 sema: &Semantics<RootDatabase>,
125 ) -> Option<Vec<HighlightedRange>> {
127 sema: &Semantics<RootDatabase>,
128 body: Option<ast::Expr>,
129 ) -> Option<Vec<HighlightedRange>> {
130 let mut highlights = Vec::new();
132 walk_expr(&body, &mut |expr| match expr {
133 ast::Expr::ReturnExpr(expr) => {
134 if let Some(token) = expr.return_token() {
135 highlights.push(HighlightedRange { category: None, range: token.text_range() });
138 ast::Expr::TryExpr(try_) => {
139 if let Some(token) = try_.question_mark_token() {
140 highlights.push(HighlightedRange { category: None, range: token.text_range() });
143 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
144 if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) {
145 highlights.push(HighlightedRange {
147 range: expr.syntax().text_range(),
153 let tail = match body {
154 ast::Expr::BlockExpr(b) => b.tail_expr(),
158 if let Some(tail) = tail {
159 for_each_tail_expr(&tail, &mut |tail| {
160 let range = match tail {
161 ast::Expr::BreakExpr(b) => b
163 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
164 _ => tail.syntax().text_range(),
166 highlights.push(HighlightedRange { category: None, range })
171 for anc in token.ancestors() {
174 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
175 ast::ClosureExpr(closure) => hl(sema, closure.body()),
176 ast::BlockExpr(block_expr) => if matches!(block_expr.modifier(), Some(ast::BlockModifier::Async(_) | ast::BlockModifier::Try(_)| ast::BlockModifier::Const(_))) {
177 hl(sema, Some(block_expr.into()))
188 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
190 token: Option<SyntaxToken>,
191 label: Option<ast::Label>,
192 body: Option<ast::StmtList>,
193 ) -> Option<Vec<HighlightedRange>> {
194 let mut highlights = Vec::new();
195 let range = cover_range(
196 token.map(|tok| tok.text_range()),
197 label.as_ref().map(|it| it.syntax().text_range()),
199 highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
200 for_each_break_expr(label, body, &mut |break_| {
201 let range = cover_range(
202 break_.break_token().map(|it| it.text_range()),
203 break_.lifetime().map(|it| it.syntax().text_range()),
205 highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
209 let parent = token.parent()?;
210 let lbl = match_ast! {
212 ast::BreakExpr(b) => b.lifetime(),
213 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
214 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
215 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
216 ast::BlockExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
220 let lbl = lbl.as_ref();
221 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
223 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
227 for anc in token.ancestors().flat_map(ast::Expr::cast) {
229 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
230 hl(l.loop_token(), l.label(), l.loop_body().and_then(|it| it.stmt_list()))
232 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
233 hl(f.for_token(), f.label(), f.loop_body().and_then(|it| it.stmt_list()))
235 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
236 hl(w.while_token(), w.label(), w.loop_body().and_then(|it| it.stmt_list()))
238 ast::Expr::BlockExpr(e) if e.label().is_some() && label_matches(e.label()) => {
239 hl(None, e.label(), e.stmt_list())
247 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
249 async_token: Option<SyntaxToken>,
250 body: Option<ast::Expr>,
251 ) -> Option<Vec<HighlightedRange>> {
253 vec![HighlightedRange { category: None, range: async_token?.text_range() }];
254 if let Some(body) = body {
255 walk_expr(&body, &mut |expr| {
256 if let ast::Expr::AwaitExpr(expr) = expr {
257 if let Some(token) = expr.await_token() {
259 .push(HighlightedRange { category: None, range: token.text_range() });
266 for anc in token.ancestors() {
269 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
270 ast::BlockExpr(block_expr) => {
271 if block_expr.async_token().is_none() {
274 hl(block_expr.async_token(), Some(block_expr.into()))
276 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
284 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
286 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
287 (Some(range), None) => Some(range),
288 (None, Some(range)) => Some(range),
289 (None, None) => None,
293 fn find_defs(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> FxHashSet<Definition> {
294 sema.descend_into_macros(token)
296 .filter_map(|token| IdentClass::classify_token(sema, &token).map(IdentClass::definitions))
307 fn check(ra_fixture: &str) {
308 let config = HighlightRelatedConfig {
315 check_with_config(ra_fixture, config);
318 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
319 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
321 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or_default();
323 let mut expected = annotations
325 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
326 .collect::<Vec<_>>();
333 hl.category.map(|it| {
335 ReferenceCategory::Read => "read",
336 ReferenceCategory::Write => "write",
342 .collect::<Vec<_>>();
343 actual.sort_by_key(|(range, _)| range.start());
344 expected.sort_by_key(|(range, _)| range.start());
346 assert_eq!(expected, actual);
350 fn test_hl_tuple_fields() {
353 struct Tuple(u32, u32);
366 fn test_hl_module() {
379 fn test_hl_self_in_crate_root() {
394 //- /main.rs crate:main deps:lib
397 //- /lib.rs crate:lib
403 fn test_hl_self_in_module() {
430 fn test_hl_local_in_attr() {
433 //- proc_macros: identity
434 #[proc_macros::identity]
446 fn test_multi_macro_usage() {
451 fn $ident() -> $ident { loop {} }
459 let bar: bar = bar();
469 fn $ident() -> $ident { loop {} }
477 let bar: bar$0 = bar();
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_exit_points3() {
616 fn test_hl_prefer_ref_over_tail_exit() {
635 fn test_hl_never_call_is_exit_point() {
640 fn never(self) -> ! { loop {} }
645 fn never() -> ! { loop {} }
650 // FIXME sema doesn't give us types for macrocalls
663 fn test_hl_inner_tail_exit_points() {
704 fn test_hl_inner_tail_exit_points_labeled_block() {
725 fn test_hl_break_loop() {
753 fn test_hl_break_loop2() {
780 fn test_hl_break_for() {
784 'outer: for _ in () {
788 'inner: for _ in () {
790 'innermost: for _ in () {
808 fn test_hl_break_while() {
818 'innermost: while true {
836 fn test_hl_break_labeled_block() {
864 fn test_hl_break_unlabeled_loop() {
879 fn test_hl_break_unlabeled_block_in_loop() {
896 fn test_hl_field_shorthand() {
899 struct Struct { field: u32 }
901 fn function(field: u32) {
911 fn test_hl_disabled_ref_local() {
912 let config = HighlightRelatedConfig {
925 check_with_config(ra_fixture, config);
929 fn test_hl_disabled_ref_local_preserved_break() {
930 let config = HighlightRelatedConfig {
947 check_with_config(ra_fixture, config.clone());
961 check_with_config(ra_fixture, config);
965 fn test_hl_disabled_ref_local_preserved_yield() {
966 let config = HighlightRelatedConfig {
981 check_with_config(ra_fixture, config.clone());
993 check_with_config(ra_fixture, config);
997 fn test_hl_disabled_ref_local_preserved_exit() {
998 let config = HighlightRelatedConfig {
1005 let ra_fixture = r#"
1017 check_with_config(ra_fixture, config.clone());
1019 let ra_fixture = r#"
1033 check_with_config(ra_fixture, config);
1037 fn test_hl_disabled_break() {
1038 let config = HighlightRelatedConfig {
1040 break_points: false,
1045 let ra_fixture = r#"
1052 check_with_config(ra_fixture, config);
1056 fn test_hl_disabled_yield() {
1057 let config = HighlightRelatedConfig {
1061 yield_points: false,
1064 let ra_fixture = r#"
1069 check_with_config(ra_fixture, config);
1073 fn test_hl_disabled_exit() {
1074 let config = HighlightRelatedConfig {
1081 let ra_fixture = r#"
1090 check_with_config(ra_fixture, config);