3 base_db::{FileId, FilePosition},
4 defs::{Definition, IdentClass},
6 for_each_break_and_continue_expr, for_each_tail_expr, node_ext::walk_expr, pick_best_token,
8 search::{FileReference, ReferenceCategory, SearchScope},
11 use rustc_hash::FxHashSet;
13 ast::{self, HasLoopBody},
15 SyntaxKind::{self, IDENT, INT_NUMBER},
16 SyntaxNode, SyntaxToken, TextRange, T,
19 use crate::{references, NavigationTarget, TryToNav};
21 #[derive(PartialEq, Eq, Hash)]
22 pub struct HighlightedRange {
24 // FIXME: This needs to be more precise. Reference category makes sense only
25 // for references, but we also have defs. And things like exit points are
27 pub category: Option<ReferenceCategory>,
30 #[derive(Default, Clone)]
31 pub struct HighlightRelatedConfig {
33 pub exit_points: bool,
34 pub break_points: bool,
35 pub yield_points: bool,
38 // Feature: Highlight Related
40 // Highlights constructs related to the thing under the cursor:
41 // - if on an identifier, highlights all references to that identifier in the current file
42 // - if on an `async` or `await token, highlights all yield points for that async context
43 // - if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context
44 // - if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
46 // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor.
47 pub(crate) fn highlight_related(
48 sema: &Semantics<RootDatabase>,
49 config: HighlightRelatedConfig,
50 FilePosition { offset, file_id }: FilePosition,
51 ) -> Option<Vec<HighlightedRange>> {
52 let _p = profile::span("highlight_related");
53 let syntax = sema.parse(file_id).syntax().clone();
55 let token = pick_best_token(syntax.token_at_offset(offset), |kind| match kind {
56 T![?] => 4, // prefer `?` when the cursor is sandwiched like in `await$0?`
58 kind if kind.is_keyword() => 2,
59 IDENT | INT_NUMBER => 1,
63 T![?] if config.exit_points && token.parent().and_then(ast::TryExpr::cast).is_some() => {
64 highlight_exit_points(sema, token)
66 T![fn] | T![return] | T![->] if config.exit_points => highlight_exit_points(sema, token),
67 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
68 T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => {
69 highlight_break_points(token)
71 T![break] | T![loop] | T![while] | T![continue] if config.break_points => {
72 highlight_break_points(token)
74 _ if config.references => highlight_references(sema, &syntax, token, file_id),
79 fn highlight_references(
80 sema: &Semantics<RootDatabase>,
84 ) -> Option<Vec<HighlightedRange>> {
85 let defs = find_defs(sema, token);
90 .set_scope(Some(SearchScope::single_file(file_id)))
97 .map(|FileReference { category: access, range, .. }| HighlightedRange {
102 let declarations = defs.iter().flat_map(|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)
111 let range = decl.focus_range?;
113 references::decl_mutability(&def, node, range).then(|| ReferenceCategory::Write);
114 Some(HighlightedRange { range, category })
118 let res: FxHashSet<_> = declarations.chain(usages).collect();
122 Some(res.into_iter().collect())
126 fn highlight_exit_points(
127 sema: &Semantics<RootDatabase>,
129 ) -> Option<Vec<HighlightedRange>> {
131 sema: &Semantics<RootDatabase>,
132 body: Option<ast::Expr>,
133 ) -> Option<Vec<HighlightedRange>> {
134 let mut highlights = Vec::new();
136 walk_expr(&body, &mut |expr| match expr {
137 ast::Expr::ReturnExpr(expr) => {
138 if let Some(token) = expr.return_token() {
139 highlights.push(HighlightedRange { category: None, range: token.text_range() });
142 ast::Expr::TryExpr(try_) => {
143 if let Some(token) = try_.question_mark_token() {
144 highlights.push(HighlightedRange { category: None, range: token.text_range() });
147 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
148 if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) {
149 highlights.push(HighlightedRange {
151 range: expr.syntax().text_range(),
157 let tail = match body {
158 ast::Expr::BlockExpr(b) => b.tail_expr(),
162 if let Some(tail) = tail {
163 for_each_tail_expr(&tail, &mut |tail| {
164 let range = match tail {
165 ast::Expr::BreakExpr(b) => b
167 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
168 _ => tail.syntax().text_range(),
170 highlights.push(HighlightedRange { category: None, range })
175 for anc in token.ancestors() {
178 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
179 ast::ClosureExpr(closure) => hl(sema, closure.body()),
180 ast::BlockExpr(block_expr) => if matches!(block_expr.modifier(), Some(ast::BlockModifier::Async(_) | ast::BlockModifier::Try(_)| ast::BlockModifier::Const(_))) {
181 hl(sema, Some(block_expr.into()))
192 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
194 cursor_token_kind: SyntaxKind,
195 token: Option<SyntaxToken>,
196 label: Option<ast::Label>,
197 body: Option<ast::StmtList>,
198 ) -> Option<Vec<HighlightedRange>> {
199 let mut highlights = Vec::new();
200 let range = cover_range(
201 token.map(|tok| tok.text_range()),
202 label.as_ref().map(|it| it.syntax().text_range()),
204 highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
205 for_each_break_and_continue_expr(label, body, &mut |expr| {
206 let range: Option<TextRange> = match (cursor_token_kind, expr) {
207 (T![for] | T![while] | T![loop] | T![break], ast::Expr::BreakExpr(break_)) => {
209 break_.break_token().map(|it| it.text_range()),
210 break_.lifetime().map(|it| it.syntax().text_range()),
214 T![for] | T![while] | T![loop] | T![continue],
215 ast::Expr::ContinueExpr(continue_),
217 continue_.continue_token().map(|it| it.text_range()),
218 continue_.lifetime().map(|it| it.syntax().text_range()),
222 highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
226 let parent = token.parent()?;
227 let lbl = match_ast! {
229 ast::BreakExpr(b) => b.lifetime(),
230 ast::ContinueExpr(c) => c.lifetime(),
231 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
232 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
233 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
234 ast::BlockExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
238 let lbl = lbl.as_ref();
239 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
241 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
245 let token_kind = token.kind();
246 for anc in token.ancestors().flat_map(ast::Expr::cast) {
248 ast::Expr::LoopExpr(l) if label_matches(l.label()) => hl(
252 l.loop_body().and_then(|it| it.stmt_list()),
254 ast::Expr::ForExpr(f) if label_matches(f.label()) => hl(
258 f.loop_body().and_then(|it| it.stmt_list()),
260 ast::Expr::WhileExpr(w) if label_matches(w.label()) => hl(
264 w.loop_body().and_then(|it| it.stmt_list()),
266 ast::Expr::BlockExpr(e) if e.label().is_some() && label_matches(e.label()) => {
267 hl(token_kind, None, e.label(), e.stmt_list())
275 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
277 async_token: Option<SyntaxToken>,
278 body: Option<ast::Expr>,
279 ) -> Option<Vec<HighlightedRange>> {
281 vec![HighlightedRange { category: None, range: async_token?.text_range() }];
282 if let Some(body) = body {
283 walk_expr(&body, &mut |expr| {
284 if let ast::Expr::AwaitExpr(expr) = expr {
285 if let Some(token) = expr.await_token() {
287 .push(HighlightedRange { category: None, range: token.text_range() });
294 for anc in token.ancestors() {
297 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
298 ast::BlockExpr(block_expr) => {
299 if block_expr.async_token().is_none() {
302 hl(block_expr.async_token(), Some(block_expr.into()))
304 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
312 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
314 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
315 (Some(range), None) => Some(range),
316 (None, Some(range)) => Some(range),
317 (None, None) => None,
321 fn find_defs(sema: &Semantics<RootDatabase>, token: SyntaxToken) -> FxHashSet<Definition> {
322 sema.descend_into_macros(token)
324 .filter_map(|token| IdentClass::classify_token(sema, &token).map(IdentClass::definitions))
335 fn check(ra_fixture: &str) {
336 let config = HighlightRelatedConfig {
343 check_with_config(ra_fixture, config);
346 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
347 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
349 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or_default();
351 let mut expected = annotations
353 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
354 .collect::<Vec<_>>();
361 hl.category.map(|it| {
363 ReferenceCategory::Read => "read",
364 ReferenceCategory::Write => "write",
370 .collect::<Vec<_>>();
371 actual.sort_by_key(|(range, _)| range.start());
372 expected.sort_by_key(|(range, _)| range.start());
374 assert_eq!(expected, actual);
378 fn test_hl_tuple_fields() {
381 struct Tuple(u32, u32);
394 fn test_hl_module() {
407 fn test_hl_self_in_crate_root() {
422 //- /main.rs crate:main deps:lib
425 //- /lib.rs crate:lib
431 fn test_hl_self_in_module() {
458 fn test_hl_local_in_attr() {
461 //- proc_macros: identity
462 #[proc_macros::identity]
474 fn test_multi_macro_usage() {
479 fn $ident() -> $ident { loop {} }
487 let bar: bar = bar();
497 fn $ident() -> $ident { loop {} }
505 let bar: bar$0 = bar();
513 fn test_hl_yield_points() {
524 (async { 0.await }).await
532 fn test_hl_yield_points2() {
535 pub async$0 fn foo() {
543 (async { 0.await }).await
551 fn test_hl_yield_nested_fn() {
570 fn test_hl_yield_nested_async_blocks() {
587 fn test_hl_exit_points() {
606 fn test_hl_exit_points2() {
625 fn test_hl_exit_points3() {
644 fn test_hl_prefer_ref_over_tail_exit() {
663 fn test_hl_never_call_is_exit_point() {
668 fn never(self) -> ! { loop {} }
673 fn never() -> ! { loop {} }
678 // FIXME sema doesn't give us types for macrocalls
691 fn test_hl_inner_tail_exit_points() {
732 fn test_hl_inner_tail_exit_points_labeled_block() {
753 fn test_hl_break_loop() {
781 fn test_hl_break_loop2() {
808 fn test_hl_break_for() {
812 'outer: for _ in () {
816 'inner: for _ in () {
818 'innermost: for _ in () {
836 fn test_hl_break_for_but_not_continue() {
840 'outer: for _ in () {
845 'inner: for _ in () {
848 'innermost: for _ in () {
871 fn test_hl_continue_for_but_not_break() {
875 'outer: for _ in () {
880 'inner: for _ in () {
883 'innermost: for _ in () {
906 fn test_hl_break_and_continue() {
910 'outer: fo$0r _ in () {
916 'inner: for _ in () {
919 'innermost: for _ in () {
945 fn test_hl_break_while() {
955 'innermost: while true {
973 fn test_hl_break_labeled_block() {
1001 fn test_hl_break_unlabeled_loop() {
1016 fn test_hl_break_unlabeled_block_in_loop() {
1033 fn test_hl_field_shorthand() {
1036 struct Struct { field: u32 }
1038 fn function(field: u32) {
1048 fn test_hl_disabled_ref_local() {
1049 let config = HighlightRelatedConfig {
1056 let ra_fixture = r#"
1062 check_with_config(ra_fixture, config);
1066 fn test_hl_disabled_ref_local_preserved_break() {
1067 let config = HighlightRelatedConfig {
1074 let ra_fixture = r#"
1084 check_with_config(ra_fixture, config.clone());
1086 let ra_fixture = r#"
1098 check_with_config(ra_fixture, config);
1102 fn test_hl_disabled_ref_local_preserved_yield() {
1103 let config = HighlightRelatedConfig {
1110 let ra_fixture = r#"
1118 check_with_config(ra_fixture, config.clone());
1120 let ra_fixture = r#"
1130 check_with_config(ra_fixture, config);
1134 fn test_hl_disabled_ref_local_preserved_exit() {
1135 let config = HighlightRelatedConfig {
1142 let ra_fixture = r#"
1154 check_with_config(ra_fixture, config.clone());
1156 let ra_fixture = r#"
1170 check_with_config(ra_fixture, config);
1174 fn test_hl_disabled_break() {
1175 let config = HighlightRelatedConfig {
1177 break_points: false,
1182 let ra_fixture = r#"
1189 check_with_config(ra_fixture, config);
1193 fn test_hl_disabled_yield() {
1194 let config = HighlightRelatedConfig {
1198 yield_points: false,
1201 let ra_fixture = r#"
1206 check_with_config(ra_fixture, config);
1210 fn test_hl_disabled_exit() {
1211 let config = HighlightRelatedConfig {
1218 let ra_fixture = r#"
1227 check_with_config(ra_fixture, config);