aboutsummaryrefslogtreecommitdiff
path: root/crates
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2019-04-21 15:47:55 +0100
committerAleksey Kladov <[email protected]>2019-04-21 18:51:20 +0100
commit7cc845e88d870173e1baa39ce4d3885a5b1f7043 (patch)
treed5342b6079aa55281ad605c0e8164479f87c8a8b /crates
parentee94edc722c9649bd16bb754959ad349593045e2 (diff)
start structured editing API
Diffstat (limited to 'crates')
-rw-r--r--crates/ra_assists/Cargo.toml2
-rw-r--r--crates/ra_assists/src/ast_editor.rs153
-rw-r--r--crates/ra_assists/src/lib.rs1
-rw-r--r--crates/ra_syntax/src/lib.rs2
-rw-r--r--crates/ra_syntax/src/ptr.rs2
-rw-r--r--crates/ra_syntax/src/syntax_node.rs81
6 files changed, 238 insertions, 3 deletions
diff --git a/crates/ra_assists/Cargo.toml b/crates/ra_assists/Cargo.toml
index d4056a349..29d9ceb59 100644
--- a/crates/ra_assists/Cargo.toml
+++ b/crates/ra_assists/Cargo.toml
@@ -5,8 +5,10 @@ version = "0.1.0"
5authors = ["rust-analyzer developers"] 5authors = ["rust-analyzer developers"]
6 6
7[dependencies] 7[dependencies]
8lazy_static = "1.3.0"
8join_to_string = "0.1.3" 9join_to_string = "0.1.3"
9itertools = "0.8.0" 10itertools = "0.8.0"
11arrayvec = "0.4.10"
10 12
11ra_syntax = { path = "../ra_syntax" } 13ra_syntax = { path = "../ra_syntax" }
12ra_text_edit = { path = "../ra_text_edit" } 14ra_text_edit = { path = "../ra_text_edit" }
diff --git a/crates/ra_assists/src/ast_editor.rs b/crates/ra_assists/src/ast_editor.rs
new file mode 100644
index 000000000..7347c1738
--- /dev/null
+++ b/crates/ra_assists/src/ast_editor.rs
@@ -0,0 +1,153 @@
1use arrayvec::ArrayVec;
2use ra_text_edit::{TextEdit, TextEditBuilder};
3use ra_syntax::{AstNode, TreeArc, ast, SyntaxKind::*, SyntaxElement, SourceFile, InsertPosition, Direction};
4
5pub struct AstEditor<N: AstNode> {
6 original_ast: TreeArc<N>,
7 ast: TreeArc<N>,
8}
9
10impl<N: AstNode> AstEditor<N> {
11 pub fn new(node: &N) -> AstEditor<N> {
12 AstEditor { original_ast: node.to_owned(), ast: node.to_owned() }
13 }
14
15 pub fn into_text_edit(self) -> TextEdit {
16 // FIXME: compute a more fine-grained diff here.
17 // If *you* know a nice algorithm to compute diff between two syntax
18 // tree, tell me about it!
19 let mut builder = TextEditBuilder::default();
20 builder.replace(self.original_ast.syntax().range(), self.ast().syntax().text().to_string());
21 builder.finish()
22 }
23
24 pub fn ast(&self) -> &N {
25 &*self.ast
26 }
27}
28
29impl AstEditor<ast::NamedFieldList> {
30 pub fn append_field(&mut self, field: &ast::NamedField) {
31 self.insert_field(InsertPosition::Last, field)
32 }
33
34 pub fn insert_field(
35 &mut self,
36 position: InsertPosition<&'_ ast::NamedField>,
37 field: &ast::NamedField,
38 ) {
39 let mut to_insert: ArrayVec<[SyntaxElement; 2]> =
40 [field.syntax().into(), tokens::comma().into()].into();
41 let position = match position {
42 InsertPosition::First => {
43 let anchor = match self
44 .ast()
45 .syntax()
46 .children_with_tokens()
47 .find(|it| it.kind() == L_CURLY)
48 {
49 Some(it) => it,
50 None => return,
51 };
52 InsertPosition::After(anchor)
53 }
54 InsertPosition::Last => {
55 let anchor = match self
56 .ast()
57 .syntax()
58 .children_with_tokens()
59 .find(|it| it.kind() == R_CURLY)
60 {
61 Some(it) => it,
62 None => return,
63 };
64 InsertPosition::Before(anchor)
65 }
66 InsertPosition::Before(anchor) => InsertPosition::Before(anchor.syntax().into()),
67 InsertPosition::After(anchor) => {
68 if let Some(comma) = anchor
69 .syntax()
70 .siblings_with_tokens(Direction::Next)
71 .find(|it| it.kind() == COMMA)
72 {
73 InsertPosition::After(comma)
74 } else {
75 to_insert.insert(0, tokens::comma().into());
76 InsertPosition::After(anchor.syntax().into())
77 }
78 }
79 };
80 self.ast = insert_children_into_ast(self.ast(), position, to_insert.iter().cloned());
81 }
82}
83
84fn insert_children_into_ast<'a, N: AstNode>(
85 node: &N,
86 position: InsertPosition<SyntaxElement<'_>>,
87 to_insert: impl Iterator<Item = SyntaxElement<'a>>,
88) -> TreeArc<N> {
89 let new_syntax = node.syntax().insert_children(position, to_insert);
90 N::cast(&new_syntax).unwrap().to_owned()
91}
92
93pub struct AstBuilder<N: AstNode> {
94 _phantom: std::marker::PhantomData<N>,
95}
96
97impl AstBuilder<ast::NamedField> {
98 pub fn from_text(text: &str) -> TreeArc<ast::NamedField> {
99 ast_node_from_file_text(&format!("fn f() {{ S {{ {}, }} }}", text))
100 }
101}
102
103fn ast_node_from_file_text<N: AstNode>(text: &str) -> TreeArc<N> {
104 let file = SourceFile::parse(text);
105 let res = file.syntax().descendants().find_map(N::cast).unwrap().to_owned();
106 res
107}
108
109mod tokens {
110 use lazy_static::lazy_static;
111 use ra_syntax::{AstNode, SourceFile, TreeArc, SyntaxToken, SyntaxKind::*};
112
113 lazy_static! {
114 static ref SOURCE_FILE: TreeArc<SourceFile> = SourceFile::parse(",");
115 }
116
117 pub(crate) fn comma() -> SyntaxToken<'static> {
118 SOURCE_FILE
119 .syntax()
120 .descendants_with_tokens()
121 .filter_map(|it| it.as_token())
122 .find(|it| it.kind() == COMMA)
123 .unwrap()
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130
131 use ra_syntax::SourceFile;
132
133 #[test]
134 fn structure_editing() {
135 let file = SourceFile::parse(
136 "\
137fn foo() {
138 let s = S {
139 original: 92,
140 }
141}
142",
143 );
144 let field_list = file.syntax().descendants().find_map(ast::NamedFieldList::cast).unwrap();
145 let mut editor = AstEditor::new(field_list);
146
147 let field = AstBuilder::<ast::NamedField>::from_text("first_inserted: 1");
148 editor.append_field(&field);
149 let field = AstBuilder::<ast::NamedField>::from_text("second_inserted: 2");
150 editor.append_field(&field);
151 eprintln!("{}", editor.ast().syntax());
152 }
153}
diff --git a/crates/ra_assists/src/lib.rs b/crates/ra_assists/src/lib.rs
index ded401b63..3151b1c44 100644
--- a/crates/ra_assists/src/lib.rs
+++ b/crates/ra_assists/src/lib.rs
@@ -7,6 +7,7 @@
7 7
8mod assist_ctx; 8mod assist_ctx;
9mod marks; 9mod marks;
10pub mod ast_editor;
10 11
11use itertools::Itertools; 12use itertools::Itertools;
12 13
diff --git a/crates/ra_syntax/src/lib.rs b/crates/ra_syntax/src/lib.rs
index a6ce14f06..9cb66b76b 100644
--- a/crates/ra_syntax/src/lib.rs
+++ b/crates/ra_syntax/src/lib.rs
@@ -38,7 +38,7 @@ pub use crate::{
38 ast::AstNode, 38 ast::AstNode,
39 syntax_error::{SyntaxError, SyntaxErrorKind, Location}, 39 syntax_error::{SyntaxError, SyntaxErrorKind, Location},
40 syntax_text::SyntaxText, 40 syntax_text::SyntaxText,
41 syntax_node::{Direction, SyntaxNode, WalkEvent, TreeArc, SyntaxTreeBuilder, SyntaxElement, SyntaxToken}, 41 syntax_node::{Direction, SyntaxNode, WalkEvent, TreeArc, SyntaxTreeBuilder, SyntaxElement, SyntaxToken, InsertPosition},
42 ptr::{SyntaxNodePtr, AstPtr}, 42 ptr::{SyntaxNodePtr, AstPtr},
43 parsing::{tokenize, classify_literal, Token}, 43 parsing::{tokenize, classify_literal, Token},
44}; 44};
diff --git a/crates/ra_syntax/src/ptr.rs b/crates/ra_syntax/src/ptr.rs
index 15a8b94cd..b0816b135 100644
--- a/crates/ra_syntax/src/ptr.rs
+++ b/crates/ra_syntax/src/ptr.rs
@@ -10,7 +10,7 @@ use crate::{
10/// specific node across reparses of the same file. 10/// specific node across reparses of the same file.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] 11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub struct SyntaxNodePtr { 12pub struct SyntaxNodePtr {
13 range: TextRange, 13 pub(crate) range: TextRange,
14 kind: SyntaxKind, 14 kind: SyntaxKind,
15} 15}
16 16
diff --git a/crates/ra_syntax/src/syntax_node.rs b/crates/ra_syntax/src/syntax_node.rs
index dc2352c76..d9591781d 100644
--- a/crates/ra_syntax/src/syntax_node.rs
+++ b/crates/ra_syntax/src/syntax_node.rs
@@ -17,13 +17,20 @@ use ra_parser::ParseError;
17use rowan::{TransparentNewType, GreenNodeBuilder}; 17use rowan::{TransparentNewType, GreenNodeBuilder};
18 18
19use crate::{ 19use crate::{
20 SmolStr, SyntaxKind, TextUnit, TextRange, SyntaxText, SourceFile, AstNode, 20 SmolStr, SyntaxKind, TextUnit, TextRange, SyntaxText, SourceFile, AstNode, SyntaxNodePtr,
21 syntax_error::{SyntaxError, SyntaxErrorKind}, 21 syntax_error::{SyntaxError, SyntaxErrorKind},
22}; 22};
23 23
24pub use rowan::WalkEvent; 24pub use rowan::WalkEvent;
25pub(crate) use rowan::{GreenNode, GreenToken}; 25pub(crate) use rowan::{GreenNode, GreenToken};
26 26
27pub enum InsertPosition<T> {
28 First,
29 Last,
30 Before(T),
31 After(T),
32}
33
27/// Marker trait for CST and AST nodes 34/// Marker trait for CST and AST nodes
28pub trait SyntaxNodeWrapper: TransparentNewType<Repr = rowan::SyntaxNode> {} 35pub trait SyntaxNodeWrapper: TransparentNewType<Repr = rowan::SyntaxNode> {}
29impl<T: TransparentNewType<Repr = rowan::SyntaxNode>> SyntaxNodeWrapper for T {} 36impl<T: TransparentNewType<Repr = rowan::SyntaxNode>> SyntaxNodeWrapper for T {}
@@ -309,6 +316,71 @@ impl SyntaxNode {
309 pub(crate) fn replace_with(&self, replacement: GreenNode) -> GreenNode { 316 pub(crate) fn replace_with(&self, replacement: GreenNode) -> GreenNode {
310 self.0.replace_with(replacement) 317 self.0.replace_with(replacement)
311 } 318 }
319
320 /// Adds specified children (tokens or nodes) to the current node at the
321 /// specific position.
322 ///
323 /// This is a type-unsafe low-level editing API, if you need to use it,
324 /// prefer to create a type-safe abstraction on top of it instead.
325 ///
326 ///
327 pub fn insert_children<'a>(
328 &self,
329 position: InsertPosition<SyntaxElement<'_>>,
330 to_insert: impl Iterator<Item = SyntaxElement<'a>>,
331 ) -> TreeArc<SyntaxNode> {
332 let mut delta = TextUnit::default();
333 let to_insert = to_insert.map(|element| {
334 delta += element.text_len();
335 to_green_element(element)
336 });
337
338 let old_children = self.0.green().children();
339
340 let get_anchor_pos = |anchor: SyntaxElement| -> usize {
341 self.children_with_tokens()
342 .position(|it| it == anchor)
343 .expect("anchor is not a child of current element")
344 };
345
346 let new_children = match position {
347 InsertPosition::First => {
348 to_insert.chain(old_children.iter().cloned()).collect::<Box<[_]>>()
349 }
350 InsertPosition::Last => {
351 old_children.iter().cloned().chain(to_insert).collect::<Box<[_]>>()
352 }
353 InsertPosition::Before(anchor) | InsertPosition::After(anchor) => {
354 let take_anchor = if let InsertPosition::After(_) = position { 1 } else { 0 };
355 let (before, after) = old_children.split_at(get_anchor_pos(anchor) + take_anchor);
356 before
357 .iter()
358 .cloned()
359 .chain(to_insert)
360 .chain(after.iter().cloned())
361 .collect::<Box<[_]>>()
362 }
363 };
364
365 let new_node = GreenNode::new(rowan::SyntaxKind(self.kind() as u16), new_children);
366 let new_file_node = self.replace_with(new_node);
367 let file = SourceFile::new(new_file_node, Vec::new());
368
369 // FIXME: use a more elegant way to re-fetch the node (#1185), make
370 // `range` private afterwards
371 let mut ptr = SyntaxNodePtr::new(self);
372 ptr.range = TextRange::from_to(ptr.range().start(), ptr.range().end() + delta);
373 return ptr.to_node(&file).to_owned();
374
375 fn to_green_element(element: SyntaxElement) -> rowan::GreenElement {
376 match element {
377 SyntaxElement::Node(node) => node.0.green().clone().into(),
378 SyntaxElement::Token(tok) => {
379 GreenToken::new(rowan::SyntaxKind(tok.kind() as u16), tok.text().clone()).into()
380 }
381 }
382 }
383 }
312} 384}
313 385
314#[derive(Clone, Copy, PartialEq, Eq, Hash)] 386#[derive(Clone, Copy, PartialEq, Eq, Hash)]
@@ -451,6 +523,13 @@ impl<'a> SyntaxElement<'a> {
451 } 523 }
452 .ancestors() 524 .ancestors()
453 } 525 }
526
527 fn text_len(&self) -> TextUnit {
528 match self {
529 SyntaxElement::Node(node) => node.0.green().text_len(),
530 SyntaxElement::Token(token) => TextUnit::of_str(token.0.text()),
531 }
532 }
454} 533}
455 534
456impl<'a> From<rowan::SyntaxElement<'a>> for SyntaxElement<'a> { 535impl<'a> From<rowan::SyntaxElement<'a>> for SyntaxElement<'a> {