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<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(ref segment, ref receiver, ref args, _) => {
311 self.print_expr_method_call(segment, &receiver, &args);
313 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
314 self.print_expr_binary(op, lhs, rhs);
316 ast::ExprKind::Unary(op, ref expr) => {
317 self.print_expr_unary(op, expr);
319 ast::ExprKind::AddrOf(k, m, ref expr) => {
320 self.print_expr_addr_of(k, m, expr);
322 ast::ExprKind::Lit(ref lit) => {
323 self.print_literal(lit);
325 ast::ExprKind::IncludedBytes(ref bytes) => {
326 let lit = ast::Lit::from_included_bytes(bytes, expr.span);
327 self.print_literal(&lit)
329 ast::ExprKind::Cast(ref expr, ref ty) => {
330 let prec = AssocOp::As.precedence() as i8;
331 self.print_expr_maybe_paren(expr, prec);
333 self.word_space("as");
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(":");
342 ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
343 self.print_let(pat, scrutinee);
345 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
346 self.print_if(test, blk, elseopt.as_deref())
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(":");
355 self.word_nbsp("while");
356 self.print_expr_as_cond(test);
358 self.print_block_with_attrs(blk, attrs);
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(":");
367 self.word_nbsp("for");
370 self.word_space("in");
371 self.print_expr_as_cond(iter);
373 self.print_block_with_attrs(blk, attrs);
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(":");
382 self.word_nbsp("loop");
383 self.print_block_with_attrs(blk, attrs);
385 ast::ExprKind::Match(ref expr, ref arms) => {
388 self.word_nbsp("match");
389 self.print_expr_as_cond(expr);
392 self.print_inner_attributes_no_trailing_hardbreak(attrs);
396 let empty = attrs.is_empty() && arms.is_empty();
397 self.bclose(expr.span, empty);
399 ast::ExprKind::Closure(
408 self.print_closure_binder(binder);
409 self.print_movability(movability);
410 self.print_asyncness(asyncness);
411 self.print_capture_clause(capture_clause);
413 self.print_fn_params_and_ret(decl, true);
415 self.print_expr(body);
416 self.end(); // need to close a box
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.
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(":");
428 // containing cbox, will be closed by print-block at }
430 // head-box, will be closed by print-block after {
432 self.print_block_with_attrs(blk, attrs);
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
440 self.print_block_with_attrs(blk, attrs);
442 ast::ExprKind::Await(ref expr) => {
443 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
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);
450 self.word_space("=");
451 self.print_expr_maybe_paren(rhs, prec);
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);
457 self.word(op.node.to_string());
458 self.word_space("=");
459 self.print_expr_maybe_paren(rhs, prec);
461 ast::ExprKind::Field(ref expr, ident) => {
462 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
464 self.print_ident(ident);
466 ast::ExprKind::Index(ref expr, ref index) => {
467 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
469 self.print_expr(index);
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);
481 if limits == ast::RangeLimits::HalfOpen {
486 if let Some(ref e) = *end {
487 self.print_expr_maybe_paren(e, fake_prec);
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) => {
495 if let Some(label) = opt_label {
497 self.print_ident(label.ident);
499 if let Some(ref expr) = *opt_expr {
501 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
504 ast::ExprKind::Continue(opt_label) => {
505 self.word("continue");
506 if let Some(label) = opt_label {
508 self.print_ident(label.ident);
511 ast::ExprKind::Ret(ref result) => {
513 if let Some(ref expr) = *result {
515 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
518 ast::ExprKind::Yeet(ref result) => {
522 if let Some(ref expr) = *result {
524 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
527 ast::ExprKind::InlineAsm(ref a) => {
529 self.print_inline_asm(a);
531 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
532 ast::ExprKind::Paren(ref e) => {
537 ast::ExprKind::Yield(ref e) => {
540 if let Some(ref expr) = *e {
542 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
545 ast::ExprKind::Try(ref e) => {
546 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
549 ast::ExprKind::TryBlock(ref blk) => {
552 self.word_nbsp("try");
553 self.print_block_with_attrs(blk, attrs)
555 ast::ExprKind::Err => {
557 self.word("/*ERROR*/");
561 self.ann.post(self, AnnNode::Expr(expr));
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() {
570 self.cbox(INDENT_UNIT);
572 self.maybe_print_comment(arm.pat.span.lo());
573 self.print_outer_attributes(&arm.attrs);
574 self.print_pat(&arm.pat);
576 if let Some(ref e) = arm.guard {
577 self.word_space("if");
581 self.word_space("=>");
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(":");
590 // The block will close the pattern's ibox.
591 self.print_block_unclosed_indent(blk);
593 // If it is a user-provided unsafe block, print a comma after it.
594 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
599 self.end(); // Close the ibox for the pattern.
600 self.print_expr(&arm.body);
604 self.end(); // Close enclosing cbox.
607 fn print_closure_binder(&mut self, binder: &ast::ClosureBinder) {
609 ast::ClosureBinder::NotPresent => {}
610 ast::ClosureBinder::For { generic_params, .. } => {
611 self.print_formal_generic_params(&generic_params)
616 fn print_movability(&mut self, movability: ast::Movability) {
618 ast::Movability::Static => self.word_space("static"),
619 ast::Movability::Movable => {}
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 => {}