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