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 rustc_hash::FxHashSet;
11 ast::{self, LoopBodyOwner},
14 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
17 use crate::{display::TryToNav, references, NavigationTarget};
19 #[derive(PartialEq, Eq, Hash)]
20 pub struct HighlightedRange {
22 pub access: Option<ReferenceAccess>,
25 #[derive(Default, Clone)]
26 pub struct HighlightRelatedConfig {
28 pub exit_points: bool,
29 pub break_points: bool,
30 pub yield_points: bool,
33 // Feature: Highlight Related
35 // Highlights constructs related to the thing under the cursor:
36 // - if on an identifier, highlights all references to that identifier in the current file
37 // - if on an `async` or `await token, highlights all yield points for that async context
38 // - if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context
39 // - if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
41 // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor.
42 pub(crate) fn highlight_related(
43 sema: &Semantics<RootDatabase>,
44 config: HighlightRelatedConfig,
45 position: FilePosition,
46 ) -> Option<Vec<HighlightedRange>> {
47 let _p = profile::span("highlight_related");
48 let syntax = sema.parse(position.file_id).syntax().clone();
50 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
51 T![?] => 4, // prefer `?` when the cursor is sandwiched like in `await$0?`
53 kind if kind.is_keyword() => 2,
59 T![?] if config.exit_points && token.parent().and_then(ast::TryExpr::cast).is_some() => {
60 highlight_exit_points(sema, token)
62 T![fn] | T![return] | T![->] if config.exit_points => highlight_exit_points(sema, token),
63 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
64 T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => {
65 highlight_break_points(token)
67 T![break] | T![loop] | T![while] if config.break_points => highlight_break_points(token),
68 _ if config.references => highlight_references(sema, &syntax, position),
73 fn highlight_references(
74 sema: &Semantics<RootDatabase>,
76 FilePosition { offset, file_id }: FilePosition,
77 ) -> Option<Vec<HighlightedRange>> {
78 let defs = find_defs(sema, syntax, offset);
83 .set_scope(Some(SearchScope::single_file(file_id)))
90 .map(|FileReference { access, range, .. }| HighlightedRange { range, access });
92 let declarations = defs.iter().flat_map(|def| {
94 &Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
95 Some(NavigationTarget::from_module_to_decl(sema.db, module))
97 def => def.try_to_nav(sema.db),
99 .filter(|decl| decl.file_id == file_id)
101 let range = decl.focus_range?;
102 let access = references::decl_access(&def, syntax, range);
103 Some(HighlightedRange { range, access })
107 let res: FxHashSet<_> = declarations.chain(usages).collect();
111 Some(res.into_iter().collect())
115 fn highlight_exit_points(
116 sema: &Semantics<RootDatabase>,
118 ) -> Option<Vec<HighlightedRange>> {
120 sema: &Semantics<RootDatabase>,
121 body: Option<ast::Expr>,
122 ) -> Option<Vec<HighlightedRange>> {
123 let mut highlights = Vec::new();
125 body.walk(&mut |expr| match expr {
126 ast::Expr::ReturnExpr(expr) => {
127 if let Some(token) = expr.return_token() {
128 highlights.push(HighlightedRange { access: None, range: token.text_range() });
131 ast::Expr::TryExpr(try_) => {
132 if let Some(token) = try_.question_mark_token() {
133 highlights.push(HighlightedRange { access: None, range: token.text_range() });
136 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
137 if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) {
139 .push(HighlightedRange { access: None, range: expr.syntax().text_range() });
144 let tail = match body {
145 ast::Expr::BlockExpr(b) => b.tail_expr(),
149 if let Some(tail) = tail {
150 for_each_tail_expr(&tail, &mut |tail| {
151 let range = match tail {
152 ast::Expr::BreakExpr(b) => b
154 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
155 _ => tail.syntax().text_range(),
157 highlights.push(HighlightedRange { access: None, range })
162 for anc in token.ancestors() {
165 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
166 ast::ClosureExpr(closure) => hl(sema, closure.body()),
167 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
168 hl(sema, effect.block_expr().map(ast::Expr::BlockExpr))
179 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
181 token: Option<SyntaxToken>,
182 label: Option<ast::Label>,
183 body: Option<ast::BlockExpr>,
184 ) -> Option<Vec<HighlightedRange>> {
185 let mut highlights = Vec::new();
186 let range = cover_range(
187 token.map(|tok| tok.text_range()),
188 label.as_ref().map(|it| it.syntax().text_range()),
190 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
191 for_each_break_expr(label, body, &mut |break_| {
192 let range = cover_range(
193 break_.break_token().map(|it| it.text_range()),
194 break_.lifetime().map(|it| it.syntax().text_range()),
196 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
200 let parent = token.parent()?;
201 let lbl = match_ast! {
203 ast::BreakExpr(b) => b.lifetime(),
204 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
205 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
206 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
207 ast::EffectExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
211 let lbl = lbl.as_ref();
212 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
214 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
218 for anc in token.ancestors().flat_map(ast::Expr::cast) {
220 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
221 hl(l.loop_token(), l.label(), l.loop_body())
223 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
224 hl(f.for_token(), f.label(), f.loop_body())
226 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
227 hl(w.while_token(), w.label(), w.loop_body())
229 ast::Expr::EffectExpr(e) if e.label().is_some() && label_matches(e.label()) => {
230 hl(None, e.label(), e.block_expr())
238 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
240 async_token: Option<SyntaxToken>,
241 body: Option<ast::Expr>,
242 ) -> Option<Vec<HighlightedRange>> {
244 vec![HighlightedRange { access: None, range: async_token?.text_range() }];
245 if let Some(body) = body {
246 body.walk(&mut |expr| {
247 if let ast::Expr::AwaitExpr(expr) = expr {
248 if let Some(token) = expr.await_token() {
250 .push(HighlightedRange { access: None, range: token.text_range() });
257 for anc in token.ancestors() {
260 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
261 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr().map(ast::Expr::BlockExpr)),
262 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
270 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
272 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
273 (Some(range), None) => Some(range),
274 (None, Some(range)) => Some(range),
275 (None, None) => None,
280 sema: &Semantics<RootDatabase>,
283 ) -> FxHashSet<Definition> {
284 sema.find_nodes_at_offset_with_descend(syntax, offset)
285 .flat_map(|name_like| {
286 Some(match name_like {
287 ast::NameLike::NameRef(name_ref) => {
288 match NameRefClass::classify(sema, &name_ref)? {
289 NameRefClass::Definition(def) => vec![def],
290 NameRefClass::FieldShorthand { local_ref, field_ref } => {
291 vec![Definition::Local(local_ref), Definition::Field(field_ref)]
295 ast::NameLike::Name(name) => match NameClass::classify(sema, &name)? {
296 NameClass::Definition(it) | NameClass::ConstReference(it) => vec![it],
297 NameClass::PatFieldShorthand { local_def, field_ref } => {
298 vec![Definition::Local(local_def), Definition::Field(field_ref)]
301 ast::NameLike::Lifetime(lifetime) => {
302 NameRefClass::classify_lifetime(sema, &lifetime)
303 .and_then(|class| match class {
304 NameRefClass::Definition(it) => Some(it),
308 NameClass::classify_lifetime(sema, &lifetime)
309 .and_then(NameClass::defined)
325 fn check(ra_fixture: &str) {
326 let config = HighlightRelatedConfig {
333 check_with_config(ra_fixture, config);
336 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
337 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
339 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or(Vec::default());
341 let mut expected = annotations
343 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
344 .collect::<Vec<_>>();
353 ReferenceAccess::Read => "read",
354 ReferenceAccess::Write => "write",
360 .collect::<Vec<_>>();
361 actual.sort_by_key(|(range, _)| range.start());
362 expected.sort_by_key(|(range, _)| range.start());
364 assert_eq!(expected, actual);
368 fn test_hl_module() {
381 fn test_hl_self_in_crate_root() {
390 fn test_hl_self_in_module() {
417 fn test_multi_macro_usage() {
422 fn $ident() -> $ident { loop {} }
430 let bar: bar = bar();
440 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) {
882 fn test_hl_disabled_ref_local() {
883 let config = HighlightRelatedConfig {
896 check_with_config(ra_fixture, config);
900 fn test_hl_disabled_ref_local_preserved_break() {
901 let config = HighlightRelatedConfig {
918 check_with_config(ra_fixture, config.clone());
932 check_with_config(ra_fixture, config);
936 fn test_hl_disabled_ref_local_preserved_yield() {
937 let config = HighlightRelatedConfig {
952 check_with_config(ra_fixture, config.clone());
964 check_with_config(ra_fixture, config);
968 fn test_hl_disabled_ref_local_preserved_exit() {
969 let config = HighlightRelatedConfig {
988 check_with_config(ra_fixture, config.clone());
1004 check_with_config(ra_fixture, config);
1008 fn test_hl_disabled_break() {
1009 let config = HighlightRelatedConfig {
1011 break_points: false,
1016 let ra_fixture = r#"
1023 check_with_config(ra_fixture, config);
1027 fn test_hl_disabled_yield() {
1028 let config = HighlightRelatedConfig {
1032 yield_points: false,
1035 let ra_fixture = r#"
1040 check_with_config(ra_fixture, config);
1044 fn test_hl_disabled_exit() {
1045 let config = HighlightRelatedConfig {
1052 let ra_fixture = r#"
1061 check_with_config(ra_fixture, config);