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 pub access: Option<ReferenceCategory>,
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 { category: 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 walk_expr(&body, &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::BlockExpr(block_expr) => if matches!(block_expr.modifier(), Some(ast::BlockModifier::Async(_) | ast::BlockModifier::Try(_)| ast::BlockModifier::Const(_))) {
168 hl(sema, Some(block_expr.into()))
179 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
181 token: Option<SyntaxToken>,
182 label: Option<ast::Label>,
183 body: Option<ast::StmtList>,
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::BlockExpr(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().and_then(|it| it.stmt_list()))
223 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
224 hl(f.for_token(), f.label(), f.loop_body().and_then(|it| it.stmt_list()))
226 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
227 hl(w.while_token(), w.label(), w.loop_body().and_then(|it| it.stmt_list()))
229 ast::Expr::BlockExpr(e) if e.label().is_some() && label_matches(e.label()) => {
230 hl(None, e.label(), e.stmt_list())
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 walk_expr(&body, &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::BlockExpr(block_expr) => {
262 if block_expr.async_token().is_none() {
265 hl(block_expr.async_token(), Some(block_expr.into()))
267 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
275 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
277 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
278 (Some(range), None) => Some(range),
279 (None, Some(range)) => Some(range),
280 (None, None) => None,
285 sema: &Semantics<RootDatabase>,
288 ) -> FxHashSet<Definition> {
289 sema.find_nodes_at_offset_with_descend(syntax, offset)
290 .flat_map(|name_like| {
291 Some(match name_like {
292 ast::NameLike::NameRef(name_ref) => {
293 match NameRefClass::classify(sema, &name_ref)? {
294 NameRefClass::Definition(def) => vec![def],
295 NameRefClass::FieldShorthand { local_ref, field_ref } => {
296 vec![Definition::Local(local_ref), Definition::Field(field_ref)]
300 ast::NameLike::Name(name) => match NameClass::classify(sema, &name)? {
301 NameClass::Definition(it) | NameClass::ConstReference(it) => vec![it],
302 NameClass::PatFieldShorthand { local_def, field_ref } => {
303 vec![Definition::Local(local_def), Definition::Field(field_ref)]
306 ast::NameLike::Lifetime(lifetime) => {
307 NameRefClass::classify_lifetime(sema, &lifetime)
308 .and_then(|class| match class {
309 NameRefClass::Definition(it) => Some(it),
313 NameClass::classify_lifetime(sema, &lifetime)
314 .and_then(NameClass::defined)
330 fn check(ra_fixture: &str) {
331 let config = HighlightRelatedConfig {
338 check_with_config(ra_fixture, config);
341 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
342 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
344 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or(Vec::default());
346 let mut expected = annotations
348 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
349 .collect::<Vec<_>>();
358 ReferenceCategory::Read => "read",
359 ReferenceCategory::Write => "write",
365 .collect::<Vec<_>>();
366 actual.sort_by_key(|(range, _)| range.start());
367 expected.sort_by_key(|(range, _)| range.start());
369 assert_eq!(expected, actual);
373 fn test_hl_module() {
386 fn test_hl_self_in_crate_root() {
395 fn test_hl_self_in_module() {
422 fn test_hl_local_in_attr() {
425 //- proc_macros: identity
426 #[proc_macros::identity]
438 fn test_multi_macro_usage() {
443 fn $ident() -> $ident { loop {} }
451 let bar: bar = bar();
461 fn $ident() -> $ident { loop {} }
469 let bar: bar$0 = bar();
477 fn test_hl_yield_points() {
488 (async { 0.await }).await
496 fn test_hl_yield_points2() {
499 pub async$0 fn foo() {
507 (async { 0.await }).await
515 fn test_hl_yield_nested_fn() {
534 fn test_hl_yield_nested_async_blocks() {
551 fn test_hl_exit_points() {
570 fn test_hl_exit_points2() {
589 fn test_hl_exit_points3() {
608 fn test_hl_prefer_ref_over_tail_exit() {
627 fn test_hl_never_call_is_exit_point() {
632 fn never(self) -> ! { loop {} }
637 fn never() -> ! { loop {} }
642 // FIXME sema doesn't give us types for macrocalls
655 fn test_hl_inner_tail_exit_points() {
696 fn test_hl_inner_tail_exit_points_labeled_block() {
717 fn test_hl_break_loop() {
745 fn test_hl_break_loop2() {
772 fn test_hl_break_for() {
776 'outer: for _ in () {
780 'inner: for _ in () {
782 'innermost: for _ in () {
800 fn test_hl_break_while() {
810 'innermost: while true {
828 fn test_hl_break_labeled_block() {
856 fn test_hl_break_unlabeled_loop() {
871 fn test_hl_break_unlabeled_block_in_loop() {
888 fn test_hl_field_shorthand() {
891 struct Struct { field: u32 }
893 fn function(field: u32) {
903 fn test_hl_disabled_ref_local() {
904 let config = HighlightRelatedConfig {
917 check_with_config(ra_fixture, config);
921 fn test_hl_disabled_ref_local_preserved_break() {
922 let config = HighlightRelatedConfig {
939 check_with_config(ra_fixture, config.clone());
953 check_with_config(ra_fixture, config);
957 fn test_hl_disabled_ref_local_preserved_yield() {
958 let config = HighlightRelatedConfig {
973 check_with_config(ra_fixture, config.clone());
985 check_with_config(ra_fixture, config);
989 fn test_hl_disabled_ref_local_preserved_exit() {
990 let config = HighlightRelatedConfig {
1009 check_with_config(ra_fixture, config.clone());
1011 let ra_fixture = r#"
1025 check_with_config(ra_fixture, config);
1029 fn test_hl_disabled_break() {
1030 let config = HighlightRelatedConfig {
1032 break_points: false,
1037 let ra_fixture = r#"
1044 check_with_config(ra_fixture, config);
1048 fn test_hl_disabled_yield() {
1049 let config = HighlightRelatedConfig {
1053 yield_points: false,
1056 let ra_fixture = r#"
1061 check_with_config(ra_fixture, config);
1065 fn test_hl_disabled_exit() {
1066 let config = HighlightRelatedConfig {
1073 let ra_fixture = r#"
1082 check_with_config(ra_fixture, config);