]> git.lizzy.rs Git - rust.git/blob - crates/ide_ssr/src/fragments.rs
add ssr fragment for statements
[rust.git] / crates / ide_ssr / src / fragments.rs
1 //! When specifying SSR rule, you generally want to map one *kind* of thing to
2 //! the same kind of thing: path to path, expression to expression, type to
3 //! type.
4 //!
5 //! The problem is, while this *kind* is generally obvious to the human, the ide
6 //! needs to determine it somehow. We do this in a stupid way -- by pasting SSR
7 //! rule into different contexts and checking what works.
8
9 use syntax::{ast, AstNode, SyntaxNode};
10
11 pub(crate) fn ty(s: &str) -> Result<SyntaxNode, ()> {
12     let template = "type T = {};";
13     let input = template.replace("{}", s);
14     let parse = syntax::SourceFile::parse(&input);
15     if !parse.errors().is_empty() {
16         return Err(());
17     }
18     let node = parse.tree().syntax().descendants().find_map(ast::Type::cast).ok_or(())?;
19     if node.to_string() != s {
20         return Err(());
21     }
22     Ok(node.syntax().clone_subtree())
23 }
24
25 pub(crate) fn item(s: &str) -> Result<SyntaxNode, ()> {
26     let template = "{}";
27     let input = template.replace("{}", s);
28     let parse = syntax::SourceFile::parse(&input);
29     if !parse.errors().is_empty() {
30         return Err(());
31     }
32     let node = parse.tree().syntax().descendants().find_map(ast::Item::cast).ok_or(())?;
33     if node.to_string() != s {
34         return Err(());
35     }
36     Ok(node.syntax().clone_subtree())
37 }
38
39 pub(crate) fn expr(s: &str) -> Result<SyntaxNode, ()> {
40     let template = "const _: () = {};";
41     let input = template.replace("{}", s);
42     let parse = syntax::SourceFile::parse(&input);
43     if !parse.errors().is_empty() {
44         return Err(());
45     }
46     let node = parse.tree().syntax().descendants().find_map(ast::Expr::cast).ok_or(())?;
47     if node.to_string() != s {
48         return Err(());
49     }
50     Ok(node.syntax().clone_subtree())
51 }
52
53 pub(crate) fn stmt(s: &str) -> Result<SyntaxNode, ()> {
54     let template = "const _: () = { {}; };";
55     let input = template.replace("{}", s);
56     let parse = syntax::SourceFile::parse(&input);
57     if !parse.errors().is_empty() {
58         return Err(());
59     }
60     let mut node =
61         parse.tree().syntax().descendants().skip(2).find_map(ast::Stmt::cast).ok_or(())?;
62     if !s.ends_with(';') && node.to_string().ends_with(';') {
63         node = node.clone_for_update();
64         node.syntax().last_token().map(|it| it.detach());
65     }
66     if node.to_string() != s {
67         return Err(());
68     }
69     Ok(node.syntax().clone_subtree())
70 }