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
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.
9 use syntax::{ast, AstNode, SyntaxNode};
11 pub(crate) fn ty(s: &str) -> Result<SyntaxNode, ()> {
12 fragment::<ast::Type>("type T = {};", s)
15 pub(crate) fn item(s: &str) -> Result<SyntaxNode, ()> {
16 fragment::<ast::Item>("{}", s)
19 pub(crate) fn pat(s: &str) -> Result<SyntaxNode, ()> {
20 fragment::<ast::Pat>("const _: () = {let {} = ();};", s)
23 pub(crate) fn expr(s: &str) -> Result<SyntaxNode, ()> {
24 fragment::<ast::Expr>("const _: () = {};", s)
27 pub(crate) fn stmt(s: &str) -> Result<SyntaxNode, ()> {
28 let template = "const _: () = { {}; };";
29 let input = template.replace("{}", s);
30 let parse = syntax::SourceFile::parse(&input);
31 if !parse.errors().is_empty() {
35 parse.tree().syntax().descendants().skip(2).find_map(ast::Stmt::cast).ok_or(())?;
36 if !s.ends_with(';') && node.to_string().ends_with(';') {
37 node = node.clone_for_update();
38 node.syntax().last_token().map(|it| it.detach());
40 if node.to_string() != s {
43 Ok(node.syntax().clone_subtree())
46 fn fragment<T: AstNode>(template: &str, s: &str) -> Result<SyntaxNode, ()> {
48 let input = template.replace("{}", s);
49 let parse = syntax::SourceFile::parse(&input);
50 if !parse.errors().is_empty() {
53 let node = parse.tree().syntax().descendants().find_map(T::cast).ok_or(())?;
54 if node.syntax().text() != s {
57 Ok(node.syntax().clone_subtree())