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},
12 match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, TextSize, T,
15 use crate::{display::TryToNav, references, NavigationTarget};
17 #[derive(PartialEq, Eq, Hash)]
18 pub struct HighlightedRange {
20 pub access: Option<ReferenceAccess>,
23 #[derive(Default, Clone)]
24 pub struct HighlightRelatedConfig {
26 pub exit_points: bool,
27 pub break_points: bool,
28 pub yield_points: bool,
31 // Feature: Highlight Related
33 // Highlights constructs related to the thing under the cursor:
34 // - if on an identifier, highlights all references to that identifier in the current file
35 // - if on an `async` or `await token, highlights all yield points for that async context
36 // - if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context
37 // - if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
39 // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor.
40 pub(crate) fn highlight_related(
41 sema: &Semantics<RootDatabase>,
42 config: HighlightRelatedConfig,
43 position: FilePosition,
44 ) -> Option<Vec<HighlightedRange>> {
45 let _p = profile::span("highlight_related");
46 let syntax = sema.parse(position.file_id).syntax().clone();
48 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
49 T![?] => 3, // prefer `?` when the cursor is sandwiched like in `await$0?`
51 kind if kind.is_keyword() => 1,
56 T![?] if config.exit_points && token.parent().and_then(ast::TryExpr::cast).is_some() => {
57 highlight_exit_points(sema, token)
59 T![fn] | T![return] | T![->] if config.exit_points => highlight_exit_points(sema, token),
60 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
61 T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => {
62 highlight_break_points(token)
64 T![break] | T![loop] | T![while] if config.break_points => highlight_break_points(token),
65 _ if config.references => highlight_references(sema, &syntax, position),
70 fn highlight_references(
71 sema: &Semantics<RootDatabase>,
73 FilePosition { offset, file_id }: FilePosition,
74 ) -> Option<Vec<HighlightedRange>> {
75 let defs = find_defs(sema, syntax, offset);
80 .set_scope(Some(SearchScope::single_file(file_id)))
87 .map(|FileReference { access, range, .. }| HighlightedRange { range, access });
89 let declarations = defs.iter().flat_map(|def| {
91 &Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
92 Some(NavigationTarget::from_module_to_decl(sema.db, module))
94 def => def.try_to_nav(sema.db),
96 .filter(|decl| decl.file_id == file_id)
98 let range = decl.focus_range?;
99 let access = references::decl_access(&def, syntax, range);
100 Some(HighlightedRange { range, access })
104 let res: FxHashSet<_> = declarations.chain(usages).collect();
108 Some(res.into_iter().collect())
112 fn highlight_exit_points(
113 sema: &Semantics<RootDatabase>,
115 ) -> Option<Vec<HighlightedRange>> {
117 sema: &Semantics<RootDatabase>,
118 body: Option<ast::Expr>,
119 ) -> Option<Vec<HighlightedRange>> {
120 let mut highlights = Vec::new();
122 body.walk(&mut |expr| match expr {
123 ast::Expr::ReturnExpr(expr) => {
124 if let Some(token) = expr.return_token() {
125 highlights.push(HighlightedRange { access: None, range: token.text_range() });
128 ast::Expr::TryExpr(try_) => {
129 if let Some(token) = try_.question_mark_token() {
130 highlights.push(HighlightedRange { access: None, range: token.text_range() });
133 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
134 if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) {
136 .push(HighlightedRange { access: None, range: expr.syntax().text_range() });
141 let tail = match body {
142 ast::Expr::BlockExpr(b) => b.tail_expr(),
146 if let Some(tail) = tail {
147 for_each_tail_expr(&tail, &mut |tail| {
148 let range = match tail {
149 ast::Expr::BreakExpr(b) => b
151 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
152 _ => tail.syntax().text_range(),
154 highlights.push(HighlightedRange { access: None, range })
159 for anc in token.ancestors() {
162 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
163 ast::ClosureExpr(closure) => hl(sema, closure.body()),
164 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
165 hl(sema, effect.block_expr().map(ast::Expr::BlockExpr))
176 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
178 token: Option<SyntaxToken>,
179 label: Option<ast::Label>,
180 body: Option<ast::BlockExpr>,
181 ) -> Option<Vec<HighlightedRange>> {
182 let mut highlights = Vec::new();
183 let range = cover_range(
184 token.map(|tok| tok.text_range()),
185 label.as_ref().map(|it| it.syntax().text_range()),
187 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
188 for_each_break_expr(label, body, &mut |break_| {
189 let range = cover_range(
190 break_.break_token().map(|it| it.text_range()),
191 break_.lifetime().map(|it| it.syntax().text_range()),
193 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
197 let parent = token.parent()?;
198 let lbl = match_ast! {
200 ast::BreakExpr(b) => b.lifetime(),
201 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
202 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
203 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
204 ast::EffectExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
208 let lbl = lbl.as_ref();
209 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
211 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
215 for anc in token.ancestors().flat_map(ast::Expr::cast) {
217 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
218 hl(l.loop_token(), l.label(), l.loop_body())
220 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
221 hl(f.for_token(), f.label(), f.loop_body())
223 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
224 hl(w.while_token(), w.label(), w.loop_body())
226 ast::Expr::EffectExpr(e) if e.label().is_some() && label_matches(e.label()) => {
227 hl(None, e.label(), e.block_expr())
235 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
237 async_token: Option<SyntaxToken>,
238 body: Option<ast::Expr>,
239 ) -> Option<Vec<HighlightedRange>> {
241 vec![HighlightedRange { access: None, range: async_token?.text_range() }];
242 if let Some(body) = body {
243 body.walk(&mut |expr| {
244 if let ast::Expr::AwaitExpr(expr) = expr {
245 if let Some(token) = expr.await_token() {
247 .push(HighlightedRange { access: None, range: token.text_range() });
254 for anc in token.ancestors() {
257 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
258 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr().map(ast::Expr::BlockExpr)),
259 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
267 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
269 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
270 (Some(range), None) => Some(range),
271 (None, Some(range)) => Some(range),
272 (None, None) => None,
277 sema: &Semantics<RootDatabase>,
280 ) -> FxHashSet<Definition> {
281 sema.find_nodes_at_offset_with_descend(syntax, offset)
282 .flat_map(|name_like| {
283 Some(match name_like {
284 ast::NameLike::NameRef(name_ref) => {
285 match NameRefClass::classify(sema, &name_ref)? {
286 NameRefClass::Definition(def) => vec![def],
287 NameRefClass::FieldShorthand { local_ref, field_ref } => {
288 vec![Definition::Local(local_ref), Definition::Field(field_ref)]
292 ast::NameLike::Name(name) => match NameClass::classify(sema, &name)? {
293 NameClass::Definition(it) | NameClass::ConstReference(it) => vec![it],
294 NameClass::PatFieldShorthand { local_def, field_ref } => {
295 vec![Definition::Local(local_def), Definition::Field(field_ref)]
298 ast::NameLike::Lifetime(lifetime) => {
299 NameRefClass::classify_lifetime(sema, &lifetime)
300 .and_then(|class| match class {
301 NameRefClass::Definition(it) => Some(it),
305 NameClass::classify_lifetime(sema, &lifetime)
306 .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 {} }
427 let bar: bar = bar();
437 fn $ident() -> $ident { loop {} }
445 let bar: bar$0 = bar();
453 fn test_hl_yield_points() {
464 (async { 0.await }).await
472 fn test_hl_yield_points2() {
475 pub async$0 fn foo() {
483 (async { 0.await }).await
491 fn test_hl_yield_nested_fn() {
510 fn test_hl_yield_nested_async_blocks() {
527 fn test_hl_exit_points() {
546 fn test_hl_exit_points2() {
565 fn test_hl_exit_points3() {
584 fn test_hl_prefer_ref_over_tail_exit() {
603 fn test_hl_never_call_is_exit_point() {
608 fn never(self) -> ! { loop {} }
613 fn never() -> ! { loop {} }
618 // FIXME sema doesn't give us types for macrocalls
631 fn test_hl_inner_tail_exit_points() {
672 fn test_hl_inner_tail_exit_points_labeled_block() {
693 fn test_hl_break_loop() {
721 fn test_hl_break_loop2() {
748 fn test_hl_break_for() {
752 'outer: for _ in () {
756 'inner: for _ in () {
758 'innermost: for _ in () {
776 fn test_hl_break_while() {
786 'innermost: while true {
804 fn test_hl_break_labeled_block() {
832 fn test_hl_break_unlabeled_loop() {
847 fn test_hl_break_unlabeled_block_in_loop() {
864 fn test_hl_field_shorthand() {
867 struct Struct { field: u32 }
869 fn function(field: u32) {
879 fn test_hl_disabled_ref_local() {
880 let config = HighlightRelatedConfig {
893 check_with_config(ra_fixture, config);
897 fn test_hl_disabled_ref_local_preserved_break() {
898 let config = HighlightRelatedConfig {
915 check_with_config(ra_fixture, config.clone());
929 check_with_config(ra_fixture, config);
933 fn test_hl_disabled_ref_local_preserved_yield() {
934 let config = HighlightRelatedConfig {
949 check_with_config(ra_fixture, config.clone());
961 check_with_config(ra_fixture, config);
965 fn test_hl_disabled_ref_local_preserved_exit() {
966 let config = HighlightRelatedConfig {
985 check_with_config(ra_fixture, config.clone());
1001 check_with_config(ra_fixture, config);
1005 fn test_hl_disabled_break() {
1006 let config = HighlightRelatedConfig {
1008 break_points: false,
1013 let ra_fixture = r#"
1020 check_with_config(ra_fixture, config);
1024 fn test_hl_disabled_yield() {
1025 let config = HighlightRelatedConfig {
1029 yield_points: false,
1032 let ra_fixture = r#"
1037 check_with_config(ra_fixture, config);
1041 fn test_hl_disabled_exit() {
1042 let config = HighlightRelatedConfig {
1049 let ra_fixture = r#"
1058 check_with_config(ra_fixture, config);