1 use crate::pp::Breaks::Inconsistent;
2 use crate::pprust::state::{AnnNode, IterDelimited, PrintState, State, INDENT_UNIT};
5 use rustc_ast::util::parser::{self, AssocOp, Fixity};
6 use rustc_ast::{self as ast, BlockCheckMode};
9 fn print_else(&mut self, els: Option<&ast::Expr>) {
10 if let Some(_else) = els {
12 // Another `else if` block.
13 ast::ExprKind::If(ref i, ref then, ref e) => {
14 self.cbox(INDENT_UNIT - 1);
16 self.word(" else if ");
17 self.print_expr_as_cond(i);
19 self.print_block(then);
20 self.print_else(e.as_deref())
22 // Final `else` block.
23 ast::ExprKind::Block(ref b, _) => {
24 self.cbox(INDENT_UNIT - 1);
29 // Constraints would be great here!
31 panic!("print_if saw if with weird alternative");
37 fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
39 self.print_expr_as_cond(test);
41 self.print_block(blk);
42 self.print_else(elseopt)
45 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
47 self.commasep_exprs(Inconsistent, args);
51 fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
52 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
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))
61 // Does `expr` need parentheses when printed in a condition position?
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 {
67 ast::ExprKind::Break(..)
68 | ast::ExprKind::Closure(..)
69 | ast::ExprKind::Ret(..)
70 | ast::ExprKind::Yeet(..) => true,
71 _ => parser::contains_exterior_struct_lit(expr),
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) {
80 self.print_expr(expr);
86 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
87 self.ibox(INDENT_UNIT);
89 self.commasep_exprs(Inconsistent, exprs);
94 pub(super) fn print_expr_anon_const(
96 expr: &ast::AnonConst,
97 attrs: &[ast::Attribute],
99 self.ibox(INDENT_UNIT);
102 if let ast::ExprKind::Block(block, None) = &expr.value.kind {
105 self.print_block_with_attrs(block, attrs);
107 self.print_expr(&expr.value);
112 fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
113 self.ibox(INDENT_UNIT);
115 self.print_expr(element);
116 self.word_space(";");
117 self.print_expr(&count.value);
122 fn print_expr_struct(
124 qself: &Option<P<ast::QSelf>>,
126 fields: &[ast::ExprField],
127 rest: &ast::StructRest,
129 if let Some(qself) = qself {
130 self.print_qpath(path, qself, true);
132 self.print_path(path, true, 0);
136 let has_rest = match rest {
137 ast::StructRest::Base(_) | ast::StructRest::Rest(_) => true,
138 ast::StructRest::None => false,
140 if fields.is_empty() && !has_rest {
145 for field in fields.iter().delimited() {
146 self.maybe_print_comment(field.span.hi());
147 self.print_outer_attributes(&field.attrs);
149 self.space_if_not_bol();
151 if !field.is_shorthand {
152 self.print_ident(field.ident);
155 self.print_expr(&field.expr);
156 if !field.is_last || has_rest {
157 self.word_space(",");
159 self.trailing_comma_or_space();
163 if fields.is_empty() {
167 if let ast::StructRest::Base(expr) = rest {
168 self.print_expr(expr);
172 self.offset(-INDENT_UNIT);
177 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
179 self.commasep_exprs(Inconsistent, exprs);
180 if exprs.len() == 1 {
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,
192 self.print_expr_maybe_paren(func, prec);
193 self.print_call_post(args)
196 fn print_expr_method_call(
198 segment: &ast::PathSegment,
199 receiver: &ast::Expr,
200 base_args: &[P<ast::Expr>],
202 self.print_expr_maybe_paren(receiver, parser::PREC_POSTFIX);
204 self.print_ident(segment.ident);
205 if let Some(ref args) = segment.args {
206 self.print_generic_args(args, true);
208 self.print_call_post(base_args)
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();
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),
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
229 // We are given `(let _ = a) OP b`.
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`.
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
243 self.print_expr_maybe_paren(lhs, left_prec);
245 self.word_space(op.node.to_string());
246 self.print_expr_maybe_paren(rhs, right_prec)
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)
254 fn print_expr_addr_of(
256 kind: ast::BorrowKind,
257 mutability: ast::Mutability,
262 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
263 ast::BorrowKind::Raw => {
264 self.word_nbsp("raw");
265 self.print_mutability(mutability, true);
268 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
271 pub fn print_expr(&mut self, expr: &ast::Expr) {
272 self.print_expr_outer_attr_style(expr, true)
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());
278 let attrs = &expr.attrs;
280 self.print_outer_attributes_inline(attrs);
282 self.print_outer_attributes(attrs);
285 self.ibox(INDENT_UNIT);
286 self.ann.pre(self, AnnNode::Expr(expr));
288 ast::ExprKind::Box(ref expr) => {
289 self.word_space("box");
290 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
292 ast::ExprKind::Array(ref exprs) => {
293 self.print_expr_vec(exprs);
295 ast::ExprKind::ConstBlock(ref anon_const) => {
296 self.print_expr_anon_const(anon_const, attrs);
298 ast::ExprKind::Repeat(ref element, ref count) => {
299 self.print_expr_repeat(element, count);
301 ast::ExprKind::Struct(ref se) => {
302 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
304 ast::ExprKind::Tup(ref exprs) => {
305 self.print_expr_tup(exprs);
307 ast::ExprKind::Call(ref func, ref args) => {
308 self.print_expr_call(func, &args);
310 ast::ExprKind::MethodCall(box ast::MethodCall {
316 self.print_expr_method_call(seg, &receiver, &args);
318 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
319 self.print_expr_binary(op, lhs, rhs);
321 ast::ExprKind::Unary(op, ref expr) => {
322 self.print_expr_unary(op, expr);
324 ast::ExprKind::AddrOf(k, m, ref expr) => {
325 self.print_expr_addr_of(k, m, expr);
327 ast::ExprKind::Lit(token_lit) => {
328 self.print_token_literal(token_lit, expr.span);
330 ast::ExprKind::IncludedBytes(ref bytes) => {
331 let lit = ast::Lit::from_included_bytes(bytes, expr.span);
332 self.print_literal(&lit)
334 ast::ExprKind::Cast(ref expr, ref ty) => {
335 let prec = AssocOp::As.precedence() as i8;
336 self.print_expr_maybe_paren(expr, prec);
338 self.word_space("as");
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(":");
347 ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
348 self.print_let(pat, scrutinee);
350 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
351 self.print_if(test, blk, elseopt.as_deref())
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(":");
360 self.word_nbsp("while");
361 self.print_expr_as_cond(test);
363 self.print_block_with_attrs(blk, attrs);
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(":");
372 self.word_nbsp("for");
375 self.word_space("in");
376 self.print_expr_as_cond(iter);
378 self.print_block_with_attrs(blk, attrs);
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(":");
387 self.word_nbsp("loop");
388 self.print_block_with_attrs(blk, attrs);
390 ast::ExprKind::Match(ref expr, ref arms) => {
393 self.word_nbsp("match");
394 self.print_expr_as_cond(expr);
397 self.print_inner_attributes_no_trailing_hardbreak(attrs);
401 let empty = attrs.is_empty() && arms.is_empty();
402 self.bclose(expr.span, empty);
404 ast::ExprKind::Closure(box ast::Closure {
413 self.print_closure_binder(binder);
414 self.print_movability(movability);
415 self.print_asyncness(asyncness);
416 self.print_capture_clause(capture_clause);
418 self.print_fn_params_and_ret(fn_decl, true);
420 self.print_expr(body);
421 self.end(); // need to close a box
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.
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(":");
433 // containing cbox, will be closed by print-block at }
435 // head-box, will be closed by print-block after {
437 self.print_block_with_attrs(blk, attrs);
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
445 self.print_block_with_attrs(blk, attrs);
447 ast::ExprKind::Await(ref expr) => {
448 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
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);
455 self.word_space("=");
456 self.print_expr_maybe_paren(rhs, prec);
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);
462 self.word(op.node.to_string());
463 self.word_space("=");
464 self.print_expr_maybe_paren(rhs, prec);
466 ast::ExprKind::Field(ref expr, ident) => {
467 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
469 self.print_ident(ident);
471 ast::ExprKind::Index(ref expr, ref index) => {
472 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
474 self.print_expr(index);
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);
486 if limits == ast::RangeLimits::HalfOpen {
491 if let Some(ref e) = *end {
492 self.print_expr_maybe_paren(e, fake_prec);
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) => {
500 if let Some(label) = opt_label {
502 self.print_ident(label.ident);
504 if let Some(ref expr) = *opt_expr {
506 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
509 ast::ExprKind::Continue(opt_label) => {
510 self.word("continue");
511 if let Some(label) = opt_label {
513 self.print_ident(label.ident);
516 ast::ExprKind::Ret(ref result) => {
518 if let Some(ref expr) = *result {
520 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
523 ast::ExprKind::Yeet(ref result) => {
527 if let Some(ref expr) = *result {
529 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
532 ast::ExprKind::InlineAsm(ref a) => {
534 self.print_inline_asm(a);
536 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
537 ast::ExprKind::Paren(ref e) => {
542 ast::ExprKind::Yield(ref e) => {
545 if let Some(ref expr) = *e {
547 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
550 ast::ExprKind::Try(ref e) => {
551 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
554 ast::ExprKind::TryBlock(ref blk) => {
557 self.word_nbsp("try");
558 self.print_block_with_attrs(blk, attrs)
560 ast::ExprKind::Err => {
562 self.word("/*ERROR*/");
566 self.ann.post(self, AnnNode::Expr(expr));
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() {
575 self.cbox(INDENT_UNIT);
577 self.maybe_print_comment(arm.pat.span.lo());
578 self.print_outer_attributes(&arm.attrs);
579 self.print_pat(&arm.pat);
581 if let Some(ref e) = arm.guard {
582 self.word_space("if");
586 self.word_space("=>");
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(":");
595 // The block will close the pattern's ibox.
596 self.print_block_unclosed_indent(blk);
598 // If it is a user-provided unsafe block, print a comma after it.
599 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
604 self.end(); // Close the ibox for the pattern.
605 self.print_expr(&arm.body);
609 self.end(); // Close enclosing cbox.
612 fn print_closure_binder(&mut self, binder: &ast::ClosureBinder) {
614 ast::ClosureBinder::NotPresent => {}
615 ast::ClosureBinder::For { generic_params, .. } => {
616 self.print_formal_generic_params(&generic_params)
621 fn print_movability(&mut self, movability: ast::Movability) {
623 ast::Movability::Static => self.word_space("static"),
624 ast::Movability::Movable => {}
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 => {}