aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_assists/src/ast_editor.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_assists/src/ast_editor.rs')
-rw-r--r--crates/ra_assists/src/ast_editor.rs231
1 files changed, 3 insertions, 228 deletions
diff --git a/crates/ra_assists/src/ast_editor.rs b/crates/ra_assists/src/ast_editor.rs
index cf32ea52d..55c0aa59f 100644
--- a/crates/ra_assists/src/ast_editor.rs
+++ b/crates/ra_assists/src/ast_editor.rs
@@ -1,18 +1,18 @@
1use std::{iter, ops::RangeInclusive}; 1use std::{iter, ops::RangeInclusive};
2 2
3use arrayvec::ArrayVec; 3use arrayvec::ArrayVec;
4use itertools::Itertools;
5 4
6use hir::Name;
7use ra_fmt::leading_indent; 5use ra_fmt::leading_indent;
8use ra_syntax::{ 6use ra_syntax::{
9 algo::{insert_children, replace_children}, 7 algo::{insert_children, replace_children},
10 ast, AstNode, Direction, InsertPosition, SourceFile, SyntaxElement, 8 ast, AstNode, Direction, InsertPosition, SyntaxElement,
11 SyntaxKind::*, 9 SyntaxKind::*,
12 T, 10 T,
13}; 11};
14use ra_text_edit::TextEditBuilder; 12use ra_text_edit::TextEditBuilder;
15 13
14use crate::ast_builder::tokens;
15
16pub struct AstEditor<N: AstNode> { 16pub struct AstEditor<N: AstNode> {
17 original_ast: N, 17 original_ast: N,
18 ast: N, 18 ast: N,
@@ -240,228 +240,3 @@ impl AstEditor<ast::FnDef> {
240 self.ast = self.replace_children(replace_range, to_insert.into_iter()) 240 self.ast = self.replace_children(replace_range, to_insert.into_iter())
241 } 241 }
242} 242}
243
244pub struct AstBuilder<N: AstNode> {
245 _phantom: std::marker::PhantomData<N>,
246}
247
248impl AstBuilder<ast::RecordField> {
249 pub fn from_name(name: &Name) -> ast::RecordField {
250 ast_node_from_file_text(&format!("fn f() {{ S {{ {}: (), }} }}", name))
251 }
252
253 fn from_text(text: &str) -> ast::RecordField {
254 ast_node_from_file_text(&format!("fn f() {{ S {{ {}, }} }}", text))
255 }
256
257 pub fn from_pieces(name: &ast::NameRef, expr: Option<&ast::Expr>) -> ast::RecordField {
258 match expr {
259 Some(expr) => Self::from_text(&format!("{}: {}", name.syntax(), expr.syntax())),
260 None => Self::from_text(&name.syntax().to_string()),
261 }
262 }
263}
264
265impl AstBuilder<ast::Block> {
266 fn from_text(text: &str) -> ast::Block {
267 ast_node_from_file_text(&format!("fn f() {}", text))
268 }
269
270 pub fn single_expr(e: &ast::Expr) -> ast::Block {
271 Self::from_text(&format!("{{ {} }}", e.syntax()))
272 }
273}
274
275impl AstBuilder<ast::Expr> {
276 fn from_text(text: &str) -> ast::Expr {
277 ast_node_from_file_text(&format!("const C: () = {};", text))
278 }
279
280 pub fn unit() -> ast::Expr {
281 Self::from_text("()")
282 }
283
284 pub fn unimplemented() -> ast::Expr {
285 Self::from_text("unimplemented!()")
286 }
287}
288
289impl AstBuilder<ast::NameRef> {
290 pub fn new(text: &str) -> ast::NameRef {
291 ast_node_from_file_text(&format!("fn f() {{ {}; }}", text))
292 }
293}
294
295impl AstBuilder<ast::Path> {
296 fn from_text(text: &str) -> ast::Path {
297 ast_node_from_file_text(text)
298 }
299
300 pub fn from_name(name: ast::Name) -> ast::Path {
301 let name = name.syntax().to_string();
302 Self::from_text(name.as_str())
303 }
304
305 pub fn from_pieces(enum_name: ast::Name, var_name: ast::Name) -> ast::Path {
306 Self::from_text(&format!("{}::{}", enum_name.syntax(), var_name.syntax()))
307 }
308}
309
310impl AstBuilder<ast::BindPat> {
311 fn from_text(text: &str) -> ast::BindPat {
312 ast_node_from_file_text(&format!("fn f({}: ())", text))
313 }
314
315 pub fn from_name(name: &ast::Name) -> ast::BindPat {
316 Self::from_text(name.text())
317 }
318}
319
320impl AstBuilder<ast::PlaceholderPat> {
321 fn from_text(text: &str) -> ast::PlaceholderPat {
322 ast_node_from_file_text(&format!("fn f({}: ())", text))
323 }
324
325 pub fn placeholder() -> ast::PlaceholderPat {
326 Self::from_text("_")
327 }
328}
329
330impl AstBuilder<ast::TupleStructPat> {
331 fn from_text(text: &str) -> ast::TupleStructPat {
332 ast_node_from_file_text(&format!("fn f({}: ())", text))
333 }
334
335 pub fn from_pieces(
336 path: &ast::Path,
337 pats: impl Iterator<Item = ast::Pat>,
338 ) -> ast::TupleStructPat {
339 let pats_str = pats.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
340 Self::from_text(&format!("{}({})", path.syntax(), pats_str))
341 }
342}
343
344impl AstBuilder<ast::RecordPat> {
345 fn from_text(text: &str) -> ast::RecordPat {
346 ast_node_from_file_text(&format!("fn f({}: ())", text))
347 }
348
349 pub fn from_pieces(path: &ast::Path, pats: impl Iterator<Item = ast::Pat>) -> ast::RecordPat {
350 let pats_str = pats.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
351 Self::from_text(&format!("{}{{ {} }}", path.syntax(), pats_str))
352 }
353}
354
355impl AstBuilder<ast::PathPat> {
356 fn from_text(text: &str) -> ast::PathPat {
357 ast_node_from_file_text(&format!("fn f({}: ())", text))
358 }
359
360 pub fn from_path(path: &ast::Path) -> ast::PathPat {
361 let path_str = path.syntax().text().to_string();
362 Self::from_text(path_str.as_str())
363 }
364}
365
366impl AstBuilder<ast::MatchArm> {
367 fn from_text(text: &str) -> ast::MatchArm {
368 ast_node_from_file_text(&format!("fn f() {{ match () {{{}}} }}", text))
369 }
370
371 pub fn from_pieces(pats: impl Iterator<Item = ast::Pat>, expr: &ast::Expr) -> ast::MatchArm {
372 let pats_str = pats.map(|p| p.syntax().to_string()).join(" | ");
373 Self::from_text(&format!("{} => {}", pats_str, expr.syntax()))
374 }
375}
376
377impl AstBuilder<ast::MatchArmList> {
378 fn from_text(text: &str) -> ast::MatchArmList {
379 ast_node_from_file_text(&format!("fn f() {{ match () {{{}}} }}", text))
380 }
381
382 pub fn from_arms(arms: impl Iterator<Item = ast::MatchArm>) -> ast::MatchArmList {
383 let arms_str = arms.map(|arm| format!("\n {}", arm.syntax())).join(",");
384 Self::from_text(&format!("{},\n", arms_str))
385 }
386}
387
388impl AstBuilder<ast::WherePred> {
389 fn from_text(text: &str) -> ast::WherePred {
390 ast_node_from_file_text(&format!("fn f() where {} {{ }}", text))
391 }
392
393 pub fn from_pieces(
394 path: ast::Path,
395 bounds: impl Iterator<Item = ast::TypeBound>,
396 ) -> ast::WherePred {
397 let bounds = bounds.map(|b| b.syntax().to_string()).collect::<Vec<_>>().join(" + ");
398 Self::from_text(&format!("{}: {}", path.syntax(), bounds))
399 }
400}
401
402impl AstBuilder<ast::WhereClause> {
403 fn from_text(text: &str) -> ast::WhereClause {
404 ast_node_from_file_text(&format!("fn f() where {} {{ }}", text))
405 }
406
407 pub fn from_predicates(preds: impl Iterator<Item = ast::WherePred>) -> ast::WhereClause {
408 let preds = preds.map(|p| p.syntax().to_string()).collect::<Vec<_>>().join(", ");
409 Self::from_text(preds.as_str())
410 }
411}
412
413fn ast_node_from_file_text<N: AstNode>(text: &str) -> N {
414 let parse = SourceFile::parse(text);
415 let res = parse.tree().syntax().descendants().find_map(N::cast).unwrap();
416 res
417}
418
419mod tokens {
420 use once_cell::sync::Lazy;
421 use ra_syntax::{AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken, T};
422
423 static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| SourceFile::parse(",\n; ;"));
424
425 pub(crate) fn comma() -> SyntaxToken {
426 SOURCE_FILE
427 .tree()
428 .syntax()
429 .descendants_with_tokens()
430 .filter_map(|it| it.into_token())
431 .find(|it| it.kind() == T![,])
432 .unwrap()
433 }
434
435 pub(crate) fn single_space() -> SyntaxToken {
436 SOURCE_FILE
437 .tree()
438 .syntax()
439 .descendants_with_tokens()
440 .filter_map(|it| it.into_token())
441 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == " ")
442 .unwrap()
443 }
444
445 #[allow(unused)]
446 pub(crate) fn single_newline() -> SyntaxToken {
447 SOURCE_FILE
448 .tree()
449 .syntax()
450 .descendants_with_tokens()
451 .filter_map(|it| it.into_token())
452 .find(|it| it.kind() == WHITESPACE && it.text().as_str() == "\n")
453 .unwrap()
454 }
455
456 pub(crate) struct WsBuilder(SourceFile);
457
458 impl WsBuilder {
459 pub(crate) fn new(text: &str) -> WsBuilder {
460 WsBuilder(SourceFile::parse(text).ok().unwrap())
461 }
462 pub(crate) fn ws(&self) -> SyntaxToken {
463 self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()
464 }
465 }
466
467}