1 //! This module contains free-standing functions for creating AST fragments out
2 //! of smaller pieces.
3 //!
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.
7 //!
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};
14
15 use crate::{ast, AstNode, SourceFile, SyntaxKind, SyntaxToken};
16
17 /// While the parent module defines basic atomic "constructors", the `ext`
18 /// module defines shortcuts for common things.
19 ///
20 /// It's named `ext` rather than `shortcuts` just to keep it short.
21 pub mod ext {
22 use super::*;
23
simple_ident_pat(name: ast::Name) -> ast::IdentPat24 pub fn simple_ident_pat(name: ast::Name) -> ast::IdentPat {
25 return from_text(&name.text());
26
27 fn from_text(text: &str) -> ast::IdentPat {
28 ast_from_text(&format!("fn f({}: ())", text))
29 }
30 }
ident_path(ident: &str) -> ast::Path31 pub fn ident_path(ident: &str) -> ast::Path {
32 path_unqualified(path_segment(name_ref(ident)))
33 }
34
path_from_idents<'a>( parts: impl std::iter::IntoIterator<Item = &'a str>, ) -> Option<ast::Path>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)
43 });
44 Some(path)
45 }
46
field_from_idents<'a>( parts: impl std::iter::IntoIterator<Item = &'a str>, ) -> Option<ast::Expr>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));
53 Some(expr)
54 }
55
expr_unreachable() -> ast::Expr56 pub fn expr_unreachable() -> ast::Expr {
57 expr_from_text("unreachable!()")
58 }
expr_todo() -> ast::Expr59 pub fn expr_todo() -> ast::Expr {
60 expr_from_text("todo!()")
61 }
empty_block_expr() -> ast::BlockExpr62 pub fn empty_block_expr() -> ast::BlockExpr {
63 block_expr(None, None)
64 }
65
ty_bool() -> ast::Type66 pub fn ty_bool() -> ast::Type {
67 ty_path(ident_path("bool"))
68 }
ty_option(t: ast::Type) -> ast::Type69 pub fn ty_option(t: ast::Type) -> ast::Type {
70 ty_from_text(&format!("Option<{}>", t))
71 }
ty_result(t: ast::Type, e: ast::Type) -> ast::Type72 pub fn ty_result(t: ast::Type, e: ast::Type) -> ast::Type {
73 ty_from_text(&format!("Result<{}, {}>", t, e))
74 }
75 }
76
name(text: &str) -> ast::Name77 pub fn name(text: &str) -> ast::Name {
78 ast_from_text(&format!("mod {}{};", raw_ident_esc(text), text))
79 }
name_ref(text: &str) -> ast::NameRef80 pub fn name_ref(text: &str) -> ast::NameRef {
81 ast_from_text(&format!("fn f() {{ {}{}; }}", raw_ident_esc(text), text))
82 }
raw_ident_esc(ident: &str) -> &'static str83 fn raw_ident_esc(ident: &str) -> &'static str {
84 let is_keyword = parser::SyntaxKind::from_keyword(ident).is_some();
85 if is_keyword && !matches!(ident, "self" | "crate" | "super" | "Self") {
86 "r#"
87 } else {
88 ""
89 }
90 }
91
lifetime(text: &str) -> ast::Lifetime92 pub fn lifetime(text: &str) -> ast::Lifetime {
93 let mut text = text;
94 let tmp;
95 if never!(!text.starts_with('\'')) {
96 tmp = format!("'{}", text);
97 text = &tmp;
98 }
99 ast_from_text(&format!("fn f<{}>() {{ }}", text))
100 }
101
102 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
103 // `expr_xxx`.
ty(text: &str) -> ast::Type104 pub fn ty(text: &str) -> ast::Type {
105 ty_from_text(text)
106 }
ty_placeholder() -> ast::Type107 pub fn ty_placeholder() -> ast::Type {
108 ty_from_text("_")
109 }
ty_unit() -> ast::Type110 pub fn ty_unit() -> ast::Type {
111 ty_from_text("()")
112 }
ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type113 pub fn ty_tuple(types: impl IntoIterator<Item = ast::Type>) -> ast::Type {
114 let mut count: usize = 0;
115 let mut contents = types.into_iter().inspect(|_| count += 1).join(", ");
116 if count == 1 {
117 contents.push(',');
118 }
119
120 ty_from_text(&format!("({})", contents))
121 }
ty_ref(target: ast::Type, exclusive: bool) -> ast::Type122 pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
123 ty_from_text(&if exclusive { format!("&mut {}", target) } else { format!("&{}", target) })
124 }
ty_path(path: ast::Path) -> ast::Type125 pub fn ty_path(path: ast::Path) -> ast::Type {
126 ty_from_text(&path.to_string())
127 }
ty_from_text(text: &str) -> ast::Type128 fn ty_from_text(text: &str) -> ast::Type {
129 ast_from_text(&format!("type _T = {};", text))
130 }
131
assoc_item_list() -> ast::AssocItemList132 pub fn assoc_item_list() -> ast::AssocItemList {
133 ast_from_text("impl C for D {}")
134 }
135
impl_( ty: ast::Path, params: Option<ast::GenericParamList>, ty_params: Option<ast::GenericParamList>, ) -> ast::Impl136 pub fn impl_(
137 ty: ast::Path,
138 params: Option<ast::GenericParamList>,
139 ty_params: Option<ast::GenericParamList>,
140 ) -> ast::Impl {
141 let params = match params {
142 Some(params) => params.to_string(),
143 None => String::new(),
144 };
145 let ty_params = match ty_params {
146 Some(params) => params.to_string(),
147 None => String::new(),
148 };
149 ast_from_text(&format!("impl{} {}{} {{}}", params, ty, ty_params))
150 }
151
impl_trait( trait_: ast::Path, ty: ast::Path, ty_params: Option<ast::GenericParamList>, ) -> ast::Impl152 pub fn impl_trait(
153 trait_: ast::Path,
154 ty: ast::Path,
155 ty_params: Option<ast::GenericParamList>,
156 ) -> ast::Impl {
157 let ty_params = ty_params.map_or_else(String::new, |params| params.to_string());
158 ast_from_text(&format!("impl{2} {} for {}{2} {{}}", trait_, ty, ty_params))
159 }
160
generic_arg_list() -> ast::GenericArgList161 pub(crate) fn generic_arg_list() -> ast::GenericArgList {
162 ast_from_text("const S: T<> = ();")
163 }
164
path_segment(name_ref: ast::NameRef) -> ast::PathSegment165 pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
166 ast_from_text(&format!("use {};", name_ref))
167 }
168
path_segment_self() -> ast::PathSegment169 pub fn path_segment_self() -> ast::PathSegment {
170 ast_from_text("use self;")
171 }
172
path_segment_super() -> ast::PathSegment173 pub fn path_segment_super() -> ast::PathSegment {
174 ast_from_text("use super;")
175 }
176
path_segment_crate() -> ast::PathSegment177 pub fn path_segment_crate() -> ast::PathSegment {
178 ast_from_text("use crate;")
179 }
180
path_unqualified(segment: ast::PathSegment) -> ast::Path181 pub fn path_unqualified(segment: ast::PathSegment) -> ast::Path {
182 ast_from_text(&format!("use {}", segment))
183 }
184
path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path185 pub fn path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path {
186 ast_from_text(&format!("{}::{}", qual, segment))
187 }
188 // FIXME: path concatenation operation doesn't make sense as AST op.
path_concat(first: ast::Path, second: ast::Path) -> ast::Path189 pub fn path_concat(first: ast::Path, second: ast::Path) -> ast::Path {
190 ast_from_text(&format!("{}::{}", first, second))
191 }
192
path_from_segments( segments: impl IntoIterator<Item = ast::PathSegment>, is_abs: bool, ) -> ast::Path193 pub fn path_from_segments(
194 segments: impl IntoIterator<Item = ast::PathSegment>,
195 is_abs: bool,
196 ) -> ast::Path {
197 let segments = segments.into_iter().map(|it| it.syntax().clone()).join("::");
198 ast_from_text(&if is_abs {
199 format!("use ::{};", segments)
200 } else {
201 format!("use {};", segments)
202 })
203 }
204
join_paths(paths: impl IntoIterator<Item = ast::Path>) -> ast::Path205 pub fn join_paths(paths: impl IntoIterator<Item = ast::Path>) -> ast::Path {
206 let paths = paths.into_iter().map(|it| it.syntax().clone()).join("::");
207 ast_from_text(&format!("use {};", paths))
208 }
209
210 // FIXME: should not be pub
path_from_text(text: &str) -> ast::Path211 pub fn path_from_text(text: &str) -> ast::Path {
212 ast_from_text(&format!("fn main() {{ let test = {}; }}", text))
213 }
214
use_tree_glob() -> ast::UseTree215 pub fn use_tree_glob() -> ast::UseTree {
216 ast_from_text("use *;")
217 }
use_tree( path: ast::Path, use_tree_list: Option<ast::UseTreeList>, alias: Option<ast::Rename>, add_star: bool, ) -> ast::UseTree218 pub fn use_tree(
219 path: ast::Path,
220 use_tree_list: Option<ast::UseTreeList>,
221 alias: Option<ast::Rename>,
222 add_star: bool,
223 ) -> ast::UseTree {
224 let mut buf = "use ".to_string();
225 buf += &path.syntax().to_string();
226 if let Some(use_tree_list) = use_tree_list {
227 format_to!(buf, "::{}", use_tree_list);
228 }
229 if add_star {
230 buf += "::*";
231 }
232
233 if let Some(alias) = alias {
234 format_to!(buf, " {}", alias);
235 }
236 ast_from_text(&buf)
237 }
238
use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList239 pub fn use_tree_list(use_trees: impl IntoIterator<Item = ast::UseTree>) -> ast::UseTreeList {
240 let use_trees = use_trees.into_iter().map(|it| it.syntax().clone()).join(", ");
241 ast_from_text(&format!("use {{{}}};", use_trees))
242 }
243
use_(visibility: Option<ast::Visibility>, use_tree: ast::UseTree) -> ast::Use244 pub fn use_(visibility: Option<ast::Visibility>, use_tree: ast::UseTree) -> ast::Use {
245 let visibility = match visibility {
246 None => String::new(),
247 Some(it) => format!("{} ", it),
248 };
249 ast_from_text(&format!("{}use {};", visibility, use_tree))
250 }
251
record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr252 pub fn record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr {
253 ast_from_text(&format!("fn f() {{ {} {} }}", path, fields))
254 }
255
record_expr_field_list( fields: impl IntoIterator<Item = ast::RecordExprField>, ) -> ast::RecordExprFieldList256 pub fn record_expr_field_list(
257 fields: impl IntoIterator<Item = ast::RecordExprField>,
258 ) -> ast::RecordExprFieldList {
259 let fields = fields.into_iter().join(", ");
260 ast_from_text(&format!("fn f() {{ S {{ {} }} }}", fields))
261 }
262
record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField263 pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField {
264 return match expr {
265 Some(expr) => from_text(&format!("{}: {}", name, expr)),
266 None => from_text(&name.to_string()),
267 };
268
269 fn from_text(text: &str) -> ast::RecordExprField {
270 ast_from_text(&format!("fn f() {{ S {{ {}, }} }}", text))
271 }
272 }
273
record_field( visibility: Option<ast::Visibility>, name: ast::Name, ty: ast::Type, ) -> ast::RecordField274 pub fn record_field(
275 visibility: Option<ast::Visibility>,
276 name: ast::Name,
277 ty: ast::Type,
278 ) -> ast::RecordField {
279 let visibility = match visibility {
280 None => String::new(),
281 Some(it) => format!("{} ", it),
282 };
283 ast_from_text(&format!("struct S {{ {}{}: {}, }}", visibility, name, ty))
284 }
285
286 // TODO
block_expr( stmts: impl IntoIterator<Item = ast::Stmt>, tail_expr: Option<ast::Expr>, ) -> ast::BlockExpr287 pub fn block_expr(
288 stmts: impl IntoIterator<Item = ast::Stmt>,
289 tail_expr: Option<ast::Expr>,
290 ) -> ast::BlockExpr {
291 let mut buf = "{\n".to_string();
292 for stmt in stmts.into_iter() {
293 format_to!(buf, " {}\n", stmt);
294 }
295 if let Some(tail_expr) = tail_expr {
296 format_to!(buf, " {}\n", tail_expr);
297 }
298 buf += "}";
299 ast_from_text(&format!("fn f() {}", buf))
300 }
301
expr_unit() -> ast::Expr302 pub fn expr_unit() -> ast::Expr {
303 expr_from_text("()")
304 }
expr_literal(text: &str) -> ast::Literal305 pub fn expr_literal(text: &str) -> ast::Literal {
306 assert_eq!(text.trim(), text);
307 ast_from_text(&format!("fn f() {{ let _ = {}; }}", text))
308 }
309
expr_empty_block() -> ast::Expr310 pub fn expr_empty_block() -> ast::Expr {
311 expr_from_text("{}")
312 }
expr_path(path: ast::Path) -> ast::Expr313 pub fn expr_path(path: ast::Path) -> ast::Expr {
314 expr_from_text(&path.to_string())
315 }
expr_continue() -> ast::Expr316 pub fn expr_continue() -> ast::Expr {
317 expr_from_text("continue")
318 }
319 // Consider `op: SyntaxKind` instead for nicer syntax at the call-site?
expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr320 pub fn expr_bin_op(lhs: ast::Expr, op: ast::BinaryOp, rhs: ast::Expr) -> ast::Expr {
321 expr_from_text(&format!("{} {} {}", lhs, op, rhs))
322 }
expr_break(expr: Option<ast::Expr>) -> ast::Expr323 pub fn expr_break(expr: Option<ast::Expr>) -> ast::Expr {
324 match expr {
325 Some(expr) => expr_from_text(&format!("break {}", expr)),
326 None => expr_from_text("break"),
327 }
328 }
expr_return(expr: Option<ast::Expr>) -> ast::Expr329 pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
330 match expr {
331 Some(expr) => expr_from_text(&format!("return {}", expr)),
332 None => expr_from_text("return"),
333 }
334 }
expr_try(expr: ast::Expr) -> ast::Expr335 pub fn expr_try(expr: ast::Expr) -> ast::Expr {
336 expr_from_text(&format!("{}?", expr))
337 }
expr_await(expr: ast::Expr) -> ast::Expr338 pub fn expr_await(expr: ast::Expr) -> ast::Expr {
339 expr_from_text(&format!("{}.await", expr))
340 }
expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr341 pub fn expr_match(expr: ast::Expr, match_arm_list: ast::MatchArmList) -> ast::Expr {
342 expr_from_text(&format!("match {} {}", expr, match_arm_list))
343 }
expr_if( condition: ast::Condition, then_branch: ast::BlockExpr, else_branch: Option<ast::ElseBranch>, ) -> ast::Expr344 pub fn expr_if(
345 condition: ast::Condition,
346 then_branch: ast::BlockExpr,
347 else_branch: Option<ast::ElseBranch>,
348 ) -> ast::Expr {
349 let else_branch = match else_branch {
350 Some(ast::ElseBranch::Block(block)) => format!("else {}", block),
351 Some(ast::ElseBranch::IfExpr(if_expr)) => format!("else {}", if_expr),
352 None => String::new(),
353 };
354 expr_from_text(&format!("if {} {} {}", condition, then_branch, else_branch))
355 }
expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr356 pub fn expr_for_loop(pat: ast::Pat, expr: ast::Expr, block: ast::BlockExpr) -> ast::Expr {
357 expr_from_text(&format!("for {} in {} {}", pat, expr, block))
358 }
359
expr_loop(block: ast::BlockExpr) -> ast::Expr360 pub fn expr_loop(block: ast::BlockExpr) -> ast::Expr {
361 expr_from_text(&format!("loop {}", block))
362 }
363
expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr364 pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
365 let token = token(op);
366 expr_from_text(&format!("{}{}", token, expr))
367 }
expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr368 pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
369 expr_from_text(&format!("{}{}", f, arg_list))
370 }
expr_method_call( receiver: ast::Expr, method: ast::NameRef, arg_list: ast::ArgList, ) -> ast::Expr371 pub fn expr_method_call(
372 receiver: ast::Expr,
373 method: ast::NameRef,
374 arg_list: ast::ArgList,
375 ) -> ast::Expr {
376 expr_from_text(&format!("{}.{}{}", receiver, method, arg_list))
377 }
expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr378 pub fn expr_macro_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
379 expr_from_text(&format!("{}!{}", f, arg_list))
380 }
expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr381 pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
382 expr_from_text(&if exclusive { format!("&mut {}", expr) } else { format!("&{}", expr) })
383 }
expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr384 pub fn expr_closure(pats: impl IntoIterator<Item = ast::Param>, expr: ast::Expr) -> ast::Expr {
385 let params = pats.into_iter().join(", ");
386 expr_from_text(&format!("|{}| {}", params, expr))
387 }
expr_field(receiver: ast::Expr, field: &str) -> ast::Expr388 pub fn expr_field(receiver: ast::Expr, field: &str) -> ast::Expr {
389 expr_from_text(&format!("{}.{}", receiver, field))
390 }
expr_paren(expr: ast::Expr) -> ast::Expr391 pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
392 expr_from_text(&format!("({})", expr))
393 }
expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr394 pub fn expr_tuple(elements: impl IntoIterator<Item = ast::Expr>) -> ast::Expr {
395 let expr = elements.into_iter().format(", ");
396 expr_from_text(&format!("({})", expr))
397 }
expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr398 pub fn expr_assignment(lhs: ast::Expr, rhs: ast::Expr) -> ast::Expr {
399 expr_from_text(&format!("{} = {}", lhs, rhs))
400 }
expr_from_text(text: &str) -> ast::Expr401 fn expr_from_text(text: &str) -> ast::Expr {
402 ast_from_text(&format!("const C: () = {};", text))
403 }
404
condition(expr: ast::Expr, pattern: Option<ast::Pat>) -> ast::Condition405 pub fn condition(expr: ast::Expr, pattern: Option<ast::Pat>) -> ast::Condition {
406 match pattern {
407 None => ast_from_text(&format!("const _: () = while {} {{}};", expr)),
408 Some(pattern) => {
409 ast_from_text(&format!("const _: () = while let {} = {} {{}};", pattern, expr))
410 }
411 }
412 }
413
arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList414 pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
415 ast_from_text(&format!("fn main() {{ ()({}) }}", args.into_iter().format(", ")))
416 }
417
ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat418 pub fn ident_pat(ref_: bool, mut_: bool, name: ast::Name) -> ast::IdentPat {
419 let mut s = String::from("fn f(");
420 if ref_ {
421 s.push_str("ref ");
422 }
423 if mut_ {
424 s.push_str("mut ");
425 }
426 format_to!(s, "{}", name);
427 s.push_str(": ())");
428 ast_from_text(&s)
429 }
430
wildcard_pat() -> ast::WildcardPat431 pub fn wildcard_pat() -> ast::WildcardPat {
432 return from_text("_");
433
434 fn from_text(text: &str) -> ast::WildcardPat {
435 ast_from_text(&format!("fn f({}: ())", text))
436 }
437 }
438
literal_pat(lit: &str) -> ast::LiteralPat439 pub fn literal_pat(lit: &str) -> ast::LiteralPat {
440 return from_text(lit);
441
442 fn from_text(text: &str) -> ast::LiteralPat {
443 ast_from_text(&format!("fn f() {{ match x {{ {} => {{}} }} }}", text))
444 }
445 }
446
447 /// Creates a tuple of patterns from an iterator of patterns.
448 ///
449 /// Invariant: `pats` must be length > 0
tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat450 pub fn tuple_pat(pats: impl IntoIterator<Item = ast::Pat>) -> ast::TuplePat {
451 let mut count: usize = 0;
452 let mut pats_str = pats.into_iter().inspect(|_| count += 1).join(", ");
453 if count == 1 {
454 pats_str.push(',');
455 }
456 return from_text(&format!("({})", pats_str));
457
458 fn from_text(text: &str) -> ast::TuplePat {
459 ast_from_text(&format!("fn f({}: ())", text))
460 }
461 }
462
tuple_struct_pat( path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>, ) -> ast::TupleStructPat463 pub fn tuple_struct_pat(
464 path: ast::Path,
465 pats: impl IntoIterator<Item = ast::Pat>,
466 ) -> ast::TupleStructPat {
467 let pats_str = pats.into_iter().join(", ");
468 return from_text(&format!("{}({})", path, pats_str));
469
470 fn from_text(text: &str) -> ast::TupleStructPat {
471 ast_from_text(&format!("fn f({}: ())", text))
472 }
473 }
474
record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat475 pub fn record_pat(path: ast::Path, pats: impl IntoIterator<Item = ast::Pat>) -> ast::RecordPat {
476 let pats_str = pats.into_iter().join(", ");
477 return from_text(&format!("{} {{ {} }}", path, pats_str));
478
479 fn from_text(text: &str) -> ast::RecordPat {
480 ast_from_text(&format!("fn f({}: ())", text))
481 }
482 }
483
record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat484 pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
485 ast_from_text(&format!("fn f({} {}: ()))", path, fields))
486 }
487
record_pat_field_list( fields: impl IntoIterator<Item = ast::RecordPatField>, ) -> ast::RecordPatFieldList488 pub fn record_pat_field_list(
489 fields: impl IntoIterator<Item = ast::RecordPatField>,
490 ) -> ast::RecordPatFieldList {
491 let fields = fields.into_iter().join(", ");
492 ast_from_text(&format!("fn f(S {{ {} }}: ()))", fields))
493 }
494
record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField495 pub fn record_pat_field(name_ref: ast::NameRef, pat: ast::Pat) -> ast::RecordPatField {
496 ast_from_text(&format!("fn f(S {{ {}: {} }}: ()))", name_ref, pat))
497 }
498
499 /// Returns a `BindPat` if the path has just one segment, a `PathPat` otherwise.
path_pat(path: ast::Path) -> ast::Pat500 pub fn path_pat(path: ast::Path) -> ast::Pat {
501 return from_text(&path.to_string());
502 fn from_text(text: &str) -> ast::Pat {
503 ast_from_text(&format!("fn f({}: ())", text))
504 }
505 }
506
match_arm( pats: impl IntoIterator<Item = ast::Pat>, guard: Option<ast::Expr>, expr: ast::Expr, ) -> ast::MatchArm507 pub fn match_arm(
508 pats: impl IntoIterator<Item = ast::Pat>,
509 guard: Option<ast::Expr>,
510 expr: ast::Expr,
511 ) -> ast::MatchArm {
512 let pats_str = pats.into_iter().join(" | ");
513 return match guard {
514 Some(guard) => from_text(&format!("{} if {} => {}", pats_str, guard, expr)),
515 None => from_text(&format!("{} => {}", pats_str, expr)),
516 };
517
518 fn from_text(text: &str) -> ast::MatchArm {
519 ast_from_text(&format!("fn f() {{ match () {{{}}} }}", text))
520 }
521 }
522
match_arm_with_guard( pats: impl IntoIterator<Item = ast::Pat>, guard: ast::Expr, expr: ast::Expr, ) -> ast::MatchArm523 pub fn match_arm_with_guard(
524 pats: impl IntoIterator<Item = ast::Pat>,
525 guard: ast::Expr,
526 expr: ast::Expr,
527 ) -> ast::MatchArm {
528 let pats_str = pats.into_iter().join(" | ");
529 return from_text(&format!("{} if {} => {}", pats_str, guard, expr));
530
531 fn from_text(text: &str) -> ast::MatchArm {
532 ast_from_text(&format!("fn f() {{ match () {{{}}} }}", text))
533 }
534 }
535
match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList536 pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
537 let arms_str = arms
538 .into_iter()
539 .map(|arm| {
540 let needs_comma = arm.expr().map_or(true, |it| !it.is_block_like());
541 let comma = if needs_comma { "," } else { "" };
542 format!(" {}{}\n", arm.syntax(), comma)
543 })
544 .collect::<String>();
545 return from_text(&arms_str);
546
547 fn from_text(text: &str) -> ast::MatchArmList {
548 ast_from_text(&format!("fn f() {{ match () {{\n{}}} }}", text))
549 }
550 }
551
where_pred( path: ast::Path, bounds: impl IntoIterator<Item = ast::TypeBound>, ) -> ast::WherePred552 pub fn where_pred(
553 path: ast::Path,
554 bounds: impl IntoIterator<Item = ast::TypeBound>,
555 ) -> ast::WherePred {
556 let bounds = bounds.into_iter().join(" + ");
557 return from_text(&format!("{}: {}", path, bounds));
558
559 fn from_text(text: &str) -> ast::WherePred {
560 ast_from_text(&format!("fn f() where {} {{ }}", text))
561 }
562 }
563
where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause564 pub fn where_clause(preds: impl IntoIterator<Item = ast::WherePred>) -> ast::WhereClause {
565 let preds = preds.into_iter().join(", ");
566 return from_text(preds.as_str());
567
568 fn from_text(text: &str) -> ast::WhereClause {
569 ast_from_text(&format!("fn f() where {} {{ }}", text))
570 }
571 }
572
let_stmt( pattern: ast::Pat, ty: Option<ast::Type>, initializer: Option<ast::Expr>, ) -> ast::LetStmt573 pub fn let_stmt(
574 pattern: ast::Pat,
575 ty: Option<ast::Type>,
576 initializer: Option<ast::Expr>,
577 ) -> ast::LetStmt {
578 let mut text = String::new();
579 format_to!(text, "let {}", pattern);
580 if let Some(ty) = ty {
581 format_to!(text, ": {}", ty);
582 }
583 match initializer {
584 Some(it) => format_to!(text, " = {};", it),
585 None => format_to!(text, ";"),
586 };
587 ast_from_text(&format!("fn f() {{ {} }}", text))
588 }
expr_stmt(expr: ast::Expr) -> ast::ExprStmt589 pub fn expr_stmt(expr: ast::Expr) -> ast::ExprStmt {
590 let semi = if expr.is_block_like() { "" } else { ";" };
591 ast_from_text(&format!("fn f() {{ {}{} (); }}", expr, semi))
592 }
593
item_const( visibility: Option<ast::Visibility>, name: ast::Name, ty: ast::Type, expr: ast::Expr, ) -> ast::Const594 pub fn item_const(
595 visibility: Option<ast::Visibility>,
596 name: ast::Name,
597 ty: ast::Type,
598 expr: ast::Expr,
599 ) -> ast::Const {
600 let visibility = match visibility {
601 None => String::new(),
602 Some(it) => format!("{} ", it),
603 };
604 ast_from_text(&format!("{} const {}: {} = {};", visibility, name, ty, expr))
605 }
606
param(pat: ast::Pat, ty: ast::Type) -> ast::Param607 pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
608 ast_from_text(&format!("fn f({}: {}) {{ }}", pat, ty))
609 }
610
self_param() -> ast::SelfParam611 pub fn self_param() -> ast::SelfParam {
612 ast_from_text("fn f(&self) { }")
613 }
614
ret_type(ty: ast::Type) -> ast::RetType615 pub fn ret_type(ty: ast::Type) -> ast::RetType {
616 ast_from_text(&format!("fn f() -> {} {{ }}", ty))
617 }
618
param_list( self_param: Option<ast::SelfParam>, pats: impl IntoIterator<Item = ast::Param>, ) -> ast::ParamList619 pub fn param_list(
620 self_param: Option<ast::SelfParam>,
621 pats: impl IntoIterator<Item = ast::Param>,
622 ) -> ast::ParamList {
623 let args = pats.into_iter().join(", ");
624 let list = match self_param {
625 Some(self_param) if args.is_empty() => format!("fn f({}) {{ }}", self_param),
626 Some(self_param) => format!("fn f({}, {}) {{ }}", self_param, args),
627 None => format!("fn f({}) {{ }}", args),
628 };
629 ast_from_text(&list)
630 }
631
type_param(name: ast::Name, ty: Option<ast::TypeBoundList>) -> ast::TypeParam632 pub fn type_param(name: ast::Name, ty: Option<ast::TypeBoundList>) -> ast::TypeParam {
633 let bound = match ty {
634 Some(it) => format!(": {}", it),
635 None => String::new(),
636 };
637 ast_from_text(&format!("fn f<{}{}>() {{ }}", name, bound))
638 }
639
lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam640 pub fn lifetime_param(lifetime: ast::Lifetime) -> ast::LifetimeParam {
641 ast_from_text(&format!("fn f<{}>() {{ }}", lifetime))
642 }
643
generic_param_list( pats: impl IntoIterator<Item = ast::GenericParam>, ) -> ast::GenericParamList644 pub fn generic_param_list(
645 pats: impl IntoIterator<Item = ast::GenericParam>,
646 ) -> ast::GenericParamList {
647 let args = pats.into_iter().join(", ");
648 ast_from_text(&format!("fn f<{}>() {{ }}", args))
649 }
650
visibility_pub_crate() -> ast::Visibility651 pub fn visibility_pub_crate() -> ast::Visibility {
652 ast_from_text("pub(crate) struct S")
653 }
654
visibility_pub() -> ast::Visibility655 pub fn visibility_pub() -> ast::Visibility {
656 ast_from_text("pub struct S")
657 }
658
tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList659 pub fn tuple_field_list(fields: impl IntoIterator<Item = ast::TupleField>) -> ast::TupleFieldList {
660 let fields = fields.into_iter().join(", ");
661 ast_from_text(&format!("struct f({});", fields))
662 }
663
record_field_list( fields: impl IntoIterator<Item = ast::RecordField>, ) -> ast::RecordFieldList664 pub fn record_field_list(
665 fields: impl IntoIterator<Item = ast::RecordField>,
666 ) -> ast::RecordFieldList {
667 let fields = fields.into_iter().join(", ");
668 ast_from_text(&format!("struct f {{ {} }}", fields))
669 }
670
tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField671 pub fn tuple_field(visibility: Option<ast::Visibility>, ty: ast::Type) -> ast::TupleField {
672 let visibility = match visibility {
673 None => String::new(),
674 Some(it) => format!("{} ", it),
675 };
676 ast_from_text(&format!("struct f({}{});", visibility, ty))
677 }
678
variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant679 pub fn variant(name: ast::Name, field_list: Option<ast::FieldList>) -> ast::Variant {
680 let field_list = match field_list {
681 None => String::new(),
682 Some(it) => format!("{}", it),
683 };
684 ast_from_text(&format!("enum f {{ {}{} }}", name, field_list))
685 }
686
fn_( visibility: Option<ast::Visibility>, fn_name: ast::Name, type_params: Option<ast::GenericParamList>, params: ast::ParamList, body: ast::BlockExpr, ret_type: Option<ast::RetType>, is_async: bool, ) -> ast::Fn687 pub fn fn_(
688 visibility: Option<ast::Visibility>,
689 fn_name: ast::Name,
690 type_params: Option<ast::GenericParamList>,
691 params: ast::ParamList,
692 body: ast::BlockExpr,
693 ret_type: Option<ast::RetType>,
694 is_async: bool,
695 ) -> ast::Fn {
696 let type_params = match type_params {
697 Some(type_params) => format!("{}", type_params),
698 None => "".into(),
699 };
700 let ret_type = match ret_type {
701 Some(ret_type) => format!("{} ", ret_type),
702 None => "".into(),
703 };
704 let visibility = match visibility {
705 None => String::new(),
706 Some(it) => format!("{} ", it),
707 };
708
709 let async_literal = if is_async { "async " } else { "" };
710
711 ast_from_text(&format!(
712 "{}{}fn {}{}{} {}{}",
713 visibility, async_literal, fn_name, type_params, params, ret_type, body
714 ))
715 }
716
struct_( visibility: Option<ast::Visibility>, strukt_name: ast::Name, generic_param_list: Option<ast::GenericParamList>, field_list: ast::FieldList, ) -> ast::Struct717 pub fn struct_(
718 visibility: Option<ast::Visibility>,
719 strukt_name: ast::Name,
720 generic_param_list: Option<ast::GenericParamList>,
721 field_list: ast::FieldList,
722 ) -> ast::Struct {
723 let semicolon = if matches!(field_list, ast::FieldList::TupleFieldList(_)) { ";" } else { "" };
724 let type_params = generic_param_list.map_or_else(String::new, |it| it.to_string());
725 let visibility = match visibility {
726 None => String::new(),
727 Some(it) => format!("{} ", it),
728 };
729
730 ast_from_text(&format!(
731 "{}struct {}{}{}{}",
732 visibility, strukt_name, type_params, field_list, semicolon
733 ))
734 }
735
ast_from_text<N: AstNode>(text: &str) -> N736 fn ast_from_text<N: AstNode>(text: &str) -> N {
737 let parse = SourceFile::parse(text);
738 let node = match parse.tree().syntax().descendants().find_map(N::cast) {
739 Some(it) => it,
740 None => {
741 panic!("Failed to make ast node `{}` from text {}", std::any::type_name::<N>(), text)
742 }
743 };
744 let node = node.clone_subtree();
745 assert_eq!(node.syntax().text_range().start(), 0.into());
746 node
747 }
748
token(kind: SyntaxKind) -> SyntaxToken749 pub fn token(kind: SyntaxKind) -> SyntaxToken {
750 tokens::SOURCE_FILE
751 .tree()
752 .syntax()
753 .clone_for_update()
754 .descendants_with_tokens()
755 .filter_map(|it| it.into_token())
756 .find(|it| it.kind() == kind)
757 .unwrap_or_else(|| panic!("unhandled token: {:?}", kind))
758 }
759
760 pub mod tokens {
761 use once_cell::sync::Lazy;
762
763 use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
764
765 pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
766 SourceFile::parse(
767 "const C: <()>::Item = (1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p)\n;\n\n",
768 )
769 });
770
single_space() -> SyntaxToken771 pub fn single_space() -> SyntaxToken {
772 SOURCE_FILE
773 .tree()
774 .syntax()
775 .clone_for_update()
776 .descendants_with_tokens()
777 .filter_map(|it| it.into_token())
778 .find(|it| it.kind() == WHITESPACE && it.text() == " ")
779 .unwrap()
780 }
781
whitespace(text: &str) -> SyntaxToken782 pub fn whitespace(text: &str) -> SyntaxToken {
783 assert!(text.trim().is_empty());
784 let sf = SourceFile::parse(text).ok().unwrap();
785 sf.syntax().clone_for_update().first_child_or_token().unwrap().into_token().unwrap()
786 }
787
doc_comment(text: &str) -> SyntaxToken788 pub fn doc_comment(text: &str) -> SyntaxToken {
789 assert!(!text.trim().is_empty());
790 let sf = SourceFile::parse(text).ok().unwrap();
791 sf.syntax().first_child_or_token().unwrap().into_token().unwrap()
792 }
793
literal(text: &str) -> SyntaxToken794 pub fn literal(text: &str) -> SyntaxToken {
795 assert_eq!(text.trim(), text);
796 let lit: ast::Literal = super::ast_from_text(&format!("fn f() {{ let _ = {}; }}", text));
797 lit.syntax().first_child_or_token().unwrap().into_token().unwrap()
798 }
799
single_newline() -> SyntaxToken800 pub fn single_newline() -> SyntaxToken {
801 let res = SOURCE_FILE
802 .tree()
803 .syntax()
804 .clone_for_update()
805 .descendants_with_tokens()
806 .filter_map(|it| it.into_token())
807 .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
808 .unwrap();
809 res.detach();
810 res
811 }
812
blank_line() -> SyntaxToken813 pub fn blank_line() -> SyntaxToken {
814 SOURCE_FILE
815 .tree()
816 .syntax()
817 .clone_for_update()
818 .descendants_with_tokens()
819 .filter_map(|it| it.into_token())
820 .find(|it| it.kind() == WHITESPACE && it.text() == "\n\n")
821 .unwrap()
822 }
823
824 pub struct WsBuilder(SourceFile);
825
826 impl WsBuilder {
new(text: &str) -> WsBuilder827 pub fn new(text: &str) -> WsBuilder {
828 WsBuilder(SourceFile::parse(text).ok().unwrap())
829 }
ws(&self) -> SyntaxToken830 pub fn ws(&self) -> SyntaxToken {
831 self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()
832 }
833 }
834 }
835