From ea96c376c85e02ec86df5ff6522754395ad819e9 Mon Sep 17 00:00:00 2001 From: Aleksey Kladov Date: Tue, 28 Dec 2021 19:17:34 +0300 Subject: [PATCH] compress --- crates/ide_ssr/src/fragments.rs | 62 ++++++++++----------------------- 1 file changed, 18 insertions(+), 44 deletions(-) diff --git a/crates/ide_ssr/src/fragments.rs b/crates/ide_ssr/src/fragments.rs index dab214b407..503754afe7 100644 --- a/crates/ide_ssr/src/fragments.rs +++ b/crates/ide_ssr/src/fragments.rs @@ -9,59 +9,19 @@ use syntax::{ast, AstNode, SyntaxNode}; pub(crate) fn ty(s: &str) -> Result { - let template = "type T = {};"; - let input = template.replace("{}", s); - let parse = syntax::SourceFile::parse(&input); - if !parse.errors().is_empty() { - return Err(()); - } - let node = parse.tree().syntax().descendants().find_map(ast::Type::cast).ok_or(())?; - if node.to_string() != s { - return Err(()); - } - Ok(node.syntax().clone_subtree()) + fragment::("type T = {};", s) } pub(crate) fn item(s: &str) -> Result { - let template = "{}"; - let input = template.replace("{}", s); - let parse = syntax::SourceFile::parse(&input); - if !parse.errors().is_empty() { - return Err(()); - } - let node = parse.tree().syntax().descendants().find_map(ast::Item::cast).ok_or(())?; - if node.to_string() != s { - return Err(()); - } - Ok(node.syntax().clone_subtree()) + fragment::("{}", s) } pub(crate) fn pat(s: &str) -> Result { - let template = "const _: () = {let {} = ();};"; - let input = template.replace("{}", s); - let parse = syntax::SourceFile::parse(&input); - if !parse.errors().is_empty() { - return Err(()); - } - let node = parse.tree().syntax().descendants().find_map(ast::Pat::cast).ok_or(())?; - if node.to_string() != s { - return Err(()); - } - Ok(node.syntax().clone_subtree()) + fragment::("const _: () = {let {} = ();};", s) } pub(crate) fn expr(s: &str) -> Result { - let template = "const _: () = {};"; - let input = template.replace("{}", s); - let parse = syntax::SourceFile::parse(&input); - if !parse.errors().is_empty() { - return Err(()); - } - let node = parse.tree().syntax().descendants().find_map(ast::Expr::cast).ok_or(())?; - if node.to_string() != s { - return Err(()); - } - Ok(node.syntax().clone_subtree()) + fragment::("const _: () = {};", s) } pub(crate) fn stmt(s: &str) -> Result { @@ -82,3 +42,17 @@ pub(crate) fn stmt(s: &str) -> Result { } Ok(node.syntax().clone_subtree()) } + +fn fragment(template: &str, s: &str) -> Result { + let s = s.trim(); + let input = template.replace("{}", s); + let parse = syntax::SourceFile::parse(&input); + 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()) +}