1mod quote;
15
16use either::Either;
17use itertools::Itertools;
18use parser::{Edition, T};
19use rowan::NodeOrToken;
20use stdx::{format_to, format_to_acc, never};
21
22use crate::{
23 AstNode, SourceFile, SyntaxKind, SyntaxToken,
24 ast::{self, Param, make::quote::quote},
25 utils::is_raw_identifier,
26};
27
28pub mod ext {
33 use super::*;
34
35 pub fn simple_ident_pat(name: ast::Name) -> ast::IdentPat {
36 ast_from_text(&format!("fn f({}: ())", name.text()))
37 }
38
39 pub fn ident_path(ident: &str) -> ast::Path {
40 path_unqualified(path_segment(name_ref(ident)))
41 }
42
43 pub fn path_from_idents<'a>(
44 parts: impl std::iter::IntoIterator<Item = &'a str>,
45 ) -> Option<ast::Path> {
46 let mut iter = parts.into_iter();
47 let base = ext::ident_path(iter.next()?);
48 let path = iter.fold(base, |base, s| {
49 let path = ext::ident_path(s);
50 path_concat(base, path)
51 });
52 Some(path)
53 }
54
55 pub fn field_from_idents<'a>(
56 parts: impl std::iter::IntoIterator<Item = &'a str>,
57 ) -> Option<ast::Expr> {
58 let mut iter = parts.into_iter();
59 let base = expr_path(ext::ident_path(iter.next()?));
60 let expr = iter.fold(base, expr_field);
61 Some(expr)
62 }
63
64 pub fn expr_unit() -> ast::Expr {
65 expr_tuple([]).into()
66 }
67 pub fn expr_unreachable() -> ast::Expr {
68 expr_from_text("unreachable!()")
69 }
70 pub fn expr_todo() -> ast::Expr {
71 expr_from_text("todo!()")
72 }
73 pub fn expr_underscore() -> ast::Expr {
74 expr_from_text("_")
75 }
76 pub fn expr_ty_default(ty: &ast::Type) -> ast::Expr {
77 if !ty.needs_angles_in_path() {
78 expr_from_text(&format!("{ty}::default()"))
79 } else {
80 expr_from_text(&format!("<{ty}>::default()"))
81 }
82 }
83 pub fn expr_ty_new(ty: &ast::Type) -> ast::Expr {
84 if !ty.needs_angles_in_path() {
85 expr_from_text(&format!("{ty}::new()"))
86 } else {
87 expr_from_text(&format!("<{ty}>::new()"))
88 }
89 }
90 pub fn expr_self() -> ast::Expr {
91 expr_from_text("self")
92 }
93 pub fn zero_number() -> ast::Expr {
94 expr_from_text("0")
95 }
96 pub fn zero_float() -> ast::Expr {
97 expr_from_text("0.0")
98 }
99 pub fn empty_str() -> ast::Expr {
100 expr_from_text(r#""""#)
101 }
102 pub fn empty_char() -> ast::Expr {
103 expr_from_text("'\x00'")
104 }
105 pub fn default_bool() -> ast::Expr {
106 expr_from_text("false")
107 }
108 pub fn option_none() -> ast::Expr {
109 expr_from_text("None")
110 }
111 pub fn empty_block_expr() -> ast::BlockExpr {
112 block_expr(None, None)
113 }
114
115 pub fn ty_name(name: ast::Name) -> ast::Type {
116 ty_path(ident_path(&name.to_string()))
117 }
118 pub fn ty_bool() -> ast::Type {
119 ty_path(ident_path("bool"))
120 }
121 pub fn ty_option(t: ast::Type) -> ast::Type {
122 ty_from_text(&format!("Option<{t}>"))
123 }
124 pub fn ty_result(t: ast::Type, e: ast::Type) -> ast::Type {
125 ty_from_text(&format!("Result<{t}, {e}>"))
126 }
127
128 pub fn token_tree_from_node(node: &ast::SyntaxNode) -> ast::TokenTree {
129 ast_from_text(&format!("todo!{node}"))
130 }
131}
132
133pub fn name(name: &str) -> ast::Name {
134 let raw_escape = raw_ident_esc(name);
135 ast_from_text(&format!("mod {raw_escape}{name};"))
136}
137pub fn name_ref(name_ref: &str) -> ast::NameRef {
138 let raw_escape = raw_ident_esc(name_ref);
139 quote! {
140 NameRef {
141 [IDENT format!("{raw_escape}{name_ref}")]
142 }
143 }
144}
145pub fn name_ref_self_ty() -> ast::NameRef {
146 quote! {
147 NameRef {
148 [Self]
149 }
150 }
151}
152fn raw_ident_esc(ident: &str) -> &'static str {
153 if is_raw_identifier(ident, Edition::CURRENT) { "r#" } else { "" }
154}
155
156pub fn lifetime(text: &str) -> ast::Lifetime {
157 let mut text = text;
158 let tmp;
159 if never!(!text.starts_with('\'')) {
160 tmp = format!("'{text}");
161 text = &tmp;
162 }
163 quote! {
164 Lifetime {
165 [LIFETIME_IDENT text]
166 }
167 }
168}
169
170pub fn ty(text: &str) -> ast::Type {
173 ty_from_text(text)
174}
175pub fn ty_placeholder() -> ast::Type {
176 ty_from_text("_")
177}
178pub fn ty_unit() -> ast::Type {
179 ty_from_text("()")
180}
181pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
182 let mut count: usize = 0;
183 let mut contents = types.into_iter().inspect(|_| count += 1).join(", ");
184 if count == 1 {
185 contents.push(',');
186 }
187
188 ty_from_text(&format!("({contents})"))
189}
190pub fn ty_paren(ty: ast::Type) -> ast::Type {
191 ty_from_text(&format!("({ty})"))
192}
193pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
194 ty_from_text(&if exclusive { format!("&mut {target}") } else { format!("&{target}") })
195}
196pub fn ty_path(path: ast::Path) -> ast::Type {
197 ty_from_text(&path.to_string())
198}
199fn ty_from_text(text: &str) -> ast::Type {
200 ast_from_text(&format!("type _T = {text};"))
201}
202
203pub fn ty_alias(
204 attrs: impl IntoIterator<Item = ast::Attr>,
205 ident: &str,
206 generic_param_list: Option<ast::GenericParamList>,
207 type_param_bounds: Option<ast::TypeParam>,
208 where_clause: Option<ast::WhereClause>,
209 assignment: Option<(ast::Type, Option<ast::WhereClause>)>,
210) -> ast::TypeAlias {
211 let (assignment_ty, assignment_where) = assignment.unzip();
212 let assignment_where = assignment_where.flatten();
213 quote! {
214 TypeAlias {
215 #(#attrs "\n")*
216 [type] " "
217 Name { [IDENT ident] }
218 #generic_param_list
219 #(" " [:] " " #type_param_bounds)*
220 #(" " #where_clause)*
221 #(" " [=] " " #assignment_ty)*
222 #(" " #assignment_where)*
223 [;]
224 }
225 }
226}
227
228pub fn ty_fn_ptr<I: Iterator<Item = Param>>(
229 is_unsafe: bool,
230 abi: Option<ast::Abi>,
231 mut params: I,
232 ret_type: Option<ast::RetType>,
233) -> ast::FnPtrType {
234 let is_unsafe = is_unsafe.then_some(());
235 let first_param = params.next();
236 quote! {
237 FnPtrType {
238 #(#is_unsafe [unsafe] " ")* #(#abi " ")* [fn]
239 ['('] #first_param #([,] " " #params)* [')']
240 #(" " #ret_type)*
241 }
242 }
243}
244
245pub fn item_list(body: Option<Vec<ast::Item>>) -> ast::ItemList {
246 let is_break_braces = body.is_some();
247 let body_newline = if is_break_braces { "\n" } else { "" };
248 let body_indent = if is_break_braces { " " } else { "" };
249
250 let body = match body {
251 Some(bd) => bd.iter().map(|elem| elem.to_string()).join("\n\n "),
252 None => String::new(),
253 };
254 ast_from_text(&format!("mod C {{{body_newline}{body_indent}{body}{body_newline}}}"))
255}
256
257pub fn mod_(name: ast::Name, body: Option<ast::ItemList>) -> ast::Module {
258 let body = body.map_or(";".to_owned(), |body| format!(" {body}"));
259 ast_from_text(&format!("mod {name}{body}"))
260}
261
262pub fn assoc_item_list(body: Option<Vec<ast::AssocItem>>) -> ast::AssocItemList {
263 let is_break_braces = body.is_some();
264 let body_newline = if is_break_braces { "\n".to_owned() } else { String::new() };
265 let body_indent = if is_break_braces { " ".to_owned() } else { String::new() };
266
267 let body = match body {
268 Some(bd) => bd.iter().map(|elem| elem.to_string()).join("\n\n "),
269 None => String::new(),
270 };
271 ast_from_text(&format!("impl C for D {{{body_newline}{body_indent}{body}{body_newline}}}"))
272}
273
274fn merge_gen_params(
275 ps: Option<ast::GenericParamList>,
276 bs: Option<ast::GenericParamList>,
277) -> Option<ast::GenericParamList> {
278 match (ps, bs) {
279 (None, None) => None,
280 (None, Some(bs)) => Some(bs),
281 (Some(ps), None) => Some(ps),
282 (Some(ps), Some(bs)) => {
283 let generic_params = ps.generic_params().merge_by(bs.generic_params(), |_, b| {
285 !matches!(b, ast::GenericParam::LifetimeParam(_))
286 });
287 Some(generic_param_list(generic_params))
288 }
289 }
290}
291
292fn merge_where_clause(
293 ps: Option<ast::WhereClause>,
294 bs: Option<ast::WhereClause>,
295) -> Option<ast::WhereClause> {
296 match (ps, bs) {
297 (None, None) => None,
298 (None, Some(bs)) => Some(bs),
299 (Some(ps), None) => Some(ps),
300 (Some(ps), Some(bs)) => Some(where_clause(ps.predicates().chain(bs.predicates()))),
301 }
302}
303
304pub fn impl_(
305 attrs: impl IntoIterator<Item = ast::Attr>,
306 generic_params: Option<ast::GenericParamList>,
307 generic_args: Option<ast::GenericArgList>,
308 path_type: ast::Type,
309 where_clause: Option<ast::WhereClause>,
310 body: Option<ast::AssocItemList>,
311) -> ast::Impl {
312 let attrs =
313 attrs.into_iter().fold(String::new(), |mut acc, attr| format_to_acc!(acc, "{}\n", attr));
314
315 let gen_args = generic_args.map_or_else(String::new, |it| it.to_string());
316
317 let gen_params = generic_params.map_or_else(String::new, |it| it.to_string());
318
319 let body_newline =
320 if where_clause.is_some() && body.is_none() { "\n".to_owned() } else { String::new() };
321 let where_clause = match where_clause {
322 Some(pr) => format!("\n{pr}\n"),
323 None => " ".to_owned(),
324 };
325
326 let body = body.map_or_else(|| format!("{{{body_newline}}}"), |it| it.to_string());
327 ast_from_text(&format!("{attrs}impl{gen_params} {path_type}{gen_args}{where_clause}{body}"))
328}
329
330pub fn impl_trait(
331 attrs: impl IntoIterator<Item = ast::Attr>,
332 is_unsafe: bool,
333 trait_gen_params: Option<ast::GenericParamList>,
334 trait_gen_args: Option<ast::GenericArgList>,
335 type_gen_params: Option<ast::GenericParamList>,
336 type_gen_args: Option<ast::GenericArgList>,
337 is_negative: bool,
338 path_type: ast::Type,
339 ty: ast::Type,
340 trait_where_clause: Option<ast::WhereClause>,
341 ty_where_clause: Option<ast::WhereClause>,
342 body: Option<ast::AssocItemList>,
343) -> ast::Impl {
344 let attrs =
345 attrs.into_iter().fold(String::new(), |mut acc, attr| format_to_acc!(acc, "{}\n", attr));
346 let is_unsafe = if is_unsafe { "unsafe " } else { "" };
347
348 let trait_gen_args = trait_gen_args.map(|args| args.to_string()).unwrap_or_default();
349 let type_gen_args = type_gen_args.map(|args| args.to_string()).unwrap_or_default();
350
351 let gen_params = merge_gen_params(trait_gen_params, type_gen_params)
352 .map_or_else(String::new, |it| it.to_string());
353
354 let is_negative = if is_negative { "! " } else { "" };
355
356 let body_newline =
357 if (ty_where_clause.is_some() || trait_where_clause.is_some()) && body.is_none() {
358 "\n".to_owned()
359 } else {
360 String::new()
361 };
362
363 let where_clause = merge_where_clause(ty_where_clause, trait_where_clause)
364 .map_or_else(|| " ".to_owned(), |wc| format!("\n{wc}\n"));
365
366 let body = body.map_or_else(|| format!("{{{body_newline}}}"), |it| it.to_string());
367
368 ast_from_text(&format!(
369 "{attrs}{is_unsafe}impl{gen_params} {is_negative}{path_type}{trait_gen_args} for {ty}{type_gen_args}{where_clause}{body}"
370 ))
371}
372
373pub fn impl_trait_type(bounds: ast::TypeBoundList) -> ast::ImplTraitType {
374 ast_from_text(&format!("fn f(x: impl {bounds}) {{}}"))
375}
376
377pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
378 ast_from_text(&format!("type __ = {name_ref};"))
379}
380
381pub fn generic_ty_path_segment(
384 name_ref: ast::NameRef,
385 generic_args: impl IntoIterator<Item = ast::GenericArg>,
386) -> ast::PathSegment {
387 let mut generic_args = generic_args.into_iter();
388 let first_generic_arg = generic_args.next();
389 quote! {
390 PathSegment {
391 #name_ref
392 GenericArgList {
393 [<] #first_generic_arg #([,] " " #generic_args)* [>]
394 }
395 }
396 }
397}
398
399pub fn path_segment_ty(type_ref: ast::Type, trait_ref: Option<ast::PathType>) -> ast::PathSegment {
400 let text = match trait_ref {
401 Some(trait_ref) => format!("fn f(x: <{type_ref} as {trait_ref}>) {{}}"),
402 None => format!("fn f(x: <{type_ref}>) {{}}"),
403 };
404 ast_from_text(&text)
405}
406
407pub fn path_segment_self() -> ast::PathSegment {
408 ast_from_text("use self;")
409}
410
411pub fn path_segment_super() -> ast::PathSegment {
412 ast_from_text("use super;")
413}
414
415pub fn path_segment_crate() -> ast::PathSegment {
416 ast_from_text("use crate;")
417}
418
419pub fn path_unqualified(segment: ast::PathSegment) -> ast::Path {
420 ast_from_text(&format!("type __ = {segment};"))
421}
422
423pub fn path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path {
424 ast_from_text(&format!("{qual}::{segment}"))
425}
426pub fn path_concat(first: ast::Path, second: ast::Path) -> ast::Path {
428 ast_from_text(&format!("type __ = {first}::{second};"))
429}
430
431pub fn path_from_segments(
432 segments: impl IntoIterator<Item = ast::PathSegment>,
433 is_abs: bool,
434) -> ast::Path {
435 let segments = segments.into_iter().map(|it| it.syntax().clone()).join("::");
436 ast_from_text(&if is_abs {
437 format!("fn f(x: ::{segments}) {{}}")
438 } else {
439 format!("fn f(x: {segments}) {{}}")
440 })
441}
442
443pub fn join_paths(paths: impl IntoIterator<Item = ast::Path>) -> ast::Path {
444 let paths = paths.into_iter().map(|it| it.syntax().clone()).join("::");
445 ast_from_text(&format!("type __ = {paths};"))
446}
447
448pub fn path_from_text(text: &str) -> ast::Path {
450 ast_from_text(&format!("fn main() {{ let test: {text}; }}"))
451}
452
453pub fn path_from_text_with_edition(text: &str, edition: Edition) -> ast::Path {
455 ast_from_text_with_edition(&format!("fn main() {{ let test: {text}; }}"), edition)
456}
457
458pub fn use_tree_glob() -> ast::UseTree {
459 ast_from_text("use *;")
460}
461pub fn use_tree(
462 path: ast::Path,
463 use_tree_list: Option<ast::UseTreeList>,
464 alias: Option<ast::Rename>,
465 add_star: bool,
466) -> ast::UseTree {
467 let mut buf = "use ".to_owned();
468 buf += &path.syntax().to_string();
469 if let Some(use_tree_list) = use_tree_list {
470 format_to!(buf, "::{use_tree_list}");
471 }
472 if add_star {
473 buf += "::*";
474 }
475
476 if let Some(alias) = alias {
477 format_to!(buf, " {alias}");
478 }
479 ast_from_text(&buf)
480}
481
482pub fn use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList {
483 let use_trees = use_trees.into_iter().map(|it| it.syntax().clone()).join(", ");
484 ast_from_text(&format!("use {{{use_trees}}};"))
485}
486
487pub fn use_(
488 attrs: impl IntoIterator<Item = ast::Attr>,
489 visibility: Option<ast::Visibility>,
490 use_tree: ast::UseTree,
491) -> ast::Use {
492 let attrs =
493 attrs.into_iter().fold(String::new(), |mut acc, attr| format_to_acc!(acc, "{}\n", attr));
494 let visibility = match visibility {
495 None => String::new(),
496 Some(it) => format!("{it} "),
497 };
498 ast_from_text(&format!("{attrs}{visibility}use {use_tree};"))
499}
500
501pub fn record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr {
502 ast_from_text(&format!("fn f() {{ {path} {fields} }}"))
503}
504
505pub fn record_expr_field_list(
506 fields: impl IntoIterator<Item = ast::RecordExprField>,
507) -> ast::RecordExprFieldList {
508 let fields = fields.into_iter().join(", ");
509 ast_from_text(&format!("fn f() {{ S {{ {fields} }} }}"))
510}
511
512pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField {
513 return match expr {
514 Some(expr) => from_text(&format!("{name}: {expr}")),
515 None => from_text(&name.to_string()),
516 };
517
518 fn from_text(text: &str) -> ast::RecordExprField {
519 ast_from_text(&format!("fn f() {{ S {{ {text}, }} }}"))
520 }
521}
522
523pub fn record_field(
524 visibility: Option<ast::Visibility>,
525 name: ast::Name,
526 ty: ast::Type,
527) -> ast::RecordField {
528 let visibility = match visibility {
529 None => String::new(),
530 Some(it) => format!("{it} "),
531 };
532 ast_from_text(&format!("struct S {{ {visibility}{name}: {ty}, }}"))
533}
534
535pub fn block_expr(
536 stmts: impl IntoIterator<Item = ast::Stmt>,
537 tail_expr: Option<ast::Expr>,
538) -> ast::BlockExpr {
539 quote! {
540 BlockExpr {
541 StmtList {
542 ['{']
543 #("\n " #stmts)*
544 #("\n " #tail_expr)*
545 "\n"
546 ['}']
547 }
548 }
549 }
550}
551
552pub fn async_move_block_expr(
553 stmts: impl IntoIterator<Item = ast::Stmt>,
554 tail_expr: Option<ast::Expr>,
555) -> ast::BlockExpr {
556 let mut buf = "async move {\n".to_owned();
557 for stmt in stmts.into_iter() {
558 format_to!(buf, " {stmt}\n");
559 }
560 if let Some(tail_expr) = tail_expr {
561 format_to!(buf, " {tail_expr}\n");
562 }
563 buf += "}";
564 ast_from_text(&format!("const _: () = {buf};"))
565}
566
567pub fn tail_only_block_expr(tail_expr: ast::Expr) -> ast::BlockExpr {
568 quote! {
569 BlockExpr {
570 StmtList {
571 ['{']
572 " "
573 #tail_expr
574 " "
575 ['}']
576 }
577 }
578 }
579}
580
581pub fn hacky_block_expr(
586 elements: impl IntoIterator<Item = crate::SyntaxElement>,
587 tail_expr: Option<ast::Expr>,
588) -> ast::BlockExpr {
589 let mut buf = "{\n".to_owned();
590 for node_or_token in elements.into_iter() {
591 match node_or_token {
592 rowan::NodeOrToken::Node(n) => format_to!(buf, " {n}\n"),
593 rowan::NodeOrToken::Token(t) => {
594 let kind = t.kind();
595 if kind == SyntaxKind::COMMENT {
596 format_to!(buf, " {t}\n")
597 } else if kind == SyntaxKind::WHITESPACE {
598 let content = t.text().trim_matches(|c| c != '\n');
599 if !content.is_empty() {
600 format_to!(buf, "{}", &content[1..])
601 }
602 }
603 }
604 }
605 }
606 if let Some(tail_expr) = tail_expr {
607 format_to!(buf, " {tail_expr}\n");
608 }
609 buf += "}";
610 ast_from_text(&format!("fn f() {buf}"))
611}
612
613pub fn expr_literal(text: &str) -> ast::Literal {
614 assert_eq!(text.trim(), text);
615 ast_from_text(&format!("fn f() {{ let _ = {text}; }}"))
616}
617
618pub fn expr_const_value(text: &str) -> ast::ConstArg {
619 ast_from_text(&format!("trait Foo<const N: usize = {text}> {{}}"))
620}
621
622pub fn expr_empty_block() -> ast::BlockExpr {
623 ast_from_text("const C: () = {};")
624}
625pub fn expr_path(path: ast::Path) -> ast::Expr {
626 expr_from_text(&path.to_string())
627}
628pub fn expr_continue(label: Option<ast::Lifetime>) -> ast::Expr {
629 match label {
630 Some(label) => expr_from_text(&format!("continue {label}")),
631 None => expr_from_text("continue"),
632 }
633}
634pub fn expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr {
636 expr_from_text(&format!("{lhs} {op} {rhs}"))
637}
638pub fn expr_break(label: Option<ast::Lifetime>, expr: Option<ast::Expr>) -> ast::Expr {
639 let mut s = String::from("break");
640
641 if let Some(label) = label {
642 format_to!(s, " {label}");
643 }
644
645 if let Some(expr) = expr {
646 format_to!(s, " {expr}");
647 }
648
649 expr_from_text(&s)
650}
651pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
652 match expr {
653 Some(expr) => expr_from_text(&format!("return {expr}")),
654 None => expr_from_text("return"),
655 }
656}
657pub fn expr_try(expr: ast::Expr) -> ast::Expr {
658 expr_from_text(&format!("{expr}?"))
659}
660pub fn expr_await(expr: ast::Expr) -> ast::Expr {
661 expr_from_text(&format!("{expr}.await"))
662}
663pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::MatchExpr {
664 let ws = block_whitespace(&expr);
665 expr_from_text(&format!("match {expr}{ws}{match_arm_list}"))
666}
667pub fn expr_if(
668 condition: ast::Expr,
669 then_branch: ast::BlockExpr,
670 else_branch: Option<ast::ElseBranch>,
671) -> ast::IfExpr {
672 let else_branch = match else_branch {
673 Some(ast::ElseBranch::Block(block)) => format!(" else {block}"),
674 Some(ast::ElseBranch::IfExpr(if_expr)) => format!(" else {if_expr}"),
675 None => String::new(),
676 };
677 let ws = block_whitespace(&condition);
678 expr_from_text(&format!("if {condition}{ws}{then_branch}{else_branch}"))
679}
680pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::ForExpr {
681 let ws = block_whitespace(&expr);
682 expr_from_text(&format!("for {pat} in {expr}{ws}{block}"))
683}
684
685pub fn expr_while_loop(condition: ast::Expr, block: ast::BlockExpr) -> ast::WhileExpr {
686 let ws = block_whitespace(&condition);
687 expr_from_text(&format!("while {condition}{ws}{block}"))
688}
689
690pub fn expr_loop(block: ast::BlockExpr) -> ast::Expr {
691 expr_from_text(&format!("loop {block}"))
692}
693
694pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::PrefixExpr {
695 let token = token(op);
696 expr_from_text(&format!("{token}{expr}"))
697}
698pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::CallExpr {
699 quote! {
700 CallExpr {
701 #f
702 #arg_list
703 }
704 }
705}
706pub fn expr_method_call(
707 receiver: ast::Expr,
708 method: ast::NameRef,
709 arg_list: ast::ArgList,
710) -> ast::MethodCallExpr {
711 expr_from_text(&format!("{receiver}.{method}{arg_list}"))
712}
713pub fn expr_macro(path: ast::Path, tt: ast::TokenTree) -> ast::MacroExpr {
714 expr_from_text(&format!("{path}!{tt}"))
715}
716pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
717 expr_from_text(&if exclusive { format!("&mut {expr}") } else { format!("&{expr}") })
718}
719pub fn expr_raw_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
720 expr_from_text(&if exclusive {
721 format!("&raw mut {expr}")
722 } else {
723 format!("&raw const {expr}")
724 })
725}
726pub fn expr_reborrow(expr: ast::Expr) -> ast::Expr {
727 expr_from_text(&format!("&mut *{expr}"))
728}
729pub fn expr_closure(
730 pats: impl IntoIterator<Item = ast::Param>,
731 expr: ast::Expr,
732) -> ast::ClosureExpr {
733 let params = pats.into_iter().join(", ");
734 expr_from_text(&format!("|{params}| {expr}"))
735}
736pub fn expr_field(receiver: ast::Expr, field: &str) -> ast::Expr {
737 expr_from_text(&format!("{receiver}.{field}"))
738}
739pub fn expr_paren(expr: ast::Expr) -> ast::ParenExpr {
740 expr_from_text(&format!("({expr})"))
741}
742pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::TupleExpr {
743 let expr = elements.into_iter().format(", ");
744 expr_from_text(&format!("({expr})"))
745}
746pub fn expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::BinExpr {
747 expr_from_text(&format!("{lhs} = {rhs}"))
748}
749fn block_whitespace(after: &impl AstNode) -> &'static str {
750 if after.syntax().text().contains_char('\n') { "\n" } else { " " }
751}
752pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
753 let args = args.into_iter().format(", ");
754 ast_from_text(&format!("fn main() {{ ()({args}) }}"))
755}
756
757pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
758 let mut s = String::from("fn f(");
759 if ref_ {
760 s.push_str("ref ");
761 }
762 if mut_ {
763 s.push_str("mut ");
764 }
765 format_to!(s, "{name}");
766 s.push_str(": ())");
767 ast_from_text(&s)
768}
769
770pub fn wildcard_pat() -> ast::WildcardPat {
771 return from_text("_");
772
773 fn from_text(text: &str) -> ast::WildcardPat {
774 ast_from_text(&format!("fn f({text}: ())"))
775 }
776}
777
778pub fn rest_pat() -> ast::RestPat {
779 ast_from_text("fn f() { let ..; }")
780}
781
782pub fn literal_pat(lit: &str) -> ast::LiteralPat {
783 return from_text(lit);
784
785 fn from_text(text: &str) -> ast::LiteralPat {
786 ast_from_text(&format!("fn f() {{ match x {{ {text} => {{}} }} }}"))
787 }
788}
789
790pub fn slice_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::SlicePat {
791 let pats_str = pats.into_iter().join(", ");
792 return from_text(&format!("[{pats_str}]"));
793
794 fn from_text(text: &str) -> ast::SlicePat {
795 ast_from_text(&format!("fn f() {{ match () {{{text} => ()}} }}"))
796 }
797}
798
799pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
803 let mut count: usize = 0;
804 let mut pats_str = pats.into_iter().inspect(|_| count += 1).join(", ");
805 if count == 1 {
806 pats_str.push(',');
807 }
808 return from_text(&format!("({pats_str})"));
809
810 fn from_text(text: &str) -> ast::TuplePat {
811 ast_from_text(&format!("fn f({text}: ())"))
812 }
813}
814
815pub fn tuple_struct_pat(
816 path: ast::Path,
817 pats: impl IntoIterator<Item = ast::Pat>,
818) -> ast::TupleStructPat {
819 let pats_str = pats.into_iter().join(", ");
820 return from_text(&format!("{path}({pats_str})"));
821
822 fn from_text(text: &str) -> ast::TupleStructPat {
823 ast_from_text(&format!("fn f({text}: ())"))
824 }
825}
826
827pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
828 let pats_str = pats.into_iter().join(", ");
829 return from_text(&format!("{path} {{ {pats_str} }}"));
830
831 fn from_text(text: &str) -> ast::RecordPat {
832 ast_from_text(&format!("fn f({text}: ())"))
833 }
834}
835
836pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
837 ast_from_text(&format!("fn f({path} {fields}: ()))"))
838}
839
840pub fn record_pat_field_list(
841 fields: impl IntoIterator<Item = ast::RecordPatField>,
842 rest_pat: Option<ast::RestPat>,
843) -> ast::RecordPatFieldList {
844 let mut fields = fields.into_iter().join(", ");
845 if let Some(rest_pat) = rest_pat {
846 if !fields.is_empty() {
847 fields.push_str(", ");
848 }
849 format_to!(fields, "{rest_pat}");
850 }
851 ast_from_text(&format!("fn f(S {{ {fields} }}: ()))"))
852}
853
854pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
855 ast_from_text(&format!("fn f(S {{ {name_ref}: {pat} }}: ()))"))
856}
857
858pub fn record_pat_field_shorthand(pat: ast::Pat) -> ast::RecordPatField {
859 ast_from_text(&format!("fn f(S {{ {pat} }}: ()))"))
860}
861
862pub fn path_pat(path: ast::Path) -> ast::Pat {
864 return from_text(&path.to_string());
865 fn from_text(text: &str) -> ast::Pat {
866 ast_from_text(&format!("fn f({text}: ())"))
867 }
868}
869
870pub fn or_pat(pats: impl IntoIterator<Item = ast::Pat>, leading_pipe: bool) -> ast::OrPat {
874 let leading_pipe = if leading_pipe { "| " } else { "" };
875 let pats = pats.into_iter().join(" | ");
876
877 return from_text(&format!("{leading_pipe}{pats}"));
878 fn from_text(text: &str) -> ast::OrPat {
879 ast_from_text(&format!("fn f({text}: ())"))
880 }
881}
882
883pub fn box_pat(pat: ast::Pat) -> ast::BoxPat {
884 ast_from_text(&format!("fn f(box {pat}: ())"))
885}
886
887pub fn deref_pat(pat: ast::Pat) -> ast::Pat {
888 ast_from_text(&format!("fn f(deref!({pat}): ())"))
889}
890
891pub fn paren_pat(pat: ast::Pat) -> ast::ParenPat {
892 ast_from_text(&format!("fn f(({pat}): ())"))
893}
894
895pub fn range_pat(start: Option<ast::Pat>, end: Option<ast::Pat>) -> ast::RangePat {
896 ast_from_text(&format!(
897 "fn f({}..{}: ())",
898 start.map(|e| e.to_string()).unwrap_or_default(),
899 end.map(|e| e.to_string()).unwrap_or_default()
900 ))
901}
902
903pub fn ref_pat(pat: ast::Pat) -> ast::RefPat {
904 ast_from_text(&format!("fn f(&{pat}: ())"))
905}
906
907pub fn match_arm(pat: ast::Pat, guard: Option<ast::MatchGuard>, expr: ast::Expr) -> ast::MatchArm {
908 let comma_str = if expr.is_block_like() { "" } else { "," };
909 let ws = guard.as_ref().filter(|_| expr.is_block_like()).map_or(" ", block_whitespace);
910 return match guard {
911 Some(guard) => from_text(&format!("{pat} {guard} =>{ws}{expr}{comma_str}")),
912 None => from_text(&format!("{pat} => {expr}{comma_str}")),
913 };
914
915 fn from_text(text: &str) -> ast::MatchArm {
916 ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
917 }
918}
919
920pub fn match_guard(condition: ast::Expr) -> ast::MatchGuard {
921 return from_text(&format!("if {condition}"));
922
923 fn from_text(text: &str) -> ast::MatchGuard {
924 ast_from_text(&format!("fn f() {{ match () {{() {text} => () }}"))
925 }
926}
927
928pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
929 let arms_str = arms.into_iter().fold(String::new(), |mut acc, arm| {
930 let needs_comma =
931 arm.comma_token().is_none() && arm.expr().is_none_or(|it| !it.is_block_like());
932 let comma = if needs_comma && arm.comma_token().is_none() { "," } else { "" };
933 let arm = arm.syntax();
934 format_to_acc!(acc, " {arm}{comma}\n")
935 });
936 return from_text(&arms_str);
937
938 fn from_text(text: &str) -> ast::MatchArmList {
939 ast_from_text(&format!("fn f() {{ match () {{\n{text}}} }}"))
940 }
941}
942
943pub fn where_pred(
944 path: Either<ast::Lifetime, ast::Type>,
945 bounds: impl IntoIterator<Item = ast::TypeBound>,
946) -> ast::WherePred {
947 let bounds = bounds.into_iter().join(" + ");
948 return from_text(&format!("{path}: {bounds}"));
949
950 fn from_text(text: &str) -> ast::WherePred {
951 ast_from_text(&format!("fn f() where {text} {{ }}"))
952 }
953}
954
955pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause {
956 let preds = preds.into_iter().join(", ");
957 return from_text(preds.as_str());
958
959 fn from_text(text: &str) -> ast::WhereClause {
960 ast_from_text(&format!("fn f() where {text} {{ }}"))
961 }
962}
963
964pub fn let_stmt(
965 pattern: ast::Pat,
966 ty: Option<ast::Type>,
967 initializer: Option<ast::Expr>,
968) -> ast::LetStmt {
969 let mut text = String::new();
970 format_to!(text, "let {pattern}");
971 if let Some(ty) = ty {
972 format_to!(text, ": {ty}");
973 }
974 match initializer {
975 Some(it) => format_to!(text, " = {it};"),
976 None => format_to!(text, ";"),
977 };
978 ast_from_text(&format!("fn f() {{ {text} }}"))
979}
980
981pub fn let_else_stmt(
982 pattern: ast::Pat,
983 ty: Option<ast::Type>,
984 expr: ast::Expr,
985 diverging: ast::BlockExpr,
986) -> ast::LetStmt {
987 let mut text = String::new();
988 format_to!(text, "let {pattern}");
989 if let Some(ty) = ty {
990 format_to!(text, ": {ty}");
991 }
992 format_to!(text, " = {expr} else {diverging};");
993 ast_from_text(&format!("fn f() {{ {text} }}"))
994}
995
996pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
997 let semi = if expr.is_block_like() { "" } else { ";" };
998 ast_from_text(&format!("fn f() {{ {expr}{semi} (); }}"))
999}
1000
1001pub fn item_const(
1002 attrs: impl IntoIterator<Item = ast::Attr>,
1003 visibility: Option<ast::Visibility>,
1004 name: ast::Name,
1005 ty: ast::Type,
1006 expr: ast::Expr,
1007) -> ast::Const {
1008 let attrs =
1009 attrs.into_iter().fold(String::new(), |mut acc, attr| format_to_acc!(acc, "{}\n", attr));
1010 let visibility = match visibility {
1011 None => String::new(),
1012 Some(it) => format!("{it} "),
1013 };
1014 ast_from_text(&format!("{attrs}{visibility}const {name}: {ty} = {expr};"))
1015}
1016
1017pub fn item_static(
1018 visibility: Option<ast::Visibility>,
1019 is_unsafe: bool,
1020 is_mut: bool,
1021 name: ast::Name,
1022 ty: ast::Type,
1023 expr: Option<ast::Expr>,
1024) -> ast::Static {
1025 let visibility = match visibility {
1026 None => String::new(),
1027 Some(it) => format!("{it} "),
1028 };
1029 let is_unsafe = if is_unsafe { "unsafe " } else { "" };
1030 let is_mut = if is_mut { "mut " } else { "" };
1031 let expr = match expr {
1032 Some(it) => &format!(" = {it}"),
1033 None => "",
1034 };
1035
1036 ast_from_text(&format!("{visibility}{is_unsafe}static {is_mut}{name}: {ty}{expr};"))
1037}
1038
1039pub fn unnamed_param(ty: ast::Type) -> ast::Param {
1040 quote! {
1041 Param {
1042 #ty
1043 }
1044 }
1045}
1046
1047pub fn untyped_param(pat: ast::Pat) -> ast::Param {
1048 quote! {
1049 Param {
1050 #pat
1051 }
1052 }
1053}
1054
1055pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
1056 quote! {
1057 Param {
1058 #pat
1059 [:]
1060 " "
1061 #ty
1062 }
1063 }
1064}
1065
1066pub fn self_param() -> ast::SelfParam {
1067 ast_from_text("fn f(&self) { }")
1068}
1069
1070pub fn mut_self_param() -> ast::SelfParam {
1071 ast_from_text("fn f(&mut self) { }")
1072}
1073
1074pub fn ret_type(ty: ast::Type) -> ast::RetType {
1075 ast_from_text(&format!("fn f() -> {ty} {{ }}"))
1076}
1077
1078pub fn param_list(
1079 self_param: Option<ast::SelfParam>,
1080 pats: impl IntoIterator<Item = ast::Param>,
1081) -> ast::ParamList {
1082 let args = pats.into_iter().join(", ");
1083 let list = match self_param {
1084 Some(self_param) if args.is_empty() => format!("fn f({self_param}) {{ }}"),
1085 Some(self_param) => format!("fn f({self_param}, {args}) {{ }}"),
1086 None => format!("fn f({args}) {{ }}"),
1087 };
1088 ast_from_text(&list)
1089}
1090
1091pub fn trait_(
1092 is_unsafe: bool,
1093 ident: &str,
1094 gen_params: Option<ast::GenericParamList>,
1095 where_clause: Option<ast::WhereClause>,
1096 assoc_items: ast::AssocItemList,
1097) -> ast::Trait {
1098 let mut text = String::new();
1099
1100 if is_unsafe {
1101 format_to!(text, "unsafe ");
1102 }
1103
1104 format_to!(text, "trait {ident}");
1105
1106 if let Some(gen_params) = gen_params {
1107 format_to!(text, "{} ", gen_params.to_string());
1108 } else {
1109 text.push(' ');
1110 }
1111
1112 if let Some(where_clause) = where_clause {
1113 format_to!(text, "{} ", where_clause.to_string());
1114 }
1115
1116 format_to!(text, "{}", assoc_items.to_string());
1117
1118 ast_from_text(&text)
1119}
1120
1121pub fn type_bound_text(bound: &str) -> ast::TypeBound {
1123 ast_from_text(&format!("fn f<T: {bound}>() {{ }}"))
1124}
1125
1126pub fn type_bound(bound: ast::Type) -> ast::TypeBound {
1127 ast_from_text(&format!("fn f<T: {bound}>() {{ }}"))
1128}
1129
1130pub fn type_bound_list(
1131 bounds: impl IntoIterator<Item = ast::TypeBound>,
1132) -> Option<ast::TypeBoundList> {
1133 let bounds = bounds.into_iter().map(|it| it.to_string()).unique().join(" + ");
1134 if bounds.is_empty() {
1135 return None;
1136 }
1137 Some(ast_from_text(&format!("fn f<T: {bounds}>() {{ }}")))
1138}
1139
1140pub fn type_param(name: ast::Name, bounds: Option<ast::TypeBoundList>) -> ast::TypeParam {
1141 let bounds = bounds.map_or_else(String::new, |it| format!(": {it}"));
1142 ast_from_text(&format!("fn f<{name}{bounds}>() {{ }}"))
1143}
1144
1145pub fn const_param(name: ast::Name, ty: ast::Type) -> ast::ConstParam {
1146 ast_from_text(&format!("fn f<const {name}: {ty}>() {{ }}"))
1147}
1148
1149pub fn lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam {
1150 ast_from_text(&format!("fn f<{lifetime}>() {{ }}"))
1151}
1152
1153pub fn generic_param_list(
1154 pats: impl IntoIterator<Item = ast::GenericParam>,
1155) -> ast::GenericParamList {
1156 let args = pats.into_iter().join(", ");
1157 ast_from_text(&format!("fn f<{args}>() {{ }}"))
1158}
1159
1160pub fn type_arg(ty: ast::Type) -> ast::TypeArg {
1161 ast_from_text(&format!("const S: T<{ty}> = ();"))
1162}
1163
1164pub fn lifetime_arg(lifetime: ast::Lifetime) -> ast::LifetimeArg {
1165 ast_from_text(&format!("const S: T<{lifetime}> = ();"))
1166}
1167
1168pub fn turbofish_generic_arg_list(
1169 args: impl IntoIterator<Item = ast::GenericArg>,
1170) -> ast::GenericArgList {
1171 let args = args.into_iter().join(", ");
1172 ast_from_text(&format!("const S: T::<{args}> = ();"))
1173}
1174
1175pub fn generic_arg_list(args: impl IntoIterator<Item = ast::GenericArg>) -> ast::GenericArgList {
1176 let args = args.into_iter().join(", ");
1177 ast_from_text(&format!("const S: T<{args}> = ();"))
1178}
1179
1180pub fn visibility_pub_crate() -> ast::Visibility {
1181 ast_from_text("pub(crate) struct S")
1182}
1183
1184pub fn visibility_pub() -> ast::Visibility {
1185 ast_from_text("pub struct S")
1186}
1187
1188pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
1189 let fields = fields.into_iter().join(", ");
1190 ast_from_text(&format!("struct f({fields});"))
1191}
1192
1193pub fn record_field_list(
1194 fields: impl IntoIterator<Item = ast::RecordField>,
1195) -> ast::RecordFieldList {
1196 let fields = fields.into_iter().join(", ");
1197 ast_from_text(&format!("struct f {{ {fields} }}"))
1198}
1199
1200pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
1201 let visibility = match visibility {
1202 None => String::new(),
1203 Some(it) => format!("{it} "),
1204 };
1205 ast_from_text(&format!("struct f({visibility}{ty});"))
1206}
1207
1208pub fn variant_list(variants: impl IntoIterator<Item = ast::Variant>) -> ast::VariantList {
1209 let variants = variants.into_iter().join(", ");
1210 ast_from_text(&format!("enum f {{ {variants} }}"))
1211}
1212
1213pub fn variant(
1214 visibility: Option<ast::Visibility>,
1215 name: ast::Name,
1216 field_list: Option<ast::FieldList>,
1217 discriminant: Option<ast::Expr>,
1218) -> ast::Variant {
1219 let visibility = match visibility {
1220 None => String::new(),
1221 Some(it) => format!("{it} "),
1222 };
1223
1224 let field_list = match field_list {
1225 None => String::new(),
1226 Some(it) => match it {
1227 ast::FieldList::RecordFieldList(record) => format!(" {record}"),
1228 ast::FieldList::TupleFieldList(tuple) => format!("{tuple}"),
1229 },
1230 };
1231
1232 let discriminant = match discriminant {
1233 Some(it) => format!(" = {it}"),
1234 None => String::new(),
1235 };
1236 ast_from_text(&format!("enum f {{ {visibility}{name}{field_list}{discriminant} }}"))
1237}
1238
1239pub fn fn_(
1240 attrs: impl IntoIterator<Item = ast::Attr>,
1241 visibility: Option<ast::Visibility>,
1242 fn_name: ast::Name,
1243 type_params: Option<ast::GenericParamList>,
1244 where_clause: Option<ast::WhereClause>,
1245 params: ast::ParamList,
1246 body: ast::BlockExpr,
1247 ret_type: Option<ast::RetType>,
1248 is_async: bool,
1249 is_const: bool,
1250 is_unsafe: bool,
1251 is_gen: bool,
1252) -> ast::Fn {
1253 let attrs =
1254 attrs.into_iter().fold(String::new(), |mut acc, attr| format_to_acc!(acc, "{}\n", attr));
1255 let type_params = match type_params {
1256 Some(type_params) => format!("{type_params}"),
1257 None => "".into(),
1258 };
1259 let where_clause = match where_clause {
1260 Some(it) => format!("{it} "),
1261 None => "".into(),
1262 };
1263 let ret_type = match ret_type {
1264 Some(ret_type) => format!("{ret_type} "),
1265 None => "".into(),
1266 };
1267 let visibility = match visibility {
1268 None => String::new(),
1269 Some(it) => format!("{it} "),
1270 };
1271
1272 let async_literal = if is_async { "async " } else { "" };
1273 let const_literal = if is_const { "const " } else { "" };
1274 let unsafe_literal = if is_unsafe { "unsafe " } else { "" };
1275 let gen_literal = if is_gen { "gen " } else { "" };
1276
1277 ast_from_text(&format!(
1278 "{attrs}{visibility}{const_literal}{async_literal}{gen_literal}{unsafe_literal}fn {fn_name}{type_params}{params} {ret_type}{where_clause}{body}",
1279 ))
1280}
1281pub fn struct_(
1282 visibility: Option<ast::Visibility>,
1283 strukt_name: ast::Name,
1284 generic_param_list: Option<ast::GenericParamList>,
1285 field_list: ast::FieldList,
1286) -> ast::Struct {
1287 let (semicolon, ws) =
1288 if matches!(field_list, ast::FieldList::TupleFieldList(_)) { (";", "") } else { ("", " ") };
1289 let type_params = generic_param_list.map_or_else(String::new, |it| it.to_string());
1290 let visibility = match visibility {
1291 None => String::new(),
1292 Some(it) => format!("{it} "),
1293 };
1294
1295 ast_from_text(&format!(
1296 "{visibility}struct {strukt_name}{type_params}{ws}{field_list}{semicolon}"
1297 ))
1298}
1299
1300pub fn enum_(
1301 attrs: impl IntoIterator<Item = ast::Attr>,
1302 visibility: Option<ast::Visibility>,
1303 enum_name: ast::Name,
1304 generic_param_list: Option<ast::GenericParamList>,
1305 where_clause: Option<ast::WhereClause>,
1306 variant_list: ast::VariantList,
1307) -> ast::Enum {
1308 let attrs =
1309 attrs.into_iter().fold(String::new(), |mut acc, attr| format_to_acc!(acc, "{}\n", attr));
1310 let visibility = match visibility {
1311 None => String::new(),
1312 Some(it) => format!("{it} "),
1313 };
1314
1315 let generic_params = generic_param_list.map(|it| it.to_string()).unwrap_or_default();
1316 let where_clause = where_clause.map(|it| format!(" {it}")).unwrap_or_default();
1317
1318 ast_from_text(&format!(
1319 "{attrs}{visibility}enum {enum_name}{generic_params}{where_clause} {variant_list}"
1320 ))
1321}
1322
1323pub fn attr_outer(meta: ast::Meta) -> ast::Attr {
1324 ast_from_text(&format!("#[{meta}]"))
1325}
1326
1327pub fn attr_inner(meta: ast::Meta) -> ast::Attr {
1328 ast_from_text(&format!("#![{meta}]"))
1329}
1330
1331pub fn meta_expr(path: ast::Path, expr: ast::Expr) -> ast::Meta {
1332 ast_from_text(&format!("#[{path} = {expr}]"))
1333}
1334
1335pub fn meta_token_tree(path: ast::Path, tt: ast::TokenTree) -> ast::Meta {
1336 ast_from_text(&format!("#[{path}{tt}]"))
1337}
1338
1339pub fn meta_path(path: ast::Path) -> ast::Meta {
1340 ast_from_text(&format!("#[{path}]"))
1341}
1342
1343pub fn cfg_attr_meta(
1344 predicate: ast::CfgPredicate,
1345 inner: impl IntoIterator<Item = ast::Meta>,
1346) -> ast::CfgAttrMeta {
1347 let inner = inner.into_iter().join(", ");
1348 ast_from_text(&format!("#![cfg_attr({predicate}, {inner})]"))
1349}
1350
1351pub fn cfg_flag(flag: &str) -> ast::CfgPredicate {
1352 ast_from_text(&format!("#![cfg({flag})]"))
1353}
1354
1355pub fn token_tree(
1356 delimiter: SyntaxKind,
1357 tt: impl IntoIterator<Item = NodeOrToken<ast::TokenTree, SyntaxToken>>,
1358) -> ast::TokenTree {
1359 let (l_delimiter, r_delimiter) = match delimiter {
1360 T!['('] => ('(', ')'),
1361 T!['['] => ('[', ']'),
1362 T!['{'] => ('{', '}'),
1363 _ => panic!("invalid delimiter `{delimiter:?}`"),
1364 };
1365 let tt = tt.into_iter().join("");
1366
1367 ast_from_text(&format!("tt!{l_delimiter}{tt}{r_delimiter}"))
1368}
1369
1370pub fn expr_let(pattern: ast::Pat, expr: ast::Expr) -> ast::LetExpr {
1371 expr_from_text(&format!("while let {pattern} = {expr} {{}}"))
1372}
1373
1374#[track_caller]
1375fn expr_from_text<E: Into<ast::Expr> + AstNode>(text: &str) -> E {
1376 expr_from_text_with_edition(text, Edition::CURRENT)
1377}
1378
1379#[track_caller]
1380fn expr_from_text_with_edition<E: Into<ast::Expr> + AstNode>(text: &str, edition: Edition) -> E {
1381 let parse = ast::Expr::parse(text, edition);
1382 let node = match parse.tree().syntax().descendants().find_map(E::cast) {
1383 Some(it) => it,
1384 None => {
1385 let node = std::any::type_name::<E>();
1386 panic!("Failed to make expr node `{node}` from text `{text}`")
1387 }
1388 };
1389 let node = node.clone_subtree();
1390 assert_eq!(node.syntax().text_range().start(), 0.into());
1391 node
1392}
1393
1394#[track_caller]
1395fn ast_from_text<N: AstNode>(text: &str) -> N {
1396 ast_from_text_with_edition(text, Edition::CURRENT)
1397}
1398
1399#[track_caller]
1400fn ast_from_text_with_edition<N: AstNode>(text: &str, edition: Edition) -> N {
1401 let parse = SourceFile::parse(text, edition);
1402 let node = match parse.tree().syntax().descendants().find_map(N::cast) {
1403 Some(it) => it,
1404 None => {
1405 let node = std::any::type_name::<N>();
1406 panic!("Failed to make ast node `{node}` from text `{text}`")
1407 }
1408 };
1409 let node = node.clone_subtree();
1410 assert_eq!(node.syntax().text_range().start(), 0.into());
1411 node
1412}
1413
1414pub fn token(kind: SyntaxKind) -> SyntaxToken {
1415 tokens::SOURCE_FILE
1416 .tree()
1417 .syntax()
1418 .descendants_with_tokens()
1419 .filter_map(|it| it.into_token())
1420 .find(|it| it.kind() == kind)
1421 .unwrap_or_else(|| panic!("unhandled token: {kind:?}"))
1422}
1423
1424pub mod tokens {
1425 use std::sync::LazyLock;
1426
1427 use parser::Edition;
1428
1429 use crate::{AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken, ast};
1430
1431 pub(super) static SOURCE_FILE: LazyLock<Parse<SourceFile>> = LazyLock::new(|| {
1432 SourceFile::parse(
1433 "use crate::foo; const C: <()>::Item = ( true && true , true || true , 1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p, &p , &mut p, async { let _ @ [] }, while loop {} {})\n;\n\nunsafe impl A for B where: {}",
1434 Edition::CURRENT,
1435 )
1436 });
1437
1438 pub fn whitespace(text: &str) -> SyntaxToken {
1439 assert!(text.trim().is_empty());
1440 let sf = SourceFile::parse(text, Edition::CURRENT).ok().unwrap();
1441 sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
1442 }
1443
1444 pub fn doc_comment(text: &str) -> SyntaxToken {
1445 assert!(!text.trim().is_empty());
1446 let sf = SourceFile::parse(text, Edition::CURRENT).ok().unwrap();
1447 sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
1448 }
1449
1450 pub fn literal(text: &str) -> SyntaxToken {
1451 assert_eq!(text.trim(), text);
1452 let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {text}; }}"));
1453 lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
1454 }
1455
1456 pub fn ident(text: &str) -> SyntaxToken {
1457 assert_eq!(text.trim(), text);
1458 let path: ast::Path = super::ext::ident_path(text);
1459 path.syntax()
1460 .descendants_with_tokens()
1461 .filter_map(|it| it.into_token())
1462 .find(|it| it.kind() == IDENT)
1463 .unwrap()
1464 }
1465}
1466
1467#[cfg(test)]
1468mod tests {
1469 use expect_test::expect;
1470
1471 use super::*;
1472
1473 #[track_caller]
1474 fn check(node: impl AstNode, expect: expect_test::Expect) {
1475 let node_debug = format!("{:#?}", node.syntax());
1476 expect.assert_eq(&node_debug);
1477 }
1478
1479 #[test]
1480 fn test_unnamed_param() {
1481 check(
1482 unnamed_param(ty("Vec")),
1483 expect![[r#"
1484 PARAM@0..3
1485 PATH_TYPE@0..3
1486 PATH@0..3
1487 PATH_SEGMENT@0..3
1488 NAME_REF@0..3
1489 IDENT@0..3 "Vec"
1490 "#]],
1491 );
1492
1493 check(
1494 unnamed_param(ty("Vec<T>")),
1495 expect![[r#"
1496 PARAM@0..6
1497 PATH_TYPE@0..6
1498 PATH@0..6
1499 PATH_SEGMENT@0..6
1500 NAME_REF@0..3
1501 IDENT@0..3 "Vec"
1502 GENERIC_ARG_LIST@3..6
1503 L_ANGLE@3..4 "<"
1504 TYPE_ARG@4..5
1505 PATH_TYPE@4..5
1506 PATH@4..5
1507 PATH_SEGMENT@4..5
1508 NAME_REF@4..5
1509 IDENT@4..5 "T"
1510 R_ANGLE@5..6 ">"
1511 "#]],
1512 );
1513 }
1514
1515 #[test]
1516 fn expr_if_without_else_has_no_trailing_whitespace() {
1517 let if_expr = expr_if(ext::expr_underscore(), block_expr(None, None), None);
1518 assert_eq!(if_expr.syntax().to_string(), "if _ {\n}");
1519
1520 let stmt = expr_stmt(if_expr.into());
1521 let block = block_expr([stmt.into()], None);
1522 assert_eq!(block.syntax().to_string(), "{\n if _ {\n}\n}");
1523 }
1524
1525 #[test]
1526 fn test_untyped_param() {
1527 check(
1528 untyped_param(path_pat(ext::ident_path("name"))),
1529 expect![[r#"
1530 PARAM@0..4
1531 IDENT_PAT@0..4
1532 NAME@0..4
1533 IDENT@0..4 "name"
1534 "#]],
1535 );
1536
1537 check(
1538 untyped_param(
1539 range_pat(
1540 Some(path_pat(ext::ident_path("start"))),
1541 Some(path_pat(ext::ident_path("end"))),
1542 )
1543 .into(),
1544 ),
1545 expect![[r#"
1546 PARAM@0..10
1547 RANGE_PAT@0..10
1548 IDENT_PAT@0..5
1549 NAME@0..5
1550 IDENT@0..5 "start"
1551 DOT2@5..7 ".."
1552 IDENT_PAT@7..10
1553 NAME@7..10
1554 IDENT@7..10 "end"
1555 "#]],
1556 );
1557 }
1558}