1 //! This module contains free-standing functions for creating AST fragments out
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.
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};
15 use crate::{ast, AstNode, SourceFile, SyntaxKind, SyntaxToken};
17 /// While the parent module defines basic atomic "constructors", the `ext`
18 /// module defines shortcuts for common things.
20 /// It's named `ext` rather than `shortcuts` just to keep it short.
24 pub fn simple_ident_pat(name: ast::Name) -> ast::IdentPat {
25 return from_text(&name.text());
27 fn from_text(text: &str) -> ast::IdentPat {
28 ast_from_text(&format!("fn f({text}: ())"))
31 pub fn ident_path(ident: &str) -> ast::Path {
32 path_unqualified(path_segment(name_ref(ident)))
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)
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);
56 pub fn expr_unreachable() -> ast::Expr {
57 expr_from_text("unreachable!()")
59 pub fn expr_todo() -> ast::Expr {
60 expr_from_text("todo!()")
62 pub fn expr_ty_default(ty: &ast::Type) -> ast::Expr {
63 expr_from_text(&format!("{ty}::default()"))
65 pub fn expr_ty_new(ty: &ast::Type) -> ast::Expr {
66 expr_from_text(&format!("{ty}::new()"))
69 pub fn zero_number() -> ast::Expr {
72 pub fn zero_float() -> ast::Expr {
75 pub fn empty_str() -> ast::Expr {
76 expr_from_text(r#""""#)
78 pub fn empty_char() -> ast::Expr {
79 expr_from_text("'\x00'")
81 pub fn default_bool() -> ast::Expr {
82 expr_from_text("false")
84 pub fn option_none() -> ast::Expr {
85 expr_from_text("None")
87 pub fn empty_block_expr() -> ast::BlockExpr {
88 block_expr(None, None)
91 pub fn ty_name(name: ast::Name) -> ast::Type {
92 ty_path(ident_path(&name.to_string()))
94 pub fn ty_bool() -> ast::Type {
95 ty_path(ident_path("bool"))
97 pub fn ty_option(t: ast::Type) -> ast::Type {
98 ty_from_text(&format!("Option<{t}>"))
100 pub fn ty_result(t: ast::Type, e: ast::Type) -> ast::Type {
101 ty_from_text(&format!("Result<{t}, {e}>"))
105 pub fn name(name: &str) -> ast::Name {
106 let raw_escape = raw_ident_esc(name);
107 ast_from_text(&format!("mod {raw_escape}{name};"))
109 pub fn name_ref(name_ref: &str) -> ast::NameRef {
110 let raw_escape = raw_ident_esc(name_ref);
111 ast_from_text(&format!("fn f() {{ {raw_escape}{name_ref}; }}"))
113 fn raw_ident_esc(ident: &str) -> &'static str {
114 let is_keyword = parser::SyntaxKind::from_keyword(ident).is_some();
115 if is_keyword && !matches!(ident, "self" | "crate" | "super" | "Self") {
122 pub fn lifetime(text: &str) -> ast::Lifetime {
125 if never!(!text.starts_with('\'')) {
126 tmp = format!("'{text}");
129 ast_from_text(&format!("fn f<{text}>() {{ }}"))
132 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
134 pub fn ty(text: &str) -> ast::Type {
137 pub fn ty_placeholder() -> ast::Type {
140 pub fn ty_unit() -> ast::Type {
143 pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
144 let mut count: usize = 0;
145 let mut contents = types.into_iter().inspect(|_| count += 1).join(", ");
150 ty_from_text(&format!("({contents})"))
152 pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
153 ty_from_text(&if exclusive { format!("&mut {target}") } else { format!("&{target}") })
155 pub fn ty_path(path: ast::Path) -> ast::Type {
156 ty_from_text(&path.to_string())
158 fn ty_from_text(text: &str) -> ast::Type {
159 ast_from_text(&format!("type _T = {text};"))
162 pub fn assoc_item_list() -> ast::AssocItemList {
163 ast_from_text("impl C for D {}")
166 // FIXME: `ty_params` should be `ast::GenericArgList`
169 params: Option<ast::GenericParamList>,
170 ty_params: Option<ast::GenericParamList>,
172 let params = match params {
173 Some(params) => params.to_string(),
174 None => String::new(),
176 let ty_params = match ty_params {
177 Some(params) => params.to_string(),
178 None => String::new(),
180 ast_from_text(&format!("impl{params} {ty}{ty_params} {{}}"))
186 ty_params: Option<ast::GenericParamList>,
188 let ty_params = ty_params.map_or_else(String::new, |params| params.to_string());
189 ast_from_text(&format!("impl{ty_params} {trait_} for {ty}{ty_params} {{}}"))
192 pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
193 ast_from_text(&format!("type __ = {name_ref};"))
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}>) {{}}"),
204 pub fn path_segment_self() -> ast::PathSegment {
205 ast_from_text("use self;")
208 pub fn path_segment_super() -> ast::PathSegment {
209 ast_from_text("use super;")
212 pub fn path_segment_crate() -> ast::PathSegment {
213 ast_from_text("use crate;")
216 pub fn path_unqualified(segment: ast::PathSegment) -> ast::Path {
217 ast_from_text(&format!("type __ = {segment};"))
220 pub fn path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path {
221 ast_from_text(&format!("{qual}::{segment}"))
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};"))
228 pub fn path_from_segments(
229 segments: impl IntoIterator<Item = ast::PathSegment>,
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}) {{}}")
236 format!("fn f(x: {segments}) {{}}")
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};"))
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}; }}"))
250 pub fn use_tree_glob() -> ast::UseTree {
251 ast_from_text("use *;")
255 use_tree_list: Option<ast::UseTreeList>,
256 alias: Option<ast::Rename>,
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}");
268 if let Some(alias) = alias {
269 format_to!(buf, " {alias}");
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}}};"))
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} "),
284 ast_from_text(&format!("{visibility}use {use_tree};"))
287 pub fn record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr {
288 ast_from_text(&format!("fn f() {{ {path} {fields} }}"))
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} }} }}"))
298 pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField {
300 Some(expr) => from_text(&format!("{name}: {expr}")),
301 None => from_text(&name.to_string()),
304 fn from_text(text: &str) -> ast::RecordExprField {
305 ast_from_text(&format!("fn f() {{ S {{ {text}, }} }}"))
310 visibility: Option<ast::Visibility>,
313 ) -> ast::RecordField {
314 let visibility = match visibility {
315 None => String::new(),
316 Some(it) => format!("{it} "),
318 ast_from_text(&format!("struct S {{ {visibility}{name}: {ty}, }}"))
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");
330 if let Some(tail_expr) = tail_expr {
331 format_to!(buf, " {tail_expr}\n");
334 ast_from_text(&format!("fn f() {buf}"))
337 pub fn tail_only_block_expr(tail_expr: ast::Expr) -> ast::BlockExpr {
338 ast_from_text(&format!("fn f() {{ {tail_expr} }}"))
341 /// Ideally this function wouldn't exist since it involves manual indenting.
342 /// It differs from `make::block_expr` by also supporting comments and whitespace.
344 /// FIXME: replace usages of this with the mutable syntax tree API
345 pub fn hacky_block_expr(
346 elements: impl IntoIterator<Item = crate::SyntaxElement>,
347 tail_expr: Option<ast::Expr>,
348 ) -> ast::BlockExpr {
349 let mut buf = "{\n".to_string();
350 for node_or_token in elements.into_iter() {
351 match node_or_token {
352 rowan::NodeOrToken::Node(n) => format_to!(buf, " {n}\n"),
353 rowan::NodeOrToken::Token(t) => {
355 if kind == SyntaxKind::COMMENT {
356 format_to!(buf, " {t}\n")
357 } else if kind == SyntaxKind::WHITESPACE {
358 let content = t.text().trim_matches(|c| c != '\n');
359 if content.len() >= 1 {
360 format_to!(buf, "{}", &content[1..])
366 if let Some(tail_expr) = tail_expr {
367 format_to!(buf, " {tail_expr}\n");
370 ast_from_text(&format!("fn f() {buf}"))
373 pub fn expr_unit() -> ast::Expr {
376 pub fn expr_literal(text: &str) -> ast::Literal {
377 assert_eq!(text.trim(), text);
378 ast_from_text(&format!("fn f() {{ let _ = {text}; }}"))
381 pub fn expr_empty_block() -> ast::Expr {
384 pub fn expr_path(path: ast::Path) -> ast::Expr {
385 expr_from_text(&path.to_string())
387 pub fn expr_continue(label: Option<ast::Lifetime>) -> ast::Expr {
389 Some(label) => expr_from_text(&format!("continue {label}")),
390 None => expr_from_text("continue"),
393 // Consider `op: SyntaxKind` instead for nicer syntax at the call-site?
394 pub fn expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr {
395 expr_from_text(&format!("{lhs} {op} {rhs}"))
397 pub fn expr_break(label: Option<ast::Lifetime>, expr: Option<ast::Expr>) -> ast::Expr {
398 let mut s = String::from("break");
400 if let Some(label) = label {
401 format_to!(s, " {label}");
404 if let Some(expr) = expr {
405 format_to!(s, " {expr}");
410 pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
412 Some(expr) => expr_from_text(&format!("return {expr}")),
413 None => expr_from_text("return"),
416 pub fn expr_try(expr: ast::Expr) -> ast::Expr {
417 expr_from_text(&format!("{expr}?"))
419 pub fn expr_await(expr: ast::Expr) -> ast::Expr {
420 expr_from_text(&format!("{expr}.await"))
422 pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
423 expr_from_text(&format!("match {expr} {match_arm_list}"))
426 condition: ast::Expr,
427 then_branch: ast::BlockExpr,
428 else_branch: Option<ast::ElseBranch>,
430 let else_branch = match else_branch {
431 Some(ast::ElseBranch::Block(block)) => format!("else {block}"),
432 Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {if_expr}"),
433 None => String::new(),
435 expr_from_text(&format!("if {condition} {then_branch} {else_branch}"))
437 pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr {
438 expr_from_text(&format!("for {pat} in {expr} {block}"))
441 pub fn expr_loop(block: ast::BlockExpr) -> ast::Expr {
442 expr_from_text(&format!("loop {block}"))
445 pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
446 let token = token(op);
447 expr_from_text(&format!("{token}{expr}"))
449 pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
450 expr_from_text(&format!("{f}{arg_list}"))
452 pub fn expr_method_call(
454 method: ast::NameRef,
455 arg_list: ast::ArgList,
457 expr_from_text(&format!("{receiver}.{method}{arg_list}"))
459 pub fn expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
460 expr_from_text(&format!("{f}!{arg_list}"))
462 pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
463 expr_from_text(&if exclusive { format!("&mut {expr}") } else { format!("&{expr}") })
465 pub fn expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr {
466 let params = pats.into_iter().join(", ");
467 expr_from_text(&format!("|{params}| {expr}"))
469 pub fn expr_field(receiver: ast::Expr, field: &str) -> ast::Expr {
470 expr_from_text(&format!("{receiver}.{field}"))
472 pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
473 expr_from_text(&format!("({expr})"))
475 pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr {
476 let expr = elements.into_iter().format(", ");
477 expr_from_text(&format!("({expr})"))
479 pub fn expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
480 expr_from_text(&format!("{lhs} = {rhs}"))
482 fn expr_from_text(text: &str) -> ast::Expr {
483 ast_from_text(&format!("const C: () = {text};"))
485 pub fn expr_let(pattern: ast::Pat, expr: ast::Expr) -> ast::LetExpr {
486 ast_from_text(&format!("const _: () = while let {pattern} = {expr} {{}};"))
489 pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
490 let args = args.into_iter().format(", ");
491 ast_from_text(&format!("fn main() {{ ()({args}) }}"))
494 pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
495 let mut s = String::from("fn f(");
502 format_to!(s, "{name}");
507 pub fn wildcard_pat() -> ast::WildcardPat {
508 return from_text("_");
510 fn from_text(text: &str) -> ast::WildcardPat {
511 ast_from_text(&format!("fn f({text}: ())"))
515 pub fn literal_pat(lit: &str) -> ast::LiteralPat {
516 return from_text(lit);
518 fn from_text(text: &str) -> ast::LiteralPat {
519 ast_from_text(&format!("fn f() {{ match x {{ {text} => {{}} }} }}"))
523 /// Creates a tuple of patterns from an iterator of patterns.
525 /// Invariant: `pats` must be length > 0
526 pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
527 let mut count: usize = 0;
528 let mut pats_str = pats.into_iter().inspect(|_| count += 1).join(", ");
532 return from_text(&format!("({pats_str})"));
534 fn from_text(text: &str) -> ast::TuplePat {
535 ast_from_text(&format!("fn f({text}: ())"))
539 pub fn tuple_struct_pat(
541 pats: impl IntoIterator<Item = ast::Pat>,
542 ) -> ast::TupleStructPat {
543 let pats_str = pats.into_iter().join(", ");
544 return from_text(&format!("{path}({pats_str})"));
546 fn from_text(text: &str) -> ast::TupleStructPat {
547 ast_from_text(&format!("fn f({text}: ())"))
551 pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
552 let pats_str = pats.into_iter().join(", ");
553 return from_text(&format!("{path} {{ {pats_str} }}"));
555 fn from_text(text: &str) -> ast::RecordPat {
556 ast_from_text(&format!("fn f({text}: ())"))
560 pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
561 ast_from_text(&format!("fn f({path} {fields}: ()))"))
564 pub fn record_pat_field_list(
565 fields: impl IntoIterator<Item = ast::RecordPatField>,
566 ) -> ast::RecordPatFieldList {
567 let fields = fields.into_iter().join(", ");
568 ast_from_text(&format!("fn f(S {{ {fields} }}: ()))"))
571 pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
572 ast_from_text(&format!("fn f(S {{ {name_ref}: {pat} }}: ()))"))
575 pub fn record_pat_field_shorthand(name_ref: ast::NameRef) -> ast::RecordPatField {
576 ast_from_text(&format!("fn f(S {{ {name_ref} }}: ()))"))
579 /// Returns a `BindPat` if the path has just one segment, a `PathPat` otherwise.
580 pub fn path_pat(path: ast::Path) -> ast::Pat {
581 return from_text(&path.to_string());
582 fn from_text(text: &str) -> ast::Pat {
583 ast_from_text(&format!("fn f({text}: ())"))
588 pats: impl IntoIterator<Item = ast::Pat>,
589 guard: Option<ast::Expr>,
592 let pats_str = pats.into_iter().join(" | ");
594 Some(guard) => from_text(&format!("{pats_str} if {guard} => {expr}")),
595 None => from_text(&format!("{pats_str} => {expr}")),
598 fn from_text(text: &str) -> ast::MatchArm {
599 ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
603 pub fn match_arm_with_guard(
604 pats: impl IntoIterator<Item = ast::Pat>,
608 let pats_str = pats.into_iter().join(" | ");
609 return from_text(&format!("{pats_str} if {guard} => {expr}"));
611 fn from_text(text: &str) -> ast::MatchArm {
612 ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
616 pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
620 let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
621 let comma = if needs_comma { "," } else { "" };
622 let arm = arm.syntax();
623 format!(" {arm}{comma}\n")
625 .collect::<String>();
626 return from_text(&arms_str);
628 fn from_text(text: &str) -> ast::MatchArmList {
629 ast_from_text(&format!("fn f() {{ match () {{\n{text}}} }}"))
635 bounds: impl IntoIterator<Item = ast::TypeBound>,
636 ) -> ast::WherePred {
637 let bounds = bounds.into_iter().join(" + ");
638 return from_text(&format!("{path}: {bounds}"));
640 fn from_text(text: &str) -> ast::WherePred {
641 ast_from_text(&format!("fn f() where {text} {{ }}"))
645 pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause {
646 let preds = preds.into_iter().join(", ");
647 return from_text(preds.as_str());
649 fn from_text(text: &str) -> ast::WhereClause {
650 ast_from_text(&format!("fn f() where {text} {{ }}"))
656 ty: Option<ast::Type>,
657 initializer: Option<ast::Expr>,
659 let mut text = String::new();
660 format_to!(text, "let {pattern}");
661 if let Some(ty) = ty {
662 format_to!(text, ": {ty}");
665 Some(it) => format_to!(text, " = {it};"),
666 None => format_to!(text, ";"),
668 ast_from_text(&format!("fn f() {{ {text} }}"))
671 pub fn let_else_stmt(
673 ty: Option<ast::Type>,
675 diverging: ast::BlockExpr,
677 let mut text = String::new();
678 format_to!(text, "let {pattern}");
679 if let Some(ty) = ty {
680 format_to!(text, ": {ty}");
682 format_to!(text, " = {expr} else {diverging};");
683 ast_from_text(&format!("fn f() {{ {text} }}"))
686 pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
687 let semi = if expr.is_block_like() { "" } else { ";" };
688 ast_from_text(&format!("fn f() {{ {expr}{semi} (); }}"))
692 visibility: Option<ast::Visibility>,
697 let visibility = match visibility {
698 None => String::new(),
699 Some(it) => format!("{it} "),
701 ast_from_text(&format!("{visibility} const {name}: {ty} = {expr};"))
704 pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
705 ast_from_text(&format!("fn f({pat}: {ty}) {{ }}"))
708 pub fn self_param() -> ast::SelfParam {
709 ast_from_text("fn f(&self) { }")
712 pub fn ret_type(ty: ast::Type) -> ast::RetType {
713 ast_from_text(&format!("fn f() -> {ty} {{ }}"))
717 self_param: Option<ast::SelfParam>,
718 pats: impl IntoIterator<Item = ast::Param>,
719 ) -> ast::ParamList {
720 let args = pats.into_iter().join(", ");
721 let list = match self_param {
722 Some(self_param) if args.is_empty() => format!("fn f({self_param}) {{ }}"),
723 Some(self_param) => format!("fn f({self_param}, {args}) {{ }}"),
724 None => format!("fn f({args}) {{ }}"),
729 pub fn type_bound(bound: &str) -> ast::TypeBound {
730 ast_from_text(&format!("fn f<T: {bound}>() {{ }}"))
733 pub fn type_bound_list(
734 bounds: impl IntoIterator<Item = ast::TypeBound>,
735 ) -> Option<ast::TypeBoundList> {
736 let bounds = bounds.into_iter().map(|it| it.to_string()).unique().join(" + ");
737 if bounds.is_empty() {
740 Some(ast_from_text(&format!("fn f<T: {bounds}>() {{ }}")))
743 pub fn type_param(name: ast::Name, bounds: Option<ast::TypeBoundList>) -> ast::TypeParam {
744 let bounds = bounds.map_or_else(String::new, |it| format!(": {it}"));
745 ast_from_text(&format!("fn f<{name}{bounds}>() {{ }}"))
748 pub fn lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam {
749 ast_from_text(&format!("fn f<{lifetime}>() {{ }}"))
752 pub fn generic_param_list(
753 pats: impl IntoIterator<Item = ast::GenericParam>,
754 ) -> ast::GenericParamList {
755 let args = pats.into_iter().join(", ");
756 ast_from_text(&format!("fn f<{args}>() {{ }}"))
759 pub fn type_arg(ty: ast::Type) -> ast::TypeArg {
760 ast_from_text(&format!("const S: T<{ty}> = ();"))
763 pub fn lifetime_arg(lifetime: ast::Lifetime) -> ast::LifetimeArg {
764 ast_from_text(&format!("const S: T<{lifetime}> = ();"))
767 pub(crate) fn generic_arg_list(
768 args: impl IntoIterator<Item = ast::GenericArg>,
769 ) -> ast::GenericArgList {
770 let args = args.into_iter().join(", ");
771 ast_from_text(&format!("const S: T<{args}> = ();"))
774 pub fn visibility_pub_crate() -> ast::Visibility {
775 ast_from_text("pub(crate) struct S")
778 pub fn visibility_pub() -> ast::Visibility {
779 ast_from_text("pub struct S")
782 pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
783 let fields = fields.into_iter().join(", ");
784 ast_from_text(&format!("struct f({fields});"))
787 pub fn record_field_list(
788 fields: impl IntoIterator<Item = ast::RecordField>,
789 ) -> ast::RecordFieldList {
790 let fields = fields.into_iter().join(", ");
791 ast_from_text(&format!("struct f {{ {fields} }}"))
794 pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
795 let visibility = match visibility {
796 None => String::new(),
797 Some(it) => format!("{it} "),
799 ast_from_text(&format!("struct f({visibility}{ty});"))
802 pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
803 let field_list = match field_list {
804 None => String::new(),
805 Some(it) => match it {
806 ast::FieldList::RecordFieldList(record) => format!(" {record}"),
807 ast::FieldList::TupleFieldList(tuple) => format!("{tuple}"),
810 ast_from_text(&format!("enum f {{ {name}{field_list} }}"))
814 visibility: Option<ast::Visibility>,
816 type_params: Option<ast::GenericParamList>,
817 params: ast::ParamList,
818 body: ast::BlockExpr,
819 ret_type: Option<ast::RetType>,
822 let type_params = match type_params {
823 Some(type_params) => format!("{type_params}"),
826 let ret_type = match ret_type {
827 Some(ret_type) => format!("{ret_type} "),
830 let visibility = match visibility {
831 None => String::new(),
832 Some(it) => format!("{it} "),
835 let async_literal = if is_async { "async " } else { "" };
837 ast_from_text(&format!(
838 "{visibility}{async_literal}fn {fn_name}{type_params}{params} {ret_type}{body}",
843 visibility: Option<ast::Visibility>,
844 strukt_name: ast::Name,
845 generic_param_list: Option<ast::GenericParamList>,
846 field_list: ast::FieldList,
848 let semicolon = if matches!(field_list, ast::FieldList::TupleFieldList(_)) { ";" } else { "" };
849 let type_params = generic_param_list.map_or_else(String::new, |it| it.to_string());
850 let visibility = match visibility {
851 None => String::new(),
852 Some(it) => format!("{it} "),
855 ast_from_text(&format!("{visibility}struct {strukt_name}{type_params}{field_list}{semicolon}",))
859 fn ast_from_text<N: AstNode>(text: &str) -> N {
860 let parse = SourceFile::parse(text);
861 let node = match parse.tree().syntax().descendants().find_map(N::cast) {
864 let node = std::any::type_name::<N>();
865 panic!("Failed to make ast node `{node}` from text {text}")
868 let node = node.clone_subtree();
869 assert_eq!(node.syntax().text_range().start(), 0.into());
873 pub fn token(kind: SyntaxKind) -> SyntaxToken {
878 .descendants_with_tokens()
879 .filter_map(|it| it.into_token())
880 .find(|it| it.kind() == kind)
881 .unwrap_or_else(|| panic!("unhandled token: {kind:?}"))
885 use once_cell::sync::Lazy;
887 use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
889 pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
891 "const C: <()>::Item = (1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p)\n;\n\n",
895 pub fn single_space() -> SyntaxToken {
900 .descendants_with_tokens()
901 .filter_map(|it| it.into_token())
902 .find(|it| it.kind() == WHITESPACE && it.text() == " ")
906 pub fn whitespace(text: &str) -> SyntaxToken {
907 assert!(text.trim().is_empty());
908 let sf = SourceFile::parse(text).ok().unwrap();
909 sf.syntax().clone_for_update().first_child_or_token().unwrap().into_token().unwrap()
912 pub fn doc_comment(text: &str) -> SyntaxToken {
913 assert!(!text.trim().is_empty());
914 let sf = SourceFile::parse(text).ok().unwrap();
915 sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
918 pub fn literal(text: &str) -> SyntaxToken {
919 assert_eq!(text.trim(), text);
920 let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {text}; }}"));
921 lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
924 pub fn single_newline() -> SyntaxToken {
925 let res = SOURCE_FILE
929 .descendants_with_tokens()
930 .filter_map(|it| it.into_token())
931 .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
937 pub fn blank_line() -> SyntaxToken {
942 .descendants_with_tokens()
943 .filter_map(|it| it.into_token())
944 .find(|it| it.kind() == WHITESPACE && it.text() == "\n\n")
948 pub struct WsBuilder(SourceFile);
951 pub fn new(text: &str) -> WsBuilder {
952 WsBuilder(SourceFile::parse(text).ok().unwrap())
954 pub fn ws(&self) -> SyntaxToken {
955 self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()