4 defs::{Definition, NameClass, NameRefClass},
5 helpers::{for_each_break_expr, for_each_tail_expr, node_ext::walk_expr, pick_best_token},
6 search::{FileReference, ReferenceCategory, SearchScope},
9 use rustc_hash::FxHashSet;
11 ast::{self, HasLoopBody},
14 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
17 use crate::{display::TryToNav, references, NavigationTarget};
19 #[derive(PartialEq, Eq, Hash)]
20 pub struct HighlightedRange {
22 // FIXME: This needs to be more precise. Reference category makes sense only
23 // for references, but we also have defs. And things like exit points are
25 pub category: Option<ReferenceCategory>,
28 #[derive(Default, Clone)]
29 pub struct HighlightRelatedConfig {
31 pub exit_points: bool,
32 pub break_points: bool,
33 pub yield_points: bool,
36 // Feature: Highlight Related
38 // Highlights constructs related to the thing under the cursor:
39 // - if on an identifier, highlights all references to that identifier in the current file
40 // - if on an `async` or `await token, highlights all yield points for that async context
41 // - if on a `return` or `fn` keyword, `?` character or `->` return type arrow, highlights all exit points for that context
42 // - if on a `break`, `loop`, `while` or `for` token, highlights all break points for that loop or block context
44 // Note: `?` and `->` do not currently trigger this behavior in the VSCode editor.
45 pub(crate) fn highlight_related(
46 sema: &Semantics<RootDatabase>,
47 config: HighlightRelatedConfig,
48 position: FilePosition,
49 ) -> Option<Vec<HighlightedRange>> {
50 let _p = profile::span("highlight_related");
51 let syntax = sema.parse(position.file_id).syntax().clone();
53 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
54 T![?] => 4, // prefer `?` when the cursor is sandwiched like in `await$0?`
56 kind if kind.is_keyword() => 2,
62 T![?] if config.exit_points && token.parent().and_then(ast::TryExpr::cast).is_some() => {
63 highlight_exit_points(sema, token)
65 T![fn] | T![return] | T![->] if config.exit_points => highlight_exit_points(sema, token),
66 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
67 T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => {
68 highlight_break_points(token)
70 T![break] | T![loop] | T![while] if config.break_points => highlight_break_points(token),
71 _ if config.references => highlight_references(sema, &syntax, position),
76 fn highlight_references(
77 sema: &Semantics<RootDatabase>,
79 FilePosition { offset, file_id }: FilePosition,
80 ) -> Option<Vec<HighlightedRange>> {
81 let defs = find_defs(sema, syntax, offset);
86 .set_scope(Some(SearchScope::single_file(file_id)))
93 .map(|FileReference { category: access, range, .. }| HighlightedRange {
98 let declarations = defs.iter().flat_map(|def| {
100 &Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
101 Some(NavigationTarget::from_module_to_decl(sema.db, module))
103 def => def.try_to_nav(sema.db),
105 .filter(|decl| decl.file_id == file_id)
107 let range = decl.focus_range?;
108 let category = if references::decl_mutability(&def, syntax, range) {
109 Some(ReferenceCategory::Write)
113 Some(HighlightedRange { range, category })
117 let res: FxHashSet<_> = declarations.chain(usages).collect();
121 Some(res.into_iter().collect())
125 fn highlight_exit_points(
126 sema: &Semantics<RootDatabase>,
128 ) -> Option<Vec<HighlightedRange>> {
130 sema: &Semantics<RootDatabase>,
131 body: Option<ast::Expr>,
132 ) -> Option<Vec<HighlightedRange>> {
133 let mut highlights = Vec::new();
135 walk_expr(&body, &mut |expr| match expr {
136 ast::Expr::ReturnExpr(expr) => {
137 if let Some(token) = expr.return_token() {
138 highlights.push(HighlightedRange { category: None, range: token.text_range() });
141 ast::Expr::TryExpr(try_) => {
142 if let Some(token) = try_.question_mark_token() {
143 highlights.push(HighlightedRange { category: None, range: token.text_range() });
146 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
147 if sema.type_of_expr(&expr).map_or(false, |ty| ty.original.is_never()) {
148 highlights.push(HighlightedRange {
150 range: expr.syntax().text_range(),
156 let tail = match body {
157 ast::Expr::BlockExpr(b) => b.tail_expr(),
161 if let Some(tail) = tail {
162 for_each_tail_expr(&tail, &mut |tail| {
163 let range = match tail {
164 ast::Expr::BreakExpr(b) => b
166 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
167 _ => tail.syntax().text_range(),
169 highlights.push(HighlightedRange { category: None, range })
174 for anc in token.ancestors() {
177 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
178 ast::ClosureExpr(closure) => hl(sema, closure.body()),
179 ast::BlockExpr(block_expr) => if matches!(block_expr.modifier(), Some(ast::BlockModifier::Async(_) | ast::BlockModifier::Try(_)| ast::BlockModifier::Const(_))) {
180 hl(sema, Some(block_expr.into()))
191 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
193 token: Option<SyntaxToken>,
194 label: Option<ast::Label>,
195 body: Option<ast::StmtList>,
196 ) -> Option<Vec<HighlightedRange>> {
197 let mut highlights = Vec::new();
198 let range = cover_range(
199 token.map(|tok| tok.text_range()),
200 label.as_ref().map(|it| it.syntax().text_range()),
202 highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
203 for_each_break_expr(label, body, &mut |break_| {
204 let range = cover_range(
205 break_.break_token().map(|it| it.text_range()),
206 break_.lifetime().map(|it| it.syntax().text_range()),
208 highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
212 let parent = token.parent()?;
213 let lbl = match_ast! {
215 ast::BreakExpr(b) => b.lifetime(),
216 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
217 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
218 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
219 ast::BlockExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
223 let lbl = lbl.as_ref();
224 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
226 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
230 for anc in token.ancestors().flat_map(ast::Expr::cast) {
232 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
233 hl(l.loop_token(), l.label(), l.loop_body().and_then(|it| it.stmt_list()))
235 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
236 hl(f.for_token(), f.label(), f.loop_body().and_then(|it| it.stmt_list()))
238 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
239 hl(w.while_token(), w.label(), w.loop_body().and_then(|it| it.stmt_list()))
241 ast::Expr::BlockExpr(e) if e.label().is_some() && label_matches(e.label()) => {
242 hl(None, e.label(), e.stmt_list())
250 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
252 async_token: Option<SyntaxToken>,
253 body: Option<ast::Expr>,
254 ) -> Option<Vec<HighlightedRange>> {
256 vec![HighlightedRange { category: None, range: async_token?.text_range() }];
257 if let Some(body) = body {
258 walk_expr(&body, &mut |expr| {
259 if let ast::Expr::AwaitExpr(expr) = expr {
260 if let Some(token) = expr.await_token() {
262 .push(HighlightedRange { category: None, range: token.text_range() });
269 for anc in token.ancestors() {
272 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
273 ast::BlockExpr(block_expr) => {
274 if block_expr.async_token().is_none() {
277 hl(block_expr.async_token(), Some(block_expr.into()))
279 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
287 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
289 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
290 (Some(range), None) => Some(range),
291 (None, Some(range)) => Some(range),
292 (None, None) => None,
297 sema: &Semantics<RootDatabase>,
300 ) -> FxHashSet<Definition> {
301 sema.find_nodes_at_offset_with_descend(syntax, offset)
302 .flat_map(|name_like| {
303 Some(match name_like {
304 ast::NameLike::NameRef(name_ref) => {
305 match NameRefClass::classify(sema, &name_ref)? {
306 NameRefClass::Definition(def) => vec![def],
307 NameRefClass::FieldShorthand { local_ref, field_ref } => {
308 vec![Definition::Local(local_ref), Definition::Field(field_ref)]
312 ast::NameLike::Name(name) => match NameClass::classify(sema, &name)? {
313 NameClass::Definition(it) | NameClass::ConstReference(it) => vec![it],
314 NameClass::PatFieldShorthand { local_def, field_ref } => {
315 vec![Definition::Local(local_def), Definition::Field(field_ref)]
318 ast::NameLike::Lifetime(lifetime) => {
319 NameRefClass::classify_lifetime(sema, &lifetime)
320 .and_then(|class| match class {
321 NameRefClass::Definition(it) => Some(it),
325 NameClass::classify_lifetime(sema, &lifetime)
326 .and_then(NameClass::defined)
342 fn check(ra_fixture: &str) {
343 let config = HighlightRelatedConfig {
350 check_with_config(ra_fixture, config);
353 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
354 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
356 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or(Vec::default());
358 let mut expected = annotations
360 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
361 .collect::<Vec<_>>();
368 hl.category.map(|it| {
370 ReferenceCategory::Read => "read",
371 ReferenceCategory::Write => "write",
377 .collect::<Vec<_>>();
378 actual.sort_by_key(|(range, _)| range.start());
379 expected.sort_by_key(|(range, _)| range.start());
381 assert_eq!(expected, actual);
385 fn test_hl_module() {
398 fn test_hl_self_in_crate_root() {
407 fn test_hl_self_in_module() {
434 fn test_hl_local_in_attr() {
437 //- proc_macros: identity
438 #[proc_macros::identity]
450 fn test_multi_macro_usage() {
455 fn $ident() -> $ident { loop {} }
463 let bar: bar = bar();
473 fn $ident() -> $ident { loop {} }
481 let bar: bar$0 = bar();
489 fn test_hl_yield_points() {
500 (async { 0.await }).await
508 fn test_hl_yield_points2() {
511 pub async$0 fn foo() {
519 (async { 0.await }).await
527 fn test_hl_yield_nested_fn() {
546 fn test_hl_yield_nested_async_blocks() {
563 fn test_hl_exit_points() {
582 fn test_hl_exit_points2() {
601 fn test_hl_exit_points3() {
620 fn test_hl_prefer_ref_over_tail_exit() {
639 fn test_hl_never_call_is_exit_point() {
644 fn never(self) -> ! { loop {} }
649 fn never() -> ! { loop {} }
654 // FIXME sema doesn't give us types for macrocalls
667 fn test_hl_inner_tail_exit_points() {
708 fn test_hl_inner_tail_exit_points_labeled_block() {
729 fn test_hl_break_loop() {
757 fn test_hl_break_loop2() {
784 fn test_hl_break_for() {
788 'outer: for _ in () {
792 'inner: for _ in () {
794 'innermost: for _ in () {
812 fn test_hl_break_while() {
822 'innermost: while true {
840 fn test_hl_break_labeled_block() {
868 fn test_hl_break_unlabeled_loop() {
883 fn test_hl_break_unlabeled_block_in_loop() {
900 fn test_hl_field_shorthand() {
903 struct Struct { field: u32 }
905 fn function(field: u32) {
915 fn test_hl_disabled_ref_local() {
916 let config = HighlightRelatedConfig {
929 check_with_config(ra_fixture, config);
933 fn test_hl_disabled_ref_local_preserved_break() {
934 let config = HighlightRelatedConfig {
951 check_with_config(ra_fixture, config.clone());
965 check_with_config(ra_fixture, config);
969 fn test_hl_disabled_ref_local_preserved_yield() {
970 let config = HighlightRelatedConfig {
985 check_with_config(ra_fixture, config.clone());
997 check_with_config(ra_fixture, config);
1001 fn test_hl_disabled_ref_local_preserved_exit() {
1002 let config = HighlightRelatedConfig {
1009 let ra_fixture = r#"
1021 check_with_config(ra_fixture, config.clone());
1023 let ra_fixture = r#"
1037 check_with_config(ra_fixture, config);
1041 fn test_hl_disabled_break() {
1042 let config = HighlightRelatedConfig {
1044 break_points: false,
1049 let ra_fixture = r#"
1056 check_with_config(ra_fixture, config);
1060 fn test_hl_disabled_yield() {
1061 let config = HighlightRelatedConfig {
1065 yield_points: false,
1068 let ra_fixture = r#"
1073 check_with_config(ra_fixture, config);
1077 fn test_hl_disabled_exit() {
1078 let config = HighlightRelatedConfig {
1085 let ra_fixture = r#"
1094 check_with_config(ra_fixture, config);