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_bool() -> ast::Type {
92 ty_path(ident_path("bool"))
94 pub fn ty_option(t: ast::Type) -> ast::Type {
95 ty_from_text(&format!("Option<{t}>"))
97 pub fn ty_result(t: ast::Type, e: ast::Type) -> ast::Type {
98 ty_from_text(&format!("Result<{t}, {e}>"))
102 pub fn name(name: &str) -> ast::Name {
103 let raw_escape = raw_ident_esc(name);
104 ast_from_text(&format!("mod {raw_escape}{name};"))
106 pub fn name_ref(name_ref: &str) -> ast::NameRef {
107 let raw_escape = raw_ident_esc(name_ref);
108 ast_from_text(&format!("fn f() {{ {raw_escape}{name_ref}; }}"))
110 fn raw_ident_esc(ident: &str) -> &'static str {
111 let is_keyword = parser::SyntaxKind::from_keyword(ident).is_some();
112 if is_keyword && !matches!(ident, "self" | "crate" | "super" | "Self") {
119 pub fn lifetime(text: &str) -> ast::Lifetime {
122 if never!(!text.starts_with('\'')) {
123 tmp = format!("'{text}");
126 ast_from_text(&format!("fn f<{text}>() {{ }}"))
129 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
131 pub fn ty(text: &str) -> ast::Type {
134 pub fn ty_placeholder() -> ast::Type {
137 pub fn ty_unit() -> ast::Type {
140 pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
141 let mut count: usize = 0;
142 let mut contents = types.into_iter().inspect(|_| count += 1).join(", ");
147 ty_from_text(&format!("({contents})"))
149 pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
150 ty_from_text(&if exclusive { format!("&mut {target}") } else { format!("&{target}") })
152 pub fn ty_path(path: ast::Path) -> ast::Type {
153 ty_from_text(&path.to_string())
155 fn ty_from_text(text: &str) -> ast::Type {
156 ast_from_text(&format!("type _T = {text};"))
159 pub fn assoc_item_list() -> ast::AssocItemList {
160 ast_from_text("impl C for D {}")
165 params: Option<ast::GenericParamList>,
166 ty_params: Option<ast::GenericParamList>,
168 let params = match params {
169 Some(params) => params.to_string(),
170 None => String::new(),
172 let ty_params = match ty_params {
173 Some(params) => params.to_string(),
174 None => String::new(),
176 ast_from_text(&format!("impl{params} {ty}{ty_params} {{}}"))
182 ty_params: Option<ast::GenericParamList>,
184 let ty_params = ty_params.map_or_else(String::new, |params| params.to_string());
185 ast_from_text(&format!("impl{ty_params} {trait_} for {ty}{ty_params} {{}}"))
188 pub(crate) fn generic_arg_list() -> ast::GenericArgList {
189 ast_from_text("const S: T<> = ();")
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 /// Ideally this function wouldn't exist since it involves manual indenting.
338 /// It differs from `make::block_expr` by also supporting comments.
340 /// FIXME: replace usages of this with the mutable syntax tree API
341 pub fn hacky_block_expr_with_comments(
342 elements: impl IntoIterator<Item = crate::SyntaxElement>,
343 tail_expr: Option<ast::Expr>,
344 ) -> ast::BlockExpr {
345 let mut buf = "{\n".to_string();
346 for node_or_token in elements.into_iter() {
347 match node_or_token {
348 rowan::NodeOrToken::Node(n) => format_to!(buf, " {n}\n"),
349 rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::COMMENT => {
350 format_to!(buf, " {t}\n")
355 if let Some(tail_expr) = tail_expr {
356 format_to!(buf, " {tail_expr}\n");
359 ast_from_text(&format!("fn f() {buf}"))
362 pub fn expr_unit() -> ast::Expr {
365 pub fn expr_literal(text: &str) -> ast::Literal {
366 assert_eq!(text.trim(), text);
367 ast_from_text(&format!("fn f() {{ let _ = {text}; }}"))
370 pub fn expr_empty_block() -> ast::Expr {
373 pub fn expr_path(path: ast::Path) -> ast::Expr {
374 expr_from_text(&path.to_string())
376 pub fn expr_continue(label: Option<ast::Lifetime>) -> ast::Expr {
378 Some(label) => expr_from_text(&format!("continue {label}")),
379 None => expr_from_text("continue"),
382 // Consider `op: SyntaxKind` instead for nicer syntax at the call-site?
383 pub fn expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr {
384 expr_from_text(&format!("{lhs} {op} {rhs}"))
386 pub fn expr_break(label: Option<ast::Lifetime>, expr: Option<ast::Expr>) -> ast::Expr {
387 let mut s = String::from("break");
389 if let Some(label) = label {
390 format_to!(s, " {label}");
393 if let Some(expr) = expr {
394 format_to!(s, " {expr}");
399 pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
401 Some(expr) => expr_from_text(&format!("return {expr}")),
402 None => expr_from_text("return"),
405 pub fn expr_try(expr: ast::Expr) -> ast::Expr {
406 expr_from_text(&format!("{expr}?"))
408 pub fn expr_await(expr: ast::Expr) -> ast::Expr {
409 expr_from_text(&format!("{expr}.await"))
411 pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
412 expr_from_text(&format!("match {expr} {match_arm_list}"))
415 condition: ast::Expr,
416 then_branch: ast::BlockExpr,
417 else_branch: Option<ast::ElseBranch>,
419 let else_branch = match else_branch {
420 Some(ast::ElseBranch::Block(block)) => format!("else {block}"),
421 Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {if_expr}"),
422 None => String::new(),
424 expr_from_text(&format!("if {condition} {then_branch} {else_branch}"))
426 pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr {
427 expr_from_text(&format!("for {pat} in {expr} {block}"))
430 pub fn expr_loop(block: ast::BlockExpr) -> ast::Expr {
431 expr_from_text(&format!("loop {block}"))
434 pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
435 let token = token(op);
436 expr_from_text(&format!("{token}{expr}"))
438 pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
439 expr_from_text(&format!("{f}{arg_list}"))
441 pub fn expr_method_call(
443 method: ast::NameRef,
444 arg_list: ast::ArgList,
446 expr_from_text(&format!("{receiver}.{method}{arg_list}"))
448 pub fn expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
449 expr_from_text(&format!("{f}!{arg_list}"))
451 pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
452 expr_from_text(&if exclusive { format!("&mut {expr}") } else { format!("&{expr}") })
454 pub fn expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr {
455 let params = pats.into_iter().join(", ");
456 expr_from_text(&format!("|{params}| {expr}"))
458 pub fn expr_field(receiver: ast::Expr, field: &str) -> ast::Expr {
459 expr_from_text(&format!("{receiver}.{field}"))
461 pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
462 expr_from_text(&format!("({expr})"))
464 pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr {
465 let expr = elements.into_iter().format(", ");
466 expr_from_text(&format!("({expr})"))
468 pub fn expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
469 expr_from_text(&format!("{lhs} = {rhs}"))
471 fn expr_from_text(text: &str) -> ast::Expr {
472 ast_from_text(&format!("const C: () = {text};"))
474 pub fn expr_let(pattern: ast::Pat, expr: ast::Expr) -> ast::LetExpr {
475 ast_from_text(&format!("const _: () = while let {pattern} = {expr} {{}};"))
478 pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
479 let args = args.into_iter().format(", ");
480 ast_from_text(&format!("fn main() {{ ()({args}) }}"))
483 pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
484 let mut s = String::from("fn f(");
491 format_to!(s, "{name}");
496 pub fn wildcard_pat() -> ast::WildcardPat {
497 return from_text("_");
499 fn from_text(text: &str) -> ast::WildcardPat {
500 ast_from_text(&format!("fn f({text}: ())"))
504 pub fn literal_pat(lit: &str) -> ast::LiteralPat {
505 return from_text(lit);
507 fn from_text(text: &str) -> ast::LiteralPat {
508 ast_from_text(&format!("fn f() {{ match x {{ {text} => {{}} }} }}"))
512 /// Creates a tuple of patterns from an iterator of patterns.
514 /// Invariant: `pats` must be length > 0
515 pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
516 let mut count: usize = 0;
517 let mut pats_str = pats.into_iter().inspect(|_| count += 1).join(", ");
521 return from_text(&format!("({pats_str})"));
523 fn from_text(text: &str) -> ast::TuplePat {
524 ast_from_text(&format!("fn f({text}: ())"))
528 pub fn tuple_struct_pat(
530 pats: impl IntoIterator<Item = ast::Pat>,
531 ) -> ast::TupleStructPat {
532 let pats_str = pats.into_iter().join(", ");
533 return from_text(&format!("{path}({pats_str})"));
535 fn from_text(text: &str) -> ast::TupleStructPat {
536 ast_from_text(&format!("fn f({text}: ())"))
540 pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
541 let pats_str = pats.into_iter().join(", ");
542 return from_text(&format!("{path} {{ {pats_str} }}"));
544 fn from_text(text: &str) -> ast::RecordPat {
545 ast_from_text(&format!("fn f({text}: ())"))
549 pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
550 ast_from_text(&format!("fn f({path} {fields}: ()))"))
553 pub fn record_pat_field_list(
554 fields: impl IntoIterator<Item = ast::RecordPatField>,
555 ) -> ast::RecordPatFieldList {
556 let fields = fields.into_iter().join(", ");
557 ast_from_text(&format!("fn f(S {{ {fields} }}: ()))"))
560 pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
561 ast_from_text(&format!("fn f(S {{ {name_ref}: {pat} }}: ()))"))
564 pub fn record_pat_field_shorthand(name_ref: ast::NameRef) -> ast::RecordPatField {
565 ast_from_text(&format!("fn f(S {{ {name_ref} }}: ()))"))
568 /// Returns a `BindPat` if the path has just one segment, a `PathPat` otherwise.
569 pub fn path_pat(path: ast::Path) -> ast::Pat {
570 return from_text(&path.to_string());
571 fn from_text(text: &str) -> ast::Pat {
572 ast_from_text(&format!("fn f({text}: ())"))
577 pats: impl IntoIterator<Item = ast::Pat>,
578 guard: Option<ast::Expr>,
581 let pats_str = pats.into_iter().join(" | ");
583 Some(guard) => from_text(&format!("{pats_str} if {guard} => {expr}")),
584 None => from_text(&format!("{pats_str} => {expr}")),
587 fn from_text(text: &str) -> ast::MatchArm {
588 ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
592 pub fn match_arm_with_guard(
593 pats: impl IntoIterator<Item = ast::Pat>,
597 let pats_str = pats.into_iter().join(" | ");
598 return from_text(&format!("{pats_str} if {guard} => {expr}"));
600 fn from_text(text: &str) -> ast::MatchArm {
601 ast_from_text(&format!("fn f() {{ match () {{{text}}} }}"))
605 pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
609 let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
610 let comma = if needs_comma { "," } else { "" };
611 let arm = arm.syntax();
612 format!(" {arm}{comma}\n")
614 .collect::<String>();
615 return from_text(&arms_str);
617 fn from_text(text: &str) -> ast::MatchArmList {
618 ast_from_text(&format!("fn f() {{ match () {{\n{text}}} }}"))
624 bounds: impl IntoIterator<Item = ast::TypeBound>,
625 ) -> ast::WherePred {
626 let bounds = bounds.into_iter().join(" + ");
627 return from_text(&format!("{path}: {bounds}"));
629 fn from_text(text: &str) -> ast::WherePred {
630 ast_from_text(&format!("fn f() where {text} {{ }}"))
634 pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause {
635 let preds = preds.into_iter().join(", ");
636 return from_text(preds.as_str());
638 fn from_text(text: &str) -> ast::WhereClause {
639 ast_from_text(&format!("fn f() where {text} {{ }}"))
645 ty: Option<ast::Type>,
646 initializer: Option<ast::Expr>,
648 let mut text = String::new();
649 format_to!(text, "let {pattern}");
650 if let Some(ty) = ty {
651 format_to!(text, ": {ty}");
654 Some(it) => format_to!(text, " = {it};"),
655 None => format_to!(text, ";"),
657 ast_from_text(&format!("fn f() {{ {text} }}"))
659 pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
660 let semi = if expr.is_block_like() { "" } else { ";" };
661 ast_from_text(&format!("fn f() {{ {expr}{semi} (); }}"))
665 visibility: Option<ast::Visibility>,
670 let visibility = match visibility {
671 None => String::new(),
672 Some(it) => format!("{it} "),
674 ast_from_text(&format!("{visibility} const {name}: {ty} = {expr};"))
677 pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
678 ast_from_text(&format!("fn f({pat}: {ty}) {{ }}"))
681 pub fn self_param() -> ast::SelfParam {
682 ast_from_text("fn f(&self) { }")
685 pub fn ret_type(ty: ast::Type) -> ast::RetType {
686 ast_from_text(&format!("fn f() -> {ty} {{ }}"))
690 self_param: Option<ast::SelfParam>,
691 pats: impl IntoIterator<Item = ast::Param>,
692 ) -> ast::ParamList {
693 let args = pats.into_iter().join(", ");
694 let list = match self_param {
695 Some(self_param) if args.is_empty() => format!("fn f({self_param}) {{ }}"),
696 Some(self_param) => format!("fn f({self_param}, {args}) {{ }}"),
697 None => format!("fn f({args}) {{ }}"),
702 pub fn type_param(name: ast::Name, ty: Option<ast::TypeBoundList>) -> ast::TypeParam {
703 let bound = match ty {
704 Some(it) => format!(": {it}"),
705 None => String::new(),
707 ast_from_text(&format!("fn f<{name}{bound}>() {{ }}"))
710 pub fn lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam {
711 ast_from_text(&format!("fn f<{lifetime}>() {{ }}"))
714 pub fn generic_param_list(
715 pats: impl IntoIterator<Item = ast::GenericParam>,
716 ) -> ast::GenericParamList {
717 let args = pats.into_iter().join(", ");
718 ast_from_text(&format!("fn f<{args}>() {{ }}"))
721 pub fn visibility_pub_crate() -> ast::Visibility {
722 ast_from_text("pub(crate) struct S")
725 pub fn visibility_pub() -> ast::Visibility {
726 ast_from_text("pub struct S")
729 pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
730 let fields = fields.into_iter().join(", ");
731 ast_from_text(&format!("struct f({fields});"))
734 pub fn record_field_list(
735 fields: impl IntoIterator<Item = ast::RecordField>,
736 ) -> ast::RecordFieldList {
737 let fields = fields.into_iter().join(", ");
738 ast_from_text(&format!("struct f {{ {fields} }}"))
741 pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
742 let visibility = match visibility {
743 None => String::new(),
744 Some(it) => format!("{it} "),
746 ast_from_text(&format!("struct f({visibility}{ty});"))
749 pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
750 let field_list = match field_list {
751 None => String::new(),
752 Some(it) => match it {
753 ast::FieldList::RecordFieldList(record) => format!(" {record}"),
754 ast::FieldList::TupleFieldList(tuple) => format!("{tuple}"),
757 ast_from_text(&format!("enum f {{ {name}{field_list} }}"))
761 visibility: Option<ast::Visibility>,
763 type_params: Option<ast::GenericParamList>,
764 params: ast::ParamList,
765 body: ast::BlockExpr,
766 ret_type: Option<ast::RetType>,
769 let type_params = match type_params {
770 Some(type_params) => format!("{type_params}"),
773 let ret_type = match ret_type {
774 Some(ret_type) => format!("{ret_type} "),
777 let visibility = match visibility {
778 None => String::new(),
779 Some(it) => format!("{it} "),
782 let async_literal = if is_async { "async " } else { "" };
784 ast_from_text(&format!(
785 "{visibility}{async_literal}fn {fn_name}{type_params}{params} {ret_type}{body}",
790 visibility: Option<ast::Visibility>,
791 strukt_name: ast::Name,
792 generic_param_list: Option<ast::GenericParamList>,
793 field_list: ast::FieldList,
795 let semicolon = if matches!(field_list, ast::FieldList::TupleFieldList(_)) { ";" } else { "" };
796 let type_params = generic_param_list.map_or_else(String::new, |it| it.to_string());
797 let visibility = match visibility {
798 None => String::new(),
799 Some(it) => format!("{it} "),
802 ast_from_text(&format!("{visibility}struct {strukt_name}{type_params}{field_list}{semicolon}",))
806 fn ast_from_text<N: AstNode>(text: &str) -> N {
807 let parse = SourceFile::parse(text);
808 let node = match parse.tree().syntax().descendants().find_map(N::cast) {
811 let node = std::any::type_name::<N>();
812 panic!("Failed to make ast node `{node}` from text {text}")
815 let node = node.clone_subtree();
816 assert_eq!(node.syntax().text_range().start(), 0.into());
820 pub fn token(kind: SyntaxKind) -> SyntaxToken {
825 .descendants_with_tokens()
826 .filter_map(|it| it.into_token())
827 .find(|it| it.kind() == kind)
828 .unwrap_or_else(|| panic!("unhandled token: {kind:?}"))
832 use once_cell::sync::Lazy;
834 use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
836 pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
838 "const C: <()>::Item = (1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p)\n;\n\n",
842 pub fn single_space() -> SyntaxToken {
847 .descendants_with_tokens()
848 .filter_map(|it| it.into_token())
849 .find(|it| it.kind() == WHITESPACE && it.text() == " ")
853 pub fn whitespace(text: &str) -> SyntaxToken {
854 assert!(text.trim().is_empty());
855 let sf = SourceFile::parse(text).ok().unwrap();
856 sf.syntax().clone_for_update().first_child_or_token().unwrap().into_token().unwrap()
859 pub fn doc_comment(text: &str) -> SyntaxToken {
860 assert!(!text.trim().is_empty());
861 let sf = SourceFile::parse(text).ok().unwrap();
862 sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
865 pub fn literal(text: &str) -> SyntaxToken {
866 assert_eq!(text.trim(), text);
867 let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {text}; }}"));
868 lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
871 pub fn single_newline() -> SyntaxToken {
872 let res = SOURCE_FILE
876 .descendants_with_tokens()
877 .filter_map(|it| it.into_token())
878 .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
884 pub fn blank_line() -> SyntaxToken {
889 .descendants_with_tokens()
890 .filter_map(|it| it.into_token())
891 .find(|it| it.kind() == WHITESPACE && it.text() == "\n\n")
895 pub struct WsBuilder(SourceFile);
898 pub fn new(text: &str) -> WsBuilder {
899 WsBuilder(SourceFile::parse(text).ok().unwrap())
901 pub fn ws(&self) -> SyntaxToken {
902 self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()