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 probably doesn't belong in this module.
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;
15 use crate::{ast, AstNode, SourceFile, SyntaxKind, SyntaxNode, SyntaxToken};
17 pub fn name(text: &str) -> ast::Name {
18 ast_from_text(&format!("mod {};", text))
21 pub fn name_ref(text: &str) -> ast::NameRef {
22 ast_from_text(&format!("fn f() {{ {}; }}", text))
24 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
26 pub fn ty(text: &str) -> ast::Type {
27 ast_from_text(&format!("fn f() -> {} {{}}", text))
29 pub fn ty_unit() -> ast::Type {
32 pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
33 let mut count: usize = 0;
34 let mut contents = types.into_iter().inspect(|_| count += 1).join(", ");
39 ty(&format!("({})", contents))
41 // FIXME: handle path to type
42 pub fn ty_generic(name: ast::NameRef, types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
43 let contents = types.into_iter().join(", ");
44 ty(&format!("{}<{}>", name, contents))
46 pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
47 ty(&if exclusive { format!("&mut {}", target) } else { format!("&{}", target) })
50 pub fn assoc_item_list() -> ast::AssocItemList {
51 ast_from_text("impl C for D {};")
54 pub fn impl_trait(trait_: ast::Path, ty: ast::Path) -> ast::Impl {
55 ast_from_text(&format!("impl {} for {} {{}}", trait_, ty))
58 pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
59 ast_from_text(&format!("use {};", name_ref))
62 pub fn path_segment_self() -> ast::PathSegment {
63 ast_from_text("use self;")
66 pub fn path_segment_super() -> ast::PathSegment {
67 ast_from_text("use super;")
70 pub fn path_segment_crate() -> ast::PathSegment {
71 ast_from_text("use crate;")
74 pub fn path_unqualified(segment: ast::PathSegment) -> ast::Path {
75 ast_from_text(&format!("use {}", segment))
78 pub fn path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path {
79 ast_from_text(&format!("{}::{}", qual, segment))
82 pub fn path_concat(first: ast::Path, second: ast::Path) -> ast::Path {
83 ast_from_text(&format!("{}::{}", first, second))
86 pub fn path_from_segments(
87 segments: impl IntoIterator<Item = ast::PathSegment>,
90 let segments = segments.into_iter().map(|it| it.syntax().clone()).join("::");
91 ast_from_text(&if is_abs {
92 format!("use ::{};", segments)
94 format!("use {};", segments)
98 pub fn path_from_text(text: &str) -> ast::Path {
99 ast_from_text(&format!("fn main() {{ let test = {}; }}", text))
102 pub fn glob_use_tree() -> ast::UseTree {
103 ast_from_text("use *;")
108 use_tree_list: Option<ast::UseTreeList>,
109 alias: Option<ast::Rename>,
112 let mut buf = "use ".to_string();
113 buf += &path.syntax().to_string();
114 if let Some(use_tree_list) = use_tree_list {
115 format_to!(buf, "::{}", use_tree_list);
121 if let Some(alias) = alias {
122 format_to!(buf, " {}", alias);
127 pub fn use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList {
128 let use_trees = use_trees.into_iter().map(|it| it.syntax().clone()).join(", ");
129 ast_from_text(&format!("use {{{}}};", use_trees))
132 pub fn use_(visibility: Option<ast::Visibility>, use_tree: ast::UseTree) -> ast::Use {
133 let visibility = match visibility {
134 None => String::new(),
135 Some(it) => format!("{} ", it),
137 ast_from_text(&format!("{}use {};", visibility, use_tree))
140 pub fn record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr {
141 ast_from_text(&format!("fn f() {{ {} {} }}", path, fields))
144 pub fn record_expr_field_list(
145 fields: impl IntoIterator<Item = ast::RecordExprField>,
146 ) -> ast::RecordExprFieldList {
147 let fields = fields.into_iter().join(", ");
148 ast_from_text(&format!("fn f() {{ S {{ {} }} }}", fields))
151 pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField {
153 Some(expr) => from_text(&format!("{}: {}", name, expr)),
154 None => from_text(&name.to_string()),
157 fn from_text(text: &str) -> ast::RecordExprField {
158 ast_from_text(&format!("fn f() {{ S {{ {}, }} }}", text))
163 visibility: Option<ast::Visibility>,
166 ) -> ast::RecordField {
167 let visibility = match visibility {
168 None => String::new(),
169 Some(it) => format!("{} ", it),
171 ast_from_text(&format!("struct S {{ {}{}: {}, }}", visibility, name, ty))
175 stmts: impl IntoIterator<Item = ast::Stmt>,
176 tail_expr: Option<ast::Expr>,
177 ) -> ast::BlockExpr {
178 let mut buf = "{\n".to_string();
179 for stmt in stmts.into_iter() {
180 format_to!(buf, " {}\n", stmt);
182 if let Some(tail_expr) = tail_expr {
183 format_to!(buf, " {}\n", tail_expr)
186 ast_from_text(&format!("fn f() {}", buf))
189 pub fn expr_unit() -> ast::Expr {
192 pub fn expr_literal(text: &str) -> ast::Literal {
193 assert_eq!(text.trim(), text);
194 ast_from_text(&format!("fn f() {{ let _ = {}; }}", text))
197 pub fn expr_empty_block() -> ast::Expr {
200 pub fn expr_unimplemented() -> ast::Expr {
201 expr_from_text("unimplemented!()")
203 pub fn expr_unreachable() -> ast::Expr {
204 expr_from_text("unreachable!()")
206 pub fn expr_todo() -> ast::Expr {
207 expr_from_text("todo!()")
209 pub fn expr_path(path: ast::Path) -> ast::Expr {
210 expr_from_text(&path.to_string())
212 pub fn expr_continue() -> ast::Expr {
213 expr_from_text("continue")
215 pub fn expr_break(expr: Option<ast::Expr>) -> ast::Expr {
217 Some(expr) => expr_from_text(&format!("break {}", expr)),
218 None => expr_from_text("break"),
221 pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
223 Some(expr) => expr_from_text(&format!("return {}", expr)),
224 None => expr_from_text("return"),
227 pub fn expr_try(expr: ast::Expr) -> ast::Expr {
228 expr_from_text(&format!("{}?", expr))
230 pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
231 expr_from_text(&format!("match {} {}", expr, match_arm_list))
234 condition: ast::Condition,
235 then_branch: ast::BlockExpr,
236 else_branch: Option<ast::ElseBranch>,
238 let else_branch = match else_branch {
239 Some(ast::ElseBranch::Block(block)) => format!("else {}", block),
240 Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {}", if_expr),
241 None => String::new(),
243 expr_from_text(&format!("if {} {} {}", condition, then_branch, else_branch))
245 pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr {
246 expr_from_text(&format!("for {} in {} {}", pat, expr, block))
248 pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
249 let token = token(op);
250 expr_from_text(&format!("{}{}", token, expr))
252 pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
253 expr_from_text(&format!("{}{}", f, arg_list))
255 pub fn expr_method_call(receiver: ast::Expr, method: &str, arg_list: ast::ArgList) -> ast::Expr {
256 expr_from_text(&format!("{}.{}{}", receiver, method, arg_list))
258 pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
259 expr_from_text(&if exclusive { format!("&mut {}", expr) } else { format!("&{}", expr) })
261 pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
262 expr_from_text(&format!("({})", expr))
264 pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr {
265 let expr = elements.into_iter().format(", ");
266 expr_from_text(&format!("({})", expr))
268 fn expr_from_text(text: &str) -> ast::Expr {
269 ast_from_text(&format!("const C: () = {};", text))
272 pub fn condition(expr: ast::Expr, pattern: Option<ast::Pat>) -> ast::Condition {
274 None => ast_from_text(&format!("const _: () = while {} {{}};", expr)),
276 ast_from_text(&format!("const _: () = while let {} = {} {{}};", pattern, expr))
281 pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
282 ast_from_text(&format!("fn main() {{ ()({}) }}", args.into_iter().format(", ")))
285 pub fn ident_pat(name: ast::Name) -> ast::IdentPat {
286 return from_text(&name.text());
288 fn from_text(text: &str) -> ast::IdentPat {
289 ast_from_text(&format!("fn f({}: ())", text))
292 pub fn ident_mut_pat(name: ast::Name) -> ast::IdentPat {
293 return from_text(&name.text());
295 fn from_text(text: &str) -> ast::IdentPat {
296 ast_from_text(&format!("fn f(mut {}: ())", text))
300 pub fn wildcard_pat() -> ast::WildcardPat {
301 return from_text("_");
303 fn from_text(text: &str) -> ast::WildcardPat {
304 ast_from_text(&format!("fn f({}: ())", text))
308 pub fn literal_pat(lit: &str) -> ast::LiteralPat {
309 return from_text(lit);
311 fn from_text(text: &str) -> ast::LiteralPat {
312 ast_from_text(&format!("fn f() {{ match x {{ {} => {{}} }} }}", text))
316 /// Creates a tuple of patterns from an iterator of patterns.
318 /// Invariant: `pats` must be length > 0
319 pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
320 let mut count: usize = 0;
321 let mut pats_str = pats.into_iter().inspect(|_| count += 1).join(", ");
325 return from_text(&format!("({})", pats_str));
327 fn from_text(text: &str) -> ast::TuplePat {
328 ast_from_text(&format!("fn f({}: ())", text))
332 pub fn tuple_struct_pat(
334 pats: impl IntoIterator<Item = ast::Pat>,
335 ) -> ast::TupleStructPat {
336 let pats_str = pats.into_iter().join(", ");
337 return from_text(&format!("{}({})", path, pats_str));
339 fn from_text(text: &str) -> ast::TupleStructPat {
340 ast_from_text(&format!("fn f({}: ())", text))
344 pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
345 let pats_str = pats.into_iter().join(", ");
346 return from_text(&format!("{} {{ {} }}", path, pats_str));
348 fn from_text(text: &str) -> ast::RecordPat {
349 ast_from_text(&format!("fn f({}: ())", text))
353 pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
354 ast_from_text(&format!("fn f({} {}: ()))", path, fields))
357 pub fn record_pat_field_list(
358 fields: impl IntoIterator<Item = ast::RecordPatField>,
359 ) -> ast::RecordPatFieldList {
360 let fields = fields.into_iter().join(", ");
361 ast_from_text(&format!("fn f(S {{ {} }}: ()))", fields))
364 pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
365 ast_from_text(&format!("fn f(S {{ {}: {} }}: ()))", name_ref, pat))
368 /// Returns a `BindPat` if the path has just one segment, a `PathPat` otherwise.
369 pub fn path_pat(path: ast::Path) -> ast::Pat {
370 return from_text(&path.to_string());
371 fn from_text(text: &str) -> ast::Pat {
372 ast_from_text(&format!("fn f({}: ())", text))
376 pub fn match_arm(pats: impl IntoIterator<Item = ast::Pat>, expr: ast::Expr) -> ast::MatchArm {
377 let pats_str = pats.into_iter().join(" | ");
378 return from_text(&format!("{} => {}", pats_str, expr));
380 fn from_text(text: &str) -> ast::MatchArm {
381 ast_from_text(&format!("fn f() {{ match () {{{}}} }}", text))
385 pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
389 let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
390 let comma = if needs_comma { "," } else { "" };
391 format!(" {}{}\n", arm.syntax(), comma)
393 .collect::<String>();
394 return from_text(&arms_str);
396 fn from_text(text: &str) -> ast::MatchArmList {
397 ast_from_text(&format!("fn f() {{ match () {{\n{}}} }}", text))
403 bounds: impl IntoIterator<Item = ast::TypeBound>,
404 ) -> ast::WherePred {
405 let bounds = bounds.into_iter().join(" + ");
406 return from_text(&format!("{}: {}", path, bounds));
408 fn from_text(text: &str) -> ast::WherePred {
409 ast_from_text(&format!("fn f() where {} {{ }}", text))
413 pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause {
414 let preds = preds.into_iter().join(", ");
415 return from_text(preds.as_str());
417 fn from_text(text: &str) -> ast::WhereClause {
418 ast_from_text(&format!("fn f() where {} {{ }}", text))
422 pub fn let_stmt(pattern: ast::Pat, initializer: Option<ast::Expr>) -> ast::LetStmt {
423 let text = match initializer {
424 Some(it) => format!("let {} = {};", pattern, it),
425 None => format!("let {};", pattern),
427 ast_from_text(&format!("fn f() {{ {} }}", text))
429 pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
430 let semi = if expr.is_block_like() { "" } else { ";" };
431 ast_from_text(&format!("fn f() {{ {}{} (); }}", expr, semi))
434 pub fn token(kind: SyntaxKind) -> SyntaxToken {
439 .descendants_with_tokens()
440 .filter_map(|it| it.into_token())
441 .find(|it| it.kind() == kind)
442 .unwrap_or_else(|| panic!("unhandled token: {:?}", kind))
445 pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
446 ast_from_text(&format!("fn f({}: {}) {{ }}", pat, ty))
449 pub fn ret_type(ty: ast::Type) -> ast::RetType {
450 ast_from_text(&format!("fn f() -> {} {{ }}", ty))
454 self_param: Option<ast::SelfParam>,
455 pats: impl IntoIterator<Item = ast::Param>,
456 ) -> ast::ParamList {
457 let args = pats.into_iter().join(", ");
458 let list = match self_param {
459 Some(self_param) if args.is_empty() => format!("fn f({}) {{ }}", self_param),
460 Some(self_param) => format!("fn f({}, {}) {{ }}", self_param, args),
461 None => format!("fn f({}) {{ }}", args),
466 pub fn generic_param(name: String, ty: Option<ast::TypeBoundList>) -> ast::GenericParam {
467 let bound = match ty {
468 Some(it) => format!(": {}", it),
469 None => String::new(),
471 ast_from_text(&format!("fn f<{}{}>() {{ }}", name, bound))
474 pub fn generic_param_list(
475 pats: impl IntoIterator<Item = ast::GenericParam>,
476 ) -> ast::GenericParamList {
477 let args = pats.into_iter().join(", ");
478 ast_from_text(&format!("fn f<{}>() {{ }}", args))
481 pub fn visibility_pub_crate() -> ast::Visibility {
482 ast_from_text("pub(crate) struct S")
485 pub fn visibility_pub() -> ast::Visibility {
486 ast_from_text("pub struct S")
489 pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
490 let fields = fields.into_iter().join(", ");
491 ast_from_text(&format!("struct f({});", fields))
494 pub fn record_field_list(
495 fields: impl IntoIterator<Item = ast::RecordField>,
496 ) -> ast::RecordFieldList {
497 let fields = fields.into_iter().join(", ");
498 ast_from_text(&format!("struct f {{ {} }}", fields))
501 pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
502 let visibility = match visibility {
503 None => String::new(),
504 Some(it) => format!("{} ", it),
506 ast_from_text(&format!("struct f({}{});", visibility, ty))
509 pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
510 let field_list = match field_list {
511 None => String::new(),
512 Some(it) => format!("{}", it),
514 ast_from_text(&format!("enum f {{ {}{} }}", name, field_list))
518 visibility: Option<ast::Visibility>,
520 type_params: Option<ast::GenericParamList>,
521 params: ast::ParamList,
522 body: ast::BlockExpr,
523 ret_type: Option<ast::RetType>,
526 if let Some(type_params) = type_params { format!("<{}>", type_params) } else { "".into() };
527 let ret_type = if let Some(ret_type) = ret_type { format!("{} ", ret_type) } else { "".into() };
528 let visibility = match visibility {
529 None => String::new(),
530 Some(it) => format!("{} ", it),
533 ast_from_text(&format!(
535 visibility, fn_name, type_params, params, ret_type, body
540 visibility: Option<ast::Visibility>,
541 strukt_name: ast::Name,
542 type_params: Option<ast::GenericParamList>,
543 field_list: ast::FieldList,
545 let semicolon = if matches!(field_list, ast::FieldList::TupleFieldList(_)) { ";" } else { "" };
547 if let Some(type_params) = type_params { format!("<{}>", type_params) } else { "".into() };
548 let visibility = match visibility {
549 None => String::new(),
550 Some(it) => format!("{} ", it),
553 ast_from_text(&format!(
555 visibility, strukt_name, type_params, field_list, semicolon
559 fn ast_from_text<N: AstNode>(text: &str) -> N {
560 let parse = SourceFile::parse(text);
561 let node = match parse.tree().syntax().descendants().find_map(N::cast) {
564 panic!("Failed to make ast node `{}` from text {}", std::any::type_name::<N>(), text)
567 let node = node.syntax().clone();
568 let node = unroot(node);
569 let node = N::cast(node).unwrap();
570 assert_eq!(node.syntax().text_range().start(), 0.into());
574 fn unroot(n: SyntaxNode) -> SyntaxNode {
575 SyntaxNode::new_root(n.green().into())
579 use once_cell::sync::Lazy;
581 use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
583 pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
585 "const C: <()>::Item = (1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p)\n;\n\n",
589 pub fn single_space() -> SyntaxToken {
594 .descendants_with_tokens()
595 .filter_map(|it| it.into_token())
596 .find(|it| it.kind() == WHITESPACE && it.text() == " ")
600 pub fn whitespace(text: &str) -> SyntaxToken {
601 assert!(text.trim().is_empty());
602 let sf = SourceFile::parse(text).ok().unwrap();
603 sf.syntax().clone_for_update().first_child_or_token().unwrap().into_token().unwrap()
606 pub fn doc_comment(text: &str) -> SyntaxToken {
607 assert!(!text.trim().is_empty());
608 let sf = SourceFile::parse(text).ok().unwrap();
609 sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
612 pub fn literal(text: &str) -> SyntaxToken {
613 assert_eq!(text.trim(), text);
614 let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {}; }}", text));
615 lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
618 pub fn single_newline() -> SyntaxToken {
619 let res = SOURCE_FILE
623 .descendants_with_tokens()
624 .filter_map(|it| it.into_token())
625 .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
631 pub fn blank_line() -> SyntaxToken {
636 .descendants_with_tokens()
637 .filter_map(|it| it.into_token())
638 .find(|it| it.kind() == WHITESPACE && it.text() == "\n\n")
642 pub struct WsBuilder(SourceFile);
645 pub fn new(text: &str) -> WsBuilder {
646 WsBuilder(SourceFile::parse(text).ok().unwrap())
648 pub fn ws(&self) -> SyntaxToken {
649 self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()