]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/syntax/src/ast/make.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[rust.git] / src / tools / rust-analyzer / crates / syntax / src / ast / make.rs
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, 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
24     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     }
31     pub fn ident_path(ident: &str) -> ast::Path {
32         path_unqualified(path_segment(name_ref(ident)))
33     }
34
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
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
56     pub fn expr_unreachable() -> ast::Expr {
57         expr_from_text("unreachable!()")
58     }
59     pub fn expr_todo() -> ast::Expr {
60         expr_from_text("todo!()")
61     }
62     pub fn expr_ty_default(ty: &ast::Type) -> ast::Expr {
63         expr_from_text(&format!("{ty}::default()"))
64     }
65     pub fn expr_ty_new(ty: &ast::Type) -> ast::Expr {
66         expr_from_text(&format!("{ty}::new()"))
67     }
68
69     pub fn zero_number() -> ast::Expr {
70         expr_from_text("0")
71     }
72     pub fn zero_float() -> ast::Expr {
73         expr_from_text("0.0")
74     }
75     pub fn empty_str() -> ast::Expr {
76         expr_from_text(r#""""#)
77     }
78     pub fn empty_char() -> ast::Expr {
79         expr_from_text("'\x00'")
80     }
81     pub fn default_bool() -> ast::Expr {
82         expr_from_text("false")
83     }
84     pub fn option_none() -> ast::Expr {
85         expr_from_text("None")
86     }
87     pub fn empty_block_expr() -> ast::BlockExpr {
88         block_expr(None, None)
89     }
90
91     pub fn ty_name(name: ast::Name) -> ast::Type {
92         ty_path(ident_path(&name.to_string()))
93     }
94     pub fn ty_bool() -> ast::Type {
95         ty_path(ident_path("bool"))
96     }
97     pub fn ty_option(t: ast::Type) -> ast::Type {
98         ty_from_text(&format!("Option<{t}>"))
99     }
100     pub fn ty_result(t: ast::Type, e: ast::Type) -> ast::Type {
101         ty_from_text(&format!("Result<{t}, {e}>"))
102     }
103 }
104
105 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 }
109 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 }
113 fn raw_ident_esc(ident: &str) -> &'static str {
114     let is_keyword = parser::SyntaxKind::from_keyword(ident).is_some();
115     if is_keyword && !matches!(ident, "self" | "crate" | "super" | "Self") {
116         "r#"
117     } else {
118         ""
119     }
120 }
121
122 pub fn lifetime(text: &str) -> ast::Lifetime {
123     let mut text = text;
124     let tmp;
125     if never!(!text.starts_with('\'')) {
126         tmp = format!("'{text}");
127         text = &tmp;
128     }
129     ast_from_text(&format!("fn f<{text}>() {{ }}"))
130 }
131
132 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
133 // `expr_xxx`.
134 pub fn ty(text: &str) -> ast::Type {
135     ty_from_text(text)
136 }
137 pub fn ty_placeholder() -> ast::Type {
138     ty_from_text("_")
139 }
140 pub fn ty_unit() -> ast::Type {
141     ty_from_text("()")
142 }
143 pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
144     let mut count: usize = 0;
145     let mut contents = types.into_iter().inspect(|_| count += 1).join(", ");
146     if count == 1 {
147         contents.push(',');
148     }
149
150     ty_from_text(&format!("({contents})"))
151 }
152 pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
153     ty_from_text(&if exclusive { format!("&mut {target}") } else { format!("&{target}") })
154 }
155 pub fn ty_path(path: ast::Path) -> ast::Type {
156     ty_from_text(&path.to_string())
157 }
158 fn ty_from_text(text: &str) -> ast::Type {
159     ast_from_text(&format!("type _T = {text};"))
160 }
161
162 pub fn assoc_item_list() -> ast::AssocItemList {
163     ast_from_text("impl C for D {}")
164 }
165
166 // FIXME: `ty_params` should be `ast::GenericArgList`
167 pub fn impl_(
168     ty: ast::Path,
169     params: Option<ast::GenericParamList>,
170     ty_params: Option<ast::GenericParamList>,
171 ) -> ast::Impl {
172     let params = match params {
173         Some(params) => params.to_string(),
174         None => String::new(),
175     };
176     let ty_params = match ty_params {
177         Some(params) => params.to_string(),
178         None => String::new(),
179     };
180     ast_from_text(&format!("impl{params} {ty}{ty_params} {{}}"))
181 }
182
183 pub fn impl_trait(
184     trait_: ast::Path,
185     ty: ast::Path,
186     ty_params: Option<ast::GenericParamList>,
187 ) -> ast::Impl {
188     let ty_params = ty_params.map_or_else(String::new, |params| params.to_string());
189     ast_from_text(&format!("impl{ty_params} {trait_} for {ty}{ty_params} {{}}"))
190 }
191
192 pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
193     ast_from_text(&format!("type __ = {name_ref};"))
194 }
195
196 pub fn path_segment_ty(type_ref: ast::Type, trait_ref: Option<ast::PathType>) -> ast::PathSegment {
197     let text = match trait_ref {
198         Some(trait_ref) => format!("fn f(x: <{type_ref} as {trait_ref}>) {{}}"),
199         None => format!("fn f(x: <{type_ref}>) {{}}"),
200     };
201     ast_from_text(&text)
202 }
203
204 pub fn path_segment_self() -> ast::PathSegment {
205     ast_from_text("use self;")
206 }
207
208 pub fn path_segment_super() -> ast::PathSegment {
209     ast_from_text("use super;")
210 }
211
212 pub fn path_segment_crate() -> ast::PathSegment {
213     ast_from_text("use crate;")
214 }
215
216 pub fn path_unqualified(segment: ast::PathSegment) -> ast::Path {
217     ast_from_text(&format!("type __ = {segment};"))
218 }
219
220 pub fn path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path {
221     ast_from_text(&format!("{qual}::{segment}"))
222 }
223 // FIXME: path concatenation operation doesn't make sense as AST op.
224 pub fn path_concat(first: ast::Path, second: ast::Path) -> ast::Path {
225     ast_from_text(&format!("type __ = {first}::{second};"))
226 }
227
228 pub fn path_from_segments(
229     segments: impl IntoIterator<Item = ast::PathSegment>,
230     is_abs: bool,
231 ) -> ast::Path {
232     let segments = segments.into_iter().map(|it| it.syntax().clone()).join("::");
233     ast_from_text(&if is_abs {
234         format!("fn f(x: ::{segments}) {{}}")
235     } else {
236         format!("fn f(x: {segments}) {{}}")
237     })
238 }
239
240 pub fn join_paths(paths: impl IntoIterator<Item = ast::Path>) -> ast::Path {
241     let paths = paths.into_iter().map(|it| it.syntax().clone()).join("::");
242     ast_from_text(&format!("type __ = {paths};"))
243 }
244
245 // FIXME: should not be pub
246 pub fn path_from_text(text: &str) -> ast::Path {
247     ast_from_text(&format!("fn main() {{ let test = {text}; }}"))
248 }
249
250 pub fn use_tree_glob() -> ast::UseTree {
251     ast_from_text("use *;")
252 }
253 pub fn use_tree(
254     path: ast::Path,
255     use_tree_list: Option<ast::UseTreeList>,
256     alias: Option<ast::Rename>,
257     add_star: bool,
258 ) -> ast::UseTree {
259     let mut buf = "use ".to_string();
260     buf += &path.syntax().to_string();
261     if let Some(use_tree_list) = use_tree_list {
262         format_to!(buf, "::{use_tree_list}");
263     }
264     if add_star {
265         buf += "::*";
266     }
267
268     if let Some(alias) = alias {
269         format_to!(buf, " {alias}");
270     }
271     ast_from_text(&buf)
272 }
273
274 pub fn use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList {
275     let use_trees = use_trees.into_iter().map(|it| it.syntax().clone()).join(", ");
276     ast_from_text(&format!("use {{{use_trees}}};"))
277 }
278
279 pub fn use_(visibility: Option<ast::Visibility>, use_tree: ast::UseTree) -> ast::Use {
280     let visibility = match visibility {
281         None => String::new(),
282         Some(it) => format!("{it} "),
283     };
284     ast_from_text(&format!("{visibility}use {use_tree};"))
285 }
286
287 pub fn record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr {
288     ast_from_text(&format!("fn f() {{ {path} {fields} }}"))
289 }
290
291 pub fn record_expr_field_list(
292     fields: impl IntoIterator<Item = ast::RecordExprField>,
293 ) -> ast::RecordExprFieldList {
294     let fields = fields.into_iter().join(", ");
295     ast_from_text(&format!("fn f() {{ S {{ {fields} }} }}"))
296 }
297
298 pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField {
299     return match expr {
300         Some(expr) => from_text(&format!("{name}: {expr}")),
301         None => from_text(&name.to_string()),
302     };
303
304     fn from_text(text: &str) -> ast::RecordExprField {
305         ast_from_text(&format!("fn f() {{ S {{ {text}, }} }}"))
306     }
307 }
308
309 pub fn record_field(
310     visibility: Option<ast::Visibility>,
311     name: ast::Name,
312     ty: ast::Type,
313 ) -> ast::RecordField {
314     let visibility = match visibility {
315         None => String::new(),
316         Some(it) => format!("{it} "),
317     };
318     ast_from_text(&format!("struct S {{ {visibility}{name}: {ty}, }}"))
319 }
320
321 // TODO
322 pub fn block_expr(
323     stmts: impl IntoIterator<Item = ast::Stmt>,
324     tail_expr: Option<ast::Expr>,
325 ) -> ast::BlockExpr {
326     let mut buf = "{\n".to_string();
327     for stmt in stmts.into_iter() {
328         format_to!(buf, "    {stmt}\n");
329     }
330     if let Some(tail_expr) = tail_expr {
331         format_to!(buf, "    {tail_expr}\n");
332     }
333     buf += "}";
334     ast_from_text(&format!("fn f() {buf}"))
335 }
336
337 pub fn tail_only_block_expr(tail_expr: ast::Expr) -> ast::BlockExpr {
338     ast_from_text(&format!("fn f() {{ {tail_expr} }}"))
339 }
340
341 /// Ideally this function wouldn't exist since it involves manual indenting.
342 /// It differs from `make::block_expr` by also supporting comments and whitespace.
343 ///
344 /// FIXME: replace usages of this with the mutable syntax tree API
345 pub fn hacky_block_expr(
346     elements: impl IntoIterator<Item = crate::SyntaxElement>,
347     tail_expr: Option<ast::Expr>,
348 ) -> ast::BlockExpr {
349     let mut buf = "{\n".to_string();
350     for node_or_token in elements.into_iter() {
351         match node_or_token {
352             rowan::NodeOrToken::Node(n) => format_to!(buf, "    {n}\n"),
353             rowan::NodeOrToken::Token(t) => {
354                 let kind = t.kind();
355                 if kind == SyntaxKind::COMMENT {
356                     format_to!(buf, "    {t}\n")
357                 } else if kind == SyntaxKind::WHITESPACE {
358                     let content = t.text().trim_matches(|c| c != '\n');
359                     if content.len() >= 1 {
360                         format_to!(buf, "{}", &content[1..])
361                     }
362                 }
363             }
364         }
365     }
366     if let Some(tail_expr) = tail_expr {
367         format_to!(buf, "    {tail_expr}\n");
368     }
369     buf += "}";
370     ast_from_text(&format!("fn f() {buf}"))
371 }
372
373 pub fn expr_unit() -> ast::Expr {
374     expr_from_text("()")
375 }
376 pub fn expr_literal(text: &str) -> ast::Literal {
377     assert_eq!(text.trim(), text);
378     ast_from_text(&format!("fn f() {{ let _ = {text}; }}"))
379 }
380
381 pub fn expr_empty_block() -> ast::Expr {
382     expr_from_text("{}")
383 }
384 pub fn expr_path(path: ast::Path) -> ast::Expr {
385     expr_from_text(&path.to_string())
386 }
387 pub fn expr_continue(label: Option<ast::Lifetime>) -> ast::Expr {
388     match label {
389         Some(label) => expr_from_text(&format!("continue {label}")),
390         None => expr_from_text("continue"),
391     }
392 }
393 // Consider `op: SyntaxKind` instead for nicer syntax at the call-site?
394 pub fn expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr {
395     expr_from_text(&format!("{lhs} {op} {rhs}"))
396 }
397 pub fn expr_break(label: Option<ast::Lifetime>, expr: Option<ast::Expr>) -> ast::Expr {
398     let mut s = String::from("break");
399
400     if let Some(label) = label {
401         format_to!(s, " {label}");
402     }
403
404     if let Some(expr) = expr {
405         format_to!(s, " {expr}");
406     }
407
408     expr_from_text(&s)
409 }
410 pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
411     match expr {
412         Some(expr) => expr_from_text(&format!("return {expr}")),
413         None => expr_from_text("return"),
414     }
415 }
416 pub fn expr_try(expr: ast::Expr) -> ast::Expr {
417     expr_from_text(&format!("{expr}?"))
418 }
419 pub fn expr_await(expr: ast::Expr) -> ast::Expr {
420     expr_from_text(&format!("{expr}.await"))
421 }
422 pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
423     expr_from_text(&format!("match {expr} {match_arm_list}"))
424 }
425 pub fn expr_if(
426     condition: ast::Expr,
427     then_branch: ast::BlockExpr,
428     else_branch: Option<ast::ElseBranch>,
429 ) -> ast::Expr {
430     let else_branch = match else_branch {
431         Some(ast::ElseBranch::Block(block)) => format!("else {block}"),
432         Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {if_expr}"),
433         None => String::new(),
434     };
435     expr_from_text(&format!("if {condition} {then_branch} {else_branch}"))
436 }
437 pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr {
438     expr_from_text(&format!("for {pat} in {expr} {block}"))
439 }
440
441 pub fn expr_loop(block: ast::BlockExpr) -> ast::Expr {
442     expr_from_text(&format!("loop {block}"))
443 }
444
445 pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
446     let token = token(op);
447     expr_from_text(&format!("{token}{expr}"))
448 }
449 pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
450     expr_from_text(&format!("{f}{arg_list}"))
451 }
452 pub fn expr_method_call(
453     receiver: ast::Expr,
454     method: ast::NameRef,
455     arg_list: ast::ArgList,
456 ) -> ast::Expr {
457     expr_from_text(&format!("{receiver}.{method}{arg_list}"))
458 }
459 pub fn expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
460     expr_from_text(&format!("{f}!{arg_list}"))
461 }
462 pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
463     expr_from_text(&if exclusive { format!("&mut {expr}") } else { format!("&{expr}") })
464 }
465 pub fn expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr {
466     let params = pats.into_iter().join(", ");
467     expr_from_text(&format!("|{params}| {expr}"))
468 }
469 pub fn expr_field(receiver: ast::Expr, field: &str) -> ast::Expr {
470     expr_from_text(&format!("{receiver}.{field}"))
471 }
472 pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
473     expr_from_text(&format!("({expr})"))
474 }
475 pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr {
476     let expr = elements.into_iter().format(", ");
477     expr_from_text(&format!("({expr})"))
478 }
479 pub fn expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
480     expr_from_text(&format!("{lhs} = {rhs}"))
481 }
482 fn expr_from_text(text: &str) -> ast::Expr {
483     ast_from_text(&format!("const C: () = {text};"))
484 }
485 pub fn expr_let(pattern: ast::Pat, expr: ast::Expr) -> ast::LetExpr {
486     ast_from_text(&format!("const _: () = while let {pattern} = {expr} {{}};"))
487 }
488
489 pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
490     let args = args.into_iter().format(", ");
491     ast_from_text(&format!("fn main() {{ ()({args}) }}"))
492 }
493
494 pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
495     let mut s = String::from("fn f(");
496     if ref_ {
497         s.push_str("ref ");
498     }
499     if mut_ {
500         s.push_str("mut ");
501     }
502     format_to!(s, "{name}");
503     s.push_str(": ())");
504     ast_from_text(&s)
505 }
506
507 pub fn wildcard_pat() -> ast::WildcardPat {
508     return from_text("_");
509
510     fn from_text(text: &str) -> ast::WildcardPat {
511         ast_from_text(&format!("fn f({text}: ())"))
512     }
513 }
514
515 pub fn literal_pat(lit: &str) -> ast::LiteralPat {
516     return from_text(lit);
517
518     fn from_text(text: &str) -> ast::LiteralPat {
519         ast_from_text(&format!("fn f() {{ match x {{ {text} => {{}} }} }}"))
520     }
521 }
522
523 /// Creates a tuple of patterns from an iterator of patterns.
524 ///
525 /// Invariant: `pats` must be length > 0
526 pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
527     let mut count: usize = 0;
528     let mut pats_str = pats.into_iter().inspect(|_| count += 1).join(", ");
529     if count == 1 {
530         pats_str.push(',');
531     }
532     return from_text(&format!("({pats_str})"));
533
534     fn from_text(text: &str) -> ast::TuplePat {
535         ast_from_text(&format!("fn f({text}: ())"))
536     }
537 }
538
539 pub fn tuple_struct_pat(
540     path: ast::Path,
541     pats: impl IntoIterator<Item = ast::Pat>,
542 ) -> ast::TupleStructPat {
543     let pats_str = pats.into_iter().join(", ");
544     return from_text(&format!("{path}({pats_str})"));
545
546     fn from_text(text: &str) -> ast::TupleStructPat {
547         ast_from_text(&format!("fn f({text}: ())"))
548     }
549 }
550
551 pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
552     let pats_str = pats.into_iter().join(", ");
553     return from_text(&format!("{path} {{ {pats_str} }}"));
554
555     fn from_text(text: &str) -> ast::RecordPat {
556         ast_from_text(&format!("fn f({text}: ())"))
557     }
558 }
559
560 pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
561     ast_from_text(&format!("fn f({path} {fields}: ()))"))
562 }
563
564 pub fn record_pat_field_list(
565     fields: impl IntoIterator<Item = ast::RecordPatField>,
566 ) -> ast::RecordPatFieldList {
567     let fields = fields.into_iter().join(", ");
568     ast_from_text(&format!("fn f(S {{ {fields} }}: ()))"))
569 }
570
571 pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
572     ast_from_text(&format!("fn f(S {{ {name_ref}: {pat} }}: ()))"))
573 }
574
575 pub fn record_pat_field_shorthand(name_ref: ast::NameRef) -> ast::RecordPatField {
576     ast_from_text(&format!("fn f(S {{ {name_ref} }}: ()))"))
577 }
578
579 /// Returns a `BindPat` if the path has just one segment, a `PathPat` otherwise.
580 pub fn path_pat(path: ast::Path) -> ast::Pat {
581     return from_text(&path.to_string());
582     fn from_text(text: &str) -> ast::Pat {
583         ast_from_text(&format!("fn f({text}: ())"))
584     }
585 }
586
587 pub fn match_arm(
588     pats: impl IntoIterator<Item = ast::Pat>,
589     guard: Option<ast::Expr>,
590     expr: ast::Expr,
591 ) -> ast::MatchArm {
592     let pats_str = pats.into_iter().join(" | ");
593     return match guard {
594         Some(guard) => from_text(&format!("{pats_str} if {guard} => {expr}")),
595         None => from_text(&format!("{pats_str} => {expr}")),
596     };
597
598     fn from_text(text: &str) -> ast::MatchArm {
599         ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
600     }
601 }
602
603 pub fn match_arm_with_guard(
604     pats: impl IntoIterator<Item = ast::Pat>,
605     guard: ast::Expr,
606     expr: ast::Expr,
607 ) -> ast::MatchArm {
608     let pats_str = pats.into_iter().join(" | ");
609     return from_text(&format!("{pats_str} if {guard} => {expr}"));
610
611     fn from_text(text: &str) -> ast::MatchArm {
612         ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
613     }
614 }
615
616 pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
617     let arms_str = arms
618         .into_iter()
619         .map(|arm| {
620             let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
621             let comma = if needs_comma { "," } else { "" };
622             let arm = arm.syntax();
623             format!("    {arm}{comma}\n")
624         })
625         .collect::<String>();
626     return from_text(&arms_str);
627
628     fn from_text(text: &str) -> ast::MatchArmList {
629         ast_from_text(&format!("fn f() {{ match () {{\n{text}}} }}"))
630     }
631 }
632
633 pub fn where_pred(
634     path: ast::Path,
635     bounds: impl IntoIterator<Item = ast::TypeBound>,
636 ) -> ast::WherePred {
637     let bounds = bounds.into_iter().join(" + ");
638     return from_text(&format!("{path}: {bounds}"));
639
640     fn from_text(text: &str) -> ast::WherePred {
641         ast_from_text(&format!("fn f() where {text} {{ }}"))
642     }
643 }
644
645 pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause {
646     let preds = preds.into_iter().join(", ");
647     return from_text(preds.as_str());
648
649     fn from_text(text: &str) -> ast::WhereClause {
650         ast_from_text(&format!("fn f() where {text} {{ }}"))
651     }
652 }
653
654 pub fn let_stmt(
655     pattern: ast::Pat,
656     ty: Option<ast::Type>,
657     initializer: Option<ast::Expr>,
658 ) -> ast::LetStmt {
659     let mut text = String::new();
660     format_to!(text, "let {pattern}");
661     if let Some(ty) = ty {
662         format_to!(text, ": {ty}");
663     }
664     match initializer {
665         Some(it) => format_to!(text, " = {it};"),
666         None => format_to!(text, ";"),
667     };
668     ast_from_text(&format!("fn f() {{ {text} }}"))
669 }
670
671 pub fn let_else_stmt(
672     pattern: ast::Pat,
673     ty: Option<ast::Type>,
674     expr: ast::Expr,
675     diverging: ast::BlockExpr,
676 ) -> ast::LetStmt {
677     let mut text = String::new();
678     format_to!(text, "let {pattern}");
679     if let Some(ty) = ty {
680         format_to!(text, ": {ty}");
681     }
682     format_to!(text, " = {expr} else {diverging};");
683     ast_from_text(&format!("fn f() {{ {text} }}"))
684 }
685
686 pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
687     let semi = if expr.is_block_like() { "" } else { ";" };
688     ast_from_text(&format!("fn f() {{ {expr}{semi} (); }}"))
689 }
690
691 pub fn item_const(
692     visibility: Option<ast::Visibility>,
693     name: ast::Name,
694     ty: ast::Type,
695     expr: ast::Expr,
696 ) -> ast::Const {
697     let visibility = match visibility {
698         None => String::new(),
699         Some(it) => format!("{it} "),
700     };
701     ast_from_text(&format!("{visibility} const {name}: {ty} = {expr};"))
702 }
703
704 pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
705     ast_from_text(&format!("fn f({pat}: {ty}) {{ }}"))
706 }
707
708 pub fn self_param() -> ast::SelfParam {
709     ast_from_text("fn f(&self) { }")
710 }
711
712 pub fn ret_type(ty: ast::Type) -> ast::RetType {
713     ast_from_text(&format!("fn f() -> {ty} {{ }}"))
714 }
715
716 pub fn param_list(
717     self_param: Option<ast::SelfParam>,
718     pats: impl IntoIterator<Item = ast::Param>,
719 ) -> ast::ParamList {
720     let args = pats.into_iter().join(", ");
721     let list = match self_param {
722         Some(self_param) if args.is_empty() => format!("fn f({self_param}) {{ }}"),
723         Some(self_param) => format!("fn f({self_param}, {args}) {{ }}"),
724         None => format!("fn f({args}) {{ }}"),
725     };
726     ast_from_text(&list)
727 }
728
729 pub fn type_bound(bound: &str) -> ast::TypeBound {
730     ast_from_text(&format!("fn f<T: {bound}>() {{ }}"))
731 }
732
733 pub fn type_bound_list(
734     bounds: impl IntoIterator<Item = ast::TypeBound>,
735 ) -> Option<ast::TypeBoundList> {
736     let bounds = bounds.into_iter().map(|it| it.to_string()).unique().join(" + ");
737     if bounds.is_empty() {
738         return None;
739     }
740     Some(ast_from_text(&format!("fn f<T: {bounds}>() {{ }}")))
741 }
742
743 pub fn type_param(name: ast::Name, bounds: Option<ast::TypeBoundList>) -> ast::TypeParam {
744     let bounds = bounds.map_or_else(String::new, |it| format!(": {it}"));
745     ast_from_text(&format!("fn f<{name}{bounds}>() {{ }}"))
746 }
747
748 pub fn lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam {
749     ast_from_text(&format!("fn f<{lifetime}>() {{ }}"))
750 }
751
752 pub fn generic_param_list(
753     pats: impl IntoIterator<Item = ast::GenericParam>,
754 ) -> ast::GenericParamList {
755     let args = pats.into_iter().join(", ");
756     ast_from_text(&format!("fn f<{args}>() {{ }}"))
757 }
758
759 pub fn type_arg(ty: ast::Type) -> ast::TypeArg {
760     ast_from_text(&format!("const S: T<{ty}> = ();"))
761 }
762
763 pub fn lifetime_arg(lifetime: ast::Lifetime) -> ast::LifetimeArg {
764     ast_from_text(&format!("const S: T<{lifetime}> = ();"))
765 }
766
767 pub(crate) fn generic_arg_list(
768     args: impl IntoIterator<Item = ast::GenericArg>,
769 ) -> ast::GenericArgList {
770     let args = args.into_iter().join(", ");
771     ast_from_text(&format!("const S: T<{args}> = ();"))
772 }
773
774 pub fn visibility_pub_crate() -> ast::Visibility {
775     ast_from_text("pub(crate) struct S")
776 }
777
778 pub fn visibility_pub() -> ast::Visibility {
779     ast_from_text("pub struct S")
780 }
781
782 pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
783     let fields = fields.into_iter().join(", ");
784     ast_from_text(&format!("struct f({fields});"))
785 }
786
787 pub fn record_field_list(
788     fields: impl IntoIterator<Item = ast::RecordField>,
789 ) -> ast::RecordFieldList {
790     let fields = fields.into_iter().join(", ");
791     ast_from_text(&format!("struct f {{ {fields} }}"))
792 }
793
794 pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
795     let visibility = match visibility {
796         None => String::new(),
797         Some(it) => format!("{it} "),
798     };
799     ast_from_text(&format!("struct f({visibility}{ty});"))
800 }
801
802 pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
803     let field_list = match field_list {
804         None => String::new(),
805         Some(it) => match it {
806             ast::FieldList::RecordFieldList(record) => format!(" {record}"),
807             ast::FieldList::TupleFieldList(tuple) => format!("{tuple}"),
808         },
809     };
810     ast_from_text(&format!("enum f {{ {name}{field_list} }}"))
811 }
812
813 pub fn fn_(
814     visibility: Option<ast::Visibility>,
815     fn_name: ast::Name,
816     type_params: Option<ast::GenericParamList>,
817     params: ast::ParamList,
818     body: ast::BlockExpr,
819     ret_type: Option<ast::RetType>,
820     is_async: bool,
821 ) -> ast::Fn {
822     let type_params = match type_params {
823         Some(type_params) => format!("{type_params}"),
824         None => "".into(),
825     };
826     let ret_type = match ret_type {
827         Some(ret_type) => format!("{ret_type} "),
828         None => "".into(),
829     };
830     let visibility = match visibility {
831         None => String::new(),
832         Some(it) => format!("{it} "),
833     };
834
835     let async_literal = if is_async { "async " } else { "" };
836
837     ast_from_text(&format!(
838         "{visibility}{async_literal}fn {fn_name}{type_params}{params} {ret_type}{body}",
839     ))
840 }
841
842 pub fn struct_(
843     visibility: Option<ast::Visibility>,
844     strukt_name: ast::Name,
845     generic_param_list: Option<ast::GenericParamList>,
846     field_list: ast::FieldList,
847 ) -> ast::Struct {
848     let semicolon = if matches!(field_list, ast::FieldList::TupleFieldList(_)) { ";" } else { "" };
849     let type_params = generic_param_list.map_or_else(String::new, |it| it.to_string());
850     let visibility = match visibility {
851         None => String::new(),
852         Some(it) => format!("{it} "),
853     };
854
855     ast_from_text(&format!("{visibility}struct {strukt_name}{type_params}{field_list}{semicolon}",))
856 }
857
858 #[track_caller]
859 fn ast_from_text<N: AstNode>(text: &str) -> N {
860     let parse = SourceFile::parse(text);
861     let node = match parse.tree().syntax().descendants().find_map(N::cast) {
862         Some(it) => it,
863         None => {
864             let node = std::any::type_name::<N>();
865             panic!("Failed to make ast node `{node}` from text {text}")
866         }
867     };
868     let node = node.clone_subtree();
869     assert_eq!(node.syntax().text_range().start(), 0.into());
870     node
871 }
872
873 pub fn token(kind: SyntaxKind) -> SyntaxToken {
874     tokens::SOURCE_FILE
875         .tree()
876         .syntax()
877         .clone_for_update()
878         .descendants_with_tokens()
879         .filter_map(|it| it.into_token())
880         .find(|it| it.kind() == kind)
881         .unwrap_or_else(|| panic!("unhandled token: {kind:?}"))
882 }
883
884 pub mod tokens {
885     use once_cell::sync::Lazy;
886
887     use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
888
889     pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
890         SourceFile::parse(
891             "const C: <()>::Item = (1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p)\n;\n\n",
892         )
893     });
894
895     pub fn single_space() -> SyntaxToken {
896         SOURCE_FILE
897             .tree()
898             .syntax()
899             .clone_for_update()
900             .descendants_with_tokens()
901             .filter_map(|it| it.into_token())
902             .find(|it| it.kind() == WHITESPACE && it.text() == " ")
903             .unwrap()
904     }
905
906     pub fn whitespace(text: &str) -> SyntaxToken {
907         assert!(text.trim().is_empty());
908         let sf = SourceFile::parse(text).ok().unwrap();
909         sf.syntax().clone_for_update().first_child_or_token().unwrap().into_token().unwrap()
910     }
911
912     pub fn doc_comment(text: &str) -> SyntaxToken {
913         assert!(!text.trim().is_empty());
914         let sf = SourceFile::parse(text).ok().unwrap();
915         sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
916     }
917
918     pub fn literal(text: &str) -> SyntaxToken {
919         assert_eq!(text.trim(), text);
920         let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {text}; }}"));
921         lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
922     }
923
924     pub fn single_newline() -> SyntaxToken {
925         let res = SOURCE_FILE
926             .tree()
927             .syntax()
928             .clone_for_update()
929             .descendants_with_tokens()
930             .filter_map(|it| it.into_token())
931             .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
932             .unwrap();
933         res.detach();
934         res
935     }
936
937     pub fn blank_line() -> SyntaxToken {
938         SOURCE_FILE
939             .tree()
940             .syntax()
941             .clone_for_update()
942             .descendants_with_tokens()
943             .filter_map(|it| it.into_token())
944             .find(|it| it.kind() == WHITESPACE && it.text() == "\n\n")
945             .unwrap()
946     }
947
948     pub struct WsBuilder(SourceFile);
949
950     impl WsBuilder {
951         pub fn new(text: &str) -> WsBuilder {
952             WsBuilder(SourceFile::parse(text).ok().unwrap())
953         }
954         pub fn ws(&self) -> SyntaxToken {
955             self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()
956         }
957     }
958 }