4 defs::{Definition, NameClass, NameRefClass},
5 helpers::{for_each_break_expr, for_each_tail_expr, pick_best_token},
6 search::{FileReference, ReferenceAccess, SearchScope},
10 ast::{self, LoopBodyOwner},
11 match_ast, AstNode, SyntaxNode, SyntaxToken, TextRange, TextSize, T,
14 use crate::{display::TryToNav, references, NavigationTarget};
16 pub struct HighlightedRange {
18 pub access: Option<ReferenceAccess>,
21 #[derive(Default, Clone)]
22 pub struct HighlightRelatedConfig {
24 pub exit_points: bool,
25 pub break_points: bool,
26 pub yield_points: bool,
29 // Feature: Highlight Related
31 // Highlights constructs related to the thing under the cursor:
32 // - if on an identifier, highlights all references to that identifier in the current file
33 // - if on an `async` or `await token, highlights all yield points for that async context
34 // - if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context
35 // - if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
37 // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor.
38 pub(crate) fn highlight_related(
39 sema: &Semantics<RootDatabase>,
40 config: HighlightRelatedConfig,
41 position: FilePosition,
42 ) -> Option<Vec<HighlightedRange>> {
43 let _p = profile::span("highlight_related");
44 let syntax = sema.parse(position.file_id).syntax().clone();
46 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
47 T![?] => 3, // prefer `?` when the cursor is sandwiched like in `await$0?`
49 kind if kind.is_keyword() => 1,
54 T![?] if config.exit_points && token.parent().and_then(ast::TryExpr::cast).is_some() => {
55 highlight_exit_points(sema, token)
57 T![fn] | T![return] | T![->] if config.exit_points => highlight_exit_points(sema, token),
58 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
59 T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => {
60 highlight_break_points(token)
62 T![break] | T![loop] | T![while] if config.break_points => highlight_break_points(token),
63 _ if config.references => highlight_references(sema, &syntax, position),
68 fn highlight_references(
69 sema: &Semantics<RootDatabase>,
71 FilePosition { offset, file_id }: FilePosition,
72 ) -> Option<Vec<HighlightedRange>> {
73 let defs = find_defs(sema, syntax, offset)?;
78 .set_scope(Some(SearchScope::single_file(file_id)))
85 .map(|FileReference { access, range, .. }| HighlightedRange { range, access });
87 let declarations = defs.iter().flat_map(|def| {
89 &Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
90 Some(NavigationTarget::from_module_to_decl(sema.db, module))
92 def => def.try_to_nav(sema.db),
94 .filter(|decl| decl.file_id == file_id)
96 let range = decl.focus_range?;
97 let access = references::decl_access(&def, syntax, range);
98 Some(HighlightedRange { range, access })
102 Some(declarations.chain(usages).collect())
105 fn highlight_exit_points(
106 sema: &Semantics<RootDatabase>,
108 ) -> Option<Vec<HighlightedRange>> {
110 sema: &Semantics<RootDatabase>,
111 body: Option<ast::Expr>,
112 ) -> Option<Vec<HighlightedRange>> {
113 let mut highlights = Vec::new();
115 body.walk(&mut |expr| match expr {
116 ast::Expr::ReturnExpr(expr) => {
117 if let Some(token) = expr.return_token() {
118 highlights.push(HighlightedRange { access: None, range: token.text_range() });
121 ast::Expr::TryExpr(try_) => {
122 if let Some(token) = try_.question_mark_token() {
123 highlights.push(HighlightedRange { access: None, range: token.text_range() });
126 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
127 if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) {
129 .push(HighlightedRange { access: None, range: expr.syntax().text_range() });
134 let tail = match body {
135 ast::Expr::BlockExpr(b) => b.tail_expr(),
139 if let Some(tail) = tail {
140 for_each_tail_expr(&tail, &mut |tail| {
141 let range = match tail {
142 ast::Expr::BreakExpr(b) => b
144 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
145 _ => tail.syntax().text_range(),
147 highlights.push(HighlightedRange { access: None, range })
152 for anc in token.ancestors() {
155 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
156 ast::ClosureExpr(closure) => hl(sema, closure.body()),
157 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
158 hl(sema, effect.block_expr().map(ast::Expr::BlockExpr))
169 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
171 token: Option<SyntaxToken>,
172 label: Option<ast::Label>,
173 body: Option<ast::BlockExpr>,
174 ) -> Option<Vec<HighlightedRange>> {
175 let mut highlights = Vec::new();
176 let range = cover_range(
177 token.map(|tok| tok.text_range()),
178 label.as_ref().map(|it| it.syntax().text_range()),
180 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
181 for_each_break_expr(label, body, &mut |break_| {
182 let range = cover_range(
183 break_.break_token().map(|it| it.text_range()),
184 break_.lifetime().map(|it| it.syntax().text_range()),
186 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
190 let parent = token.parent()?;
191 let lbl = match_ast! {
193 ast::BreakExpr(b) => b.lifetime(),
194 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
195 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
196 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
197 ast::EffectExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
201 let lbl = lbl.as_ref();
202 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
204 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
208 for anc in token.ancestors().flat_map(ast::Expr::cast) {
210 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
211 hl(l.loop_token(), l.label(), l.loop_body())
213 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
214 hl(f.for_token(), f.label(), f.loop_body())
216 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
217 hl(w.while_token(), w.label(), w.loop_body())
219 ast::Expr::EffectExpr(e) if e.label().is_some() && label_matches(e.label()) => {
220 hl(None, e.label(), e.block_expr())
228 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
230 async_token: Option<SyntaxToken>,
231 body: Option<ast::Expr>,
232 ) -> Option<Vec<HighlightedRange>> {
234 vec![HighlightedRange { access: None, range: async_token?.text_range() }];
235 if let Some(body) = body {
236 body.walk(&mut |expr| {
237 if let ast::Expr::AwaitExpr(expr) = expr {
238 if let Some(token) = expr.await_token() {
240 .push(HighlightedRange { access: None, range: token.text_range() });
247 for anc in token.ancestors() {
250 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
251 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr().map(ast::Expr::BlockExpr)),
252 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
260 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
262 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
263 (Some(range), None) => Some(range),
264 (None, Some(range)) => Some(range),
265 (None, None) => None,
270 sema: &Semantics<RootDatabase>,
273 ) -> Option<Vec<Definition>> {
274 let defs = match sema.find_node_at_offset_with_descend(syntax, offset)? {
275 ast::NameLike::NameRef(name_ref) => match NameRefClass::classify(sema, &name_ref)? {
276 NameRefClass::Definition(def) => vec![def],
277 NameRefClass::FieldShorthand { local_ref, field_ref } => {
278 vec![Definition::Local(local_ref), Definition::Field(field_ref)]
281 ast::NameLike::Name(name) => match NameClass::classify(sema, &name)? {
282 NameClass::Definition(it) | NameClass::ConstReference(it) => vec![it],
283 NameClass::PatFieldShorthand { local_def, field_ref } => {
284 vec![Definition::Local(local_def), Definition::Field(field_ref)]
287 ast::NameLike::Lifetime(lifetime) => NameRefClass::classify_lifetime(sema, &lifetime)
288 .and_then(|class| match class {
289 NameRefClass::Definition(it) => Some(it),
292 .or_else(|| NameClass::classify_lifetime(sema, &lifetime).and_then(NameClass::defined))
293 .map(|it| vec![it])?,
304 fn check(ra_fixture: &str) {
305 let config = HighlightRelatedConfig {
312 check_with_config(ra_fixture, config);
315 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
316 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
318 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or(Vec::default());
320 let mut expected = annotations
322 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
323 .collect::<Vec<_>>();
332 ReferenceAccess::Read => "read",
333 ReferenceAccess::Write => "write",
339 .collect::<Vec<_>>();
340 actual.sort_by_key(|(range, _)| range.start());
341 expected.sort_by_key(|(range, _)| range.start());
343 assert_eq!(expected, actual);
347 fn test_hl_module() {
360 fn test_hl_self_in_crate_root() {
369 fn test_hl_self_in_module() {
396 fn test_hl_yield_points() {
407 (async { 0.await }).await
415 fn test_hl_yield_points2() {
418 pub async$0 fn foo() {
426 (async { 0.await }).await
434 fn test_hl_yield_nested_fn() {
453 fn test_hl_yield_nested_async_blocks() {
470 fn test_hl_exit_points() {
489 fn test_hl_exit_points2() {
508 fn test_hl_exit_points3() {
527 fn test_hl_prefer_ref_over_tail_exit() {
546 fn test_hl_never_call_is_exit_point() {
551 fn never(self) -> ! { loop {} }
556 fn never() -> ! { loop {} }
561 // FIXME sema doesn't give us types for macrocalls
574 fn test_hl_inner_tail_exit_points() {
615 fn test_hl_inner_tail_exit_points_labeled_block() {
636 fn test_hl_break_loop() {
664 fn test_hl_break_loop2() {
691 fn test_hl_break_for() {
695 'outer: for _ in () {
699 'inner: for _ in () {
701 'innermost: for _ in () {
719 fn test_hl_break_while() {
729 'innermost: while true {
747 fn test_hl_break_labeled_block() {
775 fn test_hl_break_unlabeled_loop() {
790 fn test_hl_break_unlabeled_block_in_loop() {
807 fn test_hl_field_shorthand() {
810 struct Struct { field: u32 }
812 fn function(field: u32) {
823 fn test_hl_disabled_ref_local() {
824 let config = HighlightRelatedConfig {
837 check_with_config(ra_fixture, config);
841 fn test_hl_disabled_ref_local_preserved_break() {
842 let config = HighlightRelatedConfig {
859 check_with_config(ra_fixture, config.clone());
873 check_with_config(ra_fixture, config);
877 fn test_hl_disabled_ref_local_preserved_yield() {
878 let config = HighlightRelatedConfig {
893 check_with_config(ra_fixture, config.clone());
905 check_with_config(ra_fixture, config);
909 fn test_hl_disabled_ref_local_preserved_exit() {
910 let config = HighlightRelatedConfig {
929 check_with_config(ra_fixture, config.clone());
945 check_with_config(ra_fixture, config);
949 fn test_hl_disabled_break() {
950 let config = HighlightRelatedConfig {
964 check_with_config(ra_fixture, config);
968 fn test_hl_disabled_yield() {
969 let config = HighlightRelatedConfig {
981 check_with_config(ra_fixture, config);
985 fn test_hl_disabled_exit() {
986 let config = HighlightRelatedConfig {
1002 check_with_config(ra_fixture, config);