1 use crate::pp::Breaks::{Consistent, Inconsistent};
2 use crate::pprust::state::{AnnNode, 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(..) | ast::ExprKind::Closure(..) | ast::ExprKind::Ret(..) => true,
68 _ => parser::contains_exterior_struct_lit(expr),
72 /// Prints `expr` or `(expr)` when `needs_par` holds.
73 pub(super) fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
77 self.print_expr(expr);
83 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
84 self.ibox(INDENT_UNIT);
86 self.commasep_exprs(Inconsistent, exprs);
91 pub(super) fn print_expr_anon_const(&mut self, expr: &ast::AnonConst) {
92 self.ibox(INDENT_UNIT);
94 self.print_expr(&expr.value);
98 fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
99 self.ibox(INDENT_UNIT);
101 self.print_expr(element);
102 self.word_space(";");
103 self.print_expr(&count.value);
108 fn print_expr_struct(
110 qself: &Option<ast::QSelf>,
112 fields: &[ast::ExprField],
113 rest: &ast::StructRest,
115 if let Some(qself) = qself {
116 self.print_qpath(path, qself, true);
118 self.print_path(path, true, 0);
125 s.print_outer_attributes(&field.attrs);
127 if !field.is_shorthand {
128 s.print_ident(field.ident);
131 s.print_expr(&field.expr);
137 ast::StructRest::Base(_) | ast::StructRest::Rest(_) => {
138 self.ibox(INDENT_UNIT);
139 if !fields.is_empty() {
144 if let ast::StructRest::Base(ref expr) = *rest {
145 self.print_expr(expr);
149 ast::StructRest::None if !fields.is_empty() => self.word(","),
155 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
157 self.commasep_exprs(Inconsistent, exprs);
158 if exprs.len() == 1 {
164 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
165 let prec = match func.kind {
166 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
167 _ => parser::PREC_POSTFIX,
170 self.print_expr_maybe_paren(func, prec);
171 self.print_call_post(args)
174 fn print_expr_method_call(&mut self, segment: &ast::PathSegment, args: &[P<ast::Expr>]) {
175 let base_args = &args[1..];
176 self.print_expr_maybe_paren(&args[0], parser::PREC_POSTFIX);
178 self.print_ident(segment.ident);
179 if let Some(ref args) = segment.args {
180 self.print_generic_args(args, true);
182 self.print_call_post(base_args)
185 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
186 let assoc_op = AssocOp::from_ast_binop(op.node);
187 let prec = assoc_op.precedence() as i8;
188 let fixity = assoc_op.fixity();
190 let (left_prec, right_prec) = match fixity {
191 Fixity::Left => (prec, prec + 1),
192 Fixity::Right => (prec + 1, prec),
193 Fixity::None => (prec + 1, prec + 1),
196 let left_prec = match (&lhs.kind, op.node) {
197 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
198 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
199 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
200 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
201 parser::PREC_FORCE_PAREN
203 // We are given `(let _ = a) OP b`.
205 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
206 // as the parser will interpret this as `(let _ = a) OP b`.
208 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
209 // parens are required since the parser would interpret `let a = b < c` as
210 // `let a = (b < c)`. To achieve this, we force parens.
211 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
212 parser::PREC_FORCE_PAREN
217 self.print_expr_maybe_paren(lhs, left_prec);
219 self.word_space(op.node.to_string());
220 self.print_expr_maybe_paren(rhs, right_prec)
223 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
224 self.word(ast::UnOp::to_string(op));
225 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
228 fn print_expr_addr_of(
230 kind: ast::BorrowKind,
231 mutability: ast::Mutability,
236 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
237 ast::BorrowKind::Raw => {
238 self.word_nbsp("raw");
239 self.print_mutability(mutability, true);
242 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
245 pub fn print_expr(&mut self, expr: &ast::Expr) {
246 self.print_expr_outer_attr_style(expr, true)
249 pub(super) fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
250 self.maybe_print_comment(expr.span.lo());
252 let attrs = &expr.attrs;
254 self.print_outer_attributes_inline(attrs);
256 self.print_outer_attributes(attrs);
259 self.ibox(INDENT_UNIT);
260 self.ann.pre(self, AnnNode::Expr(expr));
262 ast::ExprKind::Box(ref expr) => {
263 self.word_space("box");
264 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
266 ast::ExprKind::Array(ref exprs) => {
267 self.print_expr_vec(exprs);
269 ast::ExprKind::ConstBlock(ref anon_const) => {
270 self.print_expr_anon_const(anon_const);
272 ast::ExprKind::Repeat(ref element, ref count) => {
273 self.print_expr_repeat(element, count);
275 ast::ExprKind::Struct(ref se) => {
276 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
278 ast::ExprKind::Tup(ref exprs) => {
279 self.print_expr_tup(exprs);
281 ast::ExprKind::Call(ref func, ref args) => {
282 self.print_expr_call(func, &args);
284 ast::ExprKind::MethodCall(ref segment, ref args, _) => {
285 self.print_expr_method_call(segment, &args);
287 ast::ExprKind::Binary(op, ref lhs, ref rhs) => {
288 self.print_expr_binary(op, lhs, rhs);
290 ast::ExprKind::Unary(op, ref expr) => {
291 self.print_expr_unary(op, expr);
293 ast::ExprKind::AddrOf(k, m, ref expr) => {
294 self.print_expr_addr_of(k, m, expr);
296 ast::ExprKind::Lit(ref lit) => {
297 self.print_literal(lit);
299 ast::ExprKind::Cast(ref expr, ref ty) => {
300 let prec = AssocOp::As.precedence() as i8;
301 self.print_expr_maybe_paren(expr, prec);
303 self.word_space("as");
306 ast::ExprKind::Type(ref expr, ref ty) => {
307 let prec = AssocOp::Colon.precedence() as i8;
308 self.print_expr_maybe_paren(expr, prec);
309 self.word_space(":");
312 ast::ExprKind::Let(ref pat, ref scrutinee, _) => {
313 self.print_let(pat, scrutinee);
315 ast::ExprKind::If(ref test, ref blk, ref elseopt) => {
316 self.print_if(test, blk, elseopt.as_deref())
318 ast::ExprKind::While(ref test, ref blk, opt_label) => {
319 if let Some(label) = opt_label {
320 self.print_ident(label.ident);
321 self.word_space(":");
325 self.word_nbsp("while");
326 self.print_expr_as_cond(test);
328 self.print_block_with_attrs(blk, attrs);
330 ast::ExprKind::ForLoop(ref pat, ref iter, ref blk, opt_label) => {
331 if let Some(label) = opt_label {
332 self.print_ident(label.ident);
333 self.word_space(":");
337 self.word_nbsp("for");
340 self.word_space("in");
341 self.print_expr_as_cond(iter);
343 self.print_block_with_attrs(blk, attrs);
345 ast::ExprKind::Loop(ref blk, opt_label) => {
346 if let Some(label) = opt_label {
347 self.print_ident(label.ident);
348 self.word_space(":");
352 self.word_nbsp("loop");
353 self.print_block_with_attrs(blk, attrs);
355 ast::ExprKind::Match(ref expr, ref arms) => {
358 self.word_nbsp("match");
359 self.print_expr_as_cond(expr);
362 self.print_inner_attributes_no_trailing_hardbreak(attrs);
366 let empty = attrs.is_empty() && arms.is_empty();
367 self.bclose(expr.span, empty);
369 ast::ExprKind::Closure(
377 self.print_movability(movability);
378 self.print_asyncness(asyncness);
379 self.print_capture_clause(capture_clause);
381 self.print_fn_params_and_ret(decl, true);
383 self.print_expr(body);
384 self.end(); // need to close a box
386 // a box will be closed by print_expr, but we didn't want an overall
387 // wrapper so we closed the corresponding opening. so create an
388 // empty box to satisfy the close.
391 ast::ExprKind::Block(ref blk, opt_label) => {
392 if let Some(label) = opt_label {
393 self.print_ident(label.ident);
394 self.word_space(":");
396 // containing cbox, will be closed by print-block at }
398 // head-box, will be closed by print-block after {
400 self.print_block_with_attrs(blk, attrs);
402 ast::ExprKind::Async(capture_clause, _, ref blk) => {
403 self.word_nbsp("async");
404 self.print_capture_clause(capture_clause);
405 // cbox/ibox in analogy to the `ExprKind::Block` arm above
408 self.print_block_with_attrs(blk, attrs);
410 ast::ExprKind::Await(ref expr) => {
411 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
414 ast::ExprKind::Assign(ref lhs, ref rhs, _) => {
415 let prec = AssocOp::Assign.precedence() as i8;
416 self.print_expr_maybe_paren(lhs, prec + 1);
418 self.word_space("=");
419 self.print_expr_maybe_paren(rhs, prec);
421 ast::ExprKind::AssignOp(op, ref lhs, ref rhs) => {
422 let prec = AssocOp::Assign.precedence() as i8;
423 self.print_expr_maybe_paren(lhs, prec + 1);
425 self.word(op.node.to_string());
426 self.word_space("=");
427 self.print_expr_maybe_paren(rhs, prec);
429 ast::ExprKind::Field(ref expr, ident) => {
430 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
432 self.print_ident(ident);
434 ast::ExprKind::Index(ref expr, ref index) => {
435 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
437 self.print_expr(index);
440 ast::ExprKind::Range(ref start, ref end, limits) => {
441 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
442 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
443 // Here we use a fake precedence value so that any child with lower precedence than
444 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
445 let fake_prec = AssocOp::LOr.precedence() as i8;
446 if let Some(ref e) = *start {
447 self.print_expr_maybe_paren(e, fake_prec);
449 if limits == ast::RangeLimits::HalfOpen {
454 if let Some(ref e) = *end {
455 self.print_expr_maybe_paren(e, fake_prec);
458 ast::ExprKind::Underscore => self.word("_"),
459 ast::ExprKind::Path(None, ref path) => self.print_path(path, true, 0),
460 ast::ExprKind::Path(Some(ref qself), ref path) => self.print_qpath(path, qself, true),
461 ast::ExprKind::Break(opt_label, ref opt_expr) => {
463 if let Some(label) = opt_label {
465 self.print_ident(label.ident);
467 if let Some(ref expr) = *opt_expr {
469 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
472 ast::ExprKind::Continue(opt_label) => {
473 self.word("continue");
474 if let Some(label) = opt_label {
476 self.print_ident(label.ident);
479 ast::ExprKind::Ret(ref result) => {
481 if let Some(ref expr) = *result {
483 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
486 ast::ExprKind::InlineAsm(ref a) => {
488 self.print_inline_asm(a);
490 ast::ExprKind::MacCall(ref m) => self.print_mac(m),
491 ast::ExprKind::Paren(ref e) => {
496 ast::ExprKind::Yield(ref e) => {
499 if let Some(ref expr) = *e {
501 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
504 ast::ExprKind::Try(ref e) => {
505 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
508 ast::ExprKind::TryBlock(ref blk) => {
511 self.word_nbsp("try");
512 self.print_block_with_attrs(blk, attrs)
514 ast::ExprKind::Err => {
516 self.word("/*ERROR*/");
520 self.ann.post(self, AnnNode::Expr(expr));
524 fn print_arm(&mut self, arm: &ast::Arm) {
525 // Note, I have no idea why this check is necessary, but here it is.
526 if arm.attrs.is_empty() {
529 self.cbox(INDENT_UNIT);
531 self.maybe_print_comment(arm.pat.span.lo());
532 self.print_outer_attributes(&arm.attrs);
533 self.print_pat(&arm.pat);
535 if let Some(ref e) = arm.guard {
536 self.word_space("if");
540 self.word_space("=>");
542 match arm.body.kind {
543 ast::ExprKind::Block(ref blk, opt_label) => {
544 if let Some(label) = opt_label {
545 self.print_ident(label.ident);
546 self.word_space(":");
549 // The block will close the pattern's ibox.
550 self.print_block_unclosed_indent(blk);
552 // If it is a user-provided unsafe block, print a comma after it.
553 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
558 self.end(); // Close the ibox for the pattern.
559 self.print_expr(&arm.body);
563 self.end(); // Close enclosing cbox.
566 fn print_movability(&mut self, movability: ast::Movability) {
568 ast::Movability::Static => self.word_space("static"),
569 ast::Movability::Movable => {}
573 fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
574 match capture_clause {
575 ast::CaptureBy::Value => self.word_space("move"),
576 ast::CaptureBy::Ref => {}