]> git.lizzy.rs Git - rust.git/blob - crates/syntax/src/ast/make.rs
4bcea28cca8ba01bb354bdf3f54281a49c0dd158
[rust.git] / crates / syntax / src / ast / make.rs
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 probably doesn't belong in this module.
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;
14
15 use crate::{ast, AstNode, SourceFile, SyntaxKind, SyntaxNode, SyntaxToken};
16
17 pub fn name(text: &str) -> ast::Name {
18     ast_from_text(&format!("mod {};", text))
19 }
20
21 pub fn name_ref(text: &str) -> ast::NameRef {
22     ast_from_text(&format!("fn f() {{ {}; }}", text))
23 }
24 // FIXME: replace stringly-typed constructor with a family of typed ctors, a-la
25 // `expr_xxx`.
26 pub fn ty(text: &str) -> ast::Type {
27     ast_from_text(&format!("fn f() -> {} {{}}", text))
28 }
29 pub fn ty_unit() -> ast::Type {
30     ty("()")
31 }
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(", ");
35     if count == 1 {
36         contents.push(',');
37     }
38
39     ty(&format!("({})", contents))
40 }
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))
45 }
46 pub fn ty_ref(target: ast::Type, exclusive: bool) -> ast::Type {
47     ty(&if exclusive { format!("&mut {}", target) } else { format!("&{}", target) })
48 }
49
50 pub fn assoc_item_list() -> ast::AssocItemList {
51     ast_from_text("impl C for D {};")
52 }
53
54 pub fn impl_trait(trait_: ast::Path, ty: ast::Path) -> ast::Impl {
55     ast_from_text(&format!("impl {} for {} {{}}", trait_, ty))
56 }
57
58 pub fn path_segment(name_ref: ast::NameRef) -> ast::PathSegment {
59     ast_from_text(&format!("use {};", name_ref))
60 }
61
62 pub fn path_segment_self() -> ast::PathSegment {
63     ast_from_text("use self;")
64 }
65
66 pub fn path_segment_super() -> ast::PathSegment {
67     ast_from_text("use super;")
68 }
69
70 pub fn path_segment_crate() -> ast::PathSegment {
71     ast_from_text("use crate;")
72 }
73
74 pub fn path_unqualified(segment: ast::PathSegment) -> ast::Path {
75     ast_from_text(&format!("use {}", segment))
76 }
77
78 pub fn path_qualified(qual: ast::Path, segment: ast::PathSegment) -> ast::Path {
79     ast_from_text(&format!("{}::{}", qual, segment))
80 }
81
82 pub fn path_concat(first: ast::Path, second: ast::Path) -> ast::Path {
83     ast_from_text(&format!("{}::{}", first, second))
84 }
85
86 pub fn path_from_segments(
87     segments: impl IntoIterator<Item = ast::PathSegment>,
88     is_abs: bool,
89 ) -> ast::Path {
90     let segments = segments.into_iter().map(|it| it.syntax().clone()).join("::");
91     ast_from_text(&if is_abs {
92         format!("use ::{};", segments)
93     } else {
94         format!("use {};", segments)
95     })
96 }
97
98 pub fn path_from_text(text: &str) -> ast::Path {
99     ast_from_text(&format!("fn main() {{ let test = {}; }}", text))
100 }
101
102 pub fn glob_use_tree() -> ast::UseTree {
103     ast_from_text("use *;")
104 }
105
106 pub fn use_tree(
107     path: ast::Path,
108     use_tree_list: Option<ast::UseTreeList>,
109     alias: Option<ast::Rename>,
110     add_star: bool,
111 ) -> ast::UseTree {
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);
116     }
117     if add_star {
118         buf += "::*";
119     }
120
121     if let Some(alias) = alias {
122         format_to!(buf, " {}", alias);
123     }
124     ast_from_text(&buf)
125 }
126
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))
130 }
131
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),
136     };
137     ast_from_text(&format!("{}use {};", visibility, use_tree))
138 }
139
140 pub fn record_expr(path: ast::Path, fields: ast::RecordExprFieldList) -> ast::RecordExpr {
141     ast_from_text(&format!("fn f() {{ {} {} }}", path, fields))
142 }
143
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))
149 }
150
151 pub fn record_expr_field(name: ast::NameRef, expr: Option<ast::Expr>) -> ast::RecordExprField {
152     return match expr {
153         Some(expr) => from_text(&format!("{}: {}", name, expr)),
154         None => from_text(&name.to_string()),
155     };
156
157     fn from_text(text: &str) -> ast::RecordExprField {
158         ast_from_text(&format!("fn f() {{ S {{ {}, }} }}", text))
159     }
160 }
161
162 pub fn record_field(
163     visibility: Option<ast::Visibility>,
164     name: ast::Name,
165     ty: ast::Type,
166 ) -> ast::RecordField {
167     let visibility = match visibility {
168         None => String::new(),
169         Some(it) => format!("{} ", it),
170     };
171     ast_from_text(&format!("struct S {{ {}{}: {}, }}", visibility, name, ty))
172 }
173
174 pub fn block_expr(
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);
181     }
182     if let Some(tail_expr) = tail_expr {
183         format_to!(buf, "    {}\n", tail_expr)
184     }
185     buf += "}";
186     ast_from_text(&format!("fn f() {}", buf))
187 }
188
189 pub fn expr_unit() -> ast::Expr {
190     expr_from_text("()")
191 }
192 pub fn expr_literal(text: &str) -> ast::Literal {
193     assert_eq!(text.trim(), text);
194     ast_from_text(&format!("fn f() {{ let _ = {}; }}", text))
195 }
196
197 pub fn expr_empty_block() -> ast::Expr {
198     expr_from_text("{}")
199 }
200 pub fn expr_unimplemented() -> ast::Expr {
201     expr_from_text("unimplemented!()")
202 }
203 pub fn expr_unreachable() -> ast::Expr {
204     expr_from_text("unreachable!()")
205 }
206 pub fn expr_todo() -> ast::Expr {
207     expr_from_text("todo!()")
208 }
209 pub fn expr_path(path: ast::Path) -> ast::Expr {
210     expr_from_text(&path.to_string())
211 }
212 pub fn expr_continue() -> ast::Expr {
213     expr_from_text("continue")
214 }
215 pub fn expr_break(expr: Option<ast::Expr>) -> ast::Expr {
216     match expr {
217         Some(expr) => expr_from_text(&format!("break {}", expr)),
218         None => expr_from_text("break"),
219     }
220 }
221 pub fn expr_return(expr: Option<ast::Expr>) -> ast::Expr {
222     match expr {
223         Some(expr) => expr_from_text(&format!("return {}", expr)),
224         None => expr_from_text("return"),
225     }
226 }
227 pub fn expr_try(expr: ast::Expr) -> ast::Expr {
228     expr_from_text(&format!("{}?", expr))
229 }
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))
232 }
233 pub fn expr_if(
234     condition: ast::Condition,
235     then_branch: ast::BlockExpr,
236     else_branch: Option<ast::ElseBranch>,
237 ) -> ast::Expr {
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(),
242     };
243     expr_from_text(&format!("if {} {} {}", condition, then_branch, else_branch))
244 }
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))
247 }
248 pub fn expr_prefix(op: SyntaxKind, expr: ast::Expr) -> ast::Expr {
249     let token = token(op);
250     expr_from_text(&format!("{}{}", token, expr))
251 }
252 pub fn expr_call(f: ast::Expr, arg_list: ast::ArgList) -> ast::Expr {
253     expr_from_text(&format!("{}{}", f, arg_list))
254 }
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))
257 }
258 pub fn expr_ref(expr: ast::Expr, exclusive: bool) -> ast::Expr {
259     expr_from_text(&if exclusive { format!("&mut {}", expr) } else { format!("&{}", expr) })
260 }
261 pub fn expr_paren(expr: ast::Expr) -> ast::Expr {
262     expr_from_text(&format!("({})", expr))
263 }
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))
267 }
268 fn expr_from_text(text: &str) -> ast::Expr {
269     ast_from_text(&format!("const C: () = {};", text))
270 }
271
272 pub fn condition(expr: ast::Expr, pattern: Option<ast::Pat>) -> ast::Condition {
273     match pattern {
274         None => ast_from_text(&format!("const _: () = while {} {{}};", expr)),
275         Some(pattern) => {
276             ast_from_text(&format!("const _: () = while let {} = {} {{}};", pattern, expr))
277         }
278     }
279 }
280
281 pub fn arg_list(args: impl IntoIterator<Item = ast::Expr>) -> ast::ArgList {
282     ast_from_text(&format!("fn main() {{ ()({}) }}", args.into_iter().format(", ")))
283 }
284
285 pub fn ident_pat(name: ast::Name) -> ast::IdentPat {
286     return from_text(&name.text());
287
288     fn from_text(text: &str) -> ast::IdentPat {
289         ast_from_text(&format!("fn f({}: ())", text))
290     }
291 }
292 pub fn ident_mut_pat(name: ast::Name) -> ast::IdentPat {
293     return from_text(&name.text());
294
295     fn from_text(text: &str) -> ast::IdentPat {
296         ast_from_text(&format!("fn f(mut {}: ())", text))
297     }
298 }
299
300 pub fn wildcard_pat() -> ast::WildcardPat {
301     return from_text("_");
302
303     fn from_text(text: &str) -> ast::WildcardPat {
304         ast_from_text(&format!("fn f({}: ())", text))
305     }
306 }
307
308 pub fn literal_pat(lit: &str) -> ast::LiteralPat {
309     return from_text(lit);
310
311     fn from_text(text: &str) -> ast::LiteralPat {
312         ast_from_text(&format!("fn f() {{ match x {{ {} => {{}} }} }}", text))
313     }
314 }
315
316 /// Creates a tuple of patterns from an iterator of patterns.
317 ///
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(", ");
322     if count == 1 {
323         pats_str.push(',');
324     }
325     return from_text(&format!("({})", pats_str));
326
327     fn from_text(text: &str) -> ast::TuplePat {
328         ast_from_text(&format!("fn f({}: ())", text))
329     }
330 }
331
332 pub fn tuple_struct_pat(
333     path: ast::Path,
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));
338
339     fn from_text(text: &str) -> ast::TupleStructPat {
340         ast_from_text(&format!("fn f({}: ())", text))
341     }
342 }
343
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));
347
348     fn from_text(text: &str) -> ast::RecordPat {
349         ast_from_text(&format!("fn f({}: ())", text))
350     }
351 }
352
353 pub fn record_pat_with_fields(path: ast::Path, fields: ast::RecordPatFieldList) -> ast::RecordPat {
354     ast_from_text(&format!("fn f({} {}: ()))", path, fields))
355 }
356
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))
362 }
363
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))
366 }
367
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))
373     }
374 }
375
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));
379
380     fn from_text(text: &str) -> ast::MatchArm {
381         ast_from_text(&format!("fn f() {{ match () {{{}}} }}", text))
382     }
383 }
384
385 pub fn match_arm_list(arms: impl IntoIterator<Item = ast::MatchArm>) -> ast::MatchArmList {
386     let arms_str = arms
387         .into_iter()
388         .map(|arm| {
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)
392         })
393         .collect::<String>();
394     return from_text(&arms_str);
395
396     fn from_text(text: &str) -> ast::MatchArmList {
397         ast_from_text(&format!("fn f() {{ match () {{\n{}}} }}", text))
398     }
399 }
400
401 pub fn where_pred(
402     path: ast::Path,
403     bounds: impl IntoIterator<Item = ast::TypeBound>,
404 ) -> ast::WherePred {
405     let bounds = bounds.into_iter().join(" + ");
406     return from_text(&format!("{}: {}", path, bounds));
407
408     fn from_text(text: &str) -> ast::WherePred {
409         ast_from_text(&format!("fn f() where {} {{ }}", text))
410     }
411 }
412
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());
416
417     fn from_text(text: &str) -> ast::WhereClause {
418         ast_from_text(&format!("fn f() where {} {{ }}", text))
419     }
420 }
421
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),
426     };
427     ast_from_text(&format!("fn f() {{ {} }}", text))
428 }
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))
432 }
433
434 pub fn token(kind: SyntaxKind) -> SyntaxToken {
435     tokens::SOURCE_FILE
436         .tree()
437         .syntax()
438         .clone_for_update()
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))
443 }
444
445 pub fn param(pat: ast::Pat, ty: ast::Type) -> ast::Param {
446     ast_from_text(&format!("fn f({}: {}) {{ }}", pat, ty))
447 }
448
449 pub fn ret_type(ty: ast::Type) -> ast::RetType {
450     ast_from_text(&format!("fn f() -> {} {{ }}", ty))
451 }
452
453 pub fn param_list(
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),
462     };
463     ast_from_text(&list)
464 }
465
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(),
470     };
471     ast_from_text(&format!("fn f<{}{}>() {{ }}", name, bound))
472 }
473
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))
479 }
480
481 pub fn visibility_pub_crate() -> ast::Visibility {
482     ast_from_text("pub(crate) struct S")
483 }
484
485 pub fn visibility_pub() -> ast::Visibility {
486     ast_from_text("pub struct S")
487 }
488
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))
492 }
493
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))
499 }
500
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),
505     };
506     ast_from_text(&format!("struct f({}{});", visibility, ty))
507 }
508
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),
513     };
514     ast_from_text(&format!("enum f {{ {}{} }}", name, field_list))
515 }
516
517 pub fn fn_(
518     visibility: Option<ast::Visibility>,
519     fn_name: ast::Name,
520     type_params: Option<ast::GenericParamList>,
521     params: ast::ParamList,
522     body: ast::BlockExpr,
523     ret_type: Option<ast::RetType>,
524 ) -> ast::Fn {
525     let type_params =
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),
531     };
532
533     ast_from_text(&format!(
534         "{}fn {}{}{} {}{}",
535         visibility, fn_name, type_params, params, ret_type, body
536     ))
537 }
538
539 pub fn struct_(
540     visibility: Option<ast::Visibility>,
541     strukt_name: ast::Name,
542     type_params: Option<ast::GenericParamList>,
543     field_list: ast::FieldList,
544 ) -> ast::Struct {
545     let semicolon = if matches!(field_list, ast::FieldList::TupleFieldList(_)) { ";" } else { "" };
546     let type_params =
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),
551     };
552
553     ast_from_text(&format!(
554         "{}struct {}{}{}{}",
555         visibility, strukt_name, type_params, field_list, semicolon
556     ))
557 }
558
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) {
562         Some(it) => it,
563         None => {
564             panic!("Failed to make ast node `{}` from text {}", std::any::type_name::<N>(), text)
565         }
566     };
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());
571     node
572 }
573
574 fn unroot(n: SyntaxNode) -> SyntaxNode {
575     SyntaxNode::new_root(n.green().into())
576 }
577
578 pub mod tokens {
579     use once_cell::sync::Lazy;
580
581     use crate::{ast, AstNode, Parse, SourceFile, SyntaxKind::*, SyntaxToken};
582
583     pub(super) static SOURCE_FILE: Lazy<Parse<SourceFile>> = Lazy::new(|| {
584         SourceFile::parse(
585             "const C: <()>::Item = (1 != 1, 2 == 2, 3 < 3, 4 <= 4, 5 > 5, 6 >= 6, !true, *p)\n;\n\n",
586         )
587     });
588
589     pub fn single_space() -> SyntaxToken {
590         SOURCE_FILE
591             .tree()
592             .syntax()
593             .clone_for_update()
594             .descendants_with_tokens()
595             .filter_map(|it| it.into_token())
596             .find(|it| it.kind() == WHITESPACE && it.text() == " ")
597             .unwrap()
598     }
599
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()
604     }
605
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()
610     }
611
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()
616     }
617
618     pub fn single_newline() -> SyntaxToken {
619         let res = SOURCE_FILE
620             .tree()
621             .syntax()
622             .clone_for_update()
623             .descendants_with_tokens()
624             .filter_map(|it| it.into_token())
625             .find(|it| it.kind() == WHITESPACE && it.text() == "\n")
626             .unwrap();
627         res.detach();
628         res
629     }
630
631     pub fn blank_line() -> SyntaxToken {
632         SOURCE_FILE
633             .tree()
634             .syntax()
635             .clone_for_update()
636             .descendants_with_tokens()
637             .filter_map(|it| it.into_token())
638             .find(|it| it.kind() == WHITESPACE && it.text() == "\n\n")
639             .unwrap()
640     }
641
642     pub struct WsBuilder(SourceFile);
643
644     impl WsBuilder {
645         pub fn new(text: &str) -> WsBuilder {
646             WsBuilder(SourceFile::parse(text).ok().unwrap())
647         }
648         pub fn ws(&self) -> SyntaxToken {
649             self.0.syntax().first_child_or_token().unwrap().into_token().unwrap()
650         }
651     }
652 }