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, 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` token, `?` 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
36 pub(crate) fn highlight_related(
37 sema: &Semantics<RootDatabase>,
38 config: HighlightRelatedConfig,
39 position: FilePosition,
40 ) -> Option<Vec<HighlightedRange>> {
41 let _p = profile::span("highlight_related");
42 let syntax = sema.parse(position.file_id).syntax().clone();
44 let token = pick_best_token(syntax.token_at_offset(position.offset), |kind| match kind {
45 T![?] => 2, // prefer `?` when the cursor is sandwiched like `await$0?`
58 T![return] | T![?] | T![->] if config.exit_points => highlight_exit_points(sema, token),
59 T![await] | T![async] if config.yield_points => highlight_yield_points(token),
60 T![break] | T![loop] | T![for] | T![while] if config.break_points => {
61 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 def = references::find_def(sema, syntax, offset)?;
76 .set_scope(Some(SearchScope::single_file(file_id)))
80 let declaration = match def {
81 Definition::ModuleDef(hir::ModuleDef::Module(module)) => {
82 Some(NavigationTarget::from_module_to_decl(sema.db, module))
84 def => def.try_to_nav(sema.db),
86 .filter(|decl| decl.file_id == file_id)
88 let range = decl.focus_range?;
89 let access = references::decl_access(&def, syntax, range);
90 Some(HighlightedRange { range, access })
93 let file_refs = usages.references.get(&file_id).map_or(&[][..], Vec::as_slice);
94 let mut res = Vec::with_capacity(file_refs.len() + 1);
95 res.extend(declaration);
99 .map(|&FileReference { access, range, .. }| HighlightedRange { range, access }),
104 fn highlight_exit_points(
105 sema: &Semantics<RootDatabase>,
107 ) -> Option<Vec<HighlightedRange>> {
109 sema: &Semantics<RootDatabase>,
110 body: Option<ast::Expr>,
111 ) -> Option<Vec<HighlightedRange>> {
112 let mut highlights = Vec::new();
114 body.walk(&mut |expr| match expr {
115 ast::Expr::ReturnExpr(expr) => {
116 if let Some(token) = expr.return_token() {
117 highlights.push(HighlightedRange { access: None, range: token.text_range() });
120 ast::Expr::TryExpr(try_) => {
121 if let Some(token) = try_.question_mark_token() {
122 highlights.push(HighlightedRange { access: None, range: token.text_range() });
125 ast::Expr::MethodCallExpr(_) | ast::Expr::CallExpr(_) | ast::Expr::MacroCall(_) => {
126 if sema.type_of_expr(&expr).map_or(false, |ty| ty.is_never()) {
128 .push(HighlightedRange { access: None, range: expr.syntax().text_range() });
133 let tail = match body {
134 ast::Expr::BlockExpr(b) => b.tail_expr(),
138 if let Some(tail) = tail {
139 for_each_tail_expr(&tail, &mut |tail| {
140 let range = match tail {
141 ast::Expr::BreakExpr(b) => b
143 .map_or_else(|| tail.syntax().text_range(), |tok| tok.text_range()),
144 _ => tail.syntax().text_range(),
146 highlights.push(HighlightedRange { access: None, range })
151 for anc in token.ancestors() {
154 ast::Fn(fn_) => hl(sema, fn_.body().map(ast::Expr::BlockExpr)),
155 ast::ClosureExpr(closure) => hl(sema, closure.body()),
156 ast::EffectExpr(effect) => if matches!(effect.effect(), ast::Effect::Async(_) | ast::Effect::Try(_)| ast::Effect::Const(_)) {
157 hl(sema, effect.block_expr().map(ast::Expr::BlockExpr))
168 fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
170 token: Option<SyntaxToken>,
171 label: Option<ast::Label>,
172 body: Option<ast::BlockExpr>,
173 ) -> Option<Vec<HighlightedRange>> {
174 let mut highlights = Vec::new();
175 let range = cover_range(
176 token.map(|tok| tok.text_range()),
177 label.as_ref().map(|it| it.syntax().text_range()),
179 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
180 for_each_break_expr(label, body, &mut |break_| {
181 let range = cover_range(
182 break_.break_token().map(|it| it.text_range()),
183 break_.lifetime().map(|it| it.syntax().text_range()),
185 highlights.extend(range.map(|range| HighlightedRange { access: None, range }));
189 let parent = token.parent()?;
190 let lbl = match_ast! {
192 ast::BreakExpr(b) => b.lifetime(),
193 ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
194 ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
195 ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
196 ast::EffectExpr(b) => Some(b.label().and_then(|it| it.lifetime())?),
200 let lbl = lbl.as_ref();
201 let label_matches = |def_lbl: Option<ast::Label>| match lbl {
203 Some(lbl.text()) == def_lbl.and_then(|it| it.lifetime()).as_ref().map(|it| it.text())
207 for anc in token.ancestors().flat_map(ast::Expr::cast) {
209 ast::Expr::LoopExpr(l) if label_matches(l.label()) => {
210 hl(l.loop_token(), l.label(), l.loop_body())
212 ast::Expr::ForExpr(f) if label_matches(f.label()) => {
213 hl(f.for_token(), f.label(), f.loop_body())
215 ast::Expr::WhileExpr(w) if label_matches(w.label()) => {
216 hl(w.while_token(), w.label(), w.loop_body())
218 ast::Expr::EffectExpr(e) if e.label().is_some() && label_matches(e.label()) => {
219 hl(None, e.label(), e.block_expr())
227 fn highlight_yield_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
229 async_token: Option<SyntaxToken>,
230 body: Option<ast::Expr>,
231 ) -> Option<Vec<HighlightedRange>> {
233 vec![HighlightedRange { access: None, range: async_token?.text_range() }];
234 if let Some(body) = body {
235 body.walk(&mut |expr| {
236 if let ast::Expr::AwaitExpr(expr) = expr {
237 if let Some(token) = expr.await_token() {
239 .push(HighlightedRange { access: None, range: token.text_range() });
246 for anc in token.ancestors() {
249 ast::Fn(fn_) => hl(fn_.async_token(), fn_.body().map(ast::Expr::BlockExpr)),
250 ast::EffectExpr(effect) => hl(effect.async_token(), effect.block_expr().map(ast::Expr::BlockExpr)),
251 ast::ClosureExpr(closure) => hl(closure.async_token(), closure.body()),
259 fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange> {
261 (Some(r0), Some(r1)) => Some(r0.cover(r1)),
262 (Some(range), None) => Some(range),
263 (None, Some(range)) => Some(range),
264 (None, None) => None,
274 fn check(ra_fixture: &str) {
275 let config = HighlightRelatedConfig {
282 check_with_config(ra_fixture, config);
285 fn check_with_config(ra_fixture: &str, config: HighlightRelatedConfig) {
286 let (analysis, pos, annotations) = fixture::annotations(ra_fixture);
288 let hls = analysis.highlight_related(config, pos).unwrap().unwrap_or(Vec::default());
290 let mut expected = annotations
292 .map(|(r, access)| (r.range, (!access.is_empty()).then(|| access)))
293 .collect::<Vec<_>>();
302 ReferenceAccess::Read => "read",
303 ReferenceAccess::Write => "write",
309 .collect::<Vec<_>>();
310 actual.sort_by_key(|(range, _)| range.start());
311 expected.sort_by_key(|(range, _)| range.start());
313 assert_eq!(expected, actual);
317 fn test_hl_module() {
330 fn test_hl_self_in_crate_root() {
339 fn test_hl_self_in_module() {
366 fn test_hl_yield_points() {
377 (async { 0.await }).await
385 fn test_hl_yield_points2() {
388 pub async$0 fn foo() {
396 (async { 0.await }).await
404 fn test_hl_yield_nested_fn() {
423 fn test_hl_yield_nested_async_blocks() {
440 fn test_hl_exit_points() {
459 fn test_hl_exit_points2() {
478 fn test_hl_prefer_ref_over_tail_exit() {
497 fn test_hl_never_call_is_exit_point() {
502 fn never(self) -> ! { loop {} }
507 fn never() -> ! { loop {} }
512 // FIXME sema doesn't give us types for macrocalls
525 fn test_hl_inner_tail_exit_points() {
566 fn test_hl_inner_tail_exit_points_labeled_block() {
587 fn test_hl_break_loop() {
615 fn test_hl_break_loop2() {
642 fn test_hl_break_for() {
646 'outer: for _ in () {
650 'inner: for _ in () {
652 'innermost: for _ in () {
670 fn test_hl_break_while() {
680 'innermost: while true {
698 fn test_hl_break_labeled_block() {
726 fn test_hl_break_unlabeled_loop() {
741 fn test_hl_break_unlabeled_block_in_loop() {
758 fn test_hl_disabled_ref_local() {
759 let config = HighlightRelatedConfig {
772 check_with_config(ra_fixture, config);
776 fn test_hl_disabled_ref_local_preserved_break() {
777 let config = HighlightRelatedConfig {
794 check_with_config(ra_fixture, config.clone());
808 check_with_config(ra_fixture, config);
812 fn test_hl_disabled_ref_local_preserved_yield() {
813 let config = HighlightRelatedConfig {
828 check_with_config(ra_fixture, config.clone());
840 check_with_config(ra_fixture, config);
844 fn test_hl_disabled_ref_local_preserved_exit() {
845 let config = HighlightRelatedConfig {
864 check_with_config(ra_fixture, config.clone());
880 check_with_config(ra_fixture, config);
884 fn test_hl_disabled_break() {
885 let config = HighlightRelatedConfig {
899 check_with_config(ra_fixture, config);
903 fn test_hl_disabled_yield() {
904 let config = HighlightRelatedConfig {
916 check_with_config(ra_fixture, config);
920 fn test_hl_disabled_exit() {
921 let config = HighlightRelatedConfig {
937 check_with_config(ra_fixture, config);