aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorbors[bot] <26634292+bors[bot]@users.noreply.github.com>2021-03-16 13:14:48 +0000
committerGitHub <[email protected]>2021-03-16 13:14:48 +0000
commitc49b5b7468a9954af86fd1724276261f396aba5d (patch)
treef9b9126cd0cc9a2829de3cdb20f681b354fbe67b /crates
parent1a82af3527e476d52410ff4dfd2fb4c57466abcb (diff)
parentf5a81ec4683613bd62624811733345d627f2127b (diff)
Merge #7498
7498: Clone for update r=matklad a=matklad rowan counterpart https://github.com/rust-analyzer/rowan/pull/93 #6857 Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'crates')
-rw-r--r--crates/hir/src/semantics.rs30
-rw-r--r--crates/hir_expand/src/lib.rs5
-rw-r--r--crates/ide/src/call_hierarchy.rs11
-rw-r--r--crates/ide/src/doc_links.rs2
-rw-r--r--crates/ide/src/extend_selection.rs13
-rw-r--r--crates/ide/src/goto_definition.rs4
-rw-r--r--crates/ide/src/goto_type_definition.rs2
-rw-r--r--crates/ide/src/hover.rs4
-rw-r--r--crates/ide/src/join_lines.rs44
-rw-r--r--crates/ide/src/matching_brace.rs2
-rw-r--r--crates/ide/src/references.rs7
-rw-r--r--crates/ide/src/runnables.rs3
-rw-r--r--crates/ide/src/syntax_highlighting.rs19
-rw-r--r--crates/ide/src/syntax_highlighting/format.rs2
-rw-r--r--crates/ide/src/syntax_tree.rs2
-rw-r--r--crates/ide/src/typing.rs2
-rw-r--r--crates/ide_assists/src/handlers/add_turbo_fish.rs2
-rw-r--r--crates/ide_assists/src/handlers/change_visibility.rs2
-rw-r--r--crates/ide_assists/src/handlers/expand_glob_import.rs2
-rw-r--r--crates/ide_assists/src/handlers/extract_function.rs20
-rw-r--r--crates/ide_assists/src/handlers/flip_trait_bound.rs2
-rw-r--r--crates/ide_assists/src/handlers/invert_if.rs2
-rw-r--r--crates/ide_assists/src/handlers/move_bounds.rs62
-rw-r--r--crates/ide_assists/src/handlers/split_import.rs2
-rw-r--r--crates/ide_assists/src/handlers/unwrap_block.rs2
-rw-r--r--crates/ide_completion/src/completions/fn_param.rs2
-rw-r--r--crates/ide_completion/src/completions/trait_impl.rs7
-rw-r--r--crates/ide_completion/src/context.rs15
-rw-r--r--crates/ide_completion/src/patterns.rs16
-rw-r--r--crates/ide_db/src/call_info.rs2
-rw-r--r--crates/ide_ssr/src/resolving.rs2
-rw-r--r--crates/syntax/Cargo.toml2
-rw-r--r--crates/syntax/src/algo.rs35
-rw-r--r--crates/syntax/src/ast.rs7
-rw-r--r--crates/syntax/src/ast/edit_in_place.rs105
-rw-r--r--crates/syntax/src/ast/make.rs14
-rw-r--r--crates/syntax/src/ast/node_ext.rs4
-rw-r--r--crates/syntax/src/lib.rs1
-rw-r--r--crates/syntax/src/parsing/reparsing.rs6
-rw-r--r--crates/syntax/src/ted.rs78
40 files changed, 373 insertions, 171 deletions
diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs
index 519339c0c..03c9371b5 100644
--- a/crates/hir/src/semantics.rs
+++ b/crates/hir/src/semantics.rs
@@ -143,6 +143,12 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
143 self.imp.diagnostics_display_range(diagnostics) 143 self.imp.diagnostics_display_range(diagnostics)
144 } 144 }
145 145
146 pub fn token_ancestors_with_macros(
147 &self,
148 token: SyntaxToken,
149 ) -> impl Iterator<Item = SyntaxNode> + '_ {
150 token.parent().into_iter().flat_map(move |it| self.ancestors_with_macros(it))
151 }
146 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ { 152 pub fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
147 self.imp.ancestors_with_macros(node) 153 self.imp.ancestors_with_macros(node)
148 } 154 }
@@ -270,8 +276,8 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
270 self.imp.scope(node) 276 self.imp.scope(node)
271 } 277 }
272 278
273 pub fn scope_at_offset(&self, node: &SyntaxNode, offset: TextSize) -> SemanticsScope<'db> { 279 pub fn scope_at_offset(&self, token: &SyntaxToken, offset: TextSize) -> SemanticsScope<'db> {
274 self.imp.scope_at_offset(node, offset) 280 self.imp.scope_at_offset(&token.parent().unwrap(), offset)
275 } 281 }
276 282
277 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> { 283 pub fn scope_for_def(&self, def: Trait) -> SemanticsScope<'db> {
@@ -341,7 +347,10 @@ impl<'db> SemanticsImpl<'db> {
341 347
342 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken { 348 fn descend_into_macros(&self, token: SyntaxToken) -> SyntaxToken {
343 let _p = profile::span("descend_into_macros"); 349 let _p = profile::span("descend_into_macros");
344 let parent = token.parent(); 350 let parent = match token.parent() {
351 Some(it) => it,
352 None => return token,
353 };
345 let sa = self.analyze(&parent); 354 let sa = self.analyze(&parent);
346 355
347 let token = successors(Some(InFile::new(sa.file_id, token)), |token| { 356 let token = successors(Some(InFile::new(sa.file_id, token)), |token| {
@@ -360,7 +369,9 @@ impl<'db> SemanticsImpl<'db> {
360 .as_ref()? 369 .as_ref()?
361 .map_token_down(token.as_ref())?; 370 .map_token_down(token.as_ref())?;
362 371
363 self.cache(find_root(&token.value.parent()), token.file_id); 372 if let Some(parent) = token.value.parent() {
373 self.cache(find_root(&parent), token.file_id);
374 }
364 375
365 Some(token) 376 Some(token)
366 }) 377 })
@@ -378,7 +389,7 @@ impl<'db> SemanticsImpl<'db> {
378 // Handle macro token cases 389 // Handle macro token cases
379 node.token_at_offset(offset) 390 node.token_at_offset(offset)
380 .map(|token| self.descend_into_macros(token)) 391 .map(|token| self.descend_into_macros(token))
381 .map(|it| self.ancestors_with_macros(it.parent())) 392 .map(|it| self.token_ancestors_with_macros(it))
382 .flatten() 393 .flatten()
383 } 394 }
384 395
@@ -394,6 +405,13 @@ impl<'db> SemanticsImpl<'db> {
394 src.with_value(&node).original_file_range(self.db.upcast()) 405 src.with_value(&node).original_file_range(self.db.upcast())
395 } 406 }
396 407
408 fn token_ancestors_with_macros(
409 &self,
410 token: SyntaxToken,
411 ) -> impl Iterator<Item = SyntaxNode> + '_ {
412 token.parent().into_iter().flat_map(move |parent| self.ancestors_with_macros(parent))
413 }
414
397 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ { 415 fn ancestors_with_macros(&self, node: SyntaxNode) -> impl Iterator<Item = SyntaxNode> + '_ {
398 let node = self.find_file(node); 416 let node = self.find_file(node);
399 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value) 417 node.ancestors_with_macros(self.db.upcast()).map(|it| it.value)
@@ -405,7 +423,7 @@ impl<'db> SemanticsImpl<'db> {
405 offset: TextSize, 423 offset: TextSize,
406 ) -> impl Iterator<Item = SyntaxNode> + '_ { 424 ) -> impl Iterator<Item = SyntaxNode> + '_ {
407 node.token_at_offset(offset) 425 node.token_at_offset(offset)
408 .map(|token| self.ancestors_with_macros(token.parent())) 426 .map(|token| self.token_ancestors_with_macros(token))
409 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len()) 427 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
410 } 428 }
411 429
diff --git a/crates/hir_expand/src/lib.rs b/crates/hir_expand/src/lib.rs
index e388ddacc..eee430af1 100644
--- a/crates/hir_expand/src/lib.rs
+++ b/crates/hir_expand/src/lib.rs
@@ -510,7 +510,10 @@ impl InFile<SyntaxToken> {
510 self, 510 self,
511 db: &dyn db::AstDatabase, 511 db: &dyn db::AstDatabase,
512 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ { 512 ) -> impl Iterator<Item = InFile<SyntaxNode>> + '_ {
513 self.map(|it| it.parent()).ancestors_with_macros(db) 513 self.value
514 .parent()
515 .into_iter()
516 .flat_map(move |parent| InFile::new(self.file_id, parent).ancestors_with_macros(db))
514 } 517 }
515} 518}
516 519
diff --git a/crates/ide/src/call_hierarchy.rs b/crates/ide/src/call_hierarchy.rs
index b848945d7..96021f677 100644
--- a/crates/ide/src/call_hierarchy.rs
+++ b/crates/ide/src/call_hierarchy.rs
@@ -53,10 +53,8 @@ pub(crate) fn incoming_calls(db: &RootDatabase, position: FilePosition) -> Optio
53 for (r_range, _) in references { 53 for (r_range, _) in references {
54 let token = file.token_at_offset(r_range.start()).next()?; 54 let token = file.token_at_offset(r_range.start()).next()?;
55 let token = sema.descend_into_macros(token); 55 let token = sema.descend_into_macros(token);
56 let syntax = token.parent();
57
58 // This target is the containing function 56 // This target is the containing function
59 if let Some(nav) = syntax.ancestors().find_map(|node| { 57 if let Some(nav) = token.ancestors().find_map(|node| {
60 let fn_ = ast::Fn::cast(node)?; 58 let fn_ = ast::Fn::cast(node)?;
61 let def = sema.to_def(&fn_)?; 59 let def = sema.to_def(&fn_)?;
62 def.try_to_nav(sema.db) 60 def.try_to_nav(sema.db)
@@ -77,12 +75,13 @@ pub(crate) fn outgoing_calls(db: &RootDatabase, position: FilePosition) -> Optio
77 let file = file.syntax(); 75 let file = file.syntax();
78 let token = file.token_at_offset(position.offset).next()?; 76 let token = file.token_at_offset(position.offset).next()?;
79 let token = sema.descend_into_macros(token); 77 let token = sema.descend_into_macros(token);
80 let syntax = token.parent();
81 78
82 let mut calls = CallLocations::default(); 79 let mut calls = CallLocations::default();
83 80
84 syntax 81 token
85 .descendants() 82 .parent()
83 .into_iter()
84 .flat_map(|it| it.descendants())
86 .filter_map(|node| FnCallNode::with_node_exact(&node)) 85 .filter_map(|node| FnCallNode::with_node_exact(&node))
87 .filter_map(|call_node| { 86 .filter_map(|call_node| {
88 let name_ref = call_node.name_ref()?; 87 let name_ref = call_node.name_ref()?;
diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs
index 7bdd3cca3..461e11060 100644
--- a/crates/ide/src/doc_links.rs
+++ b/crates/ide/src/doc_links.rs
@@ -279,7 +279,7 @@ pub(crate) fn external_docs(
279 let token = pick_best(file.token_at_offset(position.offset))?; 279 let token = pick_best(file.token_at_offset(position.offset))?;
280 let token = sema.descend_into_macros(token); 280 let token = sema.descend_into_macros(token);
281 281
282 let node = token.parent(); 282 let node = token.parent()?;
283 let definition = match_ast! { 283 let definition = match_ast! {
284 match node { 284 match node {
285 ast::NameRef(name_ref) => NameRefClass::classify(&sema, &name_ref).map(|d| d.referenced(sema.db)), 285 ast::NameRef(name_ref) => NameRefClass::classify(&sema, &name_ref).map(|d| d.referenced(sema.db)),
diff --git a/crates/ide/src/extend_selection.rs b/crates/ide/src/extend_selection.rs
index b540d04fe..e187243cb 100644
--- a/crates/ide/src/extend_selection.rs
+++ b/crates/ide/src/extend_selection.rs
@@ -88,7 +88,7 @@ fn try_extend_selection(
88 return Some(range); 88 return Some(range);
89 } 89 }
90 } 90 }
91 token.parent() 91 token.parent()?
92 } 92 }
93 NodeOrToken::Node(node) => node, 93 NodeOrToken::Node(node) => node,
94 }; 94 };
@@ -142,7 +142,8 @@ fn extend_tokens_from_range(
142 let extended = { 142 let extended = {
143 let fst_expanded = sema.descend_into_macros(first_token.clone()); 143 let fst_expanded = sema.descend_into_macros(first_token.clone());
144 let lst_expanded = sema.descend_into_macros(last_token.clone()); 144 let lst_expanded = sema.descend_into_macros(last_token.clone());
145 let mut lca = algo::least_common_ancestor(&fst_expanded.parent(), &lst_expanded.parent())?; 145 let mut lca =
146 algo::least_common_ancestor(&fst_expanded.parent()?, &lst_expanded.parent()?)?;
146 lca = shallowest_node(&lca); 147 lca = shallowest_node(&lca);
147 if lca.first_token() == Some(fst_expanded) && lca.last_token() == Some(lst_expanded) { 148 if lca.first_token() == Some(fst_expanded) && lca.last_token() == Some(lst_expanded) {
148 lca = lca.parent()?; 149 lca = lca.parent()?;
@@ -151,9 +152,13 @@ fn extend_tokens_from_range(
151 }; 152 };
152 153
153 // Compute parent node range 154 // Compute parent node range
154 let validate = |token: &SyntaxToken| { 155 let validate = |token: &SyntaxToken| -> bool {
155 let expanded = sema.descend_into_macros(token.clone()); 156 let expanded = sema.descend_into_macros(token.clone());
156 algo::least_common_ancestor(&extended, &expanded.parent()).as_ref() == Some(&extended) 157 let parent = match expanded.parent() {
158 Some(it) => it,
159 None => return false,
160 };
161 algo::least_common_ancestor(&extended, &parent).as_ref() == Some(&extended)
157 }; 162 };
158 163
159 // Find the first and last text range under expanded parent 164 // Find the first and last text range under expanded parent
diff --git a/crates/ide/src/goto_definition.rs b/crates/ide/src/goto_definition.rs
index e8f31e4b1..6986477a5 100644
--- a/crates/ide/src/goto_definition.rs
+++ b/crates/ide/src/goto_definition.rs
@@ -30,7 +30,7 @@ pub(crate) fn goto_definition(
30 let file = sema.parse(position.file_id).syntax().clone(); 30 let file = sema.parse(position.file_id).syntax().clone();
31 let original_token = pick_best(file.token_at_offset(position.offset))?; 31 let original_token = pick_best(file.token_at_offset(position.offset))?;
32 let token = sema.descend_into_macros(original_token.clone()); 32 let token = sema.descend_into_macros(original_token.clone());
33 let parent = token.parent(); 33 let parent = token.parent()?;
34 if let Some(comment) = ast::Comment::cast(token) { 34 if let Some(comment) = ast::Comment::cast(token) {
35 let nav = def_for_doc_comment(&sema, position, &comment)?.try_to_nav(db)?; 35 let nav = def_for_doc_comment(&sema, position, &comment)?.try_to_nav(db)?;
36 return Some(RangeInfo::new(original_token.text_range(), vec![nav])); 36 return Some(RangeInfo::new(original_token.text_range(), vec![nav]));
@@ -63,7 +63,7 @@ fn def_for_doc_comment(
63 position: FilePosition, 63 position: FilePosition,
64 doc_comment: &ast::Comment, 64 doc_comment: &ast::Comment,
65) -> Option<hir::ModuleDef> { 65) -> Option<hir::ModuleDef> {
66 let parent = doc_comment.syntax().parent(); 66 let parent = doc_comment.syntax().parent()?;
67 let (link, ns) = extract_positioned_link_from_comment(position, doc_comment)?; 67 let (link, ns) = extract_positioned_link_from_comment(position, doc_comment)?;
68 68
69 let def = doc_owner_to_def(sema, parent)?; 69 let def = doc_owner_to_def(sema, parent)?;
diff --git a/crates/ide/src/goto_type_definition.rs b/crates/ide/src/goto_type_definition.rs
index 369a59820..2d38cb112 100644
--- a/crates/ide/src/goto_type_definition.rs
+++ b/crates/ide/src/goto_type_definition.rs
@@ -22,7 +22,7 @@ pub(crate) fn goto_type_definition(
22 let token: SyntaxToken = pick_best(file.syntax().token_at_offset(position.offset))?; 22 let token: SyntaxToken = pick_best(file.syntax().token_at_offset(position.offset))?;
23 let token: SyntaxToken = sema.descend_into_macros(token); 23 let token: SyntaxToken = sema.descend_into_macros(token);
24 24
25 let (ty, node) = sema.ancestors_with_macros(token.parent()).find_map(|node| { 25 let (ty, node) = sema.token_ancestors_with_macros(token).find_map(|node| {
26 let ty = match_ast! { 26 let ty = match_ast! {
27 match node { 27 match node {
28 ast::Expr(it) => sema.type_of_expr(&it)?, 28 ast::Expr(it) => sema.type_of_expr(&it)?,
diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs
index a35805c5e..8d45b4875 100644
--- a/crates/ide/src/hover.rs
+++ b/crates/ide/src/hover.rs
@@ -92,7 +92,7 @@ pub(crate) fn hover(
92 92
93 let mut res = HoverResult::default(); 93 let mut res = HoverResult::default();
94 94
95 let node = token.parent(); 95 let node = token.parent()?;
96 let definition = match_ast! { 96 let definition = match_ast! {
97 match node { 97 match node {
98 // we don't use NameClass::referenced_or_defined here as we do not want to resolve 98 // we don't use NameClass::referenced_or_defined here as we do not want to resolve
@@ -421,7 +421,7 @@ fn hover_for_keyword(
421 if !token.kind().is_keyword() { 421 if !token.kind().is_keyword() {
422 return None; 422 return None;
423 } 423 }
424 let famous_defs = FamousDefs(&sema, sema.scope(&token.parent()).krate()); 424 let famous_defs = FamousDefs(&sema, sema.scope(&token.parent()?).krate());
425 // std exposes {}_keyword modules with docstrings on the root to document keywords 425 // std exposes {}_keyword modules with docstrings on the root to document keywords
426 let keyword_mod = format!("{}_keyword", token.text()); 426 let keyword_mod = format!("{}_keyword", token.text());
427 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?; 427 let doc_owner = find_std_module(&famous_defs, &keyword_mod)?;
diff --git a/crates/ide/src/join_lines.rs b/crates/ide/src/join_lines.rs
index d571ed559..4b25135cd 100644
--- a/crates/ide/src/join_lines.rs
+++ b/crates/ide/src/join_lines.rs
@@ -32,29 +32,35 @@ pub(crate) fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
32 range 32 range
33 }; 33 };
34 34
35 let node = match file.syntax().covering_element(range) {
36 NodeOrToken::Node(node) => node,
37 NodeOrToken::Token(token) => token.parent(),
38 };
39 let mut edit = TextEdit::builder(); 35 let mut edit = TextEdit::builder();
40 for token in node.descendants_with_tokens().filter_map(|it| it.into_token()) { 36 match file.syntax().covering_element(range) {
41 let range = match range.intersect(token.text_range()) { 37 NodeOrToken::Node(node) => {
42 Some(range) => range, 38 for token in node.descendants_with_tokens().filter_map(|it| it.into_token()) {
43 None => continue, 39 remove_newlines(&mut edit, &token, range)
44 } - token.text_range().start();
45 let text = token.text();
46 for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
47 let pos: TextSize = (pos as u32).into();
48 let offset = token.text_range().start() + range.start() + pos;
49 if !edit.invalidates_offset(offset) {
50 remove_newline(&mut edit, &token, offset);
51 } 40 }
52 } 41 }
53 } 42 NodeOrToken::Token(token) => remove_newlines(&mut edit, &token, range),
54 43 };
55 edit.finish() 44 edit.finish()
56} 45}
57 46
47fn remove_newlines(edit: &mut TextEditBuilder, token: &SyntaxToken, range: TextRange) {
48 let intersection = match range.intersect(token.text_range()) {
49 Some(range) => range,
50 None => return,
51 };
52
53 let range = intersection - token.text_range().start();
54 let text = token.text();
55 for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
56 let pos: TextSize = (pos as u32).into();
57 let offset = token.text_range().start() + range.start() + pos;
58 if !edit.invalidates_offset(offset) {
59 remove_newline(edit, &token, offset);
60 }
61 }
62}
63
58fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextSize) { 64fn remove_newline(edit: &mut TextEditBuilder, token: &SyntaxToken, offset: TextSize) {
59 if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 { 65 if token.kind() != WHITESPACE || token.text().bytes().filter(|&b| b == b'\n').count() != 1 {
60 let mut string_open_quote = false; 66 let mut string_open_quote = false;
@@ -148,7 +154,7 @@ fn has_comma_after(node: &SyntaxNode) -> bool {
148} 154}
149 155
150fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> { 156fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
151 let block_expr = ast::BlockExpr::cast(token.parent())?; 157 let block_expr = ast::BlockExpr::cast(token.parent()?)?;
152 if !block_expr.is_standalone() { 158 if !block_expr.is_standalone() {
153 return None; 159 return None;
154 } 160 }
@@ -170,7 +176,7 @@ fn join_single_expr_block(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Op
170} 176}
171 177
172fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> { 178fn join_single_use_tree(edit: &mut TextEditBuilder, token: &SyntaxToken) -> Option<()> {
173 let use_tree_list = ast::UseTreeList::cast(token.parent())?; 179 let use_tree_list = ast::UseTreeList::cast(token.parent()?)?;
174 let (tree,) = use_tree_list.use_trees().collect_tuple()?; 180 let (tree,) = use_tree_list.use_trees().collect_tuple()?;
175 edit.replace(use_tree_list.syntax().text_range(), tree.syntax().text().to_string()); 181 edit.replace(use_tree_list.syntax().text_range(), tree.syntax().text().to_string());
176 Some(()) 182 Some(())
diff --git a/crates/ide/src/matching_brace.rs b/crates/ide/src/matching_brace.rs
index 000c412d9..4241a6dac 100644
--- a/crates/ide/src/matching_brace.rs
+++ b/crates/ide/src/matching_brace.rs
@@ -25,7 +25,7 @@ pub(crate) fn matching_brace(file: &SourceFile, offset: TextSize) -> Option<Text
25 Some((node, idx)) 25 Some((node, idx))
26 }) 26 })
27 .next()?; 27 .next()?;
28 let parent = brace_token.parent(); 28 let parent = brace_token.parent()?;
29 if brace_token.kind() == T![|] && !ast::ParamList::can_cast(parent.kind()) { 29 if brace_token.kind() == T![|] && !ast::ParamList::can_cast(parent.kind()) {
30 cov_mark::hit!(pipes_not_braces); 30 cov_mark::hit!(pipes_not_braces);
31 return None; 31 return None;
diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs
index ec7c7686d..e8a5666bc 100644
--- a/crates/ide/src/references.rs
+++ b/crates/ide/src/references.rs
@@ -148,14 +148,15 @@ fn decl_access(def: &Definition, syntax: &SyntaxNode, range: TextRange) -> Optio
148 148
149fn get_name_of_item_declaration(syntax: &SyntaxNode, position: FilePosition) -> Option<ast::Name> { 149fn get_name_of_item_declaration(syntax: &SyntaxNode, position: FilePosition) -> Option<ast::Name> {
150 let token = syntax.token_at_offset(position.offset).right_biased()?; 150 let token = syntax.token_at_offset(position.offset).right_biased()?;
151 let token_parent = token.parent()?;
151 let kind = token.kind(); 152 let kind = token.kind();
152 if kind == T![;] { 153 if kind == T![;] {
153 ast::Struct::cast(token.parent()) 154 ast::Struct::cast(token_parent)
154 .filter(|struct_| struct_.field_list().is_none()) 155 .filter(|struct_| struct_.field_list().is_none())
155 .and_then(|struct_| struct_.name()) 156 .and_then(|struct_| struct_.name())
156 } else if kind == T!['{'] { 157 } else if kind == T!['{'] {
157 match_ast! { 158 match_ast! {
158 match (token.parent()) { 159 match token_parent {
159 ast::RecordFieldList(rfl) => match_ast! { 160 ast::RecordFieldList(rfl) => match_ast! {
160 match (rfl.syntax().parent()?) { 161 match (rfl.syntax().parent()?) {
161 ast::Variant(it) => it.name(), 162 ast::Variant(it) => it.name(),
@@ -169,7 +170,7 @@ fn get_name_of_item_declaration(syntax: &SyntaxNode, position: FilePosition) ->
169 } 170 }
170 } 171 }
171 } else if kind == T!['('] { 172 } else if kind == T!['('] {
172 let tfl = ast::TupleFieldList::cast(token.parent())?; 173 let tfl = ast::TupleFieldList::cast(token_parent)?;
173 match_ast! { 174 match_ast! {
174 match (tfl.syntax().parent()?) { 175 match (tfl.syntax().parent()?) {
175 ast::Variant(it) => it.name(), 176 ast::Variant(it) => it.name(),
diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs
index 0c7a8fbf8..397e2126b 100644
--- a/crates/ide/src/runnables.rs
+++ b/crates/ide/src/runnables.rs
@@ -167,8 +167,7 @@ fn find_related_tests(
167 let functions = refs.iter().filter_map(|(range, _)| { 167 let functions = refs.iter().filter_map(|(range, _)| {
168 let token = file.token_at_offset(range.start()).next()?; 168 let token = file.token_at_offset(range.start()).next()?;
169 let token = sema.descend_into_macros(token); 169 let token = sema.descend_into_macros(token);
170 let syntax = token.parent(); 170 token.ancestors().find_map(ast::Fn::cast)
171 syntax.ancestors().find_map(ast::Fn::cast)
172 }); 171 });
173 172
174 for fn_def in functions { 173 for fn_def in functions {
diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs
index 9bed329d8..870146d24 100644
--- a/crates/ide/src/syntax_highlighting.rs
+++ b/crates/ide/src/syntax_highlighting.rs
@@ -64,7 +64,7 @@ pub(crate) fn highlight(
64 Some(range) => { 64 Some(range) => {
65 let node = match source_file.syntax().covering_element(range) { 65 let node = match source_file.syntax().covering_element(range) {
66 NodeOrToken::Node(it) => it, 66 NodeOrToken::Node(it) => it,
67 NodeOrToken::Token(it) => it.parent(), 67 NodeOrToken::Token(it) => it.parent().unwrap(),
68 }; 68 };
69 (node, range) 69 (node, range)
70 } 70 }
@@ -167,16 +167,19 @@ fn traverse(
167 let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT { 167 let element_to_highlight = if current_macro_call.is_some() && element.kind() != COMMENT {
168 // Inside a macro -- expand it first 168 // Inside a macro -- expand it first
169 let token = match element.clone().into_token() { 169 let token = match element.clone().into_token() {
170 Some(it) if it.parent().kind() == TOKEN_TREE => it, 170 Some(it) if it.parent().map_or(false, |it| it.kind() == TOKEN_TREE) => it,
171 _ => continue, 171 _ => continue,
172 }; 172 };
173 let token = sema.descend_into_macros(token.clone()); 173 let token = sema.descend_into_macros(token.clone());
174 let parent = token.parent(); 174 match token.parent() {
175 175 Some(parent) => {
176 // We only care Name and Name_ref 176 // We only care Name and Name_ref
177 match (token.kind(), parent.kind()) { 177 match (token.kind(), parent.kind()) {
178 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(), 178 (IDENT, NAME) | (IDENT, NAME_REF) => parent.into(),
179 _ => token.into(), 179 _ => token.into(),
180 }
181 }
182 None => token.into(),
180 } 183 }
181 } else { 184 } else {
182 element.clone() 185 element.clone()
diff --git a/crates/ide/src/syntax_highlighting/format.rs b/crates/ide/src/syntax_highlighting/format.rs
index 8c67a0863..e503abc93 100644
--- a/crates/ide/src/syntax_highlighting/format.rs
+++ b/crates/ide/src/syntax_highlighting/format.rs
@@ -28,7 +28,7 @@ pub(super) fn highlight_format_string(
28} 28}
29 29
30fn is_format_string(string: &ast::String) -> Option<()> { 30fn is_format_string(string: &ast::String) -> Option<()> {
31 let parent = string.syntax().parent(); 31 let parent = string.syntax().parent()?;
32 32
33 let name = parent.parent().and_then(ast::MacroCall::cast)?.path()?.segment()?.name_ref()?; 33 let name = parent.parent().and_then(ast::MacroCall::cast)?.path()?.segment()?.name_ref()?;
34 if !matches!(name.text(), "format_args" | "format_args_nl") { 34 if !matches!(name.text(), "format_args" | "format_args_nl") {
diff --git a/crates/ide/src/syntax_tree.rs b/crates/ide/src/syntax_tree.rs
index f979ba434..8979de528 100644
--- a/crates/ide/src/syntax_tree.rs
+++ b/crates/ide/src/syntax_tree.rs
@@ -27,7 +27,7 @@ pub(crate) fn syntax_tree(
27 if let Some(tree) = syntax_tree_for_string(&token, text_range) { 27 if let Some(tree) = syntax_tree_for_string(&token, text_range) {
28 return tree; 28 return tree;
29 } 29 }
30 token.parent() 30 token.parent().unwrap()
31 } 31 }
32 }; 32 };
33 33
diff --git a/crates/ide/src/typing.rs b/crates/ide/src/typing.rs
index a718faf63..e10b7d98e 100644
--- a/crates/ide/src/typing.rs
+++ b/crates/ide/src/typing.rs
@@ -108,7 +108,7 @@ fn on_dot_typed(file: &SourceFile, offset: TextSize) -> Option<TextEdit> {
108 }; 108 };
109 let current_indent_len = TextSize::of(current_indent); 109 let current_indent_len = TextSize::of(current_indent);
110 110
111 let parent = whitespace.syntax().parent(); 111 let parent = whitespace.syntax().parent()?;
112 // Make sure dot is a part of call chain 112 // Make sure dot is a part of call chain
113 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) { 113 if !matches!(parent.kind(), FIELD_EXPR | METHOD_CALL_EXPR) {
114 return None; 114 return None;
diff --git a/crates/ide_assists/src/handlers/add_turbo_fish.rs b/crates/ide_assists/src/handlers/add_turbo_fish.rs
index ee879c151..436767895 100644
--- a/crates/ide_assists/src/handlers/add_turbo_fish.rs
+++ b/crates/ide_assists/src/handlers/add_turbo_fish.rs
@@ -38,7 +38,7 @@ pub(crate) fn add_turbo_fish(acc: &mut Assists, ctx: &AssistContext) -> Option<(
38 cov_mark::hit!(add_turbo_fish_one_fish_is_enough); 38 cov_mark::hit!(add_turbo_fish_one_fish_is_enough);
39 return None; 39 return None;
40 } 40 }
41 let name_ref = ast::NameRef::cast(ident.parent())?; 41 let name_ref = ast::NameRef::cast(ident.parent()?)?;
42 let def = match NameRefClass::classify(&ctx.sema, &name_ref)? { 42 let def = match NameRefClass::classify(&ctx.sema, &name_ref)? {
43 NameRefClass::Definition(def) => def, 43 NameRefClass::Definition(def) => def,
44 NameRefClass::ExternCrate(_) | NameRefClass::FieldShorthand { .. } => return None, 44 NameRefClass::ExternCrate(_) | NameRefClass::FieldShorthand { .. } => return None,
diff --git a/crates/ide_assists/src/handlers/change_visibility.rs b/crates/ide_assists/src/handlers/change_visibility.rs
index ec99a5505..d7e39b2ae 100644
--- a/crates/ide_assists/src/handlers/change_visibility.rs
+++ b/crates/ide_assists/src/handlers/change_visibility.rs
@@ -41,7 +41,7 @@ fn add_vis(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
41 }); 41 });
42 42
43 let (offset, target) = if let Some(keyword) = item_keyword { 43 let (offset, target) = if let Some(keyword) = item_keyword {
44 let parent = keyword.parent(); 44 let parent = keyword.parent()?;
45 let def_kws = vec![CONST, STATIC, TYPE_ALIAS, FN, MODULE, STRUCT, ENUM, TRAIT]; 45 let def_kws = vec![CONST, STATIC, TYPE_ALIAS, FN, MODULE, STRUCT, ENUM, TRAIT];
46 // Parent is not a definition, can't add visibility 46 // Parent is not a definition, can't add visibility
47 if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) { 47 if !def_kws.iter().any(|&def_kw| def_kw == parent.kind()) {
diff --git a/crates/ide_assists/src/handlers/expand_glob_import.rs b/crates/ide_assists/src/handlers/expand_glob_import.rs
index 5fe617ba4..5b540df5c 100644
--- a/crates/ide_assists/src/handlers/expand_glob_import.rs
+++ b/crates/ide_assists/src/handlers/expand_glob_import.rs
@@ -48,7 +48,7 @@ pub(crate) fn expand_glob_import(acc: &mut Assists, ctx: &AssistContext) -> Opti
48 _ => return None, 48 _ => return None,
49 }; 49 };
50 50
51 let current_scope = ctx.sema.scope(&star.parent()); 51 let current_scope = ctx.sema.scope(&star.parent()?);
52 let current_module = current_scope.module()?; 52 let current_module = current_scope.module()?;
53 53
54 let refs_in_target = find_refs_in_mod(ctx, target_module, Some(current_module))?; 54 let refs_in_target = find_refs_in_mod(ctx, target_module, Some(current_module))?;
diff --git a/crates/ide_assists/src/handlers/extract_function.rs b/crates/ide_assists/src/handlers/extract_function.rs
index dd4501709..5fdc8bf38 100644
--- a/crates/ide_assists/src/handlers/extract_function.rs
+++ b/crates/ide_assists/src/handlers/extract_function.rs
@@ -16,7 +16,6 @@ use syntax::{
16 edit::{AstNodeEdit, IndentLevel}, 16 edit::{AstNodeEdit, IndentLevel},
17 AstNode, 17 AstNode,
18 }, 18 },
19 SyntaxElement,
20 SyntaxKind::{self, BLOCK_EXPR, BREAK_EXPR, COMMENT, PATH_EXPR, RETURN_EXPR}, 19 SyntaxKind::{self, BLOCK_EXPR, BREAK_EXPR, COMMENT, PATH_EXPR, RETURN_EXPR},
21 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T, 20 SyntaxNode, SyntaxToken, TextRange, TextSize, TokenAtOffset, WalkEvent, T,
22}; 21};
@@ -62,7 +61,10 @@ pub(crate) fn extract_function(acc: &mut Assists, ctx: &AssistContext) -> Option
62 return None; 61 return None;
63 } 62 }
64 63
65 let node = element_to_node(node); 64 let node = match node {
65 syntax::NodeOrToken::Node(n) => n,
66 syntax::NodeOrToken::Token(t) => t.parent()?,
67 };
66 68
67 let body = extraction_target(&node, ctx.frange.range)?; 69 let body = extraction_target(&node, ctx.frange.range)?;
68 70
@@ -560,14 +562,6 @@ impl HasTokenAtOffset for FunctionBody {
560 } 562 }
561} 563}
562 564
563/// node or token's parent
564fn element_to_node(node: SyntaxElement) -> SyntaxNode {
565 match node {
566 syntax::NodeOrToken::Node(n) => n,
567 syntax::NodeOrToken::Token(t) => t.parent(),
568 }
569}
570
571/// Try to guess what user wants to extract 565/// Try to guess what user wants to extract
572/// 566///
573/// We have basically have two cases: 567/// We have basically have two cases:
@@ -1246,7 +1240,7 @@ fn make_body(
1246 }) 1240 })
1247 } 1241 }
1248 FlowHandler::If { .. } => { 1242 FlowHandler::If { .. } => {
1249 let lit_false = ast::Literal::cast(make::tokens::literal("false").parent()).unwrap(); 1243 let lit_false = make::expr_literal("false");
1250 with_tail_expr(block, lit_false.into()) 1244 with_tail_expr(block, lit_false.into())
1251 } 1245 }
1252 FlowHandler::IfOption { .. } => { 1246 FlowHandler::IfOption { .. } => {
@@ -1420,9 +1414,7 @@ fn update_external_control_flow(handler: &FlowHandler, syntax: &SyntaxNode) -> S
1420fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> { 1414fn make_rewritten_flow(handler: &FlowHandler, arg_expr: Option<ast::Expr>) -> Option<ast::Expr> {
1421 let value = match handler { 1415 let value = match handler {
1422 FlowHandler::None | FlowHandler::Try { .. } => return None, 1416 FlowHandler::None | FlowHandler::Try { .. } => return None,
1423 FlowHandler::If { .. } => { 1417 FlowHandler::If { .. } => make::expr_literal("true").into(),
1424 ast::Literal::cast(make::tokens::literal("true").parent()).unwrap().into()
1425 }
1426 FlowHandler::IfOption { .. } => { 1418 FlowHandler::IfOption { .. } => {
1427 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new())); 1419 let expr = arg_expr.unwrap_or_else(|| make::expr_tuple(Vec::new()));
1428 let args = make::arg_list(iter::once(expr)); 1420 let args = make::arg_list(iter::once(expr));
diff --git a/crates/ide_assists/src/handlers/flip_trait_bound.rs b/crates/ide_assists/src/handlers/flip_trait_bound.rs
index d419d263e..a868aa43d 100644
--- a/crates/ide_assists/src/handlers/flip_trait_bound.rs
+++ b/crates/ide_assists/src/handlers/flip_trait_bound.rs
@@ -23,7 +23,7 @@ pub(crate) fn flip_trait_bound(acc: &mut Assists, ctx: &AssistContext) -> Option
23 let plus = ctx.find_token_syntax_at_offset(T![+])?; 23 let plus = ctx.find_token_syntax_at_offset(T![+])?;
24 24
25 // Make sure we're in a `TypeBoundList` 25 // Make sure we're in a `TypeBoundList`
26 if ast::TypeBoundList::cast(plus.parent()).is_none() { 26 if ast::TypeBoundList::cast(plus.parent()?).is_none() {
27 return None; 27 return None;
28 } 28 }
29 29
diff --git a/crates/ide_assists/src/handlers/invert_if.rs b/crates/ide_assists/src/handlers/invert_if.rs
index b131dc205..53612ec3f 100644
--- a/crates/ide_assists/src/handlers/invert_if.rs
+++ b/crates/ide_assists/src/handlers/invert_if.rs
@@ -30,7 +30,7 @@ use crate::{
30 30
31pub(crate) fn invert_if(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 31pub(crate) fn invert_if(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
32 let if_keyword = ctx.find_token_syntax_at_offset(T![if])?; 32 let if_keyword = ctx.find_token_syntax_at_offset(T![if])?;
33 let expr = ast::IfExpr::cast(if_keyword.parent())?; 33 let expr = ast::IfExpr::cast(if_keyword.parent()?)?;
34 let if_range = if_keyword.text_range(); 34 let if_range = if_keyword.text_range();
35 let cursor_in_range = if_range.contains_range(ctx.frange.range); 35 let cursor_in_range = if_range.contains_range(ctx.frange.range);
36 if !cursor_in_range { 36 if !cursor_in_range {
diff --git a/crates/ide_assists/src/handlers/move_bounds.rs b/crates/ide_assists/src/handlers/move_bounds.rs
index cf260c6f8..48efa67ed 100644
--- a/crates/ide_assists/src/handlers/move_bounds.rs
+++ b/crates/ide_assists/src/handlers/move_bounds.rs
@@ -1,8 +1,6 @@
1use syntax::{ 1use syntax::{
2 ast::{self, edit::AstNodeEdit, make, AstNode, NameOwner, TypeBoundsOwner}, 2 ast::{self, edit_in_place::GenericParamsOwnerEdit, make, AstNode, NameOwner, TypeBoundsOwner},
3 match_ast, 3 match_ast,
4 SyntaxKind::*,
5 T,
6}; 4};
7 5
8use crate::{AssistContext, AssistId, AssistKind, Assists}; 6use crate::{AssistContext, AssistId, AssistKind, Assists};
@@ -23,7 +21,7 @@ use crate::{AssistContext, AssistId, AssistKind, Assists};
23// } 21// }
24// ``` 22// ```
25pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 23pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
26 let type_param_list = ctx.find_node_at_offset::<ast::GenericParamList>()?; 24 let type_param_list = ctx.find_node_at_offset::<ast::GenericParamList>()?.clone_for_update();
27 25
28 let mut type_params = type_param_list.type_params(); 26 let mut type_params = type_param_list.type_params();
29 if type_params.all(|p| p.type_bound_list().is_none()) { 27 if type_params.all(|p| p.type_bound_list().is_none()) {
@@ -31,23 +29,7 @@ pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext
31 } 29 }
32 30
33 let parent = type_param_list.syntax().parent()?; 31 let parent = type_param_list.syntax().parent()?;
34 if parent.children_with_tokens().any(|it| it.kind() == WHERE_CLAUSE) { 32 let original_parent_range = parent.text_range();
35 return None;
36 }
37
38 let anchor = match_ast! {
39 match parent {
40 ast::Fn(it) => it.body()?.syntax().clone().into(),
41 ast::Trait(it) => it.assoc_item_list()?.syntax().clone().into(),
42 ast::Impl(it) => it.assoc_item_list()?.syntax().clone().into(),
43 ast::Enum(it) => it.variant_list()?.syntax().clone().into(),
44 ast::Struct(it) => {
45 it.syntax().children_with_tokens()
46 .find(|it| it.kind() == RECORD_FIELD_LIST || it.kind() == T![;])?
47 },
48 _ => return None
49 }
50 };
51 33
52 let target = type_param_list.syntax().text_range(); 34 let target = type_param_list.syntax().text_range();
53 acc.add( 35 acc.add(
@@ -55,29 +37,27 @@ pub(crate) fn move_bounds_to_where_clause(acc: &mut Assists, ctx: &AssistContext
55 "Move to where clause", 37 "Move to where clause",
56 target, 38 target,
57 |edit| { 39 |edit| {
58 let new_params = type_param_list 40 let where_clause: ast::WhereClause = match_ast! {
59 .type_params() 41 match parent {
60 .filter(|it| it.type_bound_list().is_some()) 42 ast::Fn(it) => it.get_or_create_where_clause(),
61 .map(|type_param| { 43 // ast::Trait(it) => it.get_or_create_where_clause(),
62 let without_bounds = type_param.remove_bounds(); 44 ast::Impl(it) => it.get_or_create_where_clause(),
63 (type_param, without_bounds) 45 // ast::Enum(it) => it.get_or_create_where_clause(),
64 }); 46 ast::Struct(it) => it.get_or_create_where_clause(),
65 47 _ => return,
66 let new_type_param_list = type_param_list.replace_descendants(new_params); 48 }
67 edit.replace_ast(type_param_list.clone(), new_type_param_list);
68
69 let where_clause = {
70 let predicates = type_param_list.type_params().filter_map(build_predicate);
71 make::where_clause(predicates)
72 }; 49 };
73 50
74 let to_insert = match anchor.prev_sibling_or_token() { 51 for type_param in type_param_list.type_params() {
75 Some(ref elem) if elem.kind() == WHITESPACE => { 52 if let Some(tbl) = type_param.type_bound_list() {
76 format!("{} ", where_clause.syntax()) 53 if let Some(predicate) = build_predicate(type_param.clone()) {
54 where_clause.add_predicate(predicate.clone_for_update())
55 }
56 tbl.remove()
77 } 57 }
78 _ => format!(" {}", where_clause.syntax()), 58 }
79 }; 59
80 edit.insert(anchor.text_range().start(), to_insert); 60 edit.replace(original_parent_range, parent.to_string())
81 }, 61 },
82 ) 62 )
83} 63}
diff --git a/crates/ide_assists/src/handlers/split_import.rs b/crates/ide_assists/src/handlers/split_import.rs
index 9319a4267..446f30544 100644
--- a/crates/ide_assists/src/handlers/split_import.rs
+++ b/crates/ide_assists/src/handlers/split_import.rs
@@ -17,7 +17,7 @@ use crate::{AssistContext, AssistId, AssistKind, Assists};
17// ``` 17// ```
18pub(crate) fn split_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> { 18pub(crate) fn split_import(acc: &mut Assists, ctx: &AssistContext) -> Option<()> {
19 let colon_colon = ctx.find_token_syntax_at_offset(T![::])?; 19 let colon_colon = ctx.find_token_syntax_at_offset(T![::])?;
20 let path = ast::Path::cast(colon_colon.parent())?.qualifier()?; 20 let path = ast::Path::cast(colon_colon.parent()?)?.qualifier()?;
21 let top_path = successors(Some(path.clone()), |it| it.parent_path()).last()?; 21 let top_path = successors(Some(path.clone()), |it| it.parent_path()).last()?;
22 22
23 let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast)?; 23 let use_tree = top_path.syntax().ancestors().find_map(ast::UseTree::cast)?;
diff --git a/crates/ide_assists/src/handlers/unwrap_block.rs b/crates/ide_assists/src/handlers/unwrap_block.rs
index ed6f6177d..440639322 100644
--- a/crates/ide_assists/src/handlers/unwrap_block.rs
+++ b/crates/ide_assists/src/handlers/unwrap_block.rs
@@ -30,7 +30,7 @@ pub(crate) fn unwrap_block(acc: &mut Assists, ctx: &AssistContext) -> Option<()>
30 let assist_label = "Unwrap block"; 30 let assist_label = "Unwrap block";
31 31
32 let l_curly_token = ctx.find_token_syntax_at_offset(T!['{'])?; 32 let l_curly_token = ctx.find_token_syntax_at_offset(T!['{'])?;
33 let mut block = ast::BlockExpr::cast(l_curly_token.parent())?; 33 let mut block = ast::BlockExpr::cast(l_curly_token.parent()?)?;
34 let target = block.syntax().text_range(); 34 let target = block.syntax().text_range();
35 let mut parent = block.syntax().parent()?; 35 let mut parent = block.syntax().parent()?;
36 if ast::MatchArm::can_cast(parent.kind()) { 36 if ast::MatchArm::can_cast(parent.kind()) {
diff --git a/crates/ide_completion/src/completions/fn_param.rs b/crates/ide_completion/src/completions/fn_param.rs
index 0243dce56..0ea558489 100644
--- a/crates/ide_completion/src/completions/fn_param.rs
+++ b/crates/ide_completion/src/completions/fn_param.rs
@@ -33,7 +33,7 @@ pub(crate) fn complete_fn_param(acc: &mut Completions, ctx: &CompletionContext)
33 }); 33 });
34 }; 34 };
35 35
36 for node in ctx.token.parent().ancestors() { 36 for node in ctx.token.ancestors() {
37 match_ast! { 37 match_ast! {
38 match node { 38 match node {
39 ast::SourceFile(it) => it.items().filter_map(|item| match item { 39 ast::SourceFile(it) => it.items().filter_map(|item| match item {
diff --git a/crates/ide_completion/src/completions/trait_impl.rs b/crates/ide_completion/src/completions/trait_impl.rs
index 5a7361f8e..a26fe7c6c 100644
--- a/crates/ide_completion/src/completions/trait_impl.rs
+++ b/crates/ide_completion/src/completions/trait_impl.rs
@@ -82,13 +82,14 @@ pub(crate) fn complete_trait_impl(acc: &mut Completions, ctx: &CompletionContext
82 82
83fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, SyntaxNode, Impl)> { 83fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, SyntaxNode, Impl)> {
84 let mut token = ctx.token.clone(); 84 let mut token = ctx.token.clone();
85 // For keywork without name like `impl .. { fn $0 }`, the current position is inside 85 // For keyword without name like `impl .. { fn $0 }`, the current position is inside
86 // the whitespace token, which is outside `FN` syntax node. 86 // the whitespace token, which is outside `FN` syntax node.
87 // We need to follow the previous token in this case. 87 // We need to follow the previous token in this case.
88 if token.kind() == SyntaxKind::WHITESPACE { 88 if token.kind() == SyntaxKind::WHITESPACE {
89 token = token.prev_token()?; 89 token = token.prev_token()?;
90 } 90 }
91 91
92 let parent_kind = token.parent().map_or(SyntaxKind::EOF, |it| it.kind());
92 let impl_item_offset = match token.kind() { 93 let impl_item_offset = match token.kind() {
93 // `impl .. { const $0 }` 94 // `impl .. { const $0 }`
94 // ERROR 0 95 // ERROR 0
@@ -102,14 +103,14 @@ fn completion_match(ctx: &CompletionContext) -> Option<(ImplCompletionKind, Synt
102 // FN/TYPE_ALIAS/CONST 1 103 // FN/TYPE_ALIAS/CONST 1
103 // NAME 0 104 // NAME 0
104 // IDENT <- * 105 // IDENT <- *
105 SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME => 1, 106 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME => 1,
106 // `impl .. { foo$0 }` 107 // `impl .. { foo$0 }`
107 // MACRO_CALL 3 108 // MACRO_CALL 3
108 // PATH 2 109 // PATH 2
109 // PATH_SEGMENT 1 110 // PATH_SEGMENT 1
110 // NAME_REF 0 111 // NAME_REF 0
111 // IDENT <- * 112 // IDENT <- *
112 SyntaxKind::IDENT if token.parent().kind() == SyntaxKind::NAME_REF => 3, 113 SyntaxKind::IDENT if parent_kind == SyntaxKind::NAME_REF => 3,
113 _ => return None, 114 _ => return None,
114 }; 115 };
115 116
diff --git a/crates/ide_completion/src/context.rs b/crates/ide_completion/src/context.rs
index e6cc6329c..8cbbdb477 100644
--- a/crates/ide_completion/src/context.rs
+++ b/crates/ide_completion/src/context.rs
@@ -120,7 +120,7 @@ impl<'a> CompletionContext<'a> {
120 let original_token = 120 let original_token =
121 original_file.syntax().token_at_offset(position.offset).left_biased()?; 121 original_file.syntax().token_at_offset(position.offset).left_biased()?;
122 let token = sema.descend_into_macros(original_token.clone()); 122 let token = sema.descend_into_macros(original_token.clone());
123 let scope = sema.scope_at_offset(&token.parent(), position.offset); 123 let scope = sema.scope_at_offset(&token, position.offset);
124 let mut locals = vec![]; 124 let mut locals = vec![];
125 scope.process_all_names(&mut |name, scope| { 125 scope.process_all_names(&mut |name, scope| {
126 if let ScopeDef::Local(local) = scope { 126 if let ScopeDef::Local(local) = scope {
@@ -281,7 +281,7 @@ impl<'a> CompletionContext<'a> {
281 fn fill_impl_def(&mut self) { 281 fn fill_impl_def(&mut self) {
282 self.impl_def = self 282 self.impl_def = self
283 .sema 283 .sema
284 .ancestors_with_macros(self.token.parent()) 284 .token_ancestors_with_macros(self.token.clone())
285 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE) 285 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
286 .find_map(ast::Impl::cast); 286 .find_map(ast::Impl::cast);
287 } 287 }
@@ -293,7 +293,10 @@ impl<'a> CompletionContext<'a> {
293 offset: TextSize, 293 offset: TextSize,
294 ) { 294 ) {
295 let expected = { 295 let expected = {
296 let mut node = self.token.parent(); 296 let mut node = match self.token.parent() {
297 Some(it) => it,
298 None => return,
299 };
297 loop { 300 loop {
298 let ret = match_ast! { 301 let ret = match_ast! {
299 match node { 302 match node {
@@ -474,17 +477,17 @@ impl<'a> CompletionContext<'a> {
474 } 477 }
475 478
476 self.use_item_syntax = 479 self.use_item_syntax =
477 self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::Use::cast); 480 self.sema.token_ancestors_with_macros(self.token.clone()).find_map(ast::Use::cast);
478 481
479 self.function_syntax = self 482 self.function_syntax = self
480 .sema 483 .sema
481 .ancestors_with_macros(self.token.parent()) 484 .token_ancestors_with_macros(self.token.clone())
482 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE) 485 .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
483 .find_map(ast::Fn::cast); 486 .find_map(ast::Fn::cast);
484 487
485 self.record_field_syntax = self 488 self.record_field_syntax = self
486 .sema 489 .sema
487 .ancestors_with_macros(self.token.parent()) 490 .token_ancestors_with_macros(self.token.clone())
488 .take_while(|it| { 491 .take_while(|it| {
489 it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR 492 it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR
490 }) 493 })
diff --git a/crates/ide_completion/src/patterns.rs b/crates/ide_completion/src/patterns.rs
index f3ce91dd1..cf5ef07b7 100644
--- a/crates/ide_completion/src/patterns.rs
+++ b/crates/ide_completion/src/patterns.rs
@@ -184,11 +184,7 @@ fn test_has_impl_as_prev_sibling() {
184} 184}
185 185
186pub(crate) fn is_in_loop_body(element: SyntaxElement) -> bool { 186pub(crate) fn is_in_loop_body(element: SyntaxElement) -> bool {
187 let leaf = match element { 187 for node in element.ancestors() {
188 NodeOrToken::Node(node) => node,
189 NodeOrToken::Token(token) => token.parent(),
190 };
191 for node in leaf.ancestors() {
192 if node.kind() == FN || node.kind() == CLOSURE_EXPR { 188 if node.kind() == FN || node.kind() == CLOSURE_EXPR {
193 break; 189 break;
194 } 190 }
@@ -201,7 +197,7 @@ pub(crate) fn is_in_loop_body(element: SyntaxElement) -> bool {
201 } 197 }
202 }; 198 };
203 if let Some(body) = loop_body { 199 if let Some(body) = loop_body {
204 if body.syntax().text_range().contains_range(leaf.text_range()) { 200 if body.syntax().text_range().contains_range(element.text_range()) {
205 return true; 201 return true;
206 } 202 }
207 } 203 }
@@ -235,12 +231,8 @@ fn previous_sibling_or_ancestor_sibling(element: SyntaxElement) -> Option<Syntax
235 Some(sibling) 231 Some(sibling)
236 } else { 232 } else {
237 // if not trying to find first ancestor which has such a sibling 233 // if not trying to find first ancestor which has such a sibling
238 let node = match element { 234 let range = element.text_range();
239 NodeOrToken::Node(node) => node, 235 let top_node = element.ancestors().take_while(|it| it.text_range() == range).last()?;
240 NodeOrToken::Token(token) => token.parent(),
241 };
242 let range = node.text_range();
243 let top_node = node.ancestors().take_while(|it| it.text_range() == range).last()?;
244 let prev_sibling_node = top_node.ancestors().find(|it| { 236 let prev_sibling_node = top_node.ancestors().find(|it| {
245 non_trivia_sibling(NodeOrToken::Node(it.to_owned()), Direction::Prev).is_some() 237 non_trivia_sibling(NodeOrToken::Node(it.to_owned()), Direction::Prev).is_some()
246 })?; 238 })?;
diff --git a/crates/ide_db/src/call_info.rs b/crates/ide_db/src/call_info.rs
index d8878aa91..d4016973c 100644
--- a/crates/ide_db/src/call_info.rs
+++ b/crates/ide_db/src/call_info.rs
@@ -109,7 +109,7 @@ fn call_info_impl(
109 token: SyntaxToken, 109 token: SyntaxToken,
110) -> Option<(hir::Callable, Option<usize>)> { 110) -> Option<(hir::Callable, Option<usize>)> {
111 // Find the calling expression and it's NameRef 111 // Find the calling expression and it's NameRef
112 let calling_node = FnCallNode::with_node(&token.parent())?; 112 let calling_node = FnCallNode::with_node(&token.parent()?)?;
113 113
114 let callable = match &calling_node { 114 let callable = match &calling_node {
115 FnCallNode::CallExpr(call) => sema.type_of_expr(&call.expr()?)?.as_callable(sema.db)?, 115 FnCallNode::CallExpr(call) => sema.type_of_expr(&call.expr()?)?.as_callable(sema.db)?,
diff --git a/crates/ide_ssr/src/resolving.rs b/crates/ide_ssr/src/resolving.rs
index af94c7bb1..dc7835473 100644
--- a/crates/ide_ssr/src/resolving.rs
+++ b/crates/ide_ssr/src/resolving.rs
@@ -195,7 +195,7 @@ impl<'db> ResolutionScope<'db> {
195 .syntax() 195 .syntax()
196 .token_at_offset(resolve_context.offset) 196 .token_at_offset(resolve_context.offset)
197 .left_biased() 197 .left_biased()
198 .map(|token| token.parent()) 198 .and_then(|token| token.parent())
199 .unwrap_or_else(|| file.syntax().clone()); 199 .unwrap_or_else(|| file.syntax().clone());
200 let node = pick_node_for_resolution(node); 200 let node = pick_node_for_resolution(node);
201 let scope = sema.scope(&node); 201 let scope = sema.scope(&node);
diff --git a/crates/syntax/Cargo.toml b/crates/syntax/Cargo.toml
index c0fd894b0..74cafaa8d 100644
--- a/crates/syntax/Cargo.toml
+++ b/crates/syntax/Cargo.toml
@@ -13,7 +13,7 @@ doctest = false
13[dependencies] 13[dependencies]
14cov-mark = { version = "1.1", features = ["thread-local"] } 14cov-mark = { version = "1.1", features = ["thread-local"] }
15itertools = "0.10.0" 15itertools = "0.10.0"
16rowan = "0.12.2" 16rowan = "0.13.0-pre.2"
17rustc_lexer = { version = "710.0.0", package = "rustc-ap-rustc_lexer" } 17rustc_lexer = { version = "710.0.0", package = "rustc-ap-rustc_lexer" }
18rustc-hash = "1.1.0" 18rustc-hash = "1.1.0"
19arrayvec = "0.5.1" 19arrayvec = "0.5.1"
diff --git a/crates/syntax/src/algo.rs b/crates/syntax/src/algo.rs
index b13252eec..82ebf9037 100644
--- a/crates/syntax/src/algo.rs
+++ b/crates/syntax/src/algo.rs
@@ -4,7 +4,6 @@ use std::{
4 fmt, 4 fmt,
5 hash::BuildHasherDefault, 5 hash::BuildHasherDefault,
6 ops::{self, RangeInclusive}, 6 ops::{self, RangeInclusive},
7 ptr,
8}; 7};
9 8
10use indexmap::IndexMap; 9use indexmap::IndexMap;
@@ -27,7 +26,7 @@ pub fn ancestors_at_offset(
27 offset: TextSize, 26 offset: TextSize,
28) -> impl Iterator<Item = SyntaxNode> { 27) -> impl Iterator<Item = SyntaxNode> {
29 node.token_at_offset(offset) 28 node.token_at_offset(offset)
30 .map(|token| token.parent().ancestors()) 29 .map(|token| token.ancestors())
31 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len()) 30 .kmerge_by(|node1, node2| node1.text_range().len() < node2.text_range().len())
32} 31}
33 32
@@ -171,7 +170,7 @@ pub fn diff(from: &SyntaxNode, to: &SyntaxNode) -> TreeDiff {
171 && lhs.text_range().len() == rhs.text_range().len() 170 && lhs.text_range().len() == rhs.text_range().len()
172 && match (&lhs, &rhs) { 171 && match (&lhs, &rhs) {
173 (NodeOrToken::Node(lhs), NodeOrToken::Node(rhs)) => { 172 (NodeOrToken::Node(lhs), NodeOrToken::Node(rhs)) => {
174 ptr::eq(lhs.green(), rhs.green()) || lhs.text() == rhs.text() 173 lhs == rhs || lhs.text() == rhs.text()
175 } 174 }
176 (NodeOrToken::Token(lhs), NodeOrToken::Token(rhs)) => lhs.text() == rhs.text(), 175 (NodeOrToken::Token(lhs), NodeOrToken::Token(rhs)) => lhs.text() == rhs.text(),
177 _ => false, 176 _ => false,
@@ -280,9 +279,10 @@ fn _insert_children(
280 to_green_element(element) 279 to_green_element(element)
281 }); 280 });
282 281
283 let mut old_children = parent.green().children().map(|it| match it { 282 let parent_green = parent.green();
284 NodeOrToken::Token(it) => NodeOrToken::Token(it.clone()), 283 let mut old_children = parent_green.children().map(|it| match it {
285 NodeOrToken::Node(it) => NodeOrToken::Node(it.clone()), 284 NodeOrToken::Token(it) => NodeOrToken::Token(it.to_owned()),
285 NodeOrToken::Node(it) => NodeOrToken::Node(it.to_owned()),
286 }); 286 });
287 287
288 let new_children = match &position { 288 let new_children = match &position {
@@ -319,9 +319,10 @@ fn _replace_children(
319) -> SyntaxNode { 319) -> SyntaxNode {
320 let start = position_of_child(parent, to_delete.start().clone()); 320 let start = position_of_child(parent, to_delete.start().clone());
321 let end = position_of_child(parent, to_delete.end().clone()); 321 let end = position_of_child(parent, to_delete.end().clone());
322 let mut old_children = parent.green().children().map(|it| match it { 322 let parent_green = parent.green();
323 NodeOrToken::Token(it) => NodeOrToken::Token(it.clone()), 323 let mut old_children = parent_green.children().map(|it| match it {
324 NodeOrToken::Node(it) => NodeOrToken::Node(it.clone()), 324 NodeOrToken::Token(it) => NodeOrToken::Token(it.to_owned()),
325 NodeOrToken::Node(it) => NodeOrToken::Node(it.to_owned()),
325 }); 326 });
326 327
327 let before = old_children.by_ref().take(start).collect::<Vec<_>>(); 328 let before = old_children.by_ref().take(start).collect::<Vec<_>>();
@@ -487,9 +488,9 @@ impl<'a> SyntaxRewriter<'a> {
487 /// Returns `None` when there are no replacements. 488 /// Returns `None` when there are no replacements.
488 pub fn rewrite_root(&self) -> Option<SyntaxNode> { 489 pub fn rewrite_root(&self) -> Option<SyntaxNode> {
489 let _p = profile::span("rewrite_root"); 490 let _p = profile::span("rewrite_root");
490 fn element_to_node_or_parent(element: &SyntaxElement) -> SyntaxNode { 491 fn element_to_node_or_parent(element: &SyntaxElement) -> Option<SyntaxNode> {
491 match element { 492 match element {
492 SyntaxElement::Node(it) => it.clone(), 493 SyntaxElement::Node(it) => Some(it.clone()),
493 SyntaxElement::Token(it) => it.parent(), 494 SyntaxElement::Token(it) => it.parent(),
494 } 495 }
495 } 496 }
@@ -497,9 +498,9 @@ impl<'a> SyntaxRewriter<'a> {
497 assert!(self.f.is_none()); 498 assert!(self.f.is_none());
498 self.replacements 499 self.replacements
499 .keys() 500 .keys()
500 .map(element_to_node_or_parent) 501 .filter_map(element_to_node_or_parent)
501 .chain(self.insertions.keys().map(|pos| match pos { 502 .chain(self.insertions.keys().filter_map(|pos| match pos {
502 InsertPos::FirstChildOf(it) => it.clone(), 503 InsertPos::FirstChildOf(it) => Some(it.clone()),
503 InsertPos::After(it) => element_to_node_or_parent(it), 504 InsertPos::After(it) => element_to_node_or_parent(it),
504 })) 505 }))
505 // If we only have one replacement/insertion, we must return its parent node, since `rewrite` does 506 // If we only have one replacement/insertion, we must return its parent node, since `rewrite` does
@@ -552,7 +553,7 @@ impl<'a> SyntaxRewriter<'a> {
552 }; 553 };
553 } else { 554 } else {
554 match element { 555 match element {
555 NodeOrToken::Token(it) => acc.push(NodeOrToken::Token(it.green().clone())), 556 NodeOrToken::Token(it) => acc.push(NodeOrToken::Token(it.green().to_owned())),
556 NodeOrToken::Node(it) => { 557 NodeOrToken::Node(it) => {
557 acc.push(NodeOrToken::Node(self.rewrite_children(it))); 558 acc.push(NodeOrToken::Node(self.rewrite_children(it)));
558 } 559 }
@@ -567,7 +568,7 @@ impl<'a> SyntaxRewriter<'a> {
567fn element_to_green(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> { 568fn element_to_green(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
568 match element { 569 match element {
569 NodeOrToken::Node(it) => NodeOrToken::Node(it.green().to_owned()), 570 NodeOrToken::Node(it) => NodeOrToken::Node(it.green().to_owned()),
570 NodeOrToken::Token(it) => NodeOrToken::Token(it.green().clone()), 571 NodeOrToken::Token(it) => NodeOrToken::Token(it.green().to_owned()),
571 } 572 }
572} 573}
573 574
@@ -625,7 +626,7 @@ fn position_of_child(parent: &SyntaxNode, child: SyntaxElement) -> usize {
625fn to_green_element(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> { 626fn to_green_element(element: SyntaxElement) -> NodeOrToken<rowan::GreenNode, rowan::GreenToken> {
626 match element { 627 match element {
627 NodeOrToken::Node(it) => it.green().to_owned().into(), 628 NodeOrToken::Node(it) => it.green().to_owned().into(),
628 NodeOrToken::Token(it) => it.green().clone().into(), 629 NodeOrToken::Token(it) => it.green().to_owned().into(),
629 } 630 }
630} 631}
631 632
diff --git a/crates/syntax/src/ast.rs b/crates/syntax/src/ast.rs
index b3a24d39d..19261686c 100644
--- a/crates/syntax/src/ast.rs
+++ b/crates/syntax/src/ast.rs
@@ -6,6 +6,7 @@ mod token_ext;
6mod node_ext; 6mod node_ext;
7mod expr_ext; 7mod expr_ext;
8pub mod edit; 8pub mod edit;
9pub mod edit_in_place;
9pub mod make; 10pub mod make;
10 11
11use std::marker::PhantomData; 12use std::marker::PhantomData;
@@ -40,6 +41,12 @@ pub trait AstNode {
40 Self: Sized; 41 Self: Sized;
41 42
42 fn syntax(&self) -> &SyntaxNode; 43 fn syntax(&self) -> &SyntaxNode;
44 fn clone_for_update(&self) -> Self
45 where
46 Self: Sized,
47 {
48 Self::cast(self.syntax().clone_for_update()).unwrap()
49 }
43} 50}
44 51
45/// Like `AstNode`, but wraps tokens rather than interior nodes. 52/// Like `AstNode`, but wraps tokens rather than interior nodes.
diff --git a/crates/syntax/src/ast/edit_in_place.rs b/crates/syntax/src/ast/edit_in_place.rs
new file mode 100644
index 000000000..06cde591d
--- /dev/null
+++ b/crates/syntax/src/ast/edit_in_place.rs
@@ -0,0 +1,105 @@
1//! Structural editing for ast.
2
3use std::iter::empty;
4
5use ast::{edit::AstNodeEdit, make, GenericParamsOwner, WhereClause};
6use parser::T;
7
8use crate::{
9 ast,
10 ted::{self, Position},
11 AstNode, Direction, SyntaxKind,
12};
13
14use super::NameOwner;
15
16pub trait GenericParamsOwnerEdit: ast::GenericParamsOwner + AstNodeEdit {
17 fn get_or_create_where_clause(&self) -> ast::WhereClause;
18}
19
20impl GenericParamsOwnerEdit for ast::Fn {
21 fn get_or_create_where_clause(&self) -> WhereClause {
22 if self.where_clause().is_none() {
23 let position = if let Some(ty) = self.ret_type() {
24 Position::after(ty.syntax().clone())
25 } else if let Some(param_list) = self.param_list() {
26 Position::after(param_list.syntax().clone())
27 } else {
28 Position::last_child_of(self.syntax().clone())
29 };
30 create_where_clause(position)
31 }
32 self.where_clause().unwrap()
33 }
34}
35
36impl GenericParamsOwnerEdit for ast::Impl {
37 fn get_or_create_where_clause(&self) -> WhereClause {
38 if self.where_clause().is_none() {
39 let position = if let Some(ty) = self.self_ty() {
40 Position::after(ty.syntax().clone())
41 } else {
42 Position::last_child_of(self.syntax().clone())
43 };
44 create_where_clause(position)
45 }
46 self.where_clause().unwrap()
47 }
48}
49impl GenericParamsOwnerEdit for ast::Struct {
50 fn get_or_create_where_clause(&self) -> WhereClause {
51 if self.where_clause().is_none() {
52 let tfl = self.field_list().and_then(|fl| match fl {
53 ast::FieldList::RecordFieldList(_) => None,
54 ast::FieldList::TupleFieldList(it) => Some(it),
55 });
56 let position = if let Some(tfl) = tfl {
57 Position::after(tfl.syntax().clone())
58 } else if let Some(gpl) = self.generic_param_list() {
59 Position::after(gpl.syntax().clone())
60 } else if let Some(name) = self.name() {
61 Position::after(name.syntax().clone())
62 } else {
63 Position::last_child_of(self.syntax().clone())
64 };
65 create_where_clause(position)
66 }
67 self.where_clause().unwrap()
68 }
69}
70
71fn create_where_clause(position: Position) {
72 let elements = vec![
73 make::tokens::single_space().into(),
74 make::where_clause(empty()).clone_for_update().syntax().clone().into(),
75 ];
76 ted::insert_all(position, elements);
77}
78
79impl ast::WhereClause {
80 pub fn add_predicate(&self, predicate: ast::WherePred) {
81 if let Some(pred) = self.predicates().last() {
82 if !pred.syntax().siblings_with_tokens(Direction::Next).any(|it| it.kind() == T![,]) {
83 ted::append_child(self.syntax().clone(), make::token(T![,]));
84 }
85 }
86 if self.syntax().children_with_tokens().last().map(|it| it.kind())
87 != Some(SyntaxKind::WHITESPACE)
88 {
89 ted::append_child(self.syntax().clone(), make::tokens::single_space());
90 }
91 ted::append_child(self.syntax().clone(), predicate.syntax().clone())
92 }
93}
94
95impl ast::TypeBoundList {
96 pub fn remove(&self) {
97 if let Some(colon) =
98 self.syntax().siblings_with_tokens(Direction::Prev).find(|it| it.kind() == T![:])
99 {
100 ted::remove_all(colon..=self.syntax().clone().into())
101 } else {
102 ted::remove(self.syntax().clone())
103 }
104 }
105}
diff --git a/crates/syntax/src/ast/make.rs b/crates/syntax/src/ast/make.rs
index 05a6b0b25..810c8d4c8 100644
--- a/crates/syntax/src/ast/make.rs
+++ b/crates/syntax/src/ast/make.rs
@@ -174,6 +174,11 @@ pub fn block_expr(
174pub fn expr_unit() -> ast::Expr { 174pub fn expr_unit() -> ast::Expr {
175 expr_from_text("()") 175 expr_from_text("()")
176} 176}
177pub fn expr_literal(text: &str) -> ast::Literal {
178 assert_eq!(text.trim(), text);
179 ast_from_text(&format!("fn f() {{ let _ = {}; }}", text))
180}
181
177pub fn expr_empty_block() -> ast::Expr { 182pub fn expr_empty_block() -> ast::Expr {
178 expr_from_text("{}") 183 expr_from_text("{}")
179} 184}
@@ -390,6 +395,7 @@ pub fn token(kind: SyntaxKind) -> SyntaxToken {
390 tokens::SOURCE_FILE 395 tokens::SOURCE_FILE
391 .tree() 396 .tree()
392 .syntax() 397 .syntax()
398 .clone_for_update()
393 .descendants_with_tokens() 399 .descendants_with_tokens()
394 .filter_map(|it| it.into_token()) 400 .filter_map(|it| it.into_token())
395 .find(|it| it.kind() == kind) 401 .find(|it| it.kind() == kind)
@@ -544,6 +550,7 @@ pub mod tokens {
544 SOURCE_FILE 550 SOURCE_FILE
545 .tree() 551 .tree()
546 .syntax() 552 .syntax()
553 .clone_for_update()
547 .descendants_with_tokens() 554 .descendants_with_tokens()
548 .filter_map(|it| it.into_token()) 555 .filter_map(|it| it.into_token())
549 .find(|it| it.kind() == WHITESPACE && it.text() == " ") 556 .find(|it| it.kind() == WHITESPACE && it.text() == " ")
@@ -569,13 +576,16 @@ pub mod tokens {
569 } 576 }
570 577
571 pub fn single_newline() -> SyntaxToken { 578 pub fn single_newline() -> SyntaxToken {
572 SOURCE_FILE 579 let res = SOURCE_FILE
573 .tree() 580 .tree()
574 .syntax() 581 .syntax()
582 .clone_for_update()
575 .descendants_with_tokens() 583 .descendants_with_tokens()
576 .filter_map(|it| it.into_token()) 584 .filter_map(|it| it.into_token())
577 .find(|it| it.kind() == WHITESPACE && it.text() == "\n") 585 .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
578 .unwrap() 586 .unwrap();
587 res.detach();
588 res
579 } 589 }
580 590
581 pub fn blank_line() -> SyntaxToken { 591 pub fn blank_line() -> SyntaxToken {
diff --git a/crates/syntax/src/ast/node_ext.rs b/crates/syntax/src/ast/node_ext.rs
index 52ac97c84..0b0d39a75 100644
--- a/crates/syntax/src/ast/node_ext.rs
+++ b/crates/syntax/src/ast/node_ext.rs
@@ -34,7 +34,9 @@ impl ast::NameRef {
34} 34}
35 35
36fn text_of_first_token(node: &SyntaxNode) -> &str { 36fn text_of_first_token(node: &SyntaxNode) -> &str {
37 node.green().children().next().and_then(|it| it.into_token()).unwrap().text() 37 let t =
38 node.green().children().next().and_then(|it| it.into_token()).unwrap().text().to_string();
39 Box::leak(Box::new(t))
38} 40}
39 41
40pub enum Macro { 42pub enum Macro {
diff --git a/crates/syntax/src/lib.rs b/crates/syntax/src/lib.rs
index 09e212e8c..2a5c61171 100644
--- a/crates/syntax/src/lib.rs
+++ b/crates/syntax/src/lib.rs
@@ -38,6 +38,7 @@ pub mod ast;
38#[doc(hidden)] 38#[doc(hidden)]
39pub mod fuzz; 39pub mod fuzz;
40pub mod utils; 40pub mod utils;
41pub mod ted;
41 42
42use std::{marker::PhantomData, sync::Arc}; 43use std::{marker::PhantomData, sync::Arc};
43 44
diff --git a/crates/syntax/src/parsing/reparsing.rs b/crates/syntax/src/parsing/reparsing.rs
index 3d637bf91..4ad50ab72 100644
--- a/crates/syntax/src/parsing/reparsing.rs
+++ b/crates/syntax/src/parsing/reparsing.rs
@@ -124,11 +124,7 @@ fn is_contextual_kw(text: &str) -> bool {
124fn find_reparsable_node(node: &SyntaxNode, range: TextRange) -> Option<(SyntaxNode, Reparser)> { 124fn find_reparsable_node(node: &SyntaxNode, range: TextRange) -> Option<(SyntaxNode, Reparser)> {
125 let node = node.covering_element(range); 125 let node = node.covering_element(range);
126 126
127 let mut ancestors = match node { 127 node.ancestors().find_map(|node| {
128 NodeOrToken::Token(it) => it.parent().ancestors(),
129 NodeOrToken::Node(it) => it.ancestors(),
130 };
131 ancestors.find_map(|node| {
132 let first_child = node.first_child_or_token().map(|it| it.kind()); 128 let first_child = node.first_child_or_token().map(|it| it.kind());
133 let parent = node.parent().map(|it| it.kind()); 129 let parent = node.parent().map(|it| it.kind());
134 Reparser::for_node(node.kind(), first_child, parent).map(|r| (node, r)) 130 Reparser::for_node(node.kind(), first_child, parent).map(|r| (node, r))
diff --git a/crates/syntax/src/ted.rs b/crates/syntax/src/ted.rs
new file mode 100644
index 000000000..8d6175ed9
--- /dev/null
+++ b/crates/syntax/src/ted.rs
@@ -0,0 +1,78 @@
1//! Primitive tree editor, ed for trees
2#![allow(unused)]
3use std::ops::RangeInclusive;
4
5use crate::{SyntaxElement, SyntaxNode};
6
7#[derive(Debug)]
8pub struct Position {
9 repr: PositionRepr,
10}
11
12#[derive(Debug)]
13enum PositionRepr {
14 FirstChild(SyntaxNode),
15 After(SyntaxElement),
16}
17
18impl Position {
19 pub fn after(elem: impl Into<SyntaxElement>) -> Position {
20 let repr = PositionRepr::After(elem.into());
21 Position { repr }
22 }
23 pub fn before(elem: impl Into<SyntaxElement>) -> Position {
24 let elem = elem.into();
25 let repr = match elem.prev_sibling_or_token() {
26 Some(it) => PositionRepr::After(it),
27 None => PositionRepr::FirstChild(elem.parent().unwrap()),
28 };
29 Position { repr }
30 }
31 pub fn first_child_of(node: impl Into<SyntaxNode>) -> Position {
32 let repr = PositionRepr::FirstChild(node.into());
33 Position { repr }
34 }
35 pub fn last_child_of(node: impl Into<SyntaxNode>) -> Position {
36 let node = node.into();
37 let repr = match node.last_child_or_token() {
38 Some(it) => PositionRepr::After(it),
39 None => PositionRepr::FirstChild(node),
40 };
41 Position { repr }
42 }
43}
44
45pub fn insert(position: Position, elem: impl Into<SyntaxElement>) {
46 insert_all(position, vec![elem.into()])
47}
48pub fn insert_all(position: Position, elements: Vec<SyntaxElement>) {
49 let (parent, index) = match position.repr {
50 PositionRepr::FirstChild(parent) => (parent, 0),
51 PositionRepr::After(child) => (child.parent().unwrap(), child.index() + 1),
52 };
53 parent.splice_children(index..index, elements);
54}
55
56pub fn remove(elem: impl Into<SyntaxElement>) {
57 let elem = elem.into();
58 remove_all(elem.clone()..=elem)
59}
60pub fn remove_all(range: RangeInclusive<SyntaxElement>) {
61 replace_all(range, Vec::new())
62}
63
64pub fn replace(old: impl Into<SyntaxElement>, new: impl Into<SyntaxElement>) {
65 let old = old.into();
66 replace_all(old.clone()..=old, vec![new.into()])
67}
68pub fn replace_all(range: RangeInclusive<SyntaxElement>, new: Vec<SyntaxElement>) {
69 let start = range.start().index();
70 let end = range.end().index();
71 let parent = range.start().parent().unwrap();
72 parent.splice_children(start..end + 1, new)
73}
74
75pub fn append_child(node: impl Into<SyntaxNode>, child: impl Into<SyntaxElement>) {
76 let position = Position::last_child_of(node);
77 insert(position, child)
78}