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