2021-12-27 10:44:45 -06:00
|
|
|
//! When specifying SSR rule, you generally want to map one *kind* of thing to
|
|
|
|
//! the same kind of thing: path to path, expression to expression, type to
|
|
|
|
//! type.
|
|
|
|
//!
|
|
|
|
//! The problem is, while this *kind* is generally obvious to the human, the ide
|
|
|
|
//! needs to determine it somehow. We do this in a stupid way -- by pasting SSR
|
|
|
|
//! rule into different contexts and checking what works.
|
|
|
|
|
|
|
|
use syntax::{ast, AstNode, SyntaxNode};
|
|
|
|
|
|
|
|
pub(crate) fn ty(s: &str) -> Result<SyntaxNode, ()> {
|
2021-12-28 10:17:34 -06:00
|
|
|
fragment::<ast::Type>("type T = {};", s)
|
2021-12-27 10:44:45 -06:00
|
|
|
}
|
2021-12-27 11:33:33 -06:00
|
|
|
|
|
|
|
pub(crate) fn item(s: &str) -> Result<SyntaxNode, ()> {
|
2021-12-28 10:17:34 -06:00
|
|
|
fragment::<ast::Item>("{}", s)
|
2021-12-27 11:33:33 -06:00
|
|
|
}
|
2021-12-27 12:13:55 -06:00
|
|
|
|
2021-12-27 12:33:24 -06:00
|
|
|
pub(crate) fn pat(s: &str) -> Result<SyntaxNode, ()> {
|
2021-12-28 10:17:34 -06:00
|
|
|
fragment::<ast::Pat>("const _: () = {let {} = ();};", s)
|
2021-12-27 12:33:24 -06:00
|
|
|
}
|
|
|
|
|
2021-12-27 12:13:55 -06:00
|
|
|
pub(crate) fn expr(s: &str) -> Result<SyntaxNode, ()> {
|
2021-12-28 10:17:34 -06:00
|
|
|
fragment::<ast::Expr>("const _: () = {};", s)
|
2021-12-27 12:17:40 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn stmt(s: &str) -> Result<SyntaxNode, ()> {
|
|
|
|
let template = "const _: () = { {}; };";
|
|
|
|
let input = template.replace("{}", s);
|
2024-04-14 09:02:38 -05:00
|
|
|
let parse = syntax::SourceFile::parse(&input, syntax::Edition::CURRENT);
|
2021-12-27 12:17:40 -06:00
|
|
|
if !parse.errors().is_empty() {
|
|
|
|
return Err(());
|
|
|
|
}
|
|
|
|
let mut node =
|
|
|
|
parse.tree().syntax().descendants().skip(2).find_map(ast::Stmt::cast).ok_or(())?;
|
|
|
|
if !s.ends_with(';') && node.to_string().ends_with(';') {
|
|
|
|
node = node.clone_for_update();
|
2024-01-18 06:59:49 -06:00
|
|
|
if let Some(it) = node.syntax().last_token() {
|
|
|
|
it.detach()
|
|
|
|
}
|
2021-12-27 12:17:40 -06:00
|
|
|
}
|
|
|
|
if node.to_string() != s {
|
|
|
|
return Err(());
|
|
|
|
}
|
|
|
|
Ok(node.syntax().clone_subtree())
|
2021-12-27 12:13:55 -06:00
|
|
|
}
|
2021-12-28 10:17:34 -06:00
|
|
|
|
|
|
|
fn fragment<T: AstNode>(template: &str, s: &str) -> Result<SyntaxNode, ()> {
|
|
|
|
let s = s.trim();
|
|
|
|
let input = template.replace("{}", s);
|
2024-04-14 09:02:38 -05:00
|
|
|
let parse = syntax::SourceFile::parse(&input, syntax::Edition::CURRENT);
|
2021-12-28 10:17:34 -06:00
|
|
|
if !parse.errors().is_empty() {
|
|
|
|
return Err(());
|
|
|
|
}
|
|
|
|
let node = parse.tree().syntax().descendants().find_map(T::cast).ok_or(())?;
|
|
|
|
if node.syntax().text() != s {
|
|
|
|
return Err(());
|
|
|
|
}
|
|
|
|
Ok(node.syntax().clone_subtree())
|
|
|
|
}
|