11462: 11422 highlight continue and break r=Veykril a=HansAuger

Closes #11422 

Co-authored-by: Moritz Vetter <mv@3yourmind.com>
This commit is contained in:
bors[bot] 2022-02-24 20:59:27 +00:00 committed by GitHub
commit f6901c952e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 249 additions and 54 deletions

View File

@ -2,7 +2,9 @@ use hir::Semantics;
use ide_db::{ use ide_db::{
base_db::{FileId, FilePosition}, base_db::{FileId, FilePosition},
defs::{Definition, IdentClass}, defs::{Definition, IdentClass},
helpers::{for_each_break_expr, for_each_tail_expr, node_ext::walk_expr, pick_best_token}, helpers::{
for_each_break_and_continue_expr, for_each_tail_expr, node_ext::walk_expr, pick_best_token,
},
search::{FileReference, ReferenceCategory, SearchScope}, search::{FileReference, ReferenceCategory, SearchScope},
RootDatabase, RootDatabase,
}; };
@ -10,7 +12,7 @@ use rustc_hash::FxHashSet;
use syntax::{ use syntax::{
ast::{self, HasLoopBody}, ast::{self, HasLoopBody},
match_ast, AstNode, match_ast, AstNode,
SyntaxKind::{IDENT, INT_NUMBER}, SyntaxKind::{self, IDENT, INT_NUMBER},
SyntaxNode, SyntaxToken, TextRange, T, SyntaxNode, SyntaxToken, TextRange, T,
}; };
@ -66,7 +68,9 @@ pub(crate) fn highlight_related(
T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => { T![for] if config.break_points && token.parent().and_then(ast::ForExpr::cast).is_some() => {
highlight_break_points(token) highlight_break_points(token)
} }
T![break] | T![loop] | T![while] if config.break_points => highlight_break_points(token), T![break] | T![loop] | T![while] | T![continue] if config.break_points => {
highlight_break_points(token)
}
_ if config.references => highlight_references(sema, &syntax, token, file_id), _ if config.references => highlight_references(sema, &syntax, token, file_id),
_ => None, _ => None,
} }
@ -187,6 +191,7 @@ fn highlight_exit_points(
fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> { fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
fn hl( fn hl(
cursor_token_kind: SyntaxKind,
token: Option<SyntaxToken>, token: Option<SyntaxToken>,
label: Option<ast::Label>, label: Option<ast::Label>,
body: Option<ast::StmtList>, body: Option<ast::StmtList>,
@ -197,11 +202,23 @@ fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
label.as_ref().map(|it| it.syntax().text_range()), label.as_ref().map(|it| it.syntax().text_range()),
); );
highlights.extend(range.map(|range| HighlightedRange { category: None, range })); highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
for_each_break_expr(label, body, &mut |break_| { for_each_break_and_continue_expr(label, body, &mut |expr| {
let range = cover_range( let range: Option<TextRange> = match (cursor_token_kind, expr) {
(T![for] | T![while] | T![loop] | T![break], ast::Expr::BreakExpr(break_)) => {
cover_range(
break_.break_token().map(|it| it.text_range()), break_.break_token().map(|it| it.text_range()),
break_.lifetime().map(|it| it.syntax().text_range()), break_.lifetime().map(|it| it.syntax().text_range()),
); )
}
(
T![for] | T![while] | T![loop] | T![continue],
ast::Expr::ContinueExpr(continue_),
) => cover_range(
continue_.continue_token().map(|it| it.text_range()),
continue_.lifetime().map(|it| it.syntax().text_range()),
),
_ => None,
};
highlights.extend(range.map(|range| HighlightedRange { category: None, range })); highlights.extend(range.map(|range| HighlightedRange { category: None, range }));
}); });
Some(highlights) Some(highlights)
@ -210,6 +227,7 @@ fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
let lbl = match_ast! { let lbl = match_ast! {
match parent { match parent {
ast::BreakExpr(b) => b.lifetime(), ast::BreakExpr(b) => b.lifetime(),
ast::ContinueExpr(c) => c.lifetime(),
ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()), ast::LoopExpr(l) => l.label().and_then(|it| it.lifetime()),
ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()), ast::ForExpr(f) => f.label().and_then(|it| it.lifetime()),
ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()), ast::WhileExpr(w) => w.label().and_then(|it| it.lifetime()),
@ -224,19 +242,29 @@ fn highlight_break_points(token: SyntaxToken) -> Option<Vec<HighlightedRange>> {
} }
None => true, None => true,
}; };
let token_kind = token.kind();
for anc in token.ancestors().flat_map(ast::Expr::cast) { for anc in token.ancestors().flat_map(ast::Expr::cast) {
return match anc { return match anc {
ast::Expr::LoopExpr(l) if label_matches(l.label()) => { ast::Expr::LoopExpr(l) if label_matches(l.label()) => hl(
hl(l.loop_token(), l.label(), l.loop_body().and_then(|it| it.stmt_list())) token_kind,
} l.loop_token(),
ast::Expr::ForExpr(f) if label_matches(f.label()) => { l.label(),
hl(f.for_token(), f.label(), f.loop_body().and_then(|it| it.stmt_list())) l.loop_body().and_then(|it| it.stmt_list()),
} ),
ast::Expr::WhileExpr(w) if label_matches(w.label()) => { ast::Expr::ForExpr(f) if label_matches(f.label()) => hl(
hl(w.while_token(), w.label(), w.loop_body().and_then(|it| it.stmt_list())) token_kind,
} f.for_token(),
f.label(),
f.loop_body().and_then(|it| it.stmt_list()),
),
ast::Expr::WhileExpr(w) if label_matches(w.label()) => hl(
token_kind,
w.while_token(),
w.label(),
w.loop_body().and_then(|it| it.stmt_list()),
),
ast::Expr::BlockExpr(e) if e.label().is_some() && label_matches(e.label()) => { ast::Expr::BlockExpr(e) if e.label().is_some() && label_matches(e.label()) => {
hl(None, e.label(), e.stmt_list()) hl(token_kind, None, e.label(), e.stmt_list())
} }
_ => continue, _ => continue,
}; };
@ -804,6 +832,115 @@ fn foo() {
); );
} }
#[test]
fn test_hl_break_for_but_not_continue() {
check(
r#"
fn foo() {
'outer: for _ in () {
// ^^^^^^^^^^^
break;
// ^^^^^
continue;
'inner: for _ in () {
break;
continue;
'innermost: for _ in () {
continue 'outer;
break 'outer;
// ^^^^^^^^^^^^
continue 'inner;
break 'inner;
}
break$0 'outer;
// ^^^^^^^^^^^^
continue 'outer;
break;
continue;
}
break;
// ^^^^^
continue;
}
}
"#,
);
}
#[test]
fn test_hl_continue_for_but_not_break() {
check(
r#"
fn foo() {
'outer: for _ in () {
// ^^^^^^^^^^^
break;
continue;
// ^^^^^^^^
'inner: for _ in () {
break;
continue;
'innermost: for _ in () {
continue 'outer;
// ^^^^^^^^^^^^^^^
break 'outer;
continue 'inner;
break 'inner;
}
break 'outer;
continue$0 'outer;
// ^^^^^^^^^^^^^^^
break;
continue;
}
break;
continue;
// ^^^^^^^^
}
}
"#,
);
}
#[test]
fn test_hl_break_and_continue() {
check(
r#"
fn foo() {
'outer: fo$0r _ in () {
// ^^^^^^^^^^^
break;
// ^^^^^
continue;
// ^^^^^^^^
'inner: for _ in () {
break;
continue;
'innermost: for _ in () {
continue 'outer;
// ^^^^^^^^^^^^^^^
break 'outer;
// ^^^^^^^^^^^^
continue 'inner;
break 'inner;
}
break 'outer;
// ^^^^^^^^^^^^
continue 'outer;
// ^^^^^^^^^^^^^^^
break;
continue;
}
break;
// ^^^^^
continue;
// ^^^^^^^^
}
}
"#,
);
}
#[test] #[test]
fn test_hl_break_while() { fn test_hl_break_while() {
check( check(

View File

@ -16,7 +16,8 @@ use hir::{ItemInNs, MacroDef, ModuleDef, Name, Semantics};
use itertools::Itertools; use itertools::Itertools;
use syntax::{ use syntax::{
ast::{self, make, HasLoopBody}, ast::{self, make, HasLoopBody},
AstNode, AstToken, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent, T, AstNode, AstToken, Preorder, RustLanguage, SyntaxKind, SyntaxToken, TokenAtOffset, WalkEvent,
T,
}; };
use crate::{defs::Definition, RootDatabase}; use crate::{defs::Definition, RootDatabase};
@ -190,46 +191,102 @@ pub fn for_each_tail_expr(expr: &ast::Expr, cb: &mut dyn FnMut(&ast::Expr)) {
} }
} }
/// Calls `cb` on each break expr inside of `body` that is applicable for the given label. pub fn for_each_break_and_continue_expr(
pub fn for_each_break_expr( label: Option<ast::Label>,
body: Option<ast::StmtList>,
cb: &mut dyn FnMut(ast::Expr),
) {
let label = label.and_then(|lbl| lbl.lifetime());
if let Some(b) = body {
let tree_depth_iterator = TreeWithDepthIterator::new(b);
for (expr, depth) in tree_depth_iterator {
match expr {
ast::Expr::BreakExpr(b)
if (depth == 0 && b.lifetime().is_none())
|| eq_label_lt(&label, &b.lifetime()) =>
{
cb(ast::Expr::BreakExpr(b));
}
ast::Expr::ContinueExpr(c)
if (depth == 0 && c.lifetime().is_none())
|| eq_label_lt(&label, &c.lifetime()) =>
{
cb(ast::Expr::ContinueExpr(c));
}
_ => (),
}
}
}
}
fn for_each_break_expr(
label: Option<ast::Label>, label: Option<ast::Label>,
body: Option<ast::StmtList>, body: Option<ast::StmtList>,
cb: &mut dyn FnMut(ast::BreakExpr), cb: &mut dyn FnMut(ast::BreakExpr),
) { ) {
let label = label.and_then(|lbl| lbl.lifetime()); let label = label.and_then(|lbl| lbl.lifetime());
let mut depth = 0;
if let Some(b) = body { if let Some(b) = body {
let preorder = &mut b.syntax().preorder(); let tree_depth_iterator = TreeWithDepthIterator::new(b);
let ev_as_expr = |ev| match ev { for (expr, depth) in tree_depth_iterator {
WalkEvent::Enter(it) => Some(WalkEvent::Enter(ast::Expr::cast(it)?)), match expr {
WalkEvent::Leave(it) => Some(WalkEvent::Leave(ast::Expr::cast(it)?)),
};
let eq_label = |lt: Option<ast::Lifetime>| {
lt.zip(label.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
};
while let Some(node) = preorder.find_map(ev_as_expr) {
match node {
WalkEvent::Enter(expr) => match expr {
ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
depth += 1
}
ast::Expr::BlockExpr(e) if e.label().is_some() => depth += 1,
ast::Expr::BreakExpr(b) ast::Expr::BreakExpr(b)
if (depth == 0 && b.lifetime().is_none()) || eq_label(b.lifetime()) => if (depth == 0 && b.lifetime().is_none())
|| eq_label_lt(&label, &b.lifetime()) =>
{ {
cb(b); cb(b);
} }
_ => (), _ => (),
},
WalkEvent::Leave(expr) => match expr {
ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_) => {
depth -= 1
} }
ast::Expr::BlockExpr(e) if e.label().is_some() => depth -= 1, }
}
}
fn eq_label_lt(lt1: &Option<ast::Lifetime>, lt2: &Option<ast::Lifetime>) -> bool {
lt1.as_ref().zip(lt2.as_ref()).map_or(false, |(lt, lbl)| lt.text() == lbl.text())
}
struct TreeWithDepthIterator {
preorder: Preorder<RustLanguage>,
depth: u32,
}
impl TreeWithDepthIterator {
fn new(body: ast::StmtList) -> Self {
let preorder = body.syntax().preorder();
Self { preorder, depth: 0 }
}
}
impl<'a> Iterator for TreeWithDepthIterator {
type Item = (ast::Expr, u32);
fn next(&mut self) -> Option<Self::Item> {
while let Some(event) = self.preorder.find_map(|ev| match ev {
WalkEvent::Enter(it) => ast::Expr::cast(it).map(WalkEvent::Enter),
WalkEvent::Leave(it) => ast::Expr::cast(it).map(WalkEvent::Leave),
}) {
match event {
WalkEvent::Enter(
ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_),
) => {
self.depth += 1;
}
WalkEvent::Leave(
ast::Expr::LoopExpr(_) | ast::Expr::WhileExpr(_) | ast::Expr::ForExpr(_),
) => {
self.depth -= 1;
}
WalkEvent::Enter(ast::Expr::BlockExpr(e)) if e.label().is_some() => {
self.depth += 1;
}
WalkEvent::Leave(ast::Expr::BlockExpr(e)) if e.label().is_some() => {
self.depth -= 1;
}
WalkEvent::Enter(expr) => return Some((expr, self.depth)),
_ => (), _ => (),
},
} }
} }
None
} }
} }

View File

@ -52,14 +52,15 @@ pub use crate::{
ptr::{AstPtr, SyntaxNodePtr}, ptr::{AstPtr, SyntaxNodePtr},
syntax_error::SyntaxError, syntax_error::SyntaxError,
syntax_node::{ syntax_node::{
PreorderWithTokens, SyntaxElement, SyntaxElementChildren, SyntaxNode, SyntaxNodeChildren, PreorderWithTokens, RustLanguage, SyntaxElement, SyntaxElementChildren, SyntaxNode,
SyntaxToken, SyntaxTreeBuilder, SyntaxNodeChildren, SyntaxToken, SyntaxTreeBuilder,
}, },
token_text::TokenText, token_text::TokenText,
}; };
pub use parser::{SyntaxKind, T}; pub use parser::{SyntaxKind, T};
pub use rowan::{ pub use rowan::{
Direction, GreenNode, NodeOrToken, SyntaxText, TextRange, TextSize, TokenAtOffset, WalkEvent, api::Preorder, Direction, GreenNode, NodeOrToken, SyntaxText, TextRange, TextSize,
TokenAtOffset, WalkEvent,
}; };
pub use smol_str::SmolStr; pub use smol_str::SmolStr;