]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ast_pretty/src/pprust/state/expr.rs
Rollup merge of #100200 - petrochenkov:zgccld2, r=lqd,Mark-Simulacrum
[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<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(ref segment, ref receiver, ref args, _) => {
311                 self.print_expr_method_call(segment, &receiver, &args);
312             }
313             ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
314                 self.print_expr_binary(op, lhs, rhs);
315             }
316             ast::ExprKind::Unary(op, ref expr) => {
317                 self.print_expr_unary(op, expr);
318             }
319             ast::ExprKind::AddrOf(k, m, ref expr) => {
320                 self.print_expr_addr_of(k, m, expr);
321             }
322             ast::ExprKind::Lit(ref lit) => {
323                 self.print_literal(lit);
324             }
325             ast::ExprKind::Cast(ref expr, ref ty) => {
326                 let prec = AssocOp::As.precedence() as i8;
327                 self.print_expr_maybe_paren(expr, prec);
328                 self.space();
329                 self.word_space("as");
330                 self.print_type(ty);
331             }
332             ast::ExprKind::Type(ref expr, ref ty) => {
333                 let prec = AssocOp::Colon.precedence() as i8;
334                 self.print_expr_maybe_paren(expr, prec);
335                 self.word_space(":");
336                 self.print_type(ty);
337             }
338             ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
339                 self.print_let(pat, scrutinee);
340             }
341             ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
342                 self.print_if(test, blk, elseopt.as_deref())
343             }
344             ast::ExprKind::While(ref test, ref blk, opt_label) => {
345                 if let Some(label) = opt_label {
346                     self.print_ident(label.ident);
347                     self.word_space(":");
348                 }
349                 self.cbox(0);
350                 self.ibox(0);
351                 self.word_nbsp("while");
352                 self.print_expr_as_cond(test);
353                 self.space();
354                 self.print_block_with_attrs(blk, attrs);
355             }
356             ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
357                 if let Some(label) = opt_label {
358                     self.print_ident(label.ident);
359                     self.word_space(":");
360                 }
361                 self.cbox(0);
362                 self.ibox(0);
363                 self.word_nbsp("for");
364                 self.print_pat(pat);
365                 self.space();
366                 self.word_space("in");
367                 self.print_expr_as_cond(iter);
368                 self.space();
369                 self.print_block_with_attrs(blk, attrs);
370             }
371             ast::ExprKind::Loop(ref blk, opt_label) => {
372                 if let Some(label) = opt_label {
373                     self.print_ident(label.ident);
374                     self.word_space(":");
375                 }
376                 self.cbox(0);
377                 self.ibox(0);
378                 self.word_nbsp("loop");
379                 self.print_block_with_attrs(blk, attrs);
380             }
381             ast::ExprKind::Match(ref expr, ref arms) => {
382                 self.cbox(0);
383                 self.ibox(0);
384                 self.word_nbsp("match");
385                 self.print_expr_as_cond(expr);
386                 self.space();
387                 self.bopen();
388                 self.print_inner_attributes_no_trailing_hardbreak(attrs);
389                 for arm in arms {
390                     self.print_arm(arm);
391                 }
392                 let empty = attrs.is_empty() && arms.is_empty();
393                 self.bclose(expr.span, empty);
394             }
395             ast::ExprKind::Closure(
396                 ref binder,
397                 capture_clause,
398                 asyncness,
399                 movability,
400                 ref decl,
401                 ref body,
402                 _,
403             ) => {
404                 self.print_closure_binder(binder);
405                 self.print_movability(movability);
406                 self.print_asyncness(asyncness);
407                 self.print_capture_clause(capture_clause);
408
409                 self.print_fn_params_and_ret(decl, true);
410                 self.space();
411                 self.print_expr(body);
412                 self.end(); // need to close a box
413
414                 // a box will be closed by print_expr, but we didn't want an overall
415                 // wrapper so we closed the corresponding opening. so create an
416                 // empty box to satisfy the close.
417                 self.ibox(0);
418             }
419             ast::ExprKind::Block(ref blk, opt_label) => {
420                 if let Some(label) = opt_label {
421                     self.print_ident(label.ident);
422                     self.word_space(":");
423                 }
424                 // containing cbox, will be closed by print-block at }
425                 self.cbox(0);
426                 // head-box, will be closed by print-block after {
427                 self.ibox(0);
428                 self.print_block_with_attrs(blk, attrs);
429             }
430             ast::ExprKind::Async(capture_clause, _, ref blk) => {
431                 self.word_nbsp("async");
432                 self.print_capture_clause(capture_clause);
433                 // cbox/ibox in analogy to the `ExprKind::Block` arm above
434                 self.cbox(0);
435                 self.ibox(0);
436                 self.print_block_with_attrs(blk, attrs);
437             }
438             ast::ExprKind::Await(ref expr) => {
439                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
440                 self.word(".await");
441             }
442             ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
443                 let prec = AssocOp::Assign.precedence() as i8;
444                 self.print_expr_maybe_paren(lhs, prec + 1);
445                 self.space();
446                 self.word_space("=");
447                 self.print_expr_maybe_paren(rhs, prec);
448             }
449             ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
450                 let prec = AssocOp::Assign.precedence() as i8;
451                 self.print_expr_maybe_paren(lhs, prec + 1);
452                 self.space();
453                 self.word(op.node.to_string());
454                 self.word_space("=");
455                 self.print_expr_maybe_paren(rhs, prec);
456             }
457             ast::ExprKind::Field(ref expr, ident) => {
458                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
459                 self.word(".");
460                 self.print_ident(ident);
461             }
462             ast::ExprKind::Index(ref expr, ref index) => {
463                 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
464                 self.word("[");
465                 self.print_expr(index);
466                 self.word("]");
467             }
468             ast::ExprKind::Range(ref start, ref end, limits) => {
469                 // Special case for `Range`.  `AssocOp` claims that `Range` has higher precedence
470                 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
471                 // Here we use a fake precedence value so that any child with lower precedence than
472                 // a "normal" binop gets parenthesized.  (`LOr` is the lowest-precedence binop.)
473                 let fake_prec = AssocOp::LOr.precedence() as i8;
474                 if let Some(ref e) = *start {
475                     self.print_expr_maybe_paren(e, fake_prec);
476                 }
477                 if limits == ast::RangeLimits::HalfOpen {
478                     self.word("..");
479                 } else {
480                     self.word("..=");
481                 }
482                 if let Some(ref e) = *end {
483                     self.print_expr_maybe_paren(e, fake_prec);
484                 }
485             }
486             ast::ExprKind::Underscore => self.word("_"),
487             ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
488             ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
489             ast::ExprKind::Break(opt_label, ref opt_expr) => {
490                 self.word("break");
491                 if let Some(label) = opt_label {
492                     self.space();
493                     self.print_ident(label.ident);
494                 }
495                 if let Some(ref expr) = *opt_expr {
496                     self.space();
497                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
498                 }
499             }
500             ast::ExprKind::Continue(opt_label) => {
501                 self.word("continue");
502                 if let Some(label) = opt_label {
503                     self.space();
504                     self.print_ident(label.ident);
505                 }
506             }
507             ast::ExprKind::Ret(ref result) => {
508                 self.word("return");
509                 if let Some(ref expr) = *result {
510                     self.word(" ");
511                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
512                 }
513             }
514             ast::ExprKind::Yeet(ref result) => {
515                 self.word("do");
516                 self.word(" ");
517                 self.word("yeet");
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::InlineAsm(ref a) => {
524                 self.word("asm!");
525                 self.print_inline_asm(a);
526             }
527             ast::ExprKind::MacCall(ref m) => self.print_mac(m),
528             ast::ExprKind::Paren(ref e) => {
529                 self.popen();
530                 self.print_expr(e);
531                 self.pclose();
532             }
533             ast::ExprKind::Yield(ref e) => {
534                 self.word("yield");
535
536                 if let Some(ref expr) = *e {
537                     self.space();
538                     self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
539                 }
540             }
541             ast::ExprKind::Try(ref e) => {
542                 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
543                 self.word("?")
544             }
545             ast::ExprKind::TryBlock(ref blk) => {
546                 self.cbox(0);
547                 self.ibox(0);
548                 self.word_nbsp("try");
549                 self.print_block_with_attrs(blk, attrs)
550             }
551             ast::ExprKind::Err => {
552                 self.popen();
553                 self.word("/*ERROR*/");
554                 self.pclose()
555             }
556         }
557         self.ann.post(self, AnnNode::Expr(expr));
558         self.end();
559     }
560
561     fn print_arm(&mut self, arm: &ast::Arm) {
562         // Note, I have no idea why this check is necessary, but here it is.
563         if arm.attrs.is_empty() {
564             self.space();
565         }
566         self.cbox(INDENT_UNIT);
567         self.ibox(0);
568         self.maybe_print_comment(arm.pat.span.lo());
569         self.print_outer_attributes(&arm.attrs);
570         self.print_pat(&arm.pat);
571         self.space();
572         if let Some(ref e) = arm.guard {
573             self.word_space("if");
574             self.print_expr(e);
575             self.space();
576         }
577         self.word_space("=>");
578
579         match arm.body.kind {
580             ast::ExprKind::Block(ref blk, opt_label) => {
581                 if let Some(label) = opt_label {
582                     self.print_ident(label.ident);
583                     self.word_space(":");
584                 }
585
586                 // The block will close the pattern's ibox.
587                 self.print_block_unclosed_indent(blk);
588
589                 // If it is a user-provided unsafe block, print a comma after it.
590                 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
591                     self.word(",");
592                 }
593             }
594             _ => {
595                 self.end(); // Close the ibox for the pattern.
596                 self.print_expr(&arm.body);
597                 self.word(",");
598             }
599         }
600         self.end(); // Close enclosing cbox.
601     }
602
603     fn print_closure_binder(&mut self, binder: &ast::ClosureBinder) {
604         match binder {
605             ast::ClosureBinder::NotPresent => {}
606             ast::ClosureBinder::For { generic_params, .. } => {
607                 self.print_formal_generic_params(&generic_params)
608             }
609         }
610     }
611
612     fn print_movability(&mut self, movability: ast::Movability) {
613         match movability {
614             ast::Movability::Static => self.word_space("static"),
615             ast::Movability::Movable => {}
616         }
617     }
618
619     fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
620         match capture_clause {
621             ast::CaptureBy::Value => self.word_space("move"),
622             ast::CaptureBy::Ref => {}
623         }
624     }
625 }