]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_pretty/src/pprust/state/expr.rs
1da40d2302e125b5dcfc0baa1979370f7dad4f52
[rust.git] / compiler / rustc_ast_pretty / src / pprust / state / expr.rs
1 use crate::pp::Breaks::Inconsistent;
2 use crate::pprust::state::{AnnNode, IterDelimited, PrintState, State, INDENT_UNIT};
3
4 use rustc_ast::ptr::P;
5 use rustc_ast::util::parser::{self, AssocOp, Fixity};
6 use rustc_ast::{self as ast, BlockCheckMode};
7
8 impl<'a> State<'a> {
9     fn print_else(&mut self, els: Option<&ast::Expr>) {
10         if let Some(_else) = els {
11             match _else.kind {
12                 // Another `else if` block.
13                 ast::ExprKind::If(ref i, ref then, ref e) => {
14                     self.cbox(INDENT_UNIT - 1);
15                     self.ibox(0);
16                     self.word(" else if ");
17                     self.print_expr_as_cond(i);
18                     self.space();
19                     self.print_block(then);
20                     self.print_else(e.as_deref())
21                 }
22                 // Final `else` block.
23                 ast::ExprKind::Block(ref b, _) => {
24                     self.cbox(INDENT_UNIT - 1);
25                     self.ibox(0);
26                     self.word(" else ");
27                     self.print_block(b)
28                 }
29                 // Constraints would be great here!
30                 _ => {
31                     panic!("print_if saw if with weird alternative");
32                 }
33             }
34         }
35     }
36
37     fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
38         self.head("if");
39         self.print_expr_as_cond(test);
40         self.space();
41         self.print_block(blk);
42         self.print_else(elseopt)
43     }
44
45     fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
46         self.popen();
47         self.commasep_exprs(Inconsistent, args);
48         self.pclose()
49     }
50
51     fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
52         self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
53     }
54
55     /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
56     /// `if cond { ... }`.
57     fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
58         self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
59     }
60
61     // Does `expr` need parentheses when printed in a condition position?
62     //
63     // These cases need parens due to the parse error observed in #26461: `if return {}`
64     // parses as the erroneous construct `if (return {})`, not `if (return) {}`.
65     pub(super) fn cond_needs_par(expr: &ast::Expr) -> bool {
66         match expr.kind {
67             ast::ExprKind::Break(..)
68             | ast::ExprKind::Closure(..)
69             | ast::ExprKind::Ret(..)
70             | ast::ExprKind::Yeet(..) => true,
71             _ => parser::contains_exterior_struct_lit(expr),
72         }
73     }
74
75     /// Prints `expr` or `(expr)` when `needs_par` holds.
76     pub(super) fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
77         if needs_par {
78             self.popen();
79         }
80         self.print_expr(expr);
81         if needs_par {
82             self.pclose();
83         }
84     }
85
86     fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
87         self.ibox(INDENT_UNIT);
88         self.word("[");
89         self.commasep_exprs(Inconsistent, exprs);
90         self.word("]");
91         self.end();
92     }
93
94     pub(super) fn print_expr_anon_const(
95         &mut self,
96         expr: &ast::AnonConst,
97         attrs: &[ast::Attribute],
98     ) {
99         self.ibox(INDENT_UNIT);
100         self.word("const");
101         self.nbsp();
102         if let ast::ExprKind::Block(block, None) = &expr.value.kind {
103             self.cbox(0);
104             self.ibox(0);
105             self.print_block_with_attrs(block, attrs);
106         } else {
107             self.print_expr(&expr.value);
108         }
109         self.end();
110     }
111
112     fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
113         self.ibox(INDENT_UNIT);
114         self.word("[");
115         self.print_expr(element);
116         self.word_space(";");
117         self.print_expr(&count.value);
118         self.word("]");
119         self.end();
120     }
121
122     fn print_expr_struct(
123         &mut self,
124         qself: &Option<P<ast::QSelf>>,
125         path: &ast::Path,
126         fields: &[ast::ExprField],
127         rest: &ast::StructRest,
128     ) {
129         if let Some(qself) = qself {
130             self.print_qpath(path, qself, true);
131         } else {
132             self.print_path(path, true, 0);
133         }
134         self.nbsp();
135         self.word("{");
136         let has_rest = match rest {
137             ast::StructRest::Base(_) | ast::StructRest::Rest(_) => true,
138             ast::StructRest::None => false,
139         };
140         if fields.is_empty() && !has_rest {
141             self.word("}");
142             return;
143         }
144         self.cbox(0);
145         for field in fields.iter().delimited() {
146             self.maybe_print_comment(field.span.hi());
147             self.print_outer_attributes(&field.attrs);
148             if field.is_first {
149                 self.space_if_not_bol();
150             }
151             if !field.is_shorthand {
152                 self.print_ident(field.ident);
153                 self.word_nbsp(":");
154             }
155             self.print_expr(&field.expr);
156             if !field.is_last || has_rest {
157                 self.word_space(",");
158             } else {
159                 self.trailing_comma_or_space();
160             }
161         }
162         if has_rest {
163             if fields.is_empty() {
164                 self.space();
165             }
166             self.word("..");
167             if let ast::StructRest::Base(expr) = rest {
168                 self.print_expr(expr);
169             }
170             self.space();
171         }
172         self.offset(-INDENT_UNIT);
173         self.end();
174         self.word("}");
175     }
176
177     fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
178         self.popen();
179         self.commasep_exprs(Inconsistent, exprs);
180         if exprs.len() == 1 {
181             self.word(",");
182         }
183         self.pclose()
184     }
185
186     fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
187         let prec = match func.kind {
188             ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
189             _ => parser::PREC_POSTFIX,
190         };
191
192         self.print_expr_maybe_paren(func, prec);
193         self.print_call_post(args)
194     }
195
196     fn print_expr_method_call(
197         &mut self,
198         segment: &ast::PathSegment,
199         receiver: &ast::Expr,
200         base_args: &[P<ast::Expr>],
201     ) {
202         self.print_expr_maybe_paren(receiver, parser::PREC_POSTFIX);
203         self.word(".");
204         self.print_ident(segment.ident);
205         if let Some(ref args) = segment.args {
206             self.print_generic_args(args, true);
207         }
208         self.print_call_post(base_args)
209     }
210
211     fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
212         let assoc_op = AssocOp::from_ast_binop(op.node);
213         let prec = assoc_op.precedence() as i8;
214         let fixity = assoc_op.fixity();
215
216         let (left_prec, right_prec) = match fixity {
217             Fixity::Left => (prec, prec + 1),
218             Fixity::Right => (prec + 1, prec),
219             Fixity::None => (prec + 1, prec + 1),
220         };
221
222         let left_prec = match (&lhs.kind, op.node) {
223             // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
224             // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
225             // of `(x as i32) < ...`. We need to convince it _not_ to do that.
226             (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
227                 parser::PREC_FORCE_PAREN
228             }
229             // We are given `(let _ = a) OP b`.
230             //
231             // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
232             //   as the parser will interpret this as `(let _ = a) OP b`.
233             //
234             // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
235             //   parens are required since the parser would interpret `let a = b < c` as
236             //   `let a = (b < c)`. To achieve this, we force parens.
237             (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
238                 parser::PREC_FORCE_PAREN
239             }
240             _ => left_prec,
241         };
242
243         self.print_expr_maybe_paren(lhs, left_prec);
244         self.space();
245         self.word_space(op.node.to_string());
246         self.print_expr_maybe_paren(rhs, right_prec)
247     }
248
249     fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
250         self.word(ast::UnOp::to_string(op));
251         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
252     }
253
254     fn print_expr_addr_of(
255         &mut self,
256         kind: ast::BorrowKind,
257         mutability: ast::Mutability,
258         expr: &ast::Expr,
259     ) {
260         self.word("&");
261         match kind {
262             ast::BorrowKind::Ref => self.print_mutability(mutability, false),
263             ast::BorrowKind::Raw => {
264                 self.word_nbsp("raw");
265                 self.print_mutability(mutability, true);
266             }
267         }
268         self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
269     }
270
271     pub fn print_expr(&mut self, expr: &ast::Expr) {
272         self.print_expr_outer_attr_style(expr, true)
273     }
274
275     pub(super) fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
276         self.maybe_print_comment(expr.span.lo());
277
278         let attrs = &expr.attrs;
279         if is_inline {
280             self.print_outer_attributes_inline(attrs);
281         } else {
282             self.print_outer_attributes(attrs);
283         }
284
285         self.ibox(INDENT_UNIT);
286         self.ann.pre(self, AnnNode::Expr(expr));
287         match expr.kind {
288             ast::ExprKind::Box(ref expr) => {
289                 self.word_space("box");
290                 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
291             }
292             ast::ExprKind::Array(ref exprs) => {
293                 self.print_expr_vec(exprs);
294             }
295             ast::ExprKind::ConstBlock(ref anon_const) => {
296                 self.print_expr_anon_const(anon_const, attrs);
297             }
298             ast::ExprKind::Repeat(ref element, ref count) => {
299                 self.print_expr_repeat(element, count);
300             }
301             ast::ExprKind::Struct(ref se) => {
302                 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
303             }
304             ast::ExprKind::Tup(ref exprs) => {
305                 self.print_expr_tup(exprs);
306             }
307             ast::ExprKind::Call(ref func, ref args) => {
308                 self.print_expr_call(func, &args);
309             }
310             ast::ExprKind::MethodCall(box ast::MethodCall {
311                 ref seg,
312                 ref receiver,
313                 ref args,
314                 ..
315             }) => {
316                 self.print_expr_method_call(seg, &receiver, &args);
317             }
318             ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
319                 self.print_expr_binary(op, lhs, rhs);
320             }
321             ast::ExprKind::Unary(op, ref expr) => {
322                 self.print_expr_unary(op, expr);
323             }
324             ast::ExprKind::AddrOf(k, m, ref expr) => {
325                 self.print_expr_addr_of(k, m, expr);
326             }
327             ast::ExprKind::Lit(token_lit) => {
328                 self.print_token_literal(token_lit, expr.span);
329             }
330             ast::ExprKind::IncludedBytes(ref bytes) => {
331                 let lit = ast::Lit::from_included_bytes(bytes, expr.span);
332                 self.print_literal(&lit)
333             }
334             ast::ExprKind::Cast(ref expr, ref ty) => {
335                 let prec = AssocOp::As.precedence() as i8;
336                 self.print_expr_maybe_paren(expr, prec);
337                 self.space();
338                 self.word_space("as");
339                 self.print_type(ty);
340             }
341             ast::ExprKind::Type(ref expr, ref ty) => {
342                 let prec = AssocOp::Colon.precedence() as i8;
343                 self.print_expr_maybe_paren(expr, prec);
344                 self.word_space(":");
345                 self.print_type(ty);
346             }
347             ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
348                 self.print_let(pat, scrutinee);
349             }
350             ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
351                 self.print_if(test, blk, elseopt.as_deref())
352             }
353             ast::ExprKind::While(ref test, ref blk, opt_label) => {
354                 if let Some(label) = opt_label {
355                     self.print_ident(label.ident);
356                     self.word_space(":");
357                 }
358                 self.cbox(0);
359                 self.ibox(0);
360                 self.word_nbsp("while");
361                 self.print_expr_as_cond(test);
362                 self.space();
363                 self.print_block_with_attrs(blk, attrs);
364             }
365             ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
366                 if let Some(label) = opt_label {
367                     self.print_ident(label.ident);
368                     self.word_space(":");
369                 }
370                 self.cbox(0);
371                 self.ibox(0);
372                 self.word_nbsp("for");
373                 self.print_pat(pat);
374                 self.space();
375                 self.word_space("in");
376                 self.print_expr_as_cond(iter);
377                 self.space();
378                 self.print_block_with_attrs(blk, attrs);
379             }
380             ast::ExprKind::Loop(ref blk, opt_label) => {
381                 if let Some(label) = opt_label {
382                     self.print_ident(label.ident);
383                     self.word_space(":");
384                 }
385                 self.cbox(0);
386                 self.ibox(0);
387                 self.word_nbsp("loop");
388                 self.print_block_with_attrs(blk, attrs);
389             }
390             ast::ExprKind::Match(ref expr, ref arms) => {
391                 self.cbox(0);
392                 self.ibox(0);
393                 self.word_nbsp("match");
394                 self.print_expr_as_cond(expr);
395                 self.space();
396                 self.bopen();
397                 self.print_inner_attributes_no_trailing_hardbreak(attrs);
398                 for arm in arms {
399                     self.print_arm(arm);
400                 }
401                 let empty = attrs.is_empty() && arms.is_empty();
402                 self.bclose(expr.span, empty);
403             }
404             ast::ExprKind::Closure(box ast::Closure {
405                 ref binder,
406                 capture_clause,
407                 asyncness,
408                 movability,
409                 ref fn_decl,
410                 ref body,
411                 fn_decl_span: _,
412             }) => {
413                 self.print_closure_binder(binder);
414                 self.print_movability(movability);
415                 self.print_asyncness(asyncness);
416                 self.print_capture_clause(capture_clause);
417
418                 self.print_fn_params_and_ret(fn_decl, true);
419                 self.space();
420                 self.print_expr(body);
421                 self.end(); // need to close a box
422
423                 // a box will be closed by print_expr, but we didn't want an overall
424                 // wrapper so we closed the corresponding opening. so create an
425                 // empty box to satisfy the close.
426                 self.ibox(0);
427             }
428             ast::ExprKind::Block(ref blk, opt_label) => {
429                 if let Some(label) = opt_label {
430                     self.print_ident(label.ident);
431                     self.word_space(":");
432                 }
433                 // containing cbox, will be closed by print-block at }
434                 self.cbox(0);
435                 // head-box, will be closed by print-block after {
436                 self.ibox(0);
437                 self.print_block_with_attrs(blk, attrs);
438             }
439             ast::ExprKind::Async(capture_clause, _, ref blk) => {
440                 self.word_nbsp("async");
441                 self.print_capture_clause(capture_clause);
442                 // cbox/ibox in analogy to the `ExprKind::Block` arm above
443                 self.cbox(0);
444                 self.ibox(0);
445                 self.print_block_with_attrs(blk, attrs);
446             }
447             ast::ExprKind::Await(ref expr) => {
448                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
449                 self.word(".await");
450             }
451             ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
452                 let prec = AssocOp::Assign.precedence() as i8;
453                 self.print_expr_maybe_paren(lhs, prec + 1);
454                 self.space();
455                 self.word_space("=");
456                 self.print_expr_maybe_paren(rhs, prec);
457             }
458             ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
459                 let prec = AssocOp::Assign.precedence() as i8;
460                 self.print_expr_maybe_paren(lhs, prec + 1);
461                 self.space();
462                 self.word(op.node.to_string());
463                 self.word_space("=");
464                 self.print_expr_maybe_paren(rhs, prec);
465             }
466             ast::ExprKind::Field(ref expr, ident) => {
467                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
468                 self.word(".");
469                 self.print_ident(ident);
470             }
471             ast::ExprKind::Index(ref expr, ref index) => {
472                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
473                 self.word("[");
474                 self.print_expr(index);
475                 self.word("]");
476             }
477             ast::ExprKind::Range(ref start, ref end, limits) => {
478                 // Special case for `Range`.  `AssocOp` claims that `Range` has higher precedence
479                 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
480                 // Here we use a fake precedence value so that any child with lower precedence than
481                 // a "normal" binop gets parenthesized.  (`LOr` is the lowest-precedence binop.)
482                 let fake_prec = AssocOp::LOr.precedence() as i8;
483                 if let Some(ref e) = *start {
484                     self.print_expr_maybe_paren(e, fake_prec);
485                 }
486                 if limits == ast::RangeLimits::HalfOpen {
487                     self.word("..");
488                 } else {
489                     self.word("..=");
490                 }
491                 if let Some(ref e) = *end {
492                     self.print_expr_maybe_paren(e, fake_prec);
493                 }
494             }
495             ast::ExprKind::Underscore => self.word("_"),
496             ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
497             ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
498             ast::ExprKind::Break(opt_label, ref opt_expr) => {
499                 self.word("break");
500                 if let Some(label) = opt_label {
501                     self.space();
502                     self.print_ident(label.ident);
503                 }
504                 if let Some(ref expr) = *opt_expr {
505                     self.space();
506                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
507                 }
508             }
509             ast::ExprKind::Continue(opt_label) => {
510                 self.word("continue");
511                 if let Some(label) = opt_label {
512                     self.space();
513                     self.print_ident(label.ident);
514                 }
515             }
516             ast::ExprKind::Ret(ref result) => {
517                 self.word("return");
518                 if let Some(ref expr) = *result {
519                     self.word(" ");
520                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
521                 }
522             }
523             ast::ExprKind::Yeet(ref result) => {
524                 self.word("do");
525                 self.word(" ");
526                 self.word("yeet");
527                 if let Some(ref expr) = *result {
528                     self.word(" ");
529                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
530                 }
531             }
532             ast::ExprKind::InlineAsm(ref a) => {
533                 self.word("asm!");
534                 self.print_inline_asm(a);
535             }
536             ast::ExprKind::MacCall(ref m) => self.print_mac(m),
537             ast::ExprKind::Paren(ref e) => {
538                 self.popen();
539                 self.print_expr(e);
540                 self.pclose();
541             }
542             ast::ExprKind::Yield(ref e) => {
543                 self.word("yield");
544
545                 if let Some(ref expr) = *e {
546                     self.space();
547                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
548                 }
549             }
550             ast::ExprKind::Try(ref e) => {
551                 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
552                 self.word("?")
553             }
554             ast::ExprKind::TryBlock(ref blk) => {
555                 self.cbox(0);
556                 self.ibox(0);
557                 self.word_nbsp("try");
558                 self.print_block_with_attrs(blk, attrs)
559             }
560             ast::ExprKind::Err => {
561                 self.popen();
562                 self.word("/*ERROR*/");
563                 self.pclose()
564             }
565         }
566         self.ann.post(self, AnnNode::Expr(expr));
567         self.end();
568     }
569
570     fn print_arm(&mut self, arm: &ast::Arm) {
571         // Note, I have no idea why this check is necessary, but here it is.
572         if arm.attrs.is_empty() {
573             self.space();
574         }
575         self.cbox(INDENT_UNIT);
576         self.ibox(0);
577         self.maybe_print_comment(arm.pat.span.lo());
578         self.print_outer_attributes(&arm.attrs);
579         self.print_pat(&arm.pat);
580         self.space();
581         if let Some(ref e) = arm.guard {
582             self.word_space("if");
583             self.print_expr(e);
584             self.space();
585         }
586         self.word_space("=>");
587
588         match arm.body.kind {
589             ast::ExprKind::Block(ref blk, opt_label) => {
590                 if let Some(label) = opt_label {
591                     self.print_ident(label.ident);
592                     self.word_space(":");
593                 }
594
595                 // The block will close the pattern's ibox.
596                 self.print_block_unclosed_indent(blk);
597
598                 // If it is a user-provided unsafe block, print a comma after it.
599                 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
600                     self.word(",");
601                 }
602             }
603             _ => {
604                 self.end(); // Close the ibox for the pattern.
605                 self.print_expr(&arm.body);
606                 self.word(",");
607             }
608         }
609         self.end(); // Close enclosing cbox.
610     }
611
612     fn print_closure_binder(&mut self, binder: &ast::ClosureBinder) {
613         match binder {
614             ast::ClosureBinder::NotPresent => {}
615             ast::ClosureBinder::For { generic_params, .. } => {
616                 self.print_formal_generic_params(&generic_params)
617             }
618         }
619     }
620
621     fn print_movability(&mut self, movability: ast::Movability) {
622         match movability {
623             ast::Movability::Static => self.word_space("static"),
624             ast::Movability::Movable => {}
625         }
626     }
627
628     fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
629         match capture_clause {
630             ast::CaptureBy::Value => self.word_space("move"),
631             ast::CaptureBy::Ref => {}
632         }
633     }
634 }