1 use crate::pp::Breaks::Inconsistent;
2 use crate::pprust::state::{AnnNode, IterDelimited, PrintState, State, INDENT_UNIT};
6 use rustc_ast::util::literal::escape_byte_str_symbol;
7 use rustc_ast::util::parser::{self, AssocOp, Fixity};
8 use rustc_ast::{self as ast, BlockCheckMode};
11 fn print_else(&mut self, els: Option<&ast::Expr>) {
12 if let Some(_else) = els {
14 // Another `else if` block.
15 ast::ExprKind::If(i, then, e) => {
16 self.cbox(INDENT_UNIT - 1);
18 self.word(" else if ");
19 self.print_expr_as_cond(i);
21 self.print_block(then);
22 self.print_else(e.as_deref())
24 // Final `else` block.
25 ast::ExprKind::Block(b, _) => {
26 self.cbox(INDENT_UNIT - 1);
31 // Constraints would be great here!
33 panic!("print_if saw if with weird alternative");
39 fn print_if(&mut self, test: &ast::Expr, blk: &ast::Block, elseopt: Option<&ast::Expr>) {
41 self.print_expr_as_cond(test);
43 self.print_block(blk);
44 self.print_else(elseopt)
47 fn print_call_post(&mut self, args: &[P<ast::Expr>]) {
49 self.commasep_exprs(Inconsistent, args);
53 fn print_expr_maybe_paren(&mut self, expr: &ast::Expr, prec: i8) {
54 self.print_expr_cond_paren(expr, expr.precedence().order() < prec)
57 /// Prints an expr using syntax that's acceptable in a condition position, such as the `cond` in
58 /// `if cond { ... }`.
59 fn print_expr_as_cond(&mut self, expr: &ast::Expr) {
60 self.print_expr_cond_paren(expr, Self::cond_needs_par(expr))
63 /// Does `expr` need parentheses when printed in a condition position?
65 /// These cases need parens due to the parse error observed in #26461: `if return {}`
66 /// parses as the erroneous construct `if (return {})`, not `if (return) {}`.
67 pub(super) fn cond_needs_par(expr: &ast::Expr) -> bool {
69 ast::ExprKind::Break(..)
70 | ast::ExprKind::Closure(..)
71 | ast::ExprKind::Ret(..)
72 | ast::ExprKind::Yeet(..) => true,
73 _ => parser::contains_exterior_struct_lit(expr),
77 /// Prints `expr` or `(expr)` when `needs_par` holds.
78 pub(super) fn print_expr_cond_paren(&mut self, expr: &ast::Expr, needs_par: bool) {
82 self.print_expr(expr);
88 fn print_expr_vec(&mut self, exprs: &[P<ast::Expr>]) {
89 self.ibox(INDENT_UNIT);
91 self.commasep_exprs(Inconsistent, exprs);
96 pub(super) fn print_expr_anon_const(
98 expr: &ast::AnonConst,
99 attrs: &[ast::Attribute],
101 self.ibox(INDENT_UNIT);
104 if let ast::ExprKind::Block(block, None) = &expr.value.kind {
107 self.print_block_with_attrs(block, attrs);
109 self.print_expr(&expr.value);
114 fn print_expr_repeat(&mut self, element: &ast::Expr, count: &ast::AnonConst) {
115 self.ibox(INDENT_UNIT);
117 self.print_expr(element);
118 self.word_space(";");
119 self.print_expr(&count.value);
124 fn print_expr_struct(
126 qself: &Option<P<ast::QSelf>>,
128 fields: &[ast::ExprField],
129 rest: &ast::StructRest,
131 if let Some(qself) = qself {
132 self.print_qpath(path, qself, true);
134 self.print_path(path, true, 0);
138 let has_rest = match rest {
139 ast::StructRest::Base(_) | ast::StructRest::Rest(_) => true,
140 ast::StructRest::None => false,
142 if fields.is_empty() && !has_rest {
147 for field in fields.iter().delimited() {
148 self.maybe_print_comment(field.span.hi());
149 self.print_outer_attributes(&field.attrs);
151 self.space_if_not_bol();
153 if !field.is_shorthand {
154 self.print_ident(field.ident);
157 self.print_expr(&field.expr);
158 if !field.is_last || has_rest {
159 self.word_space(",");
161 self.trailing_comma_or_space();
165 if fields.is_empty() {
169 if let ast::StructRest::Base(expr) = rest {
170 self.print_expr(expr);
174 self.offset(-INDENT_UNIT);
179 fn print_expr_tup(&mut self, exprs: &[P<ast::Expr>]) {
181 self.commasep_exprs(Inconsistent, exprs);
182 if exprs.len() == 1 {
188 fn print_expr_call(&mut self, func: &ast::Expr, args: &[P<ast::Expr>]) {
189 let prec = match func.kind {
190 ast::ExprKind::Field(..) => parser::PREC_FORCE_PAREN,
191 _ => parser::PREC_POSTFIX,
194 self.print_expr_maybe_paren(func, prec);
195 self.print_call_post(args)
198 fn print_expr_method_call(
200 segment: &ast::PathSegment,
201 receiver: &ast::Expr,
202 base_args: &[P<ast::Expr>],
204 self.print_expr_maybe_paren(receiver, parser::PREC_POSTFIX);
206 self.print_ident(segment.ident);
207 if let Some(args) = &segment.args {
208 self.print_generic_args(args, true);
210 self.print_call_post(base_args)
213 fn print_expr_binary(&mut self, op: ast::BinOp, lhs: &ast::Expr, rhs: &ast::Expr) {
214 let assoc_op = AssocOp::from_ast_binop(op.node);
215 let prec = assoc_op.precedence() as i8;
216 let fixity = assoc_op.fixity();
218 let (left_prec, right_prec) = match fixity {
219 Fixity::Left => (prec, prec + 1),
220 Fixity::Right => (prec + 1, prec),
221 Fixity::None => (prec + 1, prec + 1),
224 let left_prec = match (&lhs.kind, op.node) {
225 // These cases need parens: `x as i32 < y` has the parser thinking that `i32 < y` is
226 // the beginning of a path type. It starts trying to parse `x as (i32 < y ...` instead
227 // of `(x as i32) < ...`. We need to convince it _not_ to do that.
228 (&ast::ExprKind::Cast { .. }, ast::BinOpKind::Lt | ast::BinOpKind::Shl) => {
229 parser::PREC_FORCE_PAREN
231 // We are given `(let _ = a) OP b`.
233 // - When `OP <= LAnd` we should print `let _ = a OP b` to avoid redundant parens
234 // as the parser will interpret this as `(let _ = a) OP b`.
236 // - Otherwise, e.g. when we have `(let a = b) < c` in AST,
237 // parens are required since the parser would interpret `let a = b < c` as
238 // `let a = (b < c)`. To achieve this, we force parens.
239 (&ast::ExprKind::Let { .. }, _) if !parser::needs_par_as_let_scrutinee(prec) => {
240 parser::PREC_FORCE_PAREN
245 self.print_expr_maybe_paren(lhs, left_prec);
247 self.word_space(op.node.to_string());
248 self.print_expr_maybe_paren(rhs, right_prec)
251 fn print_expr_unary(&mut self, op: ast::UnOp, expr: &ast::Expr) {
252 self.word(ast::UnOp::to_string(op));
253 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
256 fn print_expr_addr_of(
258 kind: ast::BorrowKind,
259 mutability: ast::Mutability,
264 ast::BorrowKind::Ref => self.print_mutability(mutability, false),
265 ast::BorrowKind::Raw => {
266 self.word_nbsp("raw");
267 self.print_mutability(mutability, true);
270 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX)
273 pub fn print_expr(&mut self, expr: &ast::Expr) {
274 self.print_expr_outer_attr_style(expr, true)
277 pub(super) fn print_expr_outer_attr_style(&mut self, expr: &ast::Expr, is_inline: bool) {
278 self.maybe_print_comment(expr.span.lo());
280 let attrs = &expr.attrs;
282 self.print_outer_attributes_inline(attrs);
284 self.print_outer_attributes(attrs);
287 self.ibox(INDENT_UNIT);
288 self.ann.pre(self, AnnNode::Expr(expr));
290 ast::ExprKind::Box(expr) => {
291 self.word_space("box");
292 self.print_expr_maybe_paren(expr, parser::PREC_PREFIX);
294 ast::ExprKind::Array(exprs) => {
295 self.print_expr_vec(exprs);
297 ast::ExprKind::ConstBlock(anon_const) => {
298 self.print_expr_anon_const(anon_const, attrs);
300 ast::ExprKind::Repeat(element, count) => {
301 self.print_expr_repeat(element, count);
303 ast::ExprKind::Struct(se) => {
304 self.print_expr_struct(&se.qself, &se.path, &se.fields, &se.rest);
306 ast::ExprKind::Tup(exprs) => {
307 self.print_expr_tup(exprs);
309 ast::ExprKind::Call(func, args) => {
310 self.print_expr_call(func, args);
312 ast::ExprKind::MethodCall(box ast::MethodCall { seg, receiver, args, .. }) => {
313 self.print_expr_method_call(seg, receiver, args);
315 ast::ExprKind::Binary(op, lhs, rhs) => {
316 self.print_expr_binary(*op, lhs, rhs);
318 ast::ExprKind::Unary(op, expr) => {
319 self.print_expr_unary(*op, expr);
321 ast::ExprKind::AddrOf(k, m, expr) => {
322 self.print_expr_addr_of(*k, *m, expr);
324 ast::ExprKind::Lit(token_lit) => {
325 self.print_token_literal(*token_lit, expr.span);
327 ast::ExprKind::IncludedBytes(bytes) => {
328 let lit = token::Lit::new(token::ByteStr, escape_byte_str_symbol(bytes), None);
329 self.print_token_literal(lit, expr.span)
331 ast::ExprKind::Cast(expr, ty) => {
332 let prec = AssocOp::As.precedence() as i8;
333 self.print_expr_maybe_paren(expr, prec);
335 self.word_space("as");
338 ast::ExprKind::Type(expr, ty) => {
339 let prec = AssocOp::Colon.precedence() as i8;
340 self.print_expr_maybe_paren(expr, prec);
341 self.word_space(":");
344 ast::ExprKind::Let(pat, scrutinee, _) => {
345 self.print_let(pat, scrutinee);
347 ast::ExprKind::If(test, blk, elseopt) => self.print_if(test, blk, elseopt.as_deref()),
348 ast::ExprKind::While(test, 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(pat, iter, 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(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(expr, 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(box ast::Closure {
410 self.print_closure_binder(binder);
411 self.print_constness(*constness);
412 self.print_movability(*movability);
413 self.print_asyncness(*asyncness);
414 self.print_capture_clause(*capture_clause);
416 self.print_fn_params_and_ret(fn_decl, true);
418 self.print_expr(body);
419 self.end(); // need to close a box
421 // a box will be closed by print_expr, but we didn't want an overall
422 // wrapper so we closed the corresponding opening. so create an
423 // empty box to satisfy the close.
426 ast::ExprKind::Block(blk, opt_label) => {
427 if let Some(label) = opt_label {
428 self.print_ident(label.ident);
429 self.word_space(":");
431 // containing cbox, will be closed by print-block at }
433 // head-box, will be closed by print-block after {
435 self.print_block_with_attrs(blk, attrs);
437 ast::ExprKind::Async(capture_clause, _, blk) => {
438 self.word_nbsp("async");
439 self.print_capture_clause(*capture_clause);
440 // cbox/ibox in analogy to the `ExprKind::Block` arm above
443 self.print_block_with_attrs(blk, attrs);
445 ast::ExprKind::Await(expr) => {
446 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
449 ast::ExprKind::Assign(lhs, rhs, _) => {
450 let prec = AssocOp::Assign.precedence() as i8;
451 self.print_expr_maybe_paren(lhs, prec + 1);
453 self.word_space("=");
454 self.print_expr_maybe_paren(rhs, prec);
456 ast::ExprKind::AssignOp(op, lhs, rhs) => {
457 let prec = AssocOp::Assign.precedence() as i8;
458 self.print_expr_maybe_paren(lhs, prec + 1);
460 self.word(op.node.to_string());
461 self.word_space("=");
462 self.print_expr_maybe_paren(rhs, prec);
464 ast::ExprKind::Field(expr, ident) => {
465 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
467 self.print_ident(*ident);
469 ast::ExprKind::Index(expr, index) => {
470 self.print_expr_maybe_paren(expr, parser::PREC_POSTFIX);
472 self.print_expr(index);
475 ast::ExprKind::Range(start, end, limits) => {
476 // Special case for `Range`. `AssocOp` claims that `Range` has higher precedence
477 // than `Assign`, but `x .. x = x` gives a parse error instead of `x .. (x = x)`.
478 // Here we use a fake precedence value so that any child with lower precedence than
479 // a "normal" binop gets parenthesized. (`LOr` is the lowest-precedence binop.)
480 let fake_prec = AssocOp::LOr.precedence() as i8;
481 if let Some(e) = start {
482 self.print_expr_maybe_paren(e, fake_prec);
485 ast::RangeLimits::HalfOpen => self.word(".."),
486 ast::RangeLimits::Closed => self.word("..="),
488 if let Some(e) = end {
489 self.print_expr_maybe_paren(e, fake_prec);
492 ast::ExprKind::Underscore => self.word("_"),
493 ast::ExprKind::Path(None, path) => self.print_path(path, true, 0),
494 ast::ExprKind::Path(Some(qself), path) => self.print_qpath(path, qself, true),
495 ast::ExprKind::Break(opt_label, opt_expr) => {
497 if let Some(label) = opt_label {
499 self.print_ident(label.ident);
501 if let Some(expr) = opt_expr {
503 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
506 ast::ExprKind::Continue(opt_label) => {
507 self.word("continue");
508 if let Some(label) = opt_label {
510 self.print_ident(label.ident);
513 ast::ExprKind::Ret(result) => {
515 if let Some(expr) = result {
517 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
520 ast::ExprKind::Yeet(result) => {
524 if let Some(expr) = result {
526 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
529 ast::ExprKind::InlineAsm(a) => {
531 self.print_inline_asm(a);
533 ast::ExprKind::MacCall(m) => self.print_mac(m),
534 ast::ExprKind::Paren(e) => {
539 ast::ExprKind::Yield(e) => {
542 if let Some(expr) = e {
544 self.print_expr_maybe_paren(expr, parser::PREC_JUMP);
547 ast::ExprKind::Try(e) => {
548 self.print_expr_maybe_paren(e, parser::PREC_POSTFIX);
551 ast::ExprKind::TryBlock(blk) => {
554 self.word_nbsp("try");
555 self.print_block_with_attrs(blk, attrs)
557 ast::ExprKind::Err => {
559 self.word("/*ERROR*/");
563 self.ann.post(self, AnnNode::Expr(expr));
567 fn print_arm(&mut self, arm: &ast::Arm) {
568 // Note, I have no idea why this check is necessary, but here it is.
569 if arm.attrs.is_empty() {
572 self.cbox(INDENT_UNIT);
574 self.maybe_print_comment(arm.pat.span.lo());
575 self.print_outer_attributes(&arm.attrs);
576 self.print_pat(&arm.pat);
578 if let Some(e) = &arm.guard {
579 self.word_space("if");
583 self.word_space("=>");
585 match &arm.body.kind {
586 ast::ExprKind::Block(blk, opt_label) => {
587 if let Some(label) = opt_label {
588 self.print_ident(label.ident);
589 self.word_space(":");
592 // The block will close the pattern's ibox.
593 self.print_block_unclosed_indent(blk);
595 // If it is a user-provided unsafe block, print a comma after it.
596 if let BlockCheckMode::Unsafe(ast::UserProvided) = blk.rules {
601 self.end(); // Close the ibox for the pattern.
602 self.print_expr(&arm.body);
606 self.end(); // Close enclosing cbox.
609 fn print_closure_binder(&mut self, binder: &ast::ClosureBinder) {
611 ast::ClosureBinder::NotPresent => {}
612 ast::ClosureBinder::For { generic_params, .. } => {
613 self.print_formal_generic_params(generic_params)
618 fn print_movability(&mut self, movability: ast::Movability) {
620 ast::Movability::Static => self.word_space("static"),
621 ast::Movability::Movable => {}
625 fn print_capture_clause(&mut self, capture_clause: ast::CaptureBy) {
626 match capture_clause {
627 ast::CaptureBy::Value => self.word_space("move"),
628 ast::CaptureBy::Ref => {}