1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use std::iter::ExactSizeIterator;
14 use syntax::ast::{self, FunctionRetTy, Mutability};
15 use syntax::source_map::{self, BytePos, Span};
16 use syntax::symbol::keywords;
18 use crate::config::lists::*;
19 use crate::config::{IndentStyle, TypeDensity};
20 use crate::expr::{rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix};
21 use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
22 use crate::macros::{rewrite_macro, MacroPosition};
24 use crate::pairs::{rewrite_pair, PairParts};
25 use crate::rewrite::{Rewrite, RewriteContext};
26 use crate::shape::Shape;
27 use crate::source_map::SpanUtils;
28 use crate::spanned::Spanned;
30 colon_spaces, extra_offset, first_line_width, format_abi, format_mutability,
31 last_line_extendable, last_line_width, mk_sp, rewrite_ident,
34 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
35 pub enum PathContext {
41 // Does not wrap on simple segments.
43 context: &RewriteContext<'_>,
44 path_context: PathContext,
45 qself: Option<&ast::QSelf>,
49 let skip_count = qself.map_or(0, |x| x.position);
51 let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
57 let mut span_lo = path.span.lo();
59 if let Some(qself) = qself {
62 let fmt_ty = qself.ty.rewrite(context, shape)?;
63 result.push_str(&fmt_ty);
66 result.push_str(" as ");
67 if path.is_global() && path_context != PathContext::Import {
68 result.push_str("::");
72 let shape = shape.sub_width(3)?;
74 result = rewrite_path_segments(
77 path.segments.iter().take(skip_count),
85 result.push_str(">::");
86 span_lo = qself.ty.span.hi() + BytePos(1);
89 rewrite_path_segments(
92 path.segments.iter().skip(skip_count),
100 fn rewrite_path_segments<'a, I>(
101 path_context: PathContext,
104 mut span_lo: BytePos,
106 context: &RewriteContext<'_>,
110 I: Iterator<Item = &'a ast::PathSegment>,
112 let mut first = true;
113 let shape = shape.visual_indent(0);
115 for segment in iter {
116 // Indicates a global path, shouldn't be rendered.
117 if segment.ident.name == keywords::PathRoot.name() {
123 buffer.push_str("::");
126 let extra_offset = extra_offset(&buffer, shape);
127 let new_shape = shape.shrink_left(extra_offset)?;
128 let segment_string = rewrite_segment(
137 buffer.push_str(&segment_string);
144 pub enum SegmentParam<'a> {
145 LifeTime(&'a ast::Lifetime),
147 Binding(&'a ast::TypeBinding),
150 impl<'a> SegmentParam<'a> {
151 fn from_generic_arg(arg: &ast::GenericArg) -> SegmentParam<'_> {
153 ast::GenericArg::Lifetime(ref lt) => SegmentParam::LifeTime(lt),
154 ast::GenericArg::Type(ref ty) => SegmentParam::Type(ty),
155 ast::GenericArg::Const(..) => unreachable!(), // FIXME(#3336)
160 impl<'a> Spanned for SegmentParam<'a> {
161 fn span(&self) -> Span {
163 SegmentParam::LifeTime(lt) => lt.ident.span,
164 SegmentParam::Type(ty) => ty.span,
165 SegmentParam::Binding(binding) => binding.span,
170 impl<'a> Rewrite for SegmentParam<'a> {
171 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
173 SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
174 SegmentParam::Type(ty) => ty.rewrite(context, shape),
175 SegmentParam::Binding(binding) => {
176 let mut result = match context.config.type_punctuation_density() {
177 TypeDensity::Wide => format!("{} = ", rewrite_ident(context, binding.ident)),
178 TypeDensity::Compressed => {
179 format!("{}=", rewrite_ident(context, binding.ident))
182 let budget = shape.width.checked_sub(result.len())?;
183 let rewrite = binding
185 .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
186 result.push_str(&rewrite);
193 // Formats a path segment. There are some hacks involved to correctly determine
194 // the segment's associated span since it's not part of the AST.
196 // The span_lo is assumed to be greater than the end of any previous segment's
197 // parameters and lesser or equal than the start of current segment.
199 // span_hi is assumed equal to the end of the entire path.
201 // When the segment contains a positive number of parameters, we update span_lo
202 // so that invariants described above will hold for the next segment.
204 path_context: PathContext,
205 segment: &ast::PathSegment,
206 span_lo: &mut BytePos,
208 context: &RewriteContext<'_>,
210 ) -> Option<String> {
211 let mut result = String::with_capacity(128);
212 result.push_str(rewrite_ident(context, segment.ident));
214 let ident_len = result.len();
215 let shape = if context.use_block_indent() {
216 shape.offset_left(ident_len)?
218 shape.shrink_left(ident_len)?
221 if let Some(ref args) = segment.args {
223 ast::GenericArgs::AngleBracketed(ref data)
224 if !data.args.is_empty() || !data.bindings.is_empty() =>
226 let param_list = data
229 .map(SegmentParam::from_generic_arg)
230 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
231 .collect::<Vec<_>>();
233 // HACK: squeeze out the span between the identifier and the parameters.
234 // The hack is requried so that we don't remove the separator inside macro calls.
235 // This does not work in the presence of comment, hoping that people are
236 // sane about where to put their comment.
237 let separator_snippet = context
238 .snippet(mk_sp(segment.ident.span.hi(), data.span.lo()))
240 let force_separator = context.inside_macro() && separator_snippet.starts_with("::");
241 let separator = if path_context == PathContext::Expr || force_separator {
246 result.push_str(separator);
248 let generics_str = overflow::rewrite_with_angle_brackets(
253 mk_sp(*span_lo, span_hi),
256 // Update position of last bracket.
259 .span_after(mk_sp(*span_lo, span_hi), "<");
261 result.push_str(&generics_str)
263 ast::GenericArgs::Parenthesized(ref data) => {
264 let output = match data.output {
265 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
266 None => FunctionRetTy::Default(source_map::DUMMY_SP),
268 result.push_str(&format_function_type(
269 data.inputs.iter().map(|x| &**x),
284 fn format_function_type<'a, I>(
286 output: &FunctionRetTy,
289 context: &RewriteContext<'_>,
293 I: ExactSizeIterator,
294 <I as Iterator>::Item: Deref,
295 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
297 debug!("format_function_type {:#?}", shape);
299 let ty_shape = match context.config.indent_style() {
301 IndentStyle::Block => shape.offset_left(4)?,
302 IndentStyle::Visual => shape.block_left(4)?,
304 let output = match *output {
305 FunctionRetTy::Ty(ref ty) => {
306 let type_str = ty.rewrite(context, ty_shape)?;
307 format!(" -> {}", type_str)
309 FunctionRetTy::Default(..) => String::new(),
312 // Code for handling variadics is somewhat duplicated for items, but they
313 // are different enough to need some serious refactoring to share code.
317 <T as Deref>::Target: Rewrite + Spanned,
323 let variadic_arg = if variadic {
324 let variadic_start = context.snippet_provider.span_before(span, "...");
325 Some(ArgumentKind::Variadic(variadic_start))
330 let list_shape = if context.use_block_indent() {
332 shape.block().indent.block_indent(context.config),
337 let budget = shape.width.checked_sub(2)?;
339 let offset = shape.indent + 1;
340 Shape::legacy(budget, offset)
342 let list_lo = context.snippet_provider.span_after(span, "(");
343 let items = itemize_list(
344 context.snippet_provider,
345 inputs.map(ArgumentKind::Regular).chain(variadic_arg),
349 ArgumentKind::Regular(ref ty) => ty.span().lo(),
350 ArgumentKind::Variadic(start) => start,
353 ArgumentKind::Regular(ref ty) => ty.span().hi(),
354 ArgumentKind::Variadic(start) => start + BytePos(3),
357 ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
358 ArgumentKind::Variadic(_) => Some("...".to_owned()),
365 let item_vec: Vec<_> = items.collect();
367 // If the return type is multi-lined, then force to use multiple lines for
368 // arguments as well.
369 let tactic = if output.contains('\n') {
370 DefinitiveListTactic::Vertical
374 ListTactic::HorizontalVertical,
376 shape.width.saturating_sub(2 + output.len()),
379 let trailing_separator = if !context.use_block_indent() || variadic {
380 SeparatorTactic::Never
382 context.config.trailing_comma()
385 let fmt = ListFormatting::new(list_shape, context.config)
387 .trailing_separator(trailing_separator)
388 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
389 .preserve_newline(true);
390 let list_str = write_list(&item_vec, &fmt)?;
392 let args = if tactic == DefinitiveListTactic::Horizontal || !context.use_block_indent() {
393 format!("({})", list_str)
397 list_shape.indent.to_string_with_newline(context.config),
399 shape.block().indent.to_string_with_newline(context.config),
402 if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
403 Some(format!("{}{}", args, output))
408 list_shape.indent.to_string(context.config),
414 fn type_bound_colon(context: &RewriteContext<'_>) -> &'static str {
416 context.config.space_before_colon(),
417 context.config.space_after_colon(),
421 impl Rewrite for ast::WherePredicate {
422 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
423 // FIXME: dead spans?
424 let result = match *self {
425 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
426 ref bound_generic_params,
431 let type_str = bounded_ty.rewrite(context, shape)?;
432 let colon = type_bound_colon(context).trim_end();
433 let lhs = if let Some(lifetime_str) =
434 rewrite_lifetime_param(context, shape, bound_generic_params)
436 format!("for<{}> {}{}", lifetime_str, type_str, colon)
438 format!("{}{}", type_str, colon)
441 rewrite_assign_rhs(context, lhs, bounds, shape)?
443 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
447 }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
448 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
453 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
454 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
462 impl Rewrite for ast::GenericArg {
463 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
465 ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
466 ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
467 ast::GenericArg::Const(..) => unreachable!(), // FIXME(#3336)
472 fn rewrite_bounded_lifetime(
474 bounds: &[ast::GenericBound],
475 context: &RewriteContext<'_>,
477 ) -> Option<String> {
478 let result = lt.rewrite(context, shape)?;
480 if bounds.is_empty() {
483 let colon = type_bound_colon(context);
484 let overhead = last_line_width(&result) + colon.len();
485 let result = format!(
489 join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
495 impl Rewrite for ast::Lifetime {
496 fn rewrite(&self, context: &RewriteContext<'_>, _: Shape) -> Option<String> {
497 Some(rewrite_ident(context, self.ident).to_owned())
501 impl Rewrite for ast::GenericBound {
502 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
504 ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
505 let snippet = context.snippet(self.span());
506 let has_paren = snippet.starts_with('(') && snippet.ends_with(')');
507 let rewrite = match trait_bound_modifier {
508 ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
509 ast::TraitBoundModifier::Maybe => poly_trait_ref
510 .rewrite(context, shape.offset_left(1)?)
511 .map(|s| format!("?{}", s)),
513 rewrite.map(|s| if has_paren { format!("({})", s) } else { s })
515 ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
520 impl Rewrite for ast::GenericBounds {
521 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
523 return Some(String::new());
526 join_bounds(context, shape, self, true)
530 impl Rewrite for ast::GenericParam {
531 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
532 let mut result = String::with_capacity(128);
533 // FIXME: If there are more than one attributes, this will force multiline.
534 match self.attrs.rewrite(context, shape) {
535 Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
538 result.push_str(rewrite_ident(context, self.ident));
539 if !self.bounds.is_empty() {
540 result.push_str(type_bound_colon(context));
541 result.push_str(&self.bounds.rewrite(context, shape)?)
543 if let ast::GenericParamKind::Type {
544 default: Some(ref def),
547 let eq_str = match context.config.type_punctuation_density() {
548 TypeDensity::Compressed => "=",
549 TypeDensity::Wide => " = ",
551 result.push_str(eq_str);
552 let budget = shape.width.checked_sub(result.len())?;
554 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
555 result.push_str(&rewrite);
562 impl Rewrite for ast::PolyTraitRef {
563 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
564 if let Some(lifetime_str) =
565 rewrite_lifetime_param(context, shape, &self.bound_generic_params)
567 // 6 is "for<> ".len()
568 let extra_offset = lifetime_str.len() + 6;
571 .rewrite(context, shape.offset_left(extra_offset)?)?;
573 Some(format!("for<{}> {}", lifetime_str, path_str))
575 self.trait_ref.rewrite(context, shape)
580 impl Rewrite for ast::TraitRef {
581 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
582 rewrite_path(context, PathContext::Type, None, &self.path, shape)
586 impl Rewrite for ast::Ty {
587 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
589 ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
590 // we have to consider 'dyn' keyword is used or not!!!
591 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
592 // 4 is length of 'dyn '
593 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
594 let mut res = bounds.rewrite(context, shape)?;
595 // We may have falsely removed a trailing `+` inside macro call.
596 if context.inside_macro() && bounds.len() == 1 {
597 if context.snippet(self.span).ends_with('+') && !res.ends_with('+') {
602 Some(format!("dyn {}", res))
607 ast::TyKind::Ptr(ref mt) => {
608 let prefix = match mt.mutbl {
609 Mutability::Mutable => "*mut ",
610 Mutability::Immutable => "*const ",
613 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
615 ast::TyKind::Rptr(ref lifetime, ref mt) => {
616 let mut_str = format_mutability(mt.mutbl);
617 let mut_len = mut_str.len();
618 Some(match *lifetime {
619 Some(ref lifetime) => {
620 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
621 let lt_str = lifetime.rewrite(
623 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
625 let lt_len = lt_str.len();
626 let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
633 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
638 let budget = shape.width.checked_sub(1 + mut_len)?;
644 Shape::legacy(budget, shape.indent + 1 + mut_len)
650 // FIXME: we drop any comments here, even though it's a silly place to put
652 ast::TyKind::Paren(ref ty) => {
653 let budget = shape.width.checked_sub(2)?;
654 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
655 .map(|ty_str| format!("({})", ty_str))
657 ast::TyKind::Slice(ref ty) => {
658 let budget = shape.width.checked_sub(4)?;
659 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
660 .map(|ty_str| format!("[{}]", ty_str))
662 ast::TyKind::Tup(ref items) => {
663 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
665 ast::TyKind::Path(ref q_self, ref path) => {
666 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
668 ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
671 PairParts::new("[", "; ", "]"),
674 SeparatorPlace::Back,
676 ast::TyKind::Infer => {
677 if shape.width >= 1 {
683 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
684 ast::TyKind::Never => Some(String::from("!")),
685 ast::TyKind::Mac(ref mac) => {
686 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
688 ast::TyKind::ImplicitSelf => Some(String::from("")),
689 ast::TyKind::ImplTrait(_, ref it) => it
690 .rewrite(context, shape)
691 .map(|it_str| format!("impl {}", it_str)),
692 ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
698 bare_fn: &ast::BareFnTy,
700 context: &RewriteContext<'_>,
702 ) -> Option<String> {
703 debug!("rewrite_bare_fn {:#?}", shape);
705 let mut result = String::with_capacity(128);
707 if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
709 result.push_str("for<");
710 // 6 = "for<> ".len(), 4 = "for<".
711 // This doesn't work out so nicely for multiline situation with lots of
712 // rightward drift. If that is a problem, we could use the list stuff.
713 result.push_str(lifetime_str);
714 result.push_str("> ");
717 result.push_str(crate::utils::format_unsafety(bare_fn.unsafety));
719 result.push_str(&format_abi(
721 context.config.force_explicit_abi(),
725 result.push_str("fn");
727 let func_ty_shape = if context.use_block_indent() {
728 shape.offset_left(result.len())?
730 shape.visual_indent(result.len()).sub_width(result.len())?
733 let rewrite = format_function_type(
734 bare_fn.decl.inputs.iter(),
735 &bare_fn.decl.output,
736 bare_fn.decl.variadic,
742 result.push_str(&rewrite);
747 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
748 let is_trait = |b: &ast::GenericBound| match b {
749 ast::GenericBound::Outlives(..) => false,
750 ast::GenericBound::Trait(..) => true,
752 let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
753 let last_trait_index = generic_bounds.iter().rposition(is_trait);
754 let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
755 match (last_trait_index, first_lifetime_index) {
756 (Some(last_trait_index), Some(first_lifetime_index)) => {
757 last_trait_index < first_lifetime_index
764 context: &RewriteContext<'_>,
766 items: &[ast::GenericBound],
768 ) -> Option<String> {
769 debug_assert!(!items.is_empty());
771 // Try to join types in a single line
772 let joiner = match context.config.type_punctuation_density() {
773 TypeDensity::Compressed => "+",
774 TypeDensity::Wide => " + ",
776 let type_strs = items
778 .map(|item| item.rewrite(context, shape))
779 .collect::<Option<Vec<_>>>()?;
780 let result = type_strs.join(joiner);
781 if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
785 // We need to use multiple lines.
786 let (type_strs, offset) = if need_indent {
787 // Rewrite with additional indentation.
788 let nested_shape = shape.block_indent(context.config.tab_spaces());
789 let type_strs = items
791 .map(|item| item.rewrite(context, nested_shape))
792 .collect::<Option<Vec<_>>>()?;
793 (type_strs, nested_shape.indent)
795 (type_strs, shape.indent)
798 let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
799 ast::GenericBound::Outlives(..) => true,
800 ast::GenericBound::Trait(..) => last_line_extendable(s),
802 let mut result = String::with_capacity(128);
803 result.push_str(&type_strs[0]);
804 let mut can_be_put_on_the_same_line = is_bound_extendable(&result, &items[0]);
805 let generic_bounds_in_order = is_generic_bounds_in_order(items);
806 for (bound, bound_str) in items[1..].iter().zip(type_strs[1..].iter()) {
807 if generic_bounds_in_order && can_be_put_on_the_same_line {
808 result.push_str(joiner);
810 result.push_str(&offset.to_string_with_newline(context.config));
811 result.push_str("+ ");
813 result.push_str(bound_str);
814 can_be_put_on_the_same_line = is_bound_extendable(bound_str, bound);
820 pub fn can_be_overflowed_type(context: &RewriteContext<'_>, ty: &ast::Ty, len: usize) -> bool {
822 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
823 ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
824 can_be_overflowed_type(context, &*mutty.ty, len)
830 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
831 fn rewrite_lifetime_param(
832 context: &RewriteContext<'_>,
834 generic_params: &[ast::GenericParam],
835 ) -> Option<String> {
836 let result = generic_params
838 .filter(|p| match p.kind {
839 ast::GenericParamKind::Lifetime => true,
842 .map(|lt| lt.rewrite(context, shape))
843 .collect::<Option<Vec<_>>>()?
845 if result.is_empty() {