4 defs::{Definition, NameClass, NameRefClass},
5 helpers::{for_each_break_expr, for_each_tail_expr, pick_best_token},
6 search::{FileReference, ReferenceAccess, SearchScope},
9 use itertools::Itertools;
11 ast::{self, LoopBodyOwner},
12 match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, TextSize, T,
15 use crate::{display::TryToNav, references, NavigationTarget};
17 pub struct HighlightedRange {
19 pub access: Option<ReferenceAccess>,
22 #[derive(Default, Clone)]
23 pub struct HighlightRelatedConfig {
25 pub exit_points: bool,
26 pub break_points: bool,
27 pub yield_points: bool,
30 // Feature: Highlight Related
32 // Highlights constructs related to the thing under the cursor:
33 // - if on an identifier, highlights all references to that identifier in the current file
34 // - if on an `async` or `await token, highlights all yield points for that async context
35 // - if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context
36 // - if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
38 // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor.
39 pub(crate) fn highlight_related(
40 sema: &Semantics<RootDatabase>,
41 config: HighlightRelatedConfig,
42 position: FilePosition,
43 ) -> Option<Vec<HighlightedRange>> {
44 let _p = profile::span("highlight_related");
45 let syntax = sema.parse(position.file_id).syntax().clone();
47 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
48 T![?] => 3, // prefer `?` when the cursor is sandwiched like in `await$0?`
50 kind if kind.is_keyword() => 1,
55 T![?] if config.exit_points && token.parent().and_then(ast::TryExpr::cast).is_some() => {
56 highlight_exit_points(sema, token)
58 T![fn] | T![return] | T![->] if config.exit_points => highlight_exit_points(sema, token),
59 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
60 T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => {
61 highlight_break_points(token)
63 T![break] | T![loop] | T![while] if config.break_points => highlight_break_points(token),
64 _ if config.references => highlight_references(sema, &syntax, position),
69 fn highlight_references(
70 sema: &Semantics<RootDatabase>,
72 FilePosition { offset, file_id }: FilePosition,
73 ) -> Option<Vec<HighlightedRange>> {
74 let defs = find_defs(sema, syntax, offset);
79 .set_scope(Some(SearchScope::single_file(file_id)))
86 .map(|FileReference { access, range, .. }| HighlightedRange { range, access });
88 let declarations = defs.iter().flat_map(|def| {
90 &Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
91 Some(NavigationTarget::from_module_to_decl(sema.db, module))
93 def => def.try_to_nav(sema.db),
95 .filter(|decl| decl.file_id == file_id)
97 let range = decl.focus_range?;
98 let access = references::decl_access(&def, syntax, range);
99 Some(HighlightedRange { range, access })
103 let res: Vec<_> = declarations.chain(usages).collect();
111 fn highlight_exit_points(
112 sema: &Semantics<RootDatabase>,
114 ) -> Option<Vec<HighlightedRange>> {
116 sema: &Semantics<RootDatabase>,
117 body: Option<ast::Expr>,
118 ) -> Option<Vec<HighlightedRange>> {
119 let mut highlights = Vec::new();
121 body.walk(&mut |expr| match expr {
122 ast::Expr::ReturnExpr(expr) => {
123 if let Some(token) = expr.return_token() {
124 highlights.push(HighlightedRange { access: None, range: token.text_range() });
127 ast::Expr::TryExpr(try_) => {
128 if let Some(token) = try_.question_mark_token() {
129 highlights.push(HighlightedRange { access: None, range: token.text_range() });
132 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
133 if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) {
135 .push(HighlightedRange { access: None, range: expr.syntax().text_range() });
140 let tail = match body {
141 ast::Expr::BlockExpr(b) => b.tail_expr(),
145 if let Some(tail) = tail {
146 for_each_tail_expr(&tail, &mut |tail| {
147 let range = match tail {
148 ast::Expr::BreakExpr(b) => b
150 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
151 _ => tail.syntax().text_range(),
153 highlights.push(HighlightedRange { access: None, range })
158 for anc in token.ancestors() {
161 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
162 ast::ClosureExpr(closure) => hl(sema, closure.body()),
163 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
164 hl(sema, effect.block_expr().map(ast::Expr::BlockExpr))
175 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
177 token: Option<SyntaxToken>,
178 label: Option<ast::Label>,
179 body: Option<ast::BlockExpr>,
180 ) -> Option<Vec<HighlightedRange>> {
181 let mut highlights = Vec::new();
182 let range = cover_range(
183 token.map(|tok| tok.text_range()),
184 label.as_ref().map(|it| it.syntax().text_range()),
186 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
187 for_each_break_expr(label, body, &mut |break_| {
188 let range = cover_range(
189 break_.break_token().map(|it| it.text_range()),
190 break_.lifetime().map(|it| it.syntax().text_range()),
192 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
196 let parent = token.parent()?;
197 let lbl = match_ast! {
199 ast::BreakExpr(b) => b.lifetime(),
200 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
201 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
202 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
203 ast::EffectExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
207 let lbl = lbl.as_ref();
208 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
210 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
214 for anc in token.ancestors().flat_map(ast::Expr::cast) {
216 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
217 hl(l.loop_token(), l.label(), l.loop_body())
219 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
220 hl(f.for_token(), f.label(), f.loop_body())
222 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
223 hl(w.while_token(), w.label(), w.loop_body())
225 ast::Expr::EffectExpr(e) if e.label().is_some() && label_matches(e.label()) => {
226 hl(None, e.label(), e.block_expr())
234 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
236 async_token: Option<SyntaxToken>,
237 body: Option<ast::Expr>,
238 ) -> Option<Vec<HighlightedRange>> {
240 vec![HighlightedRange { access: None, range: async_token?.text_range() }];
241 if let Some(body) = body {
242 body.walk(&mut |expr| {
243 if let ast::Expr::AwaitExpr(expr) = expr {
244 if let Some(token) = expr.await_token() {
246 .push(HighlightedRange { access: None, range: token.text_range() });
253 for anc in token.ancestors() {
256 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
257 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr().map(ast::Expr::BlockExpr)),
258 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
266 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
268 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
269 (Some(range), None) => Some(range),
270 (None, Some(range)) => Some(range),
271 (None, None) => None,
276 sema: &Semantics<RootDatabase>,
279 ) -> Vec<Definition> {
280 sema.find_nodes_at_offset_with_descend(syntax, offset)
281 .flat_map(|name_like| {
282 Some(match name_like {
283 ast::NameLike::NameRef(name_ref) => {
284 match NameRefClass::classify(sema, &name_ref)? {
285 NameRefClass::Definition(def) => vec![def],
286 NameRefClass::FieldShorthand { local_ref, field_ref } => {
287 vec![Definition::Local(local_ref), Definition::Field(field_ref)]
291 ast::NameLike::Name(name) => match NameClass::classify(sema, &name)? {
292 NameClass::Definition(it) | NameClass::ConstReference(it) => vec![it],
293 NameClass::PatFieldShorthand { local_def, field_ref } => {
294 vec![Definition::Local(local_def), Definition::Field(field_ref)]
297 ast::NameLike::Lifetime(lifetime) => {
298 NameRefClass::classify_lifetime(sema, &lifetime)
299 .and_then(|class| match class {
300 NameRefClass::Definition(it) => Some(it),
304 NameClass::classify_lifetime(sema, &lifetime)
305 .and_then(NameClass::defined)
322 fn check(ra_fixture: &str) {
323 let config = HighlightRelatedConfig {
330 check_with_config(ra_fixture, config);
333 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
334 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
336 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or(Vec::default());
338 let mut expected = annotations
340 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
341 .collect::<Vec<_>>();
350 ReferenceAccess::Read => "read",
351 ReferenceAccess::Write => "write",
357 .collect::<Vec<_>>();
358 actual.sort_by_key(|(range, _)| range.start());
359 expected.sort_by_key(|(range, _)| range.start());
361 assert_eq!(expected, actual);
365 fn test_hl_module() {
378 fn test_hl_self_in_crate_root() {
387 fn test_hl_self_in_module() {
414 fn test_multi_macro_usage() {
419 fn $ident() -> $ident { loop {} }
429 let bar: bar = bar();
439 fn $ident() -> $ident { loop {} }
448 let bar: bar$0 = bar();
456 fn test_hl_yield_points() {
467 (async { 0.await }).await
475 fn test_hl_yield_points2() {
478 pub async$0 fn foo() {
486 (async { 0.await }).await
494 fn test_hl_yield_nested_fn() {
513 fn test_hl_yield_nested_async_blocks() {
530 fn test_hl_exit_points() {
549 fn test_hl_exit_points2() {
568 fn test_hl_exit_points3() {
587 fn test_hl_prefer_ref_over_tail_exit() {
606 fn test_hl_never_call_is_exit_point() {
611 fn never(self) -> ! { loop {} }
616 fn never() -> ! { loop {} }
621 // FIXME sema doesn't give us types for macrocalls
634 fn test_hl_inner_tail_exit_points() {
675 fn test_hl_inner_tail_exit_points_labeled_block() {
696 fn test_hl_break_loop() {
724 fn test_hl_break_loop2() {
751 fn test_hl_break_for() {
755 'outer: for _ in () {
759 'inner: for _ in () {
761 'innermost: for _ in () {
779 fn test_hl_break_while() {
789 'innermost: while true {
807 fn test_hl_break_labeled_block() {
835 fn test_hl_break_unlabeled_loop() {
850 fn test_hl_break_unlabeled_block_in_loop() {
867 fn test_hl_field_shorthand() {
870 struct Struct { field: u32 }
872 fn function(field: u32) {
883 fn test_hl_disabled_ref_local() {
884 let config = HighlightRelatedConfig {
897 check_with_config(ra_fixture, config);
901 fn test_hl_disabled_ref_local_preserved_break() {
902 let config = HighlightRelatedConfig {
919 check_with_config(ra_fixture, config.clone());
933 check_with_config(ra_fixture, config);
937 fn test_hl_disabled_ref_local_preserved_yield() {
938 let config = HighlightRelatedConfig {
953 check_with_config(ra_fixture, config.clone());
965 check_with_config(ra_fixture, config);
969 fn test_hl_disabled_ref_local_preserved_exit() {
970 let config = HighlightRelatedConfig {
989 check_with_config(ra_fixture, config.clone());
1005 check_with_config(ra_fixture, config);
1009 fn test_hl_disabled_break() {
1010 let config = HighlightRelatedConfig {
1012 break_points: false,
1017 let ra_fixture = r#"
1024 check_with_config(ra_fixture, config);
1028 fn test_hl_disabled_yield() {
1029 let config = HighlightRelatedConfig {
1033 yield_points: false,
1036 let ra_fixture = r#"
1041 check_with_config(ra_fixture, config);
1045 fn test_hl_disabled_exit() {
1046 let config = HighlightRelatedConfig {
1053 let ra_fixture = r#"
1062 check_with_config(ra_fixture, config);