1use syntax::{AstNode, SyntaxNode, ast, syntax_editor::SyntaxEditor};
10
11pub(crate) fn ty(s: &str) -> Result<SyntaxNode, ()> {
12 fragment::<ast::Type>("type T = {};", s)
13}
14
15pub(crate) fn item(s: &str) -> Result<SyntaxNode, ()> {
16 fragment::<ast::Item>("{}", s)
17}
18
19pub(crate) fn pat(s: &str) -> Result<SyntaxNode, ()> {
20 fragment::<ast::Pat>("const _: () = {let {} = ();};", s)
21}
22
23pub(crate) fn expr(s: &str) -> Result<SyntaxNode, ()> {
24 fragment::<ast::Expr>("const _: () = {};", s)
25}
26
27pub(crate) fn stmt(s: &str) -> Result<SyntaxNode, ()> {
28 let template = "const _: () = { {}; };";
29 let input = template.replace("{}", s);
30 let parse = syntax::SourceFile::parse(&input, syntax::Edition::CURRENT);
31 if !parse.errors().is_empty() {
32 return Err(());
33 }
34 let node = parse.tree().syntax().descendants().skip(2).find_map(ast::Stmt::cast).ok_or(())?;
35 let (editor, node) = SyntaxEditor::new(node.syntax().clone());
36 let node = ast::Stmt::cast(node).ok_or(())?;
37 if !s.ends_with(';')
38 && node.to_string().ends_with(';')
39 && let Some(token) = node.syntax().last_token()
40 {
41 editor.delete(token);
42 }
43 let node = editor.finish().new_root().clone();
44 if node.to_string() != s {
45 return Err(());
46 }
47 Ok(node)
48}
49
50fn fragment<T: AstNode>(template: &str, s: &str) -> Result<SyntaxNode, ()> {
51 let s = s.trim();
52 let input = template.replace("{}", s);
53 let parse = syntax::SourceFile::parse(&input, syntax::Edition::CURRENT);
54 if !parse.errors().is_empty() {
55 return Err(());
56 }
57 let node = parse.tree().syntax().descendants().find_map(T::cast).ok_or(())?;
58 let (_, node) = SyntaxEditor::new(node.syntax().clone());
59 if node.text() != s {
60 return Err(());
61 }
62 Ok(node)
63}