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;
15 use syntax::ast::{self, FunctionRetTy, Mutability};
16 use syntax::codemap::{self, BytePos, Span};
17 use syntax::symbol::keywords;
19 use codemap::SpanUtils;
20 use config::{IndentStyle, TypeDensity};
22 rewrite_assign_rhs, rewrite_pair, rewrite_tuple, rewrite_unary_prefix, PairParts, ToExpr,
24 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
25 use macros::{rewrite_macro, MacroPosition};
27 use rewrite::{Rewrite, RewriteContext};
31 colon_spaces, extra_offset, first_line_width, format_abi, format_mutability, last_line_width,
35 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
36 pub enum PathContext {
42 // Does not wrap on simple segments.
44 context: &RewriteContext,
45 path_context: PathContext,
46 qself: Option<&ast::QSelf>,
50 let skip_count = qself.map_or(0, |x| x.position);
52 let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
58 let mut span_lo = path.span.lo();
60 if let Some(qself) = qself {
62 if context.config.spaces_within_parens_and_brackets() {
66 let fmt_ty = qself.ty.rewrite(context, shape)?;
67 result.push_str(&fmt_ty);
70 result.push_str(" as ");
71 if path.is_global() && path_context != PathContext::Import {
72 result.push_str("::");
76 let shape = shape.sub_width(3)?;
78 result = rewrite_path_segments(
81 path.segments.iter().take(skip_count),
89 if context.config.spaces_within_parens_and_brackets() {
93 result.push_str(">::");
94 span_lo = qself.ty.span.hi() + BytePos(1);
97 rewrite_path_segments(
100 path.segments.iter().skip(skip_count),
108 fn rewrite_path_segments<'a, I>(
109 path_context: PathContext,
112 mut span_lo: BytePos,
114 context: &RewriteContext,
118 I: Iterator<Item = &'a ast::PathSegment>,
120 let mut first = true;
121 let shape = shape.visual_indent(0);
123 for segment in iter {
124 // Indicates a global path, shouldn't be rendered.
125 if segment.ident.name == keywords::CrateRoot.name() {
131 buffer.push_str("::");
134 let extra_offset = extra_offset(&buffer, shape);
135 let new_shape = shape.shrink_left(extra_offset)?;
136 let segment_string = rewrite_segment(
145 buffer.push_str(&segment_string);
152 enum SegmentParam<'a> {
153 LifeTime(&'a ast::Lifetime),
155 Binding(&'a ast::TypeBinding),
158 impl<'a> Spanned for SegmentParam<'a> {
159 fn span(&self) -> Span {
161 SegmentParam::LifeTime(lt) => lt.ident.span,
162 SegmentParam::Type(ty) => ty.span,
163 SegmentParam::Binding(binding) => binding.span,
168 impl<'a> ToExpr for SegmentParam<'a> {
169 fn to_expr(&self) -> Option<&ast::Expr> {
173 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
175 SegmentParam::Type(ty) => ty.can_be_overflowed(context, len),
181 impl<'a> Rewrite for SegmentParam<'a> {
182 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
184 SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
185 SegmentParam::Type(ty) => ty.rewrite(context, shape),
186 SegmentParam::Binding(binding) => {
187 let mut result = match context.config.type_punctuation_density() {
188 TypeDensity::Wide => format!("{} = ", binding.ident),
189 TypeDensity::Compressed => format!("{}=", binding.ident),
191 let budget = shape.width.checked_sub(result.len())?;
192 let rewrite = binding
194 .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
195 result.push_str(&rewrite);
202 // Formats a path segment. There are some hacks involved to correctly determine
203 // the segment's associated span since it's not part of the AST.
205 // The span_lo is assumed to be greater than the end of any previous segment's
206 // parameters and lesser or equal than the start of current segment.
208 // span_hi is assumed equal to the end of the entire path.
210 // When the segment contains a positive number of parameters, we update span_lo
211 // so that invariants described above will hold for the next segment.
213 path_context: PathContext,
214 segment: &ast::PathSegment,
215 span_lo: &mut BytePos,
217 context: &RewriteContext,
219 ) -> Option<String> {
220 let mut result = String::with_capacity(128);
221 result.push_str(&segment.ident.name.as_str());
223 let ident_len = result.len();
224 let shape = if context.use_block_indent() {
225 shape.offset_left(ident_len)?
227 shape.shrink_left(ident_len)?
230 if let Some(ref params) = segment.parameters {
232 ast::PathParameters::AngleBracketed(ref data)
233 if !data.lifetimes.is_empty()
234 || !data.types.is_empty()
235 || !data.bindings.is_empty() =>
237 let param_list = data
240 .map(SegmentParam::LifeTime)
241 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
242 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
243 .collect::<Vec<_>>();
245 let separator = if path_context == PathContext::Expr {
250 result.push_str(separator);
252 let generics_str = overflow::rewrite_with_angle_brackets(
255 ¶m_list.iter().map(|e| &*e).collect::<Vec<_>>(),
257 mk_sp(*span_lo, span_hi),
260 // Update position of last bracket.
263 .span_after(mk_sp(*span_lo, span_hi), "<");
265 result.push_str(&generics_str)
267 ast::PathParameters::Parenthesized(ref data) => {
268 let output = match data.output {
269 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
270 None => FunctionRetTy::Default(codemap::DUMMY_SP),
272 result.push_str(&format_function_type(
273 data.inputs.iter().map(|x| &**x),
288 fn format_function_type<'a, I>(
290 output: &FunctionRetTy,
293 context: &RewriteContext,
297 I: ExactSizeIterator,
298 <I as Iterator>::Item: Deref,
299 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
301 // Code for handling variadics is somewhat duplicated for items, but they
302 // are different enough to need some serious refactoring to share code.
306 <T as Deref>::Target: Rewrite + Spanned,
312 let variadic_arg = if variadic {
313 let variadic_start = context.snippet_provider.span_before(span, "...");
314 Some(ArgumentKind::Variadic(variadic_start))
320 let budget = shape.width.checked_sub(2)?;
322 let offset = match context.config.indent_style() {
323 IndentStyle::Block => {
326 .block_indent(context.config.tab_spaces())
329 IndentStyle::Visual => shape.indent + 1,
331 let list_shape = Shape::legacy(budget, offset);
332 let list_lo = context.snippet_provider.span_after(span, "(");
333 let items = itemize_list(
334 context.snippet_provider,
335 inputs.map(ArgumentKind::Regular).chain(variadic_arg),
339 ArgumentKind::Regular(ref ty) => ty.span().lo(),
340 ArgumentKind::Variadic(start) => start,
343 ArgumentKind::Regular(ref ty) => ty.span().hi(),
344 ArgumentKind::Variadic(start) => start + BytePos(3),
347 ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
348 ArgumentKind::Variadic(_) => Some("...".to_owned()),
355 let item_vec: Vec<_> = items.collect();
357 let tactic = definitive_tactic(
359 ListTactic::HorizontalVertical,
364 let fmt = ListFormatting {
367 trailing_separator: if !context.use_block_indent() || variadic {
368 SeparatorTactic::Never
370 context.config.trailing_comma()
372 separator_place: SeparatorPlace::Back,
374 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
375 preserve_newline: true,
376 config: context.config,
379 let list_str = write_list(&item_vec, &fmt)?;
381 let ty_shape = match context.config.indent_style() {
383 IndentStyle::Block => shape.offset_left(4)?,
384 IndentStyle::Visual => shape.block_left(4)?,
386 let output = match *output {
387 FunctionRetTy::Ty(ref ty) => {
388 let type_str = ty.rewrite(context, ty_shape)?;
389 format!(" -> {}", type_str)
391 FunctionRetTy::Default(..) => String::new(),
394 let args = if (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n')
395 || !context.use_block_indent()
397 format!("({})", list_str)
401 offset.to_string_with_newline(context.config),
403 shape.block().indent.to_string_with_newline(context.config),
406 if last_line_width(&args) + first_line_width(&output) <= shape.width {
407 Some(format!("{}{}", args, output))
412 offset.to_string(context.config),
418 fn type_bound_colon(context: &RewriteContext) -> &'static str {
420 context.config.space_before_colon(),
421 context.config.space_after_colon(),
425 impl Rewrite for ast::WherePredicate {
426 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
428 let result = match *self {
429 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
430 ref bound_generic_params,
435 let type_str = bounded_ty.rewrite(context, shape)?;
436 let colon = type_bound_colon(context).trim_right();
437 let lhs = if let Some(lifetime_str) =
438 rewrite_lifetime_param(context, shape, bound_generic_params)
440 if context.config.spaces_within_parens_and_brackets()
441 && !lifetime_str.is_empty()
443 format!("for< {} > {}{}", lifetime_str, type_str, colon)
445 format!("for<{}> {}{}", lifetime_str, type_str, colon)
448 format!("{}{}", type_str, colon)
451 rewrite_assign_rhs(context, lhs, bounds, shape)?
453 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
457 }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
458 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
463 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
464 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
472 impl Rewrite for ast::LifetimeDef {
473 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
474 rewrite_bounded_lifetime(&self.lifetime, &self.bounds, context, shape)
478 fn rewrite_bounded_lifetime(
480 bounds: &[ast::Lifetime],
481 context: &RewriteContext,
483 ) -> Option<String> {
484 let result = lt.rewrite(context, shape)?;
486 if bounds.is_empty() {
489 let colon = type_bound_colon(context);
490 let overhead = last_line_width(&result) + colon.len();
491 let result = format!(
495 join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
501 impl Rewrite for ast::TyParamBound {
502 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
504 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
505 tref.rewrite(context, shape)
507 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => Some(
508 format!("?{}", tref.rewrite(context, shape.offset_left(1)?)?),
510 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, shape),
515 impl Rewrite for ast::Lifetime {
516 fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> {
517 Some(self.ident.to_string())
521 /// A simple wrapper over type param bounds in trait.
523 pub struct TraitTyParamBounds<'a> {
524 inner: &'a ast::TyParamBounds,
527 impl<'a> Rewrite for TraitTyParamBounds<'a> {
528 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
529 join_bounds(context, shape, self.inner, false)
533 impl Rewrite for ast::TyParamBounds {
534 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
535 join_bounds(context, shape, self, true)
539 impl Rewrite for ast::TyParam {
540 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
541 let mut result = String::with_capacity(128);
542 // FIXME: If there are more than one attributes, this will force multiline.
543 match self.attrs.rewrite(context, shape) {
544 Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
547 result.push_str(&self.ident.to_string());
548 if !self.bounds.is_empty() {
549 result.push_str(type_bound_colon(context));
550 result.push_str(&self.bounds.rewrite(context, shape)?)
552 if let Some(ref def) = self.default {
553 let eq_str = match context.config.type_punctuation_density() {
554 TypeDensity::Compressed => "=",
555 TypeDensity::Wide => " = ",
557 result.push_str(eq_str);
558 let budget = shape.width.checked_sub(result.len())?;
559 let rewrite = def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
560 result.push_str(&rewrite);
567 impl Rewrite for ast::PolyTraitRef {
568 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
569 if let Some(lifetime_str) =
570 rewrite_lifetime_param(context, shape, &self.bound_generic_params)
572 // 6 is "for<> ".len()
573 let extra_offset = lifetime_str.len() + 6;
576 .rewrite(context, shape.offset_left(extra_offset)?)?;
579 if context.config.spaces_within_parens_and_brackets() && !lifetime_str.is_empty() {
580 format!("for< {} > {}", lifetime_str, path_str)
582 format!("for<{}> {}", lifetime_str, path_str)
586 self.trait_ref.rewrite(context, shape)
591 impl Rewrite for ast::TraitRef {
592 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
593 rewrite_path(context, PathContext::Type, None, &self.path, shape)
597 impl Rewrite for ast::Ty {
598 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
600 ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
601 // we have to consider 'dyn' keyword is used or not!!!
602 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
603 // 4 is length of 'dyn '
604 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
605 let res = bounds.rewrite(context, shape)?;
607 Some(format!("dyn {}", res))
612 ast::TyKind::Ptr(ref mt) => {
613 let prefix = match mt.mutbl {
614 Mutability::Mutable => "*mut ",
615 Mutability::Immutable => "*const ",
618 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
620 ast::TyKind::Rptr(ref lifetime, ref mt) => {
621 let mut_str = format_mutability(mt.mutbl);
622 let mut_len = mut_str.len();
623 Some(match *lifetime {
624 Some(ref lifetime) => {
625 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
626 let lt_str = lifetime.rewrite(
628 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
630 let lt_len = lt_str.len();
631 let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
638 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
643 let budget = shape.width.checked_sub(1 + mut_len)?;
649 Shape::legacy(budget, shape.indent + 1 + mut_len)
655 // FIXME: we drop any comments here, even though it's a silly place to put
657 ast::TyKind::Paren(ref ty) => {
658 let budget = shape.width.checked_sub(2)?;
659 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
661 if context.config.spaces_within_parens_and_brackets() {
662 format!("( {} )", ty_str)
664 format!("({})", ty_str)
668 ast::TyKind::Slice(ref ty) => {
669 let budget = if context.config.spaces_within_parens_and_brackets() {
670 shape.width.checked_sub(4)?
672 shape.width.checked_sub(2)?
674 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
676 if context.config.spaces_within_parens_and_brackets() {
677 format!("[ {} ]", ty_str)
679 format!("[{}]", ty_str)
683 ast::TyKind::Tup(ref items) => rewrite_tuple(
685 &::utils::ptr_vec_to_ref_vec(items),
689 ast::TyKind::Path(ref q_self, ref path) => {
690 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
692 ast::TyKind::Array(ref ty, ref repeats) => {
693 let use_spaces = context.config.spaces_within_parens_and_brackets();
694 let lbr = if use_spaces { "[ " } else { "[" };
695 let rbr = if use_spaces { " ]" } else { "]" };
699 PairParts::new(lbr, "; ", rbr),
702 SeparatorPlace::Back,
705 ast::TyKind::Infer => {
706 if shape.width >= 1 {
712 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
713 ast::TyKind::Never => Some(String::from("!")),
714 ast::TyKind::Mac(ref mac) => {
715 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
717 ast::TyKind::ImplicitSelf => Some(String::from("")),
718 ast::TyKind::ImplTrait(ref it) => it
719 .rewrite(context, shape)
720 .map(|it_str| format!("impl {}", it_str)),
721 ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
727 bare_fn: &ast::BareFnTy,
729 context: &RewriteContext,
731 ) -> Option<String> {
732 let mut result = String::with_capacity(128);
734 if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
736 result.push_str("for<");
737 // 6 = "for<> ".len(), 4 = "for<".
738 // This doesn't work out so nicely for multiline situation with lots of
739 // rightward drift. If that is a problem, we could use the list stuff.
740 result.push_str(lifetime_str);
741 result.push_str("> ");
744 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
746 result.push_str(&format_abi(
748 context.config.force_explicit_abi(),
752 result.push_str("fn");
754 let func_ty_shape = shape.offset_left(result.len())?;
756 let rewrite = format_function_type(
757 bare_fn.decl.inputs.iter(),
758 &bare_fn.decl.output,
759 bare_fn.decl.variadic,
765 result.push_str(&rewrite);
771 context: &RewriteContext,
779 // Try to join types in a single line
780 let joiner = match context.config.type_punctuation_density() {
781 TypeDensity::Compressed => "+",
782 TypeDensity::Wide => " + ",
784 let type_strs = items
786 .map(|item| item.rewrite(context, shape))
787 .collect::<Option<Vec<_>>>()?;
788 let result = type_strs.join(joiner);
789 if items.len() == 1 || (!result.contains('\n') && result.len() <= shape.width) {
793 // We need to use multiple lines.
794 let (type_strs, offset) = if need_indent {
795 // Rewrite with additional indentation.
796 let nested_shape = shape.block_indent(context.config.tab_spaces());
797 let type_strs = items
799 .map(|item| item.rewrite(context, nested_shape))
800 .collect::<Option<Vec<_>>>()?;
801 (type_strs, nested_shape.indent)
803 (type_strs, shape.indent)
806 let joiner = format!("{}+ ", offset.to_string_with_newline(context.config));
807 Some(type_strs.join(&joiner))
810 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
812 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
813 ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
814 can_be_overflowed_type(context, &*mutty.ty, len)
820 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
821 fn rewrite_lifetime_param(
822 context: &RewriteContext,
824 generic_params: &[ast::GenericParam],
825 ) -> Option<String> {
826 let result = generic_params
828 .filter(|p| p.is_lifetime_param())
829 .map(|lt| lt.rewrite(context, shape))
830 .collect::<Option<Vec<_>>>()?
832 if result.is_empty() {