• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //! This module contains free-standing functions for creating AST fragments out
2 //! of smaller pieces.
3 //!
4 //! Note that all functions here intended to be stupid constructors, which just
5 //! assemble a finish node from immediate children. If you want to do something
6 //! smarter than that, it belongs to the `ext` submodule.
7 //!
8 //! Keep in mind that `from_text` functions should be kept private. The public
9 //! API should require to assemble every node piecewise. The trick of
10 //! `parse(format!())` we use internally is an implementation detail -- long
11 //! term, it will be replaced with direct tree manipulation.
12 use itertools::Itertools;
13 use stdx::{format_to, never};
14 
15 use crate::{ast, utils::is_raw_identifier, AstNode, SourceFile, SyntaxKind, SyntaxToken};
16 
17 /// While the parent module defines basic atomic "constructors", the `ext`
18 /// module defines shortcuts for common things.
19 ///
20 /// It's named `ext` rather than `shortcuts` just to keep it short.
21 pub mod ext {
22     use super::*;
23 
simple_ident_pat(name: ast::Name) -> ast::IdentPat24     pub fn simple_ident_pat(name: ast::Name) -> ast::IdentPat {
25         return from_text(&name.text());
26 
27         fn from_text(text: &str) -> ast::IdentPat {
28             ast_from_text(&format!("fn f({text}: ())"))
29         }
30     }
ident_path(ident: &str) -> ast::Path31     pub fn ident_path(ident: &str) -> ast::Path {
32         path_unqualified(path_segment(name_ref(ident)))
33     }
34 
path_from_idents<'a>( parts: impl std::iter::IntoIterator<Item = &'a str>, ) -> Option<ast::Path>35     pub fn path_from_idents<'a>(
36         parts: impl std::iter::IntoIterator<Item = &'a str>,
37     ) -> Option<ast::Path> {
38         let mut iter = parts.into_iter();
39         let base = ext::ident_path(iter.next()?);
40         let path = iter.fold(base, |base, s| {
41             let path = ext::ident_path(s);
42             path_concat(base, path)
43         });
44         Some(path)
45     }
46 
field_from_idents<'a>( parts: impl std::iter::IntoIterator<Item = &'a str>, ) -> Option<ast::Expr>47     pub fn field_from_idents<'a>(
48         parts: impl std::iter::IntoIterator<Item = &'a str>,
49     ) -> Option<ast::Expr> {
50         let mut iter = parts.into_iter();
51         let base = expr_path(ext::ident_path(iter.next()?));
52         let expr = iter.fold(base, expr_field);
53         Some(expr)
54     }
55 
expr_unreachable() -> ast::Expr56     pub fn expr_unreachable() -> ast::Expr {
57         expr_from_text("unreachable!()")
58     }
expr_todo() -> ast::Expr59     pub fn expr_todo() -> ast::Expr {
60         expr_from_text("todo!()")
61     }
expr_ty_default(ty: &ast::Type) -> ast::Expr62     pub fn expr_ty_default(ty: &ast::Type) -> ast::Expr {
63         expr_from_text(&format!("{ty}::default()"))
64     }
expr_ty_new(ty: &ast::Type) -> ast::Expr65     pub fn expr_ty_new(ty: &ast::Type) -> ast::Expr {
66         expr_from_text(&format!("{ty}::new()"))
67     }
68 
zero_number() -> ast::Expr69     pub fn zero_number() -> ast::Expr {
70         expr_from_text("0")
71     }
zero_float() -> ast::Expr72     pub fn zero_float() -> ast::Expr {
73         expr_from_text("0.0")
74     }
empty_str() -> ast::Expr75     pub fn empty_str() -> ast::Expr {
76         expr_from_text(r#""""#)
77     }
empty_char() -> ast::Expr78     pub fn empty_char() -> ast::Expr {
79         expr_from_text("'\x00'")
80     }
default_bool() -> ast::Expr81     pub fn default_bool() -> ast::Expr {
82         expr_from_text("false")
83     }
option_none() -> ast::Expr84     pub fn option_none() -> ast::Expr {
85         expr_from_text("None")
86     }
empty_block_expr() -> ast::BlockExpr87     pub fn empty_block_expr() -> ast::BlockExpr {
88         block_expr(None, None)
89     }
90 
ty_name(name: ast::Name) -> ast::Type91     pub fn ty_name(name: ast::Name) -> ast::Type {
92         ty_path(ident_path(&name.to_string()))
93     }
ty_bool() -> ast::Type94     pub fn ty_bool() -> ast::Type {
95         ty_path(ident_path("bool"))
96     }
ty_option(t: ast::Type) -> ast::Type97     pub fn ty_option(t: ast::Type) -> ast::Type {
98         ty_from_text(&format!("Option<{t}>"))
99     }
ty_result(t: ast::Type, e: ast::Type) -> ast::Type100     pub fn ty_result(t: ast::Type, e: ast::Type) -> ast::Type {
101         ty_from_text(&format!("Result<{t}, {e}>"))
102     }
103 }
104 
name(name: &str) -> ast::Name105 pub fn name(name: &str) -> ast::Name {
106     let raw_escape = raw_ident_esc(name);
107     ast_from_text(&format!("mod {raw_escape}{name};"))
108 }
name_ref(name_ref: &str) -> ast::NameRef109 pub fn name_ref(name_ref: &str) -> ast::NameRef {
110     let raw_escape = raw_ident_esc(name_ref);
111     ast_from_text(&format!("fn f() {{ {raw_escape}{name_ref}; }}"))
112 }
raw_ident_esc(ident: &str) -> &'static str113 fn raw_ident_esc(ident: &str) -> &'static str {
114     if is_raw_identifier(ident) {
115         "r#"
116     } else {
117         ""
118     }
119 }
120 
lifetime(text: &str) -> ast::Lifetime121 pub fn lifetime(text: &str) -> ast::Lifetime {
122     let mut text = text;
123     let tmp;
124     if never!(!text.starts_with('\'')) {
125         tmp = format!("'{text}");
126         text = &tmp;
127     }
128     ast_from_text(&format!("fn f<{text}>() {{ }}"))
129 }
130 
131 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
132 // `expr_xxx`.
ty(text: &str) -> ast::Type133 pub fn ty(text: &str) -> ast::Type {
134     ty_from_text(text)
135 }
ty_placeholder() -> ast::Type136 pub fn ty_placeholder() -> ast::Type {
137     ty_from_text("_")
138 }
ty_unit() -> ast::Type139 pub fn ty_unit() -> ast::Type {
140     ty_from_text("()")
141 }
ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type142 pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
143     let mut count: usize = 0;
144     let mut contents = types.into_iter().inspect(|_| count += 1).join(", ");
145     if count == 1 {
146         contents.push(',');
147     }
148 
149     ty_from_text(&format!("({contents})"))
150 }
ty_ref(target: ast::Type, exclusive: bool) -> ast::Type151 pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
152     ty_from_text(&if exclusive { format!("&mut {target}") } else { format!("&{target}") })
153 }
ty_path(path: ast::Path) -> ast::Type154 pub fn ty_path(path: ast::Path) -> ast::Type {
155     ty_from_text(&path.to_string())
156 }
ty_from_text(text: &str) -> ast::Type157 fn ty_from_text(text: &str) -> ast::Type {
158     ast_from_text(&format!("type _T = {text};"))
159 }
160 
ty_alias( ident: &str, generic_param_list: Option<ast::GenericParamList>, type_param_bounds: Option<ast::TypeParam>, where_clause: Option<ast::WhereClause>, assignment: Option<(ast::Type, Option<ast::WhereClause>)>, ) -> ast::TypeAlias161 pub fn ty_alias(
162     ident: &str,
163     generic_param_list: Option<ast::GenericParamList>,
164     type_param_bounds: Option<ast::TypeParam>,
165     where_clause: Option<ast::WhereClause>,
166     assignment: Option<(ast::Type, Option<ast::WhereClause>)>,
167 ) -> ast::TypeAlias {
168     let mut s = String::new();
169     s.push_str(&format!("type {}", ident));
170 
171     if let Some(list) = generic_param_list {
172         s.push_str(&list.to_string());
173     }
174 
175     if let Some(list) = type_param_bounds {
176         s.push_str(&format!(" : {}", &list));
177     }
178 
179     if let Some(cl) = where_clause {
180         s.push_str(&format!(" {}", &cl.to_string()));
181     }
182 
183     if let Some(exp) = assignment {
184         if let Some(cl) = exp.1 {
185             s.push_str(&format!(" = {} {}", &exp.0.to_string(), &cl.to_string()));
186         } else {
187             s.push_str(&format!(" = {}", &exp.0.to_string()));
188         }
189     }
190 
191     s.push(';');
192     ast_from_text(&s)
193 }
194 
assoc_item_list() -> ast::AssocItemList195 pub fn assoc_item_list() -> ast::AssocItemList {
196     ast_from_text("impl C for D {}")
197 }
198 
merge_gen_params( ps: Option<ast::GenericParamList>, bs: Option<ast::GenericParamList>, ) -> Option<ast::GenericParamList>199 fn merge_gen_params(
200     ps: Option<ast::GenericParamList>,
201     bs: Option<ast::GenericParamList>,
202 ) -> Option<ast::GenericParamList> {
203     match (ps, bs) {
204         (None, None) => None,
205         (None, Some(bs)) => Some(bs),
206         (Some(ps), None) => Some(ps),
207         (Some(ps), Some(bs)) => {
208             for b in bs.generic_params() {
209                 ps.add_generic_param(b);
210             }
211             Some(ps)
212         }
213     }
214 }
215 
impl_( generic_params: Option<ast::GenericParamList>, generic_args: Option<ast::GenericParamList>, path_type: ast::Type, where_clause: Option<ast::WhereClause>, body: Option<Vec<either::Either<ast::Attr, ast::AssocItem>>>, ) -> ast::Impl216 pub fn impl_(
217     generic_params: Option<ast::GenericParamList>,
218     generic_args: Option<ast::GenericParamList>,
219     path_type: ast::Type,
220     where_clause: Option<ast::WhereClause>,
221     body: Option<Vec<either::Either<ast::Attr, ast::AssocItem>>>,
222 ) -> ast::Impl {
223     let (gen_params, tr_gen_args) = match (generic_params, generic_args) {
224         (None, None) => (String::new(), String::new()),
225         (None, Some(args)) => (String::new(), args.to_generic_args().to_string()),
226         (Some(params), None) => (params.to_string(), params.to_generic_args().to_string()),
227         (Some(params), Some(args)) => match merge_gen_params(Some(params.clone()), Some(args)) {
228             Some(merged) => (params.to_string(), merged.to_generic_args().to_string()),
229             None => (params.to_string(), String::new()),
230         },
231     };
232 
233     let where_clause = match where_clause {
234         Some(pr) => pr.to_string(),
235         None => " ".to_string(),
236     };
237 
238     let body = match body {
239         Some(bd) => bd.iter().map(|elem| elem.to_string()).join(""),
240         None => String::new(),
241     };
242 
243     ast_from_text(&format!("impl{gen_params} {path_type}{tr_gen_args}{where_clause}{{{}}}", body))
244 }
245 
246 // FIXME : We must make *_gen_args' type ast::GenericArgList but in order to do so we must implement in `edit_in_place.rs`
247 // `add_generic_arg()` just like `add_generic_param()`
248 // is implemented for `ast::GenericParamList`
impl_trait( is_unsafe: bool, trait_gen_params: Option<ast::GenericParamList>, trait_gen_args: Option<ast::GenericParamList>, type_gen_params: Option<ast::GenericParamList>, type_gen_args: Option<ast::GenericParamList>, is_negative: bool, path_type: ast::Type, ty: ast::Type, trait_where_clause: Option<ast::WhereClause>, ty_where_clause: Option<ast::WhereClause>, body: Option<Vec<either::Either<ast::Attr, ast::AssocItem>>>, ) -> ast::Impl249 pub fn impl_trait(
250     is_unsafe: bool,
251     trait_gen_params: Option<ast::GenericParamList>,
252     trait_gen_args: Option<ast::GenericParamList>,
253     type_gen_params: Option<ast::GenericParamList>,
254     type_gen_args: Option<ast::GenericParamList>,
255     is_negative: bool,
256     path_type: ast::Type,
257     ty: ast::Type,
258     trait_where_clause: Option<ast::WhereClause>,
259     ty_where_clause: Option<ast::WhereClause>,
260     body: Option<Vec<either::Either<ast::Attr, ast::AssocItem>>>,
261 ) -> ast::Impl {
262     let is_unsafe = if is_unsafe { "unsafe " } else { "" };
263     let ty_gen_args = match merge_gen_params(type_gen_params.clone(), type_gen_args) {
264         Some(pars) => pars.to_generic_args().to_string(),
265         None => String::new(),
266     };
267 
268     let tr_gen_args = match merge_gen_params(trait_gen_params.clone(), trait_gen_args) {
269         Some(pars) => pars.to_generic_args().to_string(),
270         None => String::new(),
271     };
272 
273     let gen_params = match merge_gen_params(trait_gen_params, type_gen_params) {
274         Some(pars) => pars.to_string(),
275         None => String::new(),
276     };
277 
278     let is_negative = if is_negative { "! " } else { "" };
279 
280     let where_clause = match (ty_where_clause, trait_where_clause) {
281         (None, None) => " ".to_string(),
282         (None, Some(tr)) => format!("\n{}\n", tr).to_string(),
283         (Some(ty), None) => format!("\n{}\n", ty).to_string(),
284         (Some(ty), Some(tr)) => {
285             let updated = ty.clone_for_update();
286             tr.predicates().for_each(|p| {
287                 ty.add_predicate(p);
288             });
289             format!("\n{}\n", updated).to_string()
290         }
291     };
292 
293     let body = match body {
294         Some(bd) => bd.iter().map(|elem| elem.to_string()).join(""),
295         None => String::new(),
296     };
297 
298     ast_from_text(&format!("{is_unsafe}impl{gen_params} {is_negative}{path_type}{tr_gen_args} for {ty}{ty_gen_args}{where_clause}{{{}}}" , body))
299 }
300 
impl_trait_type(bounds: ast::TypeBoundList) -> ast::ImplTraitType301 pub fn impl_trait_type(bounds: ast::TypeBoundList) -> ast::ImplTraitType {
302     ast_from_text(&format!("fn f(x: impl {bounds}) {{}}"))
303 }
304 
path_segment(name_ref: ast::NameRef) -> ast::PathSegment305 pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
306     ast_from_text(&format!("type __ = {name_ref};"))
307 }
308 
path_segment_ty(type_ref: ast::Type, trait_ref: Option<ast::PathType>) -> ast::PathSegment309 pub fn path_segment_ty(type_ref: ast::Type, trait_ref: Option<ast::PathType>) -> ast::PathSegment {
310     let text = match trait_ref {
311         Some(trait_ref) => format!("fn f(x: <{type_ref} as {trait_ref}>) {{}}"),
312         None => format!("fn f(x: <{type_ref}>) {{}}"),
313     };
314     ast_from_text(&text)
315 }
316 
path_segment_self() -> ast::PathSegment317 pub fn path_segment_self() -> ast::PathSegment {
318     ast_from_text("use self;")
319 }
320 
path_segment_super() -> ast::PathSegment321 pub fn path_segment_super() -> ast::PathSegment {
322     ast_from_text("use super;")
323 }
324 
path_segment_crate() -> ast::PathSegment325 pub fn path_segment_crate() -> ast::PathSegment {
326     ast_from_text("use crate;")
327 }
328 
path_unqualified(segment: ast::PathSegment) -> ast::Path329 pub fn path_unqualified(segment: ast::PathSegment) -> ast::Path {
330     ast_from_text(&format!("type __ = {segment};"))
331 }
332 
path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path333 pub fn path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path {
334     ast_from_text(&format!("{qual}::{segment}"))
335 }
336 // FIXME: path concatenation operation doesn't make sense as AST op.
path_concat(first: ast::Path, second: ast::Path) -> ast::Path337 pub fn path_concat(first: ast::Path, second: ast::Path) -> ast::Path {
338     ast_from_text(&format!("type __ = {first}::{second};"))
339 }
340 
path_from_segments( segments: impl IntoIterator<Item = ast::PathSegment>, is_abs: bool, ) -> ast::Path341 pub fn path_from_segments(
342     segments: impl IntoIterator<Item = ast::PathSegment>,
343     is_abs: bool,
344 ) -> ast::Path {
345     let segments = segments.into_iter().map(|it| it.syntax().clone()).join("::");
346     ast_from_text(&if is_abs {
347         format!("fn f(x: ::{segments}) {{}}")
348     } else {
349         format!("fn f(x: {segments}) {{}}")
350     })
351 }
352 
join_paths(paths: impl IntoIterator<Item = ast::Path>) -> ast::Path353 pub fn join_paths(paths: impl IntoIterator<Item = ast::Path>) -> ast::Path {
354     let paths = paths.into_iter().map(|it| it.syntax().clone()).join("::");
355     ast_from_text(&format!("type __ = {paths};"))
356 }
357 
358 // FIXME: should not be pub
path_from_text(text: &str) -> ast::Path359 pub fn path_from_text(text: &str) -> ast::Path {
360     ast_from_text(&format!("fn main() {{ let test = {text}; }}"))
361 }
362 
use_tree_glob() -> ast::UseTree363 pub fn use_tree_glob() -> ast::UseTree {
364     ast_from_text("use *;")
365 }
use_tree( path: ast::Path, use_tree_list: Option<ast::UseTreeList>, alias: Option<ast::Rename>, add_star: bool, ) -> ast::UseTree366 pub fn use_tree(
367     path: ast::Path,
368     use_tree_list: Option<ast::UseTreeList>,
369     alias: Option<ast::Rename>,
370     add_star: bool,
371 ) -> ast::UseTree {
372     let mut buf = "use ".to_string();
373     buf += &path.syntax().to_string();
374     if let Some(use_tree_list) = use_tree_list {
375         format_to!(buf, "::{use_tree_list}");
376     }
377     if add_star {
378         buf += "::*";
379     }
380 
381     if let Some(alias) = alias {
382         format_to!(buf, " {alias}");
383     }
384     ast_from_text(&buf)
385 }
386 
use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList387 pub fn use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList {
388     let use_trees = use_trees.into_iter().map(|it| it.syntax().clone()).join(", ");
389     ast_from_text(&format!("use {{{use_trees}}};"))
390 }
391 
use_(visibility: Option<ast::Visibility>, use_tree: ast::UseTree) -> ast::Use392 pub fn use_(visibility: Option<ast::Visibility>, use_tree: ast::UseTree) -> ast::Use {
393     let visibility = match visibility {
394         None => String::new(),
395         Some(it) => format!("{it} "),
396     };
397     ast_from_text(&format!("{visibility}use {use_tree};"))
398 }
399 
record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr400 pub fn record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr {
401     ast_from_text(&format!("fn f() {{ {path} {fields} }}"))
402 }
403 
record_expr_field_list( fields: impl IntoIterator<Item = ast::RecordExprField>, ) -> ast::RecordExprFieldList404 pub fn record_expr_field_list(
405     fields: impl IntoIterator<Item = ast::RecordExprField>,
406 ) -> ast::RecordExprFieldList {
407     let fields = fields.into_iter().join(", ");
408     ast_from_text(&format!("fn f() {{ S {{ {fields} }} }}"))
409 }
410 
record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField411 pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField {
412     return match expr {
413         Some(expr) => from_text(&format!("{name}: {expr}")),
414         None => from_text(&name.to_string()),
415     };
416 
417     fn from_text(text: &str) -> ast::RecordExprField {
418         ast_from_text(&format!("fn f() {{ S {{ {text}, }} }}"))
419     }
420 }
421 
record_field( visibility: Option<ast::Visibility>, name: ast::Name, ty: ast::Type, ) -> ast::RecordField422 pub fn record_field(
423     visibility: Option<ast::Visibility>,
424     name: ast::Name,
425     ty: ast::Type,
426 ) -> ast::RecordField {
427     let visibility = match visibility {
428         None => String::new(),
429         Some(it) => format!("{it} "),
430     };
431     ast_from_text(&format!("struct S {{ {visibility}{name}: {ty}, }}"))
432 }
433 
434 // TODO
block_expr( stmts: impl IntoIterator<Item = ast::Stmt>, tail_expr: Option<ast::Expr>, ) -> ast::BlockExpr435 pub fn block_expr(
436     stmts: impl IntoIterator<Item = ast::Stmt>,
437     tail_expr: Option<ast::Expr>,
438 ) -> ast::BlockExpr {
439     let mut buf = "{\n".to_string();
440     for stmt in stmts.into_iter() {
441         format_to!(buf, "    {stmt}\n");
442     }
443     if let Some(tail_expr) = tail_expr {
444         format_to!(buf, "    {tail_expr}\n");
445     }
446     buf += "}";
447     ast_from_text(&format!("fn f() {buf}"))
448 }
449 
tail_only_block_expr(tail_expr: ast::Expr) -> ast::BlockExpr450 pub fn tail_only_block_expr(tail_expr: ast::Expr) -> ast::BlockExpr {
451     ast_from_text(&format!("fn f() {{ {tail_expr} }}"))
452 }
453 
454 /// Ideally this function wouldn't exist since it involves manual indenting.
455 /// It differs from `make::block_expr` by also supporting comments and whitespace.
456 ///
457 /// FIXME: replace usages of this with the mutable syntax tree API
hacky_block_expr( elements: impl IntoIterator<Item = crate::SyntaxElement>, tail_expr: Option<ast::Expr>, ) -> ast::BlockExpr458 pub fn hacky_block_expr(
459     elements: impl IntoIterator<Item = crate::SyntaxElement>,
460     tail_expr: Option<ast::Expr>,
461 ) -> ast::BlockExpr {
462     let mut buf = "{\n".to_string();
463     for node_or_token in elements.into_iter() {
464         match node_or_token {
465             rowan::NodeOrToken::Node(n) => format_to!(buf, "    {n}\n"),
466             rowan::NodeOrToken::Token(t) => {
467                 let kind = t.kind();
468                 if kind == SyntaxKind::COMMENT {
469                     format_to!(buf, "    {t}\n")
470                 } else if kind == SyntaxKind::WHITESPACE {
471                     let content = t.text().trim_matches(|c| c != '\n');
472                     if !content.is_empty() {
473                         format_to!(buf, "{}", &content[1..])
474                     }
475                 }
476             }
477         }
478     }
479     if let Some(tail_expr) = tail_expr {
480         format_to!(buf, "    {tail_expr}\n");
481     }
482     buf += "}";
483     ast_from_text(&format!("fn f() {buf}"))
484 }
485 
expr_unit() -> ast::Expr486 pub fn expr_unit() -> ast::Expr {
487     expr_from_text("()")
488 }
expr_literal(text: &str) -> ast::Literal489 pub fn expr_literal(text: &str) -> ast::Literal {
490     assert_eq!(text.trim(), text);
491     ast_from_text(&format!("fn f() {{ let _ = {text}; }}"))
492 }
493 
expr_empty_block() -> ast::Expr494 pub fn expr_empty_block() -> ast::Expr {
495     expr_from_text("{}")
496 }
expr_path(path: ast::Path) -> ast::Expr497 pub fn expr_path(path: ast::Path) -> ast::Expr {
498     expr_from_text(&path.to_string())
499 }
expr_continue(label: Option<ast::Lifetime>) -> ast::Expr500 pub fn expr_continue(label: Option<ast::Lifetime>) -> ast::Expr {
501     match label {
502         Some(label) => expr_from_text(&format!("continue {label}")),
503         None => expr_from_text("continue"),
504     }
505 }
506 // Consider `op: SyntaxKind` instead for nicer syntax at the call-site?
expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr507 pub fn expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr {
508     expr_from_text(&format!("{lhs} {op} {rhs}"))
509 }
expr_break(label: Option<ast::Lifetime>, expr: Option<ast::Expr>) -> ast::Expr510 pub fn expr_break(label: Option<ast::Lifetime>, expr: Option<ast::Expr>) -> ast::Expr {
511     let mut s = String::from("break");
512 
513     if let Some(label) = label {
514         format_to!(s, " {label}");
515     }
516 
517     if let Some(expr) = expr {
518         format_to!(s, " {expr}");
519     }
520 
521     expr_from_text(&s)
522 }
expr_return(expr: Option<ast::Expr>) -> ast::Expr523 pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
524     match expr {
525         Some(expr) => expr_from_text(&format!("return {expr}")),
526         None => expr_from_text("return"),
527     }
528 }
expr_try(expr: ast::Expr) -> ast::Expr529 pub fn expr_try(expr: ast::Expr) -> ast::Expr {
530     expr_from_text(&format!("{expr}?"))
531 }
expr_await(expr: ast::Expr) -> ast::Expr532 pub fn expr_await(expr: ast::Expr) -> ast::Expr {
533     expr_from_text(&format!("{expr}.await"))
534 }
expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr535 pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
536     expr_from_text(&format!("match {expr} {match_arm_list}"))
537 }
expr_if( condition: ast::Expr, then_branch: ast::BlockExpr, else_branch: Option<ast::ElseBranch>, ) -> ast::Expr538 pub fn expr_if(
539     condition: ast::Expr,
540     then_branch: ast::BlockExpr,
541     else_branch: Option<ast::ElseBranch>,
542 ) -> ast::Expr {
543     let else_branch = match else_branch {
544         Some(ast::ElseBranch::Block(block)) => format!("else {block}"),
545         Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {if_expr}"),
546         None => String::new(),
547     };
548     expr_from_text(&format!("if {condition} {then_branch} {else_branch}"))
549 }
expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr550 pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr {
551     expr_from_text(&format!("for {pat} in {expr} {block}"))
552 }
553 
expr_loop(block: ast::BlockExpr) -> ast::Expr554 pub fn expr_loop(block: ast::BlockExpr) -> ast::Expr {
555     expr_from_text(&format!("loop {block}"))
556 }
557 
expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr558 pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
559     let token = token(op);
560     expr_from_text(&format!("{token}{expr}"))
561 }
expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr562 pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
563     expr_from_text(&format!("{f}{arg_list}"))
564 }
expr_method_call( receiver: ast::Expr, method: ast::NameRef, arg_list: ast::ArgList, ) -> ast::Expr565 pub fn expr_method_call(
566     receiver: ast::Expr,
567     method: ast::NameRef,
568     arg_list: ast::ArgList,
569 ) -> ast::Expr {
570     expr_from_text(&format!("{receiver}.{method}{arg_list}"))
571 }
expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr572 pub fn expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
573     expr_from_text(&format!("{f}!{arg_list}"))
574 }
expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr575 pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
576     expr_from_text(&if exclusive { format!("&mut {expr}") } else { format!("&{expr}") })
577 }
expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr578 pub fn expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr {
579     let params = pats.into_iter().join(", ");
580     expr_from_text(&format!("|{params}| {expr}"))
581 }
expr_field(receiver: ast::Expr, field: &str) -> ast::Expr582 pub fn expr_field(receiver: ast::Expr, field: &str) -> ast::Expr {
583     expr_from_text(&format!("{receiver}.{field}"))
584 }
expr_paren(expr: ast::Expr) -> ast::Expr585 pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
586     expr_from_text(&format!("({expr})"))
587 }
expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr588 pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr {
589     let expr = elements.into_iter().format(", ");
590     expr_from_text(&format!("({expr})"))
591 }
expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr592 pub fn expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
593     expr_from_text(&format!("{lhs} = {rhs}"))
594 }
expr_from_text(text: &str) -> ast::Expr595 fn expr_from_text(text: &str) -> ast::Expr {
596     ast_from_text(&format!("const C: () = {text};"))
597 }
expr_let(pattern: ast::Pat, expr: ast::Expr) -> ast::LetExpr598 pub fn expr_let(pattern: ast::Pat, expr: ast::Expr) -> ast::LetExpr {
599     ast_from_text(&format!("const _: () = while let {pattern} = {expr} {{}};"))
600 }
601 
arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList602 pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
603     let args = args.into_iter().format(", ");
604     ast_from_text(&format!("fn main() {{ ()({args}) }}"))
605 }
606 
ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat607 pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
608     let mut s = String::from("fn f(");
609     if ref_ {
610         s.push_str("ref ");
611     }
612     if mut_ {
613         s.push_str("mut ");
614     }
615     format_to!(s, "{name}");
616     s.push_str(": ())");
617     ast_from_text(&s)
618 }
619 
wildcard_pat() -> ast::WildcardPat620 pub fn wildcard_pat() -> ast::WildcardPat {
621     return from_text("_");
622 
623     fn from_text(text: &str) -> ast::WildcardPat {
624         ast_from_text(&format!("fn f({text}: ())"))
625     }
626 }
627 
literal_pat(lit: &str) -> ast::LiteralPat628 pub fn literal_pat(lit: &str) -> ast::LiteralPat {
629     return from_text(lit);
630 
631     fn from_text(text: &str) -> ast::LiteralPat {
632         ast_from_text(&format!("fn f() {{ match x {{ {text} => {{}} }} }}"))
633     }
634 }
635 
slice_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::SlicePat636 pub fn slice_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::SlicePat {
637     let pats_str = pats.into_iter().join(", ");
638     return from_text(&format!("[{pats_str}]"));
639 
640     fn from_text(text: &str) -> ast::SlicePat {
641         ast_from_text(&format!("fn f() {{ match () {{{text} => ()}} }}"))
642     }
643 }
644 
645 /// Creates a tuple of patterns from an iterator of patterns.
646 ///
647 /// Invariant: `pats` must be length > 0
tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat648 pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
649     let mut count: usize = 0;
650     let mut pats_str = pats.into_iter().inspect(|_| count += 1).join(", ");
651     if count == 1 {
652         pats_str.push(',');
653     }
654     return from_text(&format!("({pats_str})"));
655 
656     fn from_text(text: &str) -> ast::TuplePat {
657         ast_from_text(&format!("fn f({text}: ())"))
658     }
659 }
660 
tuple_struct_pat( path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>, ) -> ast::TupleStructPat661 pub fn tuple_struct_pat(
662     path: ast::Path,
663     pats: impl IntoIterator<Item = ast::Pat>,
664 ) -> ast::TupleStructPat {
665     let pats_str = pats.into_iter().join(", ");
666     return from_text(&format!("{path}({pats_str})"));
667 
668     fn from_text(text: &str) -> ast::TupleStructPat {
669         ast_from_text(&format!("fn f({text}: ())"))
670     }
671 }
672 
record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat673 pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
674     let pats_str = pats.into_iter().join(", ");
675     return from_text(&format!("{path} {{ {pats_str} }}"));
676 
677     fn from_text(text: &str) -> ast::RecordPat {
678         ast_from_text(&format!("fn f({text}: ())"))
679     }
680 }
681 
record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat682 pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
683     ast_from_text(&format!("fn f({path} {fields}: ()))"))
684 }
685 
record_pat_field_list( fields: impl IntoIterator<Item = ast::RecordPatField>, ) -> ast::RecordPatFieldList686 pub fn record_pat_field_list(
687     fields: impl IntoIterator<Item = ast::RecordPatField>,
688 ) -> ast::RecordPatFieldList {
689     let fields = fields.into_iter().join(", ");
690     ast_from_text(&format!("fn f(S {{ {fields} }}: ()))"))
691 }
692 
record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField693 pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
694     ast_from_text(&format!("fn f(S {{ {name_ref}: {pat} }}: ()))"))
695 }
696 
record_pat_field_shorthand(name_ref: ast::NameRef) -> ast::RecordPatField697 pub fn record_pat_field_shorthand(name_ref: ast::NameRef) -> ast::RecordPatField {
698     ast_from_text(&format!("fn f(S {{ {name_ref} }}: ()))"))
699 }
700 
701 /// Returns a `BindPat` if the path has just one segment, a `PathPat` otherwise.
path_pat(path: ast::Path) -> ast::Pat702 pub fn path_pat(path: ast::Path) -> ast::Pat {
703     return from_text(&path.to_string());
704     fn from_text(text: &str) -> ast::Pat {
705         ast_from_text(&format!("fn f({text}: ())"))
706     }
707 }
708 
match_arm( pats: impl IntoIterator<Item = ast::Pat>, guard: Option<ast::Expr>, expr: ast::Expr, ) -> ast::MatchArm709 pub fn match_arm(
710     pats: impl IntoIterator<Item = ast::Pat>,
711     guard: Option<ast::Expr>,
712     expr: ast::Expr,
713 ) -> ast::MatchArm {
714     let pats_str = pats.into_iter().join(" | ");
715     return match guard {
716         Some(guard) => from_text(&format!("{pats_str} if {guard} => {expr}")),
717         None => from_text(&format!("{pats_str} => {expr}")),
718     };
719 
720     fn from_text(text: &str) -> ast::MatchArm {
721         ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
722     }
723 }
724 
match_arm_with_guard( pats: impl IntoIterator<Item = ast::Pat>, guard: ast::Expr, expr: ast::Expr, ) -> ast::MatchArm725 pub fn match_arm_with_guard(
726     pats: impl IntoIterator<Item = ast::Pat>,
727     guard: ast::Expr,
728     expr: ast::Expr,
729 ) -> ast::MatchArm {
730     let pats_str = pats.into_iter().join(" | ");
731     return from_text(&format!("{pats_str} if {guard} => {expr}"));
732 
733     fn from_text(text: &str) -> ast::MatchArm {
734         ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
735     }
736 }
737 
match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList738 pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
739     let arms_str = arms
740         .into_iter()
741         .map(|arm| {
742             let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
743             let comma = if needs_comma { "," } else { "" };
744             let arm = arm.syntax();
745             format!("    {arm}{comma}\n")
746         })
747         .collect::<String>();
748     return from_text(&arms_str);
749 
750     fn from_text(text: &str) -> ast::MatchArmList {
751         ast_from_text(&format!("fn f() {{ match () {{\n{text}}} }}"))
752     }
753 }
754 
where_pred( path: ast::Path, bounds: impl IntoIterator<Item = ast::TypeBound>, ) -> ast::WherePred755 pub fn where_pred(
756     path: ast::Path,
757     bounds: impl IntoIterator<Item = ast::TypeBound>,
758 ) -> ast::WherePred {
759     let bounds = bounds.into_iter().join(" + ");
760     return from_text(&format!("{path}: {bounds}"));
761 
762     fn from_text(text: &str) -> ast::WherePred {
763         ast_from_text(&format!("fn f() where {text} {{ }}"))
764     }
765 }
766 
where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause767 pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause {
768     let preds = preds.into_iter().join(", ");
769     return from_text(preds.as_str());
770 
771     fn from_text(text: &str) -> ast::WhereClause {
772         ast_from_text(&format!("fn f() where {text} {{ }}"))
773     }
774 }
775 
let_stmt( pattern: ast::Pat, ty: Option<ast::Type>, initializer: Option<ast::Expr>, ) -> ast::LetStmt776 pub fn let_stmt(
777     pattern: ast::Pat,
778     ty: Option<ast::Type>,
779     initializer: Option<ast::Expr>,
780 ) -> ast::LetStmt {
781     let mut text = String::new();
782     format_to!(text, "let {pattern}");
783     if let Some(ty) = ty {
784         format_to!(text, ": {ty}");
785     }
786     match initializer {
787         Some(it) => format_to!(text, " = {it};"),
788         None => format_to!(text, ";"),
789     };
790     ast_from_text(&format!("fn f() {{ {text} }}"))
791 }
792 
let_else_stmt( pattern: ast::Pat, ty: Option<ast::Type>, expr: ast::Expr, diverging: ast::BlockExpr, ) -> ast::LetStmt793 pub fn let_else_stmt(
794     pattern: ast::Pat,
795     ty: Option<ast::Type>,
796     expr: ast::Expr,
797     diverging: ast::BlockExpr,
798 ) -> ast::LetStmt {
799     let mut text = String::new();
800     format_to!(text, "let {pattern}");
801     if let Some(ty) = ty {
802         format_to!(text, ": {ty}");
803     }
804     format_to!(text, " = {expr} else {diverging};");
805     ast_from_text(&format!("fn f() {{ {text} }}"))
806 }
807 
expr_stmt(expr: ast::Expr) -> ast::ExprStmt808 pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
809     let semi = if expr.is_block_like() { "" } else { ";" };
810     ast_from_text(&format!("fn f() {{ {expr}{semi} (); }}"))
811 }
812 
item_const( visibility: Option<ast::Visibility>, name: ast::Name, ty: ast::Type, expr: ast::Expr, ) -> ast::Const813 pub fn item_const(
814     visibility: Option<ast::Visibility>,
815     name: ast::Name,
816     ty: ast::Type,
817     expr: ast::Expr,
818 ) -> ast::Const {
819     let visibility = match visibility {
820         None => String::new(),
821         Some(it) => format!("{it} "),
822     };
823     ast_from_text(&format!("{visibility} const {name}: {ty} = {expr};"))
824 }
825 
param(pat: ast::Pat, ty: ast::Type) -> ast::Param826 pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
827     ast_from_text(&format!("fn f({pat}: {ty}) {{ }}"))
828 }
829 
self_param() -> ast::SelfParam830 pub fn self_param() -> ast::SelfParam {
831     ast_from_text("fn f(&self) { }")
832 }
833 
ret_type(ty: ast::Type) -> ast::RetType834 pub fn ret_type(ty: ast::Type) -> ast::RetType {
835     ast_from_text(&format!("fn f() -> {ty} {{ }}"))
836 }
837 
param_list( self_param: Option<ast::SelfParam>, pats: impl IntoIterator<Item = ast::Param>, ) -> ast::ParamList838 pub fn param_list(
839     self_param: Option<ast::SelfParam>,
840     pats: impl IntoIterator<Item = ast::Param>,
841 ) -> ast::ParamList {
842     let args = pats.into_iter().join(", ");
843     let list = match self_param {
844         Some(self_param) if args.is_empty() => format!("fn f({self_param}) {{ }}"),
845         Some(self_param) => format!("fn f({self_param}, {args}) {{ }}"),
846         None => format!("fn f({args}) {{ }}"),
847     };
848     ast_from_text(&list)
849 }
850 
type_bound(bound: &str) -> ast::TypeBound851 pub fn type_bound(bound: &str) -> ast::TypeBound {
852     ast_from_text(&format!("fn f<T: {bound}>() {{ }}"))
853 }
854 
type_bound_list( bounds: impl IntoIterator<Item = ast::TypeBound>, ) -> Option<ast::TypeBoundList>855 pub fn type_bound_list(
856     bounds: impl IntoIterator<Item = ast::TypeBound>,
857 ) -> Option<ast::TypeBoundList> {
858     let bounds = bounds.into_iter().map(|it| it.to_string()).unique().join(" + ");
859     if bounds.is_empty() {
860         return None;
861     }
862     Some(ast_from_text(&format!("fn f<T: {bounds}>() {{ }}")))
863 }
864 
type_param(name: ast::Name, bounds: Option<ast::TypeBoundList>) -> ast::TypeParam865 pub fn type_param(name: ast::Name, bounds: Option<ast::TypeBoundList>) -> ast::TypeParam {
866     let bounds = bounds.map_or_else(String::new, |it| format!(": {it}"));
867     ast_from_text(&format!("fn f<{name}{bounds}>() {{ }}"))
868 }
869 
lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam870 pub fn lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam {
871     ast_from_text(&format!("fn f<{lifetime}>() {{ }}"))
872 }
873 
generic_param_list( pats: impl IntoIterator<Item = ast::GenericParam>, ) -> ast::GenericParamList874 pub fn generic_param_list(
875     pats: impl IntoIterator<Item = ast::GenericParam>,
876 ) -> ast::GenericParamList {
877     let args = pats.into_iter().join(", ");
878     ast_from_text(&format!("fn f<{args}>() {{ }}"))
879 }
880 
type_arg(ty: ast::Type) -> ast::TypeArg881 pub fn type_arg(ty: ast::Type) -> ast::TypeArg {
882     ast_from_text(&format!("const S: T<{ty}> = ();"))
883 }
884 
lifetime_arg(lifetime: ast::Lifetime) -> ast::LifetimeArg885 pub fn lifetime_arg(lifetime: ast::Lifetime) -> ast::LifetimeArg {
886     ast_from_text(&format!("const S: T<{lifetime}> = ();"))
887 }
888 
generic_arg_list( args: impl IntoIterator<Item = ast::GenericArg>, ) -> ast::GenericArgList889 pub(crate) fn generic_arg_list(
890     args: impl IntoIterator<Item = ast::GenericArg>,
891 ) -> ast::GenericArgList {
892     let args = args.into_iter().join(", ");
893     ast_from_text(&format!("const S: T<{args}> = ();"))
894 }
895 
visibility_pub_crate() -> ast::Visibility896 pub fn visibility_pub_crate() -> ast::Visibility {
897     ast_from_text("pub(crate) struct S")
898 }
899 
visibility_pub() -> ast::Visibility900 pub fn visibility_pub() -> ast::Visibility {
901     ast_from_text("pub struct S")
902 }
903 
tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList904 pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
905     let fields = fields.into_iter().join(", ");
906     ast_from_text(&format!("struct f({fields});"))
907 }
908 
record_field_list( fields: impl IntoIterator<Item = ast::RecordField>, ) -> ast::RecordFieldList909 pub fn record_field_list(
910     fields: impl IntoIterator<Item = ast::RecordField>,
911 ) -> ast::RecordFieldList {
912     let fields = fields.into_iter().join(", ");
913     ast_from_text(&format!("struct f {{ {fields} }}"))
914 }
915 
tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField916 pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
917     let visibility = match visibility {
918         None => String::new(),
919         Some(it) => format!("{it} "),
920     };
921     ast_from_text(&format!("struct f({visibility}{ty});"))
922 }
923 
variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant924 pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
925     let field_list = match field_list {
926         None => String::new(),
927         Some(it) => match it {
928             ast::FieldList::RecordFieldList(record) => format!(" {record}"),
929             ast::FieldList::TupleFieldList(tuple) => format!("{tuple}"),
930         },
931     };
932     ast_from_text(&format!("enum f {{ {name}{field_list} }}"))
933 }
934 
fn_( visibility: Option<ast::Visibility>, fn_name: ast::Name, type_params: Option<ast::GenericParamList>, where_clause: Option<ast::WhereClause>, params: ast::ParamList, body: ast::BlockExpr, ret_type: Option<ast::RetType>, is_async: bool, is_const: bool, is_unsafe: bool, ) -> ast::Fn935 pub fn fn_(
936     visibility: Option<ast::Visibility>,
937     fn_name: ast::Name,
938     type_params: Option<ast::GenericParamList>,
939     where_clause: Option<ast::WhereClause>,
940     params: ast::ParamList,
941     body: ast::BlockExpr,
942     ret_type: Option<ast::RetType>,
943     is_async: bool,
944     is_const: bool,
945     is_unsafe: bool,
946 ) -> ast::Fn {
947     let type_params = match type_params {
948         Some(type_params) => format!("{type_params}"),
949         None => "".into(),
950     };
951     let where_clause = match where_clause {
952         Some(it) => format!("{it} "),
953         None => "".into(),
954     };
955     let ret_type = match ret_type {
956         Some(ret_type) => format!("{ret_type} "),
957         None => "".into(),
958     };
959     let visibility = match visibility {
960         None => String::new(),
961         Some(it) => format!("{it} "),
962     };
963 
964     let async_literal = if is_async { "async " } else { "" };
965     let const_literal = if is_const { "const " } else { "" };
966     let unsafe_literal = if is_unsafe { "unsafe " } else { "" };
967 
968     ast_from_text(&format!(
969         "{visibility}{async_literal}{const_literal}{unsafe_literal}fn {fn_name}{type_params}{params} {ret_type}{where_clause}{body}",
970     ))
971 }
struct_( visibility: Option<ast::Visibility>, strukt_name: ast::Name, generic_param_list: Option<ast::GenericParamList>, field_list: ast::FieldList, ) -> ast::Struct972 pub fn struct_(
973     visibility: Option<ast::Visibility>,
974     strukt_name: ast::Name,
975     generic_param_list: Option<ast::GenericParamList>,
976     field_list: ast::FieldList,
977 ) -> ast::Struct {
978     let semicolon = if matches!(field_list, ast::FieldList::TupleFieldList(_)) { ";" } else { "" };
979     let type_params = generic_param_list.map_or_else(String::new, |it| it.to_string());
980     let visibility = match visibility {
981         None => String::new(),
982         Some(it) => format!("{it} "),
983     };
984 
985     ast_from_text(&format!("{visibility}struct {strukt_name}{type_params}{field_list}{semicolon}",))
986 }
987 
988 #[track_caller]
ast_from_text<N: AstNode>(text: &str) -> N989 fn ast_from_text<N: AstNode>(text: &str) -> N {
990     let parse = SourceFile::parse(text);
991     let node = match parse.tree().syntax().descendants().find_map(N::cast) {
992         Some(it) => it,
993         None => {
994             let node = std::any::type_name::<N>();
995             panic!("Failed to make ast node `{node}` from text {text}")
996         }
997     };
998     let node = node.clone_subtree();
999     assert_eq!(node.syntax().text_range().start(), 0.into());
1000     node
1001 }
1002 
token(kind: SyntaxKind) -> SyntaxToken1003 pub fn token(kind: SyntaxKind) -> SyntaxToken {
1004     tokens::SOURCE_FILE
1005         .tree()
1006         .syntax()
1007         .clone_for_update()
1008         .descendants_with_tokens()
1009         .filter_map(|it| it.into_token())
1010         .find(|it| it.kind() == kind)
1011         .unwrap_or_else(|| panic!("unhandled token: {kind:?}"))
1012 }
1013 
1014 pub mod tokens {
1015     use once_cell::sync::Lazy;
1016 
1017     use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
1018 
1019     pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
1020         SourceFile::parse(
1021             "const C: <()>::Item = (1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p, &p , &mut p)\n;\n\n",
1022         )
1023     });
1024 
single_space() -> SyntaxToken1025     pub fn single_space() -> SyntaxToken {
1026         SOURCE_FILE
1027             .tree()
1028             .syntax()
1029             .clone_for_update()
1030             .descendants_with_tokens()
1031             .filter_map(|it| it.into_token())
1032             .find(|it| it.kind() == WHITESPACE && it.text() == " ")
1033             .unwrap()
1034     }
1035 
whitespace(text: &str) -> SyntaxToken1036     pub fn whitespace(text: &str) -> SyntaxToken {
1037         assert!(text.trim().is_empty());
1038         let sf = SourceFile::parse(text).ok().unwrap();
1039         sf.syntax().clone_for_update().first_child_or_token().unwrap().into_token().unwrap()
1040     }
1041 
doc_comment(text: &str) -> SyntaxToken1042     pub fn doc_comment(text: &str) -> SyntaxToken {
1043         assert!(!text.trim().is_empty());
1044         let sf = SourceFile::parse(text).ok().unwrap();
1045         sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
1046     }
1047 
literal(text: &str) -> SyntaxToken1048     pub fn literal(text: &str) -> SyntaxToken {
1049         assert_eq!(text.trim(), text);
1050         let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {text}; }}"));
1051         lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
1052     }
1053 
single_newline() -> SyntaxToken1054     pub fn single_newline() -> SyntaxToken {
1055         let res = SOURCE_FILE
1056             .tree()
1057             .syntax()
1058             .clone_for_update()
1059             .descendants_with_tokens()
1060             .filter_map(|it| it.into_token())
1061             .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
1062             .unwrap();
1063         res.detach();
1064         res
1065     }
1066 
blank_line() -> SyntaxToken1067     pub fn blank_line() -> SyntaxToken {
1068         SOURCE_FILE
1069             .tree()
1070             .syntax()
1071             .clone_for_update()
1072             .descendants_with_tokens()
1073             .filter_map(|it| it.into_token())
1074             .find(|it| it.kind() == WHITESPACE && it.text() == "\n\n")
1075             .unwrap()
1076     }
1077 
1078     pub struct WsBuilder(SourceFile);
1079 
1080     impl WsBuilder {
new(text: &str) -> WsBuilder1081         pub fn new(text: &str) -> WsBuilder {
1082             WsBuilder(SourceFile::parse(text).ok().unwrap())
1083         }
ws(&self) -> SyntaxToken1084         pub fn ws(&self) -> SyntaxToken {
1085             self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()
1086         }
1087     }
1088 }
1089