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, |base, s| expr_field(base, s));
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!("{}::default()", ty))
65 pub fn expr_ty_new(ty: &ast::Type) -> ast::Expr {
66 expr_from_text(&format!("{}::new()", ty))
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 empty_block_expr() -> ast::BlockExpr {
85 block_expr(None, None)
88 pub fn ty_bool() -> ast::Type {
89 ty_path(ident_path("bool"))
91 pub fn ty_option(t: ast::Type) -> ast::Type {
92 ty_from_text(&format!("Option<{}>", t))
94 pub fn ty_result(t: ast::Type, e: ast::Type) -> ast::Type {
95 ty_from_text(&format!("Result<{}, {}>", t, e))
99 pub fn name(text: &str) -> ast::Name {
100 ast_from_text(&format!("mod {}{};", raw_ident_esc(text), text))
102 pub fn name_ref(text: &str) -> ast::NameRef {
103 ast_from_text(&format!("fn f() {{ {}{}; }}", raw_ident_esc(text), text))
105 fn raw_ident_esc(ident: &str) -> &'static str {
106 let is_keyword = parser::SyntaxKind::from_keyword(ident).is_some();
107 if is_keyword && !matches!(ident, "self" | "crate" | "super" | "Self") {
114 pub fn lifetime(text: &str) -> ast::Lifetime {
117 if never!(!text.starts_with('\'')) {
118 tmp = format!("'{}", text);
121 ast_from_text(&format!("fn f<{}>() {{ }}", text))
124 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
126 pub fn ty(text: &str) -> ast::Type {
129 pub fn ty_placeholder() -> ast::Type {
132 pub fn ty_unit() -> ast::Type {
135 pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
136 let mut count: usize = 0;
137 let mut contents = types.into_iter().inspect(|_| count += 1).join(", ");
142 ty_from_text(&format!("({})", contents))
144 pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
145 ty_from_text(&if exclusive { format!("&mut {}", target) } else { format!("&{}", target) })
147 pub fn ty_path(path: ast::Path) -> ast::Type {
148 ty_from_text(&path.to_string())
150 fn ty_from_text(text: &str) -> ast::Type {
151 ast_from_text(&format!("type _T = {};", text))
154 pub fn assoc_item_list() -> ast::AssocItemList {
155 ast_from_text("impl C for D {}")
160 params: Option<ast::GenericParamList>,
161 ty_params: Option<ast::GenericParamList>,
163 let params = match params {
164 Some(params) => params.to_string(),
165 None => String::new(),
167 let ty_params = match ty_params {
168 Some(params) => params.to_string(),
169 None => String::new(),
171 ast_from_text(&format!("impl{} {}{} {{}}", params, ty, ty_params))
177 ty_params: Option<ast::GenericParamList>,
179 let ty_params = ty_params.map_or_else(String::new, |params| params.to_string());
180 ast_from_text(&format!("impl{2} {} for {}{2} {{}}", trait_, ty, ty_params))
183 pub(crate) fn generic_arg_list() -> ast::GenericArgList {
184 ast_from_text("const S: T<> = ();")
187 pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
188 ast_from_text(&format!("use {};", name_ref))
191 pub fn path_segment_ty(type_ref: ast::Type, trait_ref: Option<ast::PathType>) -> ast::PathSegment {
192 let text = match trait_ref {
193 Some(trait_ref) => format!("fn f(x: <{} as {}>) {{}}", type_ref, trait_ref),
194 None => format!("fn f(x: <{}>) {{}}", type_ref),
199 pub fn path_segment_self() -> ast::PathSegment {
200 ast_from_text("use self;")
203 pub fn path_segment_super() -> ast::PathSegment {
204 ast_from_text("use super;")
207 pub fn path_segment_crate() -> ast::PathSegment {
208 ast_from_text("use crate;")
211 pub fn path_unqualified(segment: ast::PathSegment) -> ast::Path {
212 ast_from_text(&format!("use {}", segment))
215 pub fn path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path {
216 ast_from_text(&format!("{}::{}", qual, segment))
218 // FIXME: path concatenation operation doesn't make sense as AST op.
219 pub fn path_concat(first: ast::Path, second: ast::Path) -> ast::Path {
220 ast_from_text(&format!("{}::{}", first, second))
223 pub fn path_from_segments(
224 segments: impl IntoIterator<Item = ast::PathSegment>,
227 let segments = segments.into_iter().map(|it| it.syntax().clone()).join("::");
228 ast_from_text(&if is_abs {
229 format!("fn f(x: ::{}) {{}}", segments)
231 format!("fn f(x: {}) {{}}", segments)
235 pub fn join_paths(paths: impl IntoIterator<Item = ast::Path>) -> ast::Path {
236 let paths = paths.into_iter().map(|it| it.syntax().clone()).join("::");
237 ast_from_text(&format!("use {};", paths))
240 // FIXME: should not be pub
241 pub fn path_from_text(text: &str) -> ast::Path {
242 ast_from_text(&format!("fn main() {{ let test = {}; }}", text))
245 pub fn use_tree_glob() -> ast::UseTree {
246 ast_from_text("use *;")
250 use_tree_list: Option<ast::UseTreeList>,
251 alias: Option<ast::Rename>,
254 let mut buf = "use ".to_string();
255 buf += &path.syntax().to_string();
256 if let Some(use_tree_list) = use_tree_list {
257 format_to!(buf, "::{}", use_tree_list);
263 if let Some(alias) = alias {
264 format_to!(buf, " {}", alias);
269 pub fn use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList {
270 let use_trees = use_trees.into_iter().map(|it| it.syntax().clone()).join(", ");
271 ast_from_text(&format!("use {{{}}};", use_trees))
274 pub fn use_(visibility: Option<ast::Visibility>, use_tree: ast::UseTree) -> ast::Use {
275 let visibility = match visibility {
276 None => String::new(),
277 Some(it) => format!("{} ", it),
279 ast_from_text(&format!("{}use {};", visibility, use_tree))
282 pub fn record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr {
283 ast_from_text(&format!("fn f() {{ {} {} }}", path, fields))
286 pub fn record_expr_field_list(
287 fields: impl IntoIterator<Item = ast::RecordExprField>,
288 ) -> ast::RecordExprFieldList {
289 let fields = fields.into_iter().join(", ");
290 ast_from_text(&format!("fn f() {{ S {{ {} }} }}", fields))
293 pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField {
295 Some(expr) => from_text(&format!("{}: {}", name, expr)),
296 None => from_text(&name.to_string()),
299 fn from_text(text: &str) -> ast::RecordExprField {
300 ast_from_text(&format!("fn f() {{ S {{ {}, }} }}", text))
305 visibility: Option<ast::Visibility>,
308 ) -> ast::RecordField {
309 let visibility = match visibility {
310 None => String::new(),
311 Some(it) => format!("{} ", it),
313 ast_from_text(&format!("struct S {{ {}{}: {}, }}", visibility, name, ty))
318 stmts: impl IntoIterator<Item = ast::Stmt>,
319 tail_expr: Option<ast::Expr>,
320 ) -> ast::BlockExpr {
321 let mut buf = "{\n".to_string();
322 for stmt in stmts.into_iter() {
323 format_to!(buf, " {}\n", stmt);
325 if let Some(tail_expr) = tail_expr {
326 format_to!(buf, " {}\n", tail_expr);
329 ast_from_text(&format!("fn f() {}", buf))
332 /// Ideally this function wouldn't exist since it involves manual indenting.
333 /// It differs from `make::block_expr` by also supporting comments.
335 /// FIXME: replace usages of this with the mutable syntax tree API
336 pub fn hacky_block_expr_with_comments(
337 elements: impl IntoIterator<Item = crate::SyntaxElement>,
338 tail_expr: Option<ast::Expr>,
339 ) -> ast::BlockExpr {
340 let mut buf = "{\n".to_string();
341 for node_or_token in elements.into_iter() {
342 match node_or_token {
343 rowan::NodeOrToken::Node(n) => format_to!(buf, " {}\n", n),
344 rowan::NodeOrToken::Token(t) if t.kind() == SyntaxKind::COMMENT => {
345 format_to!(buf, " {}\n", t)
350 if let Some(tail_expr) = tail_expr {
351 format_to!(buf, " {}\n", tail_expr);
354 ast_from_text(&format!("fn f() {}", buf))
357 pub fn expr_unit() -> ast::Expr {
360 pub fn expr_literal(text: &str) -> ast::Literal {
361 assert_eq!(text.trim(), text);
362 ast_from_text(&format!("fn f() {{ let _ = {}; }}", text))
365 pub fn expr_empty_block() -> ast::Expr {
368 pub fn expr_path(path: ast::Path) -> ast::Expr {
369 expr_from_text(&path.to_string())
371 pub fn expr_continue() -> ast::Expr {
372 expr_from_text("continue")
374 // Consider `op: SyntaxKind` instead for nicer syntax at the call-site?
375 pub fn expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr {
376 expr_from_text(&format!("{} {} {}", lhs, op, rhs))
378 pub fn expr_break(expr: Option<ast::Expr>) -> ast::Expr {
380 Some(expr) => expr_from_text(&format!("break {}", expr)),
381 None => expr_from_text("break"),
384 pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
386 Some(expr) => expr_from_text(&format!("return {}", expr)),
387 None => expr_from_text("return"),
390 pub fn expr_try(expr: ast::Expr) -> ast::Expr {
391 expr_from_text(&format!("{}?", expr))
393 pub fn expr_await(expr: ast::Expr) -> ast::Expr {
394 expr_from_text(&format!("{}.await", expr))
396 pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
397 expr_from_text(&format!("match {} {}", expr, match_arm_list))
400 condition: ast::Condition,
401 then_branch: ast::BlockExpr,
402 else_branch: Option<ast::ElseBranch>,
404 let else_branch = match else_branch {
405 Some(ast::ElseBranch::Block(block)) => format!("else {}", block),
406 Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {}", if_expr),
407 None => String::new(),
409 expr_from_text(&format!("if {} {} {}", condition, then_branch, else_branch))
411 pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr {
412 expr_from_text(&format!("for {} in {} {}", pat, expr, block))
415 pub fn expr_loop(block: ast::BlockExpr) -> ast::Expr {
416 expr_from_text(&format!("loop {}", block))
419 pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
420 let token = token(op);
421 expr_from_text(&format!("{}{}", token, expr))
423 pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
424 expr_from_text(&format!("{}{}", f, arg_list))
426 pub fn expr_method_call(
428 method: ast::NameRef,
429 arg_list: ast::ArgList,
431 expr_from_text(&format!("{}.{}{}", receiver, method, arg_list))
433 pub fn expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
434 expr_from_text(&format!("{}!{}", f, arg_list))
436 pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
437 expr_from_text(&if exclusive { format!("&mut {}", expr) } else { format!("&{}", expr) })
439 pub fn expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr {
440 let params = pats.into_iter().join(", ");
441 expr_from_text(&format!("|{}| {}", params, expr))
443 pub fn expr_field(receiver: ast::Expr, field: &str) -> ast::Expr {
444 expr_from_text(&format!("{}.{}", receiver, field))
446 pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
447 expr_from_text(&format!("({})", expr))
449 pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr {
450 let expr = elements.into_iter().format(", ");
451 expr_from_text(&format!("({})", expr))
453 pub fn expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
454 expr_from_text(&format!("{} = {}", lhs, rhs))
456 fn expr_from_text(text: &str) -> ast::Expr {
457 ast_from_text(&format!("const C: () = {};", text))
460 pub fn condition(expr: ast::Expr, pattern: Option<ast::Pat>) -> ast::Condition {
462 None => ast_from_text(&format!("const _: () = while {} {{}};", expr)),
464 ast_from_text(&format!("const _: () = while let {} = {} {{}};", pattern, expr))
469 pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
470 ast_from_text(&format!("fn main() {{ ()({}) }}", args.into_iter().format(", ")))
473 pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
474 let mut s = String::from("fn f(");
481 format_to!(s, "{}", name);
486 pub fn wildcard_pat() -> ast::WildcardPat {
487 return from_text("_");
489 fn from_text(text: &str) -> ast::WildcardPat {
490 ast_from_text(&format!("fn f({}: ())", text))
494 pub fn literal_pat(lit: &str) -> ast::LiteralPat {
495 return from_text(lit);
497 fn from_text(text: &str) -> ast::LiteralPat {
498 ast_from_text(&format!("fn f() {{ match x {{ {} => {{}} }} }}", text))
502 /// Creates a tuple of patterns from an iterator of patterns.
504 /// Invariant: `pats` must be length > 0
505 pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
506 let mut count: usize = 0;
507 let mut pats_str = pats.into_iter().inspect(|_| count += 1).join(", ");
511 return from_text(&format!("({})", pats_str));
513 fn from_text(text: &str) -> ast::TuplePat {
514 ast_from_text(&format!("fn f({}: ())", text))
518 pub fn tuple_struct_pat(
520 pats: impl IntoIterator<Item = ast::Pat>,
521 ) -> ast::TupleStructPat {
522 let pats_str = pats.into_iter().join(", ");
523 return from_text(&format!("{}({})", path, pats_str));
525 fn from_text(text: &str) -> ast::TupleStructPat {
526 ast_from_text(&format!("fn f({}: ())", text))
530 pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
531 let pats_str = pats.into_iter().join(", ");
532 return from_text(&format!("{} {{ {} }}", path, pats_str));
534 fn from_text(text: &str) -> ast::RecordPat {
535 ast_from_text(&format!("fn f({}: ())", text))
539 pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
540 ast_from_text(&format!("fn f({} {}: ()))", path, fields))
543 pub fn record_pat_field_list(
544 fields: impl IntoIterator<Item = ast::RecordPatField>,
545 ) -> ast::RecordPatFieldList {
546 let fields = fields.into_iter().join(", ");
547 ast_from_text(&format!("fn f(S {{ {} }}: ()))", fields))
550 pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
551 ast_from_text(&format!("fn f(S {{ {}: {} }}: ()))", name_ref, pat))
554 /// Returns a `BindPat` if the path has just one segment, a `PathPat` otherwise.
555 pub fn path_pat(path: ast::Path) -> ast::Pat {
556 return from_text(&path.to_string());
557 fn from_text(text: &str) -> ast::Pat {
558 ast_from_text(&format!("fn f({}: ())", text))
563 pats: impl IntoIterator<Item = ast::Pat>,
564 guard: Option<ast::Expr>,
567 let pats_str = pats.into_iter().join(" | ");
569 Some(guard) => from_text(&format!("{} if {} => {}", pats_str, guard, expr)),
570 None => from_text(&format!("{} => {}", pats_str, expr)),
573 fn from_text(text: &str) -> ast::MatchArm {
574 ast_from_text(&format!("fn f() {{ match () {{{}}} }}", text))
578 pub fn match_arm_with_guard(
579 pats: impl IntoIterator<Item = ast::Pat>,
583 let pats_str = pats.into_iter().join(" | ");
584 return from_text(&format!("{} if {} => {}", pats_str, guard, expr));
586 fn from_text(text: &str) -> ast::MatchArm {
587 ast_from_text(&format!("fn f() {{ match () {{{}}} }}", text))
591 pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
595 let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
596 let comma = if needs_comma { "," } else { "" };
597 format!(" {}{}\n", arm.syntax(), comma)
599 .collect::<String>();
600 return from_text(&arms_str);
602 fn from_text(text: &str) -> ast::MatchArmList {
603 ast_from_text(&format!("fn f() {{ match () {{\n{}}} }}", text))
609 bounds: impl IntoIterator<Item = ast::TypeBound>,
610 ) -> ast::WherePred {
611 let bounds = bounds.into_iter().join(" + ");
612 return from_text(&format!("{}: {}", path, bounds));
614 fn from_text(text: &str) -> ast::WherePred {
615 ast_from_text(&format!("fn f() where {} {{ }}", text))
619 pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause {
620 let preds = preds.into_iter().join(", ");
621 return from_text(preds.as_str());
623 fn from_text(text: &str) -> ast::WhereClause {
624 ast_from_text(&format!("fn f() where {} {{ }}", text))
630 ty: Option<ast::Type>,
631 initializer: Option<ast::Expr>,
633 let mut text = String::new();
634 format_to!(text, "let {}", pattern);
635 if let Some(ty) = ty {
636 format_to!(text, ": {}", ty);
639 Some(it) => format_to!(text, " = {};", it),
640 None => format_to!(text, ";"),
642 ast_from_text(&format!("fn f() {{ {} }}", text))
644 pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
645 let semi = if expr.is_block_like() { "" } else { ";" };
646 ast_from_text(&format!("fn f() {{ {}{} (); }}", expr, semi))
650 visibility: Option<ast::Visibility>,
655 let visibility = match visibility {
656 None => String::new(),
657 Some(it) => format!("{} ", it),
659 ast_from_text(&format!("{} const {}: {} = {};", visibility, name, ty, expr))
662 pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
663 ast_from_text(&format!("fn f({}: {}) {{ }}", pat, ty))
666 pub fn self_param() -> ast::SelfParam {
667 ast_from_text("fn f(&self) { }")
670 pub fn ret_type(ty: ast::Type) -> ast::RetType {
671 ast_from_text(&format!("fn f() -> {} {{ }}", ty))
675 self_param: Option<ast::SelfParam>,
676 pats: impl IntoIterator<Item = ast::Param>,
677 ) -> ast::ParamList {
678 let args = pats.into_iter().join(", ");
679 let list = match self_param {
680 Some(self_param) if args.is_empty() => format!("fn f({}) {{ }}", self_param),
681 Some(self_param) => format!("fn f({}, {}) {{ }}", self_param, args),
682 None => format!("fn f({}) {{ }}", args),
687 pub fn type_param(name: ast::Name, ty: Option<ast::TypeBoundList>) -> ast::TypeParam {
688 let bound = match ty {
689 Some(it) => format!(": {}", it),
690 None => String::new(),
692 ast_from_text(&format!("fn f<{}{}>() {{ }}", name, bound))
695 pub fn lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam {
696 ast_from_text(&format!("fn f<{}>() {{ }}", lifetime))
699 pub fn generic_param_list(
700 pats: impl IntoIterator<Item = ast::GenericParam>,
701 ) -> ast::GenericParamList {
702 let args = pats.into_iter().join(", ");
703 ast_from_text(&format!("fn f<{}>() {{ }}", args))
706 pub fn visibility_pub_crate() -> ast::Visibility {
707 ast_from_text("pub(crate) struct S")
710 pub fn visibility_pub() -> ast::Visibility {
711 ast_from_text("pub struct S")
714 pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
715 let fields = fields.into_iter().join(", ");
716 ast_from_text(&format!("struct f({});", fields))
719 pub fn record_field_list(
720 fields: impl IntoIterator<Item = ast::RecordField>,
721 ) -> ast::RecordFieldList {
722 let fields = fields.into_iter().join(", ");
723 ast_from_text(&format!("struct f {{ {} }}", fields))
726 pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
727 let visibility = match visibility {
728 None => String::new(),
729 Some(it) => format!("{} ", it),
731 ast_from_text(&format!("struct f({}{});", visibility, ty))
734 pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
735 let field_list = match field_list {
736 None => String::new(),
737 Some(it) => format!("{}", it),
739 ast_from_text(&format!("enum f {{ {}{} }}", name, field_list))
743 visibility: Option<ast::Visibility>,
745 type_params: Option<ast::GenericParamList>,
746 params: ast::ParamList,
747 body: ast::BlockExpr,
748 ret_type: Option<ast::RetType>,
751 let type_params = match type_params {
752 Some(type_params) => format!("{}", type_params),
755 let ret_type = match ret_type {
756 Some(ret_type) => format!("{} ", ret_type),
759 let visibility = match visibility {
760 None => String::new(),
761 Some(it) => format!("{} ", it),
764 let async_literal = if is_async { "async " } else { "" };
766 ast_from_text(&format!(
767 "{}{}fn {}{}{} {}{}",
768 visibility, async_literal, fn_name, type_params, params, ret_type, body
773 visibility: Option<ast::Visibility>,
774 strukt_name: ast::Name,
775 generic_param_list: Option<ast::GenericParamList>,
776 field_list: ast::FieldList,
778 let semicolon = if matches!(field_list, ast::FieldList::TupleFieldList(_)) { ";" } else { "" };
779 let type_params = generic_param_list.map_or_else(String::new, |it| it.to_string());
780 let visibility = match visibility {
781 None => String::new(),
782 Some(it) => format!("{} ", it),
785 ast_from_text(&format!(
787 visibility, strukt_name, type_params, field_list, semicolon
791 fn ast_from_text<N: AstNode>(text: &str) -> N {
792 let parse = SourceFile::parse(text);
793 let node = match parse.tree().syntax().descendants().find_map(N::cast) {
796 panic!("Failed to make ast node `{}` from text {}", std::any::type_name::<N>(), text)
799 let node = node.clone_subtree();
800 assert_eq!(node.syntax().text_range().start(), 0.into());
804 pub fn token(kind: SyntaxKind) -> SyntaxToken {
809 .descendants_with_tokens()
810 .filter_map(|it| it.into_token())
811 .find(|it| it.kind() == kind)
812 .unwrap_or_else(|| panic!("unhandled token: {:?}", kind))
816 use once_cell::sync::Lazy;
818 use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
820 pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
822 "const C: <()>::Item = (1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p)\n;\n\n",
826 pub fn single_space() -> SyntaxToken {
831 .descendants_with_tokens()
832 .filter_map(|it| it.into_token())
833 .find(|it| it.kind() == WHITESPACE && it.text() == " ")
837 pub fn whitespace(text: &str) -> SyntaxToken {
838 assert!(text.trim().is_empty());
839 let sf = SourceFile::parse(text).ok().unwrap();
840 sf.syntax().clone_for_update().first_child_or_token().unwrap().into_token().unwrap()
843 pub fn doc_comment(text: &str) -> SyntaxToken {
844 assert!(!text.trim().is_empty());
845 let sf = SourceFile::parse(text).ok().unwrap();
846 sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
849 pub fn literal(text: &str) -> SyntaxToken {
850 assert_eq!(text.trim(), text);
851 let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {}; }}", text));
852 lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
855 pub fn single_newline() -> SyntaxToken {
856 let res = SOURCE_FILE
860 .descendants_with_tokens()
861 .filter_map(|it| it.into_token())
862 .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
868 pub fn blank_line() -> SyntaxToken {
873 .descendants_with_tokens()
874 .filter_map(|it| it.into_token())
875 .find(|it| it.kind() == WHITESPACE && it.text() == "\n\n")
879 pub struct WsBuilder(SourceFile);
882 pub fn new(text: &str) -> WsBuilder {
883 WsBuilder(SourceFile::parse(text).ok().unwrap())
885 pub fn ws(&self) -> SyntaxToken {
886 self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()