]> git.lizzy.rs Git - rust.git/blob - src/tools/rust-analyzer/crates/syntax/src/ast/make.rs
:arrow_up: rust-analyzer
[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_bool() -> ast::Type {
92         ty_path(ident_path("bool"))
93     }
94     pub fn ty_option(t: ast::Type) -> ast::Type {
95         ty_from_text(&format!("Option<{t}>"))
96     }
97     pub fn ty_result(t: ast::Type, e: ast::Type) -> ast::Type {
98         ty_from_text(&format!("Result<{t}, {e}>"))
99     }
100 }
101
102 pub fn name(name: &str) -> ast::Name {
103     let raw_escape = raw_ident_esc(name);
104     ast_from_text(&format!("mod {raw_escape}{name};"))
105 }
106 pub fn name_ref(name_ref: &str) -> ast::NameRef {
107     let raw_escape = raw_ident_esc(name_ref);
108     ast_from_text(&format!("fn f() {{ {raw_escape}{name_ref}; }}"))
109 }
110 fn raw_ident_esc(ident: &str) -> &'static str {
111     let is_keyword = parser::SyntaxKind::from_keyword(ident).is_some();
112     if is_keyword && !matches!(ident, "self" | "crate" | "super" | "Self") {
113         "r#"
114     } else {
115         ""
116     }
117 }
118
119 pub fn lifetime(text: &str) -> ast::Lifetime {
120     let mut text = text;
121     let tmp;
122     if never!(!text.starts_with('\'')) {
123         tmp = format!("'{text}");
124         text = &tmp;
125     }
126     ast_from_text(&format!("fn f<{text}>() {{ }}"))
127 }
128
129 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
130 // `expr_xxx`.
131 pub fn ty(text: &str) -> ast::Type {
132     ty_from_text(text)
133 }
134 pub fn ty_placeholder() -> ast::Type {
135     ty_from_text("_")
136 }
137 pub fn ty_unit() -> ast::Type {
138     ty_from_text("()")
139 }
140 pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
141     let mut count: usize = 0;
142     let mut contents = types.into_iter().inspect(|_| count += 1).join(", ");
143     if count == 1 {
144         contents.push(',');
145     }
146
147     ty_from_text(&format!("({contents})"))
148 }
149 pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
150     ty_from_text(&if exclusive { format!("&mut {target}") } else { format!("&{target}") })
151 }
152 pub fn ty_path(path: ast::Path) -> ast::Type {
153     ty_from_text(&path.to_string())
154 }
155 fn ty_from_text(text: &str) -> ast::Type {
156     ast_from_text(&format!("type _T = {text};"))
157 }
158
159 pub fn assoc_item_list() -> ast::AssocItemList {
160     ast_from_text("impl C for D {}")
161 }
162
163 pub fn impl_(
164     ty: ast::Path,
165     params: Option<ast::GenericParamList>,
166     ty_params: Option<ast::GenericParamList>,
167 ) -> ast::Impl {
168     let params = match params {
169         Some(params) => params.to_string(),
170         None => String::new(),
171     };
172     let ty_params = match ty_params {
173         Some(params) => params.to_string(),
174         None => String::new(),
175     };
176     ast_from_text(&format!("impl{params} {ty}{ty_params} {{}}"))
177 }
178
179 pub fn impl_trait(
180     trait_: ast::Path,
181     ty: ast::Path,
182     ty_params: Option<ast::GenericParamList>,
183 ) -> ast::Impl {
184     let ty_params = ty_params.map_or_else(String::new, |params| params.to_string());
185     ast_from_text(&format!("impl{ty_params} {trait_} for {ty}{ty_params} {{}}"))
186 }
187
188 pub(crate) fn generic_arg_list() -> ast::GenericArgList {
189     ast_from_text("const S: T<> = ();")
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 /// Ideally this function wouldn't exist since it involves manual indenting.
338 /// It differs from `make::block_expr` by also supporting comments.
339 ///
340 /// FIXME: replace usages of this with the mutable syntax tree API
341 pub fn hacky_block_expr_with_comments(
342     elements: impl IntoIterator<Item = crate::SyntaxElement>,
343     tail_expr: Option<ast::Expr>,
344 ) -> ast::BlockExpr {
345     let mut buf = "{\n".to_string();
346     for node_or_token in elements.into_iter() {
347         match node_or_token {
348             rowan::NodeOrToken::Node(n) => format_to!(buf, "    {n}\n"),
349             rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::COMMENT => {
350                 format_to!(buf, "    {t}\n")
351             }
352             _ => (),
353         }
354     }
355     if let Some(tail_expr) = tail_expr {
356         format_to!(buf, "    {tail_expr}\n");
357     }
358     buf += "}";
359     ast_from_text(&format!("fn f() {buf}"))
360 }
361
362 pub fn expr_unit() -> ast::Expr {
363     expr_from_text("()")
364 }
365 pub fn expr_literal(text: &str) -> ast::Literal {
366     assert_eq!(text.trim(), text);
367     ast_from_text(&format!("fn f() {{ let _ = {text}; }}"))
368 }
369
370 pub fn expr_empty_block() -> ast::Expr {
371     expr_from_text("{}")
372 }
373 pub fn expr_path(path: ast::Path) -> ast::Expr {
374     expr_from_text(&path.to_string())
375 }
376 pub fn expr_continue(label: Option<ast::Lifetime>) -> ast::Expr {
377     match label {
378         Some(label) => expr_from_text(&format!("continue {label}")),
379         None => expr_from_text("continue"),
380     }
381 }
382 // Consider `op: SyntaxKind` instead for nicer syntax at the call-site?
383 pub fn expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr {
384     expr_from_text(&format!("{lhs} {op} {rhs}"))
385 }
386 pub fn expr_break(label: Option<ast::Lifetime>, expr: Option<ast::Expr>) -> ast::Expr {
387     let mut s = String::from("break");
388
389     if let Some(label) = label {
390         format_to!(s, " {label}");
391     }
392
393     if let Some(expr) = expr {
394         format_to!(s, " {expr}");
395     }
396
397     expr_from_text(&s)
398 }
399 pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
400     match expr {
401         Some(expr) => expr_from_text(&format!("return {expr}")),
402         None => expr_from_text("return"),
403     }
404 }
405 pub fn expr_try(expr: ast::Expr) -> ast::Expr {
406     expr_from_text(&format!("{expr}?"))
407 }
408 pub fn expr_await(expr: ast::Expr) -> ast::Expr {
409     expr_from_text(&format!("{expr}.await"))
410 }
411 pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
412     expr_from_text(&format!("match {expr} {match_arm_list}"))
413 }
414 pub fn expr_if(
415     condition: ast::Expr,
416     then_branch: ast::BlockExpr,
417     else_branch: Option<ast::ElseBranch>,
418 ) -> ast::Expr {
419     let else_branch = match else_branch {
420         Some(ast::ElseBranch::Block(block)) => format!("else {block}"),
421         Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {if_expr}"),
422         None => String::new(),
423     };
424     expr_from_text(&format!("if {condition} {then_branch} {else_branch}"))
425 }
426 pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr {
427     expr_from_text(&format!("for {pat} in {expr} {block}"))
428 }
429
430 pub fn expr_loop(block: ast::BlockExpr) -> ast::Expr {
431     expr_from_text(&format!("loop {block}"))
432 }
433
434 pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
435     let token = token(op);
436     expr_from_text(&format!("{token}{expr}"))
437 }
438 pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
439     expr_from_text(&format!("{f}{arg_list}"))
440 }
441 pub fn expr_method_call(
442     receiver: ast::Expr,
443     method: ast::NameRef,
444     arg_list: ast::ArgList,
445 ) -> ast::Expr {
446     expr_from_text(&format!("{receiver}.{method}{arg_list}"))
447 }
448 pub fn expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
449     expr_from_text(&format!("{f}!{arg_list}"))
450 }
451 pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
452     expr_from_text(&if exclusive { format!("&mut {expr}") } else { format!("&{expr}") })
453 }
454 pub fn expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr {
455     let params = pats.into_iter().join(", ");
456     expr_from_text(&format!("|{params}| {expr}"))
457 }
458 pub fn expr_field(receiver: ast::Expr, field: &str) -> ast::Expr {
459     expr_from_text(&format!("{receiver}.{field}"))
460 }
461 pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
462     expr_from_text(&format!("({expr})"))
463 }
464 pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr {
465     let expr = elements.into_iter().format(", ");
466     expr_from_text(&format!("({expr})"))
467 }
468 pub fn expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
469     expr_from_text(&format!("{lhs} = {rhs}"))
470 }
471 fn expr_from_text(text: &str) -> ast::Expr {
472     ast_from_text(&format!("const C: () = {text};"))
473 }
474 pub fn expr_let(pattern: ast::Pat, expr: ast::Expr) -> ast::LetExpr {
475     ast_from_text(&format!("const _: () = while let {pattern} = {expr} {{}};"))
476 }
477
478 pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
479     let args = args.into_iter().format(", ");
480     ast_from_text(&format!("fn main() {{ ()({args}) }}"))
481 }
482
483 pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
484     let mut s = String::from("fn f(");
485     if ref_ {
486         s.push_str("ref ");
487     }
488     if mut_ {
489         s.push_str("mut ");
490     }
491     format_to!(s, "{name}");
492     s.push_str(": ())");
493     ast_from_text(&s)
494 }
495
496 pub fn wildcard_pat() -> ast::WildcardPat {
497     return from_text("_");
498
499     fn from_text(text: &str) -> ast::WildcardPat {
500         ast_from_text(&format!("fn f({text}: ())"))
501     }
502 }
503
504 pub fn literal_pat(lit: &str) -> ast::LiteralPat {
505     return from_text(lit);
506
507     fn from_text(text: &str) -> ast::LiteralPat {
508         ast_from_text(&format!("fn f() {{ match x {{ {text} => {{}} }} }}"))
509     }
510 }
511
512 /// Creates a tuple of patterns from an iterator of patterns.
513 ///
514 /// Invariant: `pats` must be length > 0
515 pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
516     let mut count: usize = 0;
517     let mut pats_str = pats.into_iter().inspect(|_| count += 1).join(", ");
518     if count == 1 {
519         pats_str.push(',');
520     }
521     return from_text(&format!("({pats_str})"));
522
523     fn from_text(text: &str) -> ast::TuplePat {
524         ast_from_text(&format!("fn f({text}: ())"))
525     }
526 }
527
528 pub fn tuple_struct_pat(
529     path: ast::Path,
530     pats: impl IntoIterator<Item = ast::Pat>,
531 ) -> ast::TupleStructPat {
532     let pats_str = pats.into_iter().join(", ");
533     return from_text(&format!("{path}({pats_str})"));
534
535     fn from_text(text: &str) -> ast::TupleStructPat {
536         ast_from_text(&format!("fn f({text}: ())"))
537     }
538 }
539
540 pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
541     let pats_str = pats.into_iter().join(", ");
542     return from_text(&format!("{path} {{ {pats_str} }}"));
543
544     fn from_text(text: &str) -> ast::RecordPat {
545         ast_from_text(&format!("fn f({text}: ())"))
546     }
547 }
548
549 pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
550     ast_from_text(&format!("fn f({path} {fields}: ()))"))
551 }
552
553 pub fn record_pat_field_list(
554     fields: impl IntoIterator<Item = ast::RecordPatField>,
555 ) -> ast::RecordPatFieldList {
556     let fields = fields.into_iter().join(", ");
557     ast_from_text(&format!("fn f(S {{ {fields} }}: ()))"))
558 }
559
560 pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
561     ast_from_text(&format!("fn f(S {{ {name_ref}: {pat} }}: ()))"))
562 }
563
564 pub fn record_pat_field_shorthand(name_ref: ast::NameRef) -> ast::RecordPatField {
565     ast_from_text(&format!("fn f(S {{ {name_ref} }}: ()))"))
566 }
567
568 /// Returns a `BindPat` if the path has just one segment, a `PathPat` otherwise.
569 pub fn path_pat(path: ast::Path) -> ast::Pat {
570     return from_text(&path.to_string());
571     fn from_text(text: &str) -> ast::Pat {
572         ast_from_text(&format!("fn f({text}: ())"))
573     }
574 }
575
576 pub fn match_arm(
577     pats: impl IntoIterator<Item = ast::Pat>,
578     guard: Option<ast::Expr>,
579     expr: ast::Expr,
580 ) -> ast::MatchArm {
581     let pats_str = pats.into_iter().join(" | ");
582     return match guard {
583         Some(guard) => from_text(&format!("{pats_str} if {guard} => {expr}")),
584         None => from_text(&format!("{pats_str} => {expr}")),
585     };
586
587     fn from_text(text: &str) -> ast::MatchArm {
588         ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
589     }
590 }
591
592 pub fn match_arm_with_guard(
593     pats: impl IntoIterator<Item = ast::Pat>,
594     guard: ast::Expr,
595     expr: ast::Expr,
596 ) -> ast::MatchArm {
597     let pats_str = pats.into_iter().join(" | ");
598     return from_text(&format!("{pats_str} if {guard} => {expr}"));
599
600     fn from_text(text: &str) -> ast::MatchArm {
601         ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
602     }
603 }
604
605 pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
606     let arms_str = arms
607         .into_iter()
608         .map(|arm| {
609             let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
610             let comma = if needs_comma { "," } else { "" };
611             let arm = arm.syntax();
612             format!("    {arm}{comma}\n")
613         })
614         .collect::<String>();
615     return from_text(&arms_str);
616
617     fn from_text(text: &str) -> ast::MatchArmList {
618         ast_from_text(&format!("fn f() {{ match () {{\n{text}}} }}"))
619     }
620 }
621
622 pub fn where_pred(
623     path: ast::Path,
624     bounds: impl IntoIterator<Item = ast::TypeBound>,
625 ) -> ast::WherePred {
626     let bounds = bounds.into_iter().join(" + ");
627     return from_text(&format!("{path}: {bounds}"));
628
629     fn from_text(text: &str) -> ast::WherePred {
630         ast_from_text(&format!("fn f() where {text} {{ }}"))
631     }
632 }
633
634 pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause {
635     let preds = preds.into_iter().join(", ");
636     return from_text(preds.as_str());
637
638     fn from_text(text: &str) -> ast::WhereClause {
639         ast_from_text(&format!("fn f() where {text} {{ }}"))
640     }
641 }
642
643 pub fn let_stmt(
644     pattern: ast::Pat,
645     ty: Option<ast::Type>,
646     initializer: Option<ast::Expr>,
647 ) -> ast::LetStmt {
648     let mut text = String::new();
649     format_to!(text, "let {pattern}");
650     if let Some(ty) = ty {
651         format_to!(text, ": {ty}");
652     }
653     match initializer {
654         Some(it) => format_to!(text, " = {it};"),
655         None => format_to!(text, ";"),
656     };
657     ast_from_text(&format!("fn f() {{ {text} }}"))
658 }
659 pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
660     let semi = if expr.is_block_like() { "" } else { ";" };
661     ast_from_text(&format!("fn f() {{ {expr}{semi} (); }}"))
662 }
663
664 pub fn item_const(
665     visibility: Option<ast::Visibility>,
666     name: ast::Name,
667     ty: ast::Type,
668     expr: ast::Expr,
669 ) -> ast::Const {
670     let visibility = match visibility {
671         None => String::new(),
672         Some(it) => format!("{it} "),
673     };
674     ast_from_text(&format!("{visibility} const {name}: {ty} = {expr};"))
675 }
676
677 pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
678     ast_from_text(&format!("fn f({pat}: {ty}) {{ }}"))
679 }
680
681 pub fn self_param() -> ast::SelfParam {
682     ast_from_text("fn f(&self) { }")
683 }
684
685 pub fn ret_type(ty: ast::Type) -> ast::RetType {
686     ast_from_text(&format!("fn f() -> {ty} {{ }}"))
687 }
688
689 pub fn param_list(
690     self_param: Option<ast::SelfParam>,
691     pats: impl IntoIterator<Item = ast::Param>,
692 ) -> ast::ParamList {
693     let args = pats.into_iter().join(", ");
694     let list = match self_param {
695         Some(self_param) if args.is_empty() => format!("fn f({self_param}) {{ }}"),
696         Some(self_param) => format!("fn f({self_param}, {args}) {{ }}"),
697         None => format!("fn f({args}) {{ }}"),
698     };
699     ast_from_text(&list)
700 }
701
702 pub fn type_param(name: ast::Name, ty: Option<ast::TypeBoundList>) -> ast::TypeParam {
703     let bound = match ty {
704         Some(it) => format!(": {it}"),
705         None => String::new(),
706     };
707     ast_from_text(&format!("fn f<{name}{bound}>() {{ }}"))
708 }
709
710 pub fn lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam {
711     ast_from_text(&format!("fn f<{lifetime}>() {{ }}"))
712 }
713
714 pub fn generic_param_list(
715     pats: impl IntoIterator<Item = ast::GenericParam>,
716 ) -> ast::GenericParamList {
717     let args = pats.into_iter().join(", ");
718     ast_from_text(&format!("fn f<{args}>() {{ }}"))
719 }
720
721 pub fn visibility_pub_crate() -> ast::Visibility {
722     ast_from_text("pub(crate) struct S")
723 }
724
725 pub fn visibility_pub() -> ast::Visibility {
726     ast_from_text("pub struct S")
727 }
728
729 pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
730     let fields = fields.into_iter().join(", ");
731     ast_from_text(&format!("struct f({fields});"))
732 }
733
734 pub fn record_field_list(
735     fields: impl IntoIterator<Item = ast::RecordField>,
736 ) -> ast::RecordFieldList {
737     let fields = fields.into_iter().join(", ");
738     ast_from_text(&format!("struct f {{ {fields} }}"))
739 }
740
741 pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
742     let visibility = match visibility {
743         None => String::new(),
744         Some(it) => format!("{it} "),
745     };
746     ast_from_text(&format!("struct f({visibility}{ty});"))
747 }
748
749 pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
750     let field_list = match field_list {
751         None => String::new(),
752         Some(it) => match it {
753             ast::FieldList::RecordFieldList(record) => format!(" {record}"),
754             ast::FieldList::TupleFieldList(tuple) => format!("{tuple}"),
755         },
756     };
757     ast_from_text(&format!("enum f {{ {name}{field_list} }}"))
758 }
759
760 pub fn fn_(
761     visibility: Option<ast::Visibility>,
762     fn_name: ast::Name,
763     type_params: Option<ast::GenericParamList>,
764     params: ast::ParamList,
765     body: ast::BlockExpr,
766     ret_type: Option<ast::RetType>,
767     is_async: bool,
768 ) -> ast::Fn {
769     let type_params = match type_params {
770         Some(type_params) => format!("{type_params}"),
771         None => "".into(),
772     };
773     let ret_type = match ret_type {
774         Some(ret_type) => format!("{ret_type} "),
775         None => "".into(),
776     };
777     let visibility = match visibility {
778         None => String::new(),
779         Some(it) => format!("{it} "),
780     };
781
782     let async_literal = if is_async { "async " } else { "" };
783
784     ast_from_text(&format!(
785         "{visibility}{async_literal}fn {fn_name}{type_params}{params} {ret_type}{body}",
786     ))
787 }
788
789 pub fn struct_(
790     visibility: Option<ast::Visibility>,
791     strukt_name: ast::Name,
792     generic_param_list: Option<ast::GenericParamList>,
793     field_list: ast::FieldList,
794 ) -> ast::Struct {
795     let semicolon = if matches!(field_list, ast::FieldList::TupleFieldList(_)) { ";" } else { "" };
796     let type_params = generic_param_list.map_or_else(String::new, |it| it.to_string());
797     let visibility = match visibility {
798         None => String::new(),
799         Some(it) => format!("{it} "),
800     };
801
802     ast_from_text(&format!("{visibility}struct {strukt_name}{type_params}{field_list}{semicolon}",))
803 }
804
805 #[track_caller]
806 fn ast_from_text<N: AstNode>(text: &str) -> N {
807     let parse = SourceFile::parse(text);
808     let node = match parse.tree().syntax().descendants().find_map(N::cast) {
809         Some(it) => it,
810         None => {
811             let node = std::any::type_name::<N>();
812             panic!("Failed to make ast node `{node}` from text {text}")
813         }
814     };
815     let node = node.clone_subtree();
816     assert_eq!(node.syntax().text_range().start(), 0.into());
817     node
818 }
819
820 pub fn token(kind: SyntaxKind) -> SyntaxToken {
821     tokens::SOURCE_FILE
822         .tree()
823         .syntax()
824         .clone_for_update()
825         .descendants_with_tokens()
826         .filter_map(|it| it.into_token())
827         .find(|it| it.kind() == kind)
828         .unwrap_or_else(|| panic!("unhandled token: {kind:?}"))
829 }
830
831 pub mod tokens {
832     use once_cell::sync::Lazy;
833
834     use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
835
836     pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
837         SourceFile::parse(
838             "const C: <()>::Item = (1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p)\n;\n\n",
839         )
840     });
841
842     pub fn single_space() -> SyntaxToken {
843         SOURCE_FILE
844             .tree()
845             .syntax()
846             .clone_for_update()
847             .descendants_with_tokens()
848             .filter_map(|it| it.into_token())
849             .find(|it| it.kind() == WHITESPACE && it.text() == " ")
850             .unwrap()
851     }
852
853     pub fn whitespace(text: &str) -> SyntaxToken {
854         assert!(text.trim().is_empty());
855         let sf = SourceFile::parse(text).ok().unwrap();
856         sf.syntax().clone_for_update().first_child_or_token().unwrap().into_token().unwrap()
857     }
858
859     pub fn doc_comment(text: &str) -> SyntaxToken {
860         assert!(!text.trim().is_empty());
861         let sf = SourceFile::parse(text).ok().unwrap();
862         sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
863     }
864
865     pub fn literal(text: &str) -> SyntaxToken {
866         assert_eq!(text.trim(), text);
867         let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {text}; }}"));
868         lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
869     }
870
871     pub fn single_newline() -> SyntaxToken {
872         let res = SOURCE_FILE
873             .tree()
874             .syntax()
875             .clone_for_update()
876             .descendants_with_tokens()
877             .filter_map(|it| it.into_token())
878             .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
879             .unwrap();
880         res.detach();
881         res
882     }
883
884     pub fn blank_line() -> SyntaxToken {
885         SOURCE_FILE
886             .tree()
887             .syntax()
888             .clone_for_update()
889             .descendants_with_tokens()
890             .filter_map(|it| it.into_token())
891             .find(|it| it.kind() == WHITESPACE && it.text() == "\n\n")
892             .unwrap()
893     }
894
895     pub struct WsBuilder(SourceFile);
896
897     impl WsBuilder {
898         pub fn new(text: &str) -> WsBuilder {
899             WsBuilder(SourceFile::parse(text).ok().unwrap())
900         }
901         pub fn ws(&self) -> SyntaxToken {
902             self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()
903         }
904     }
905 }