-/// A simple wrapper type against `ast::Arm`. Used inside `write_list()`.
-struct ArmWrapper<'a> {
- pub arm: &'a ast::Arm,
- /// True if the arm is the last one in match expression. Used to decide on whether we should add
- /// trailing comma to the match arm when `config.trailing_comma() == Never`.
- pub is_last: bool,
- /// Holds a byte position of `|` at the beginning of the arm pattern, if available.
- pub beginning_vert: Option<BytePos>,
-}
-
-impl<'a> ArmWrapper<'a> {
- pub fn new(
- arm: &'a ast::Arm,
- is_last: bool,
- beginning_vert: Option<BytePos>,
- ) -> ArmWrapper<'a> {
- ArmWrapper {
- arm,
- is_last,
- beginning_vert,
- }
- }
-}
-
-impl<'a> Spanned for ArmWrapper<'a> {
- fn span(&self) -> Span {
- if let Some(lo) = self.beginning_vert {
- mk_sp(lo, self.arm.span().hi())
- } else {
- self.arm.span()
- }
- }
-}
-
-impl<'a> Rewrite for ArmWrapper<'a> {
- fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
- rewrite_match_arm(context, self.arm, shape, self.is_last, self.beginning_vert)
- }
-}
-
-fn rewrite_match(
- context: &RewriteContext,
- cond: &ast::Expr,
- arms: &[ast::Arm],
- shape: Shape,
- span: Span,
- attrs: &[ast::Attribute],
-) -> Option<String> {
- // Do not take the rhs overhead from the upper expressions into account
- // when rewriting match condition.
- let cond_shape = Shape {
- width: context.budget(shape.used_width()),
- ..shape
- };
- // 6 = `match `
- let cond_shape = match context.config.indent_style() {
- IndentStyle::Visual => cond_shape.shrink_left(6)?,
- IndentStyle::Block => cond_shape.offset_left(6)?,
- };
- let cond_str = cond.rewrite(context, cond_shape)?;
- let alt_block_sep = &shape.indent.to_string_with_newline(context.config);
- let block_sep = match context.config.control_brace_style() {
- ControlBraceStyle::AlwaysNextLine => alt_block_sep,
- _ if last_line_extendable(&cond_str) => " ",
- // 2 = ` {`
- _ if cond_str.contains('\n') || cond_str.len() + 2 > cond_shape.width => alt_block_sep,
- _ => " ",
- };
-
- let nested_indent_str = shape
- .indent
- .block_indent(context.config)
- .to_string(context.config);
- // Inner attributes.
- let inner_attrs = &inner_attributes(attrs);
- let inner_attrs_str = if inner_attrs.is_empty() {
- String::new()
- } else {
- inner_attrs
- .rewrite(context, shape)
- .map(|s| format!("{}{}\n", nested_indent_str, s))?
- };
-
- let open_brace_pos = if inner_attrs.is_empty() {
- let hi = if arms.is_empty() {
- span.hi()
- } else {
- arms[0].span().lo()
- };
- context
- .snippet_provider
- .span_after(mk_sp(cond.span.hi(), hi), "{")
- } else {
- inner_attrs[inner_attrs.len() - 1].span().hi()
- };
-
- if arms.is_empty() {
- let snippet = context.snippet(mk_sp(open_brace_pos, span.hi() - BytePos(1)));
- if snippet.trim().is_empty() {
- Some(format!("match {} {{}}", cond_str))
- } else {
- // Empty match with comments or inner attributes? We are not going to bother, sorry ;)
- Some(context.snippet(span).to_owned())
- }
- } else {
- Some(format!(
- "match {}{}{{\n{}{}{}\n{}}}",
- cond_str,
- block_sep,
- inner_attrs_str,
- nested_indent_str,
- rewrite_match_arms(context, arms, shape, span, open_brace_pos)?,
- shape.indent.to_string(context.config),
- ))
- }
-}
-
-fn arm_comma(config: &Config, body: &ast::Expr, is_last: bool) -> &'static str {
- if is_last && config.trailing_comma() == SeparatorTactic::Never {
- ""
- } else if config.match_block_trailing_comma() {
- ","
- } else if let ast::ExprKind::Block(ref block) = body.node {
- if let ast::BlockCheckMode::Default = block.rules {
- ""
- } else {
- ","
- }
- } else {
- ","
- }
-}
-
-/// Collect a byte position of the beginning `|` for each arm, if available.
-fn collect_beginning_verts(
- context: &RewriteContext,
- arms: &[ast::Arm],
- span: Span,
-) -> Vec<Option<BytePos>> {
- let mut beginning_verts = Vec::with_capacity(arms.len());
- let mut lo = context.snippet_provider.span_after(span, "{");
- for arm in arms {
- let hi = arm.pats[0].span.lo();
- let missing_span = mk_sp(lo, hi);
- beginning_verts.push(context.snippet_provider.opt_span_before(missing_span, "|"));
- lo = arm.span().hi();
- }
- beginning_verts
-}
-
-fn rewrite_match_arms(
- context: &RewriteContext,
- arms: &[ast::Arm],
- shape: Shape,
- span: Span,
- open_brace_pos: BytePos,
-) -> Option<String> {
- let arm_shape = shape
- .block_indent(context.config.tab_spaces())
- .with_max_width(context.config);
-
- let arm_len = arms.len();
- let is_last_iter = repeat(false)
- .take(arm_len.checked_sub(1).unwrap_or(0))
- .chain(repeat(true));
- let beginning_verts = collect_beginning_verts(context, arms, span);
- let items = itemize_list(
- context.snippet_provider,
- arms.iter()
- .zip(is_last_iter)
- .zip(beginning_verts.into_iter())
- .map(|((arm, is_last), beginning_vert)| ArmWrapper::new(arm, is_last, beginning_vert)),
- "}",
- "|",
- |arm| arm.span().lo(),
- |arm| arm.span().hi(),
- |arm| arm.rewrite(context, arm_shape),
- open_brace_pos,
- span.hi(),
- false,
- );
- let arms_vec: Vec<_> = items.collect();
- let fmt = ListFormatting {
- tactic: DefinitiveListTactic::Vertical,
- // We will add/remove commas inside `arm.rewrite()`, and hence no separator here.
- separator: "",
- trailing_separator: SeparatorTactic::Never,
- separator_place: SeparatorPlace::Back,
- shape: arm_shape,
- ends_with_newline: true,
- preserve_newline: true,
- config: context.config,
- };
-
- write_list(&arms_vec, &fmt)
-}
-
-fn rewrite_match_arm(
- context: &RewriteContext,
- arm: &ast::Arm,
- shape: Shape,
- is_last: bool,
- beginning_vert: Option<BytePos>,
-) -> Option<String> {
- let (missing_span, attrs_str) = if !arm.attrs.is_empty() {
- if contains_skip(&arm.attrs) {
- let (_, body) = flatten_arm_body(context, &arm.body);
- // `arm.span()` does not include trailing comma, add it manually.
- return Some(format!(
- "{}{}",
- context.snippet(arm.span()),
- arm_comma(context.config, body, is_last),
- ));
- }
- let missing_span = mk_sp(
- arm.attrs[arm.attrs.len() - 1].span.hi(),
- arm.pats[0].span.lo(),
- );
- (missing_span, arm.attrs.rewrite(context, shape)?)
- } else {
- (mk_sp(arm.span().lo(), arm.span().lo()), String::new())
- };
- let pats_str = rewrite_match_pattern(
- context,
- &ptr_vec_to_ref_vec(&arm.pats),
- &arm.guard,
- beginning_vert.is_some(),
- shape,
- ).and_then(|pats_str| {
- combine_strs_with_missing_comments(
- context,
- &attrs_str,
- &pats_str,
- missing_span,
- shape,
- false,
- )
- })?;
- rewrite_match_body(
- context,
- &arm.body,
- &pats_str,
- shape,
- arm.guard.is_some(),
- is_last,
- )
-}
-
-/// Returns true if the given pattern is short. A short pattern is defined by the following grammer:
-///
-/// [small, ntp]:
-/// - single token
-/// - `&[single-line, ntp]`
-///
-/// [small]:
-/// - `[small, ntp]`
-/// - unary tuple constructor `([small, ntp])`
-/// - `&[small]`
-fn is_short_pattern(pat: &ast::Pat, pat_str: &str) -> bool {
- // We also require that the pattern is reasonably 'small' with its literal width.
- pat_str.len() <= 20 && !pat_str.contains('\n') && is_short_pattern_inner(pat)
-}
-
-fn is_short_pattern_inner(pat: &ast::Pat) -> bool {
- match pat.node {
- ast::PatKind::Wild | ast::PatKind::Lit(_) => true,
- ast::PatKind::Ident(_, _, ref pat) => pat.is_none(),
- ast::PatKind::Struct(..)
- | ast::PatKind::Mac(..)
- | ast::PatKind::Slice(..)
- | ast::PatKind::Path(..)
- | ast::PatKind::Range(..) => false,
- ast::PatKind::Tuple(ref subpats, _) => subpats.len() <= 1,
- ast::PatKind::TupleStruct(ref path, ref subpats, _) => {
- path.segments.len() <= 1 && subpats.len() <= 1
- }
- ast::PatKind::Box(ref p) | ast::PatKind::Ref(ref p, _) | ast::PatKind::Paren(ref p) => {
- is_short_pattern_inner(&*p)
- }
- }
-}
-
-fn rewrite_match_pattern(