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::source_map::{self, BytePos, Span};
17 use syntax::symbol::keywords;
19 use config::{IndentStyle, TypeDensity};
20 use expr::{rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix};
21 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
22 use macros::{rewrite_macro, MacroPosition};
24 use pairs::{rewrite_pair, PairParts};
25 use rewrite::{Rewrite, RewriteContext};
27 use source_map::SpanUtils;
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::CrateRoot.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),
159 impl<'a> Spanned for SegmentParam<'a> {
160 fn span(&self) -> Span {
162 SegmentParam::LifeTime(lt) => lt.ident.span,
163 SegmentParam::Type(ty) => ty.span,
164 SegmentParam::Binding(binding) => binding.span,
169 impl<'a> Rewrite for SegmentParam<'a> {
170 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
172 SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
173 SegmentParam::Type(ty) => ty.rewrite(context, shape),
174 SegmentParam::Binding(binding) => {
175 let mut result = match context.config.type_punctuation_density() {
176 TypeDensity::Wide => format!("{} = ", rewrite_ident(context, binding.ident)),
177 TypeDensity::Compressed => {
178 format!("{}=", rewrite_ident(context, binding.ident))
181 let budget = shape.width.checked_sub(result.len())?;
182 let rewrite = binding
184 .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
185 result.push_str(&rewrite);
192 // Formats a path segment. There are some hacks involved to correctly determine
193 // the segment's associated span since it's not part of the AST.
195 // The span_lo is assumed to be greater than the end of any previous segment's
196 // parameters and lesser or equal than the start of current segment.
198 // span_hi is assumed equal to the end of the entire path.
200 // When the segment contains a positive number of parameters, we update span_lo
201 // so that invariants described above will hold for the next segment.
203 path_context: PathContext,
204 segment: &ast::PathSegment,
205 span_lo: &mut BytePos,
207 context: &RewriteContext,
209 ) -> Option<String> {
210 let mut result = String::with_capacity(128);
211 result.push_str(rewrite_ident(context, segment.ident));
213 let ident_len = result.len();
214 let shape = if context.use_block_indent() {
215 shape.offset_left(ident_len)?
217 shape.shrink_left(ident_len)?
220 if let Some(ref args) = segment.args {
222 ast::GenericArgs::AngleBracketed(ref data)
223 if !data.args.is_empty() || !data.bindings.is_empty() =>
225 let param_list = data
228 .map(SegmentParam::from_generic_arg)
229 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
230 .collect::<Vec<_>>();
232 let separator = if path_context == PathContext::Expr {
237 result.push_str(separator);
239 let generics_str = overflow::rewrite_with_angle_brackets(
244 mk_sp(*span_lo, span_hi),
247 // Update position of last bracket.
250 .span_after(mk_sp(*span_lo, span_hi), "<");
252 result.push_str(&generics_str)
254 ast::GenericArgs::Parenthesized(ref data) => {
255 let output = match data.output {
256 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
257 None => FunctionRetTy::Default(source_map::DUMMY_SP),
259 result.push_str(&format_function_type(
260 data.inputs.iter().map(|x| &**x),
275 fn format_function_type<'a, I>(
277 output: &FunctionRetTy,
280 context: &RewriteContext,
284 I: ExactSizeIterator,
285 <I as Iterator>::Item: Deref,
286 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
288 debug!("format_function_type {:#?}", shape);
290 // Code for handling variadics is somewhat duplicated for items, but they
291 // are different enough to need some serious refactoring to share code.
295 <T as Deref>::Target: Rewrite + Spanned,
301 let variadic_arg = if variadic {
302 let variadic_start = context.snippet_provider.span_before(span, "...");
303 Some(ArgumentKind::Variadic(variadic_start))
309 let budget = shape.width.checked_sub(2)?;
311 let offset = match context.config.indent_style() {
312 IndentStyle::Block => {
315 .block_indent(context.config.tab_spaces())
318 IndentStyle::Visual => shape.indent + 1,
320 let list_shape = Shape::legacy(budget, offset);
321 let list_lo = context.snippet_provider.span_after(span, "(");
322 let items = itemize_list(
323 context.snippet_provider,
324 inputs.map(ArgumentKind::Regular).chain(variadic_arg),
328 ArgumentKind::Regular(ref ty) => ty.span().lo(),
329 ArgumentKind::Variadic(start) => start,
332 ArgumentKind::Regular(ref ty) => ty.span().hi(),
333 ArgumentKind::Variadic(start) => start + BytePos(3),
336 ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
337 ArgumentKind::Variadic(_) => Some("...".to_owned()),
344 let item_vec: Vec<_> = items.collect();
346 let tactic = definitive_tactic(
348 ListTactic::HorizontalVertical,
352 let trailing_separator = if !context.use_block_indent() || variadic {
353 SeparatorTactic::Never
355 context.config.trailing_comma()
358 let fmt = ListFormatting::new(list_shape, context.config)
360 .trailing_separator(trailing_separator)
361 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
362 .preserve_newline(true);
363 let list_str = write_list(&item_vec, &fmt)?;
365 let ty_shape = match context.config.indent_style() {
367 IndentStyle::Block => shape.offset_left(4)?,
368 IndentStyle::Visual => shape.block_left(4)?,
370 let output = match *output {
371 FunctionRetTy::Ty(ref ty) => {
372 let type_str = ty.rewrite(context, ty_shape)?;
373 format!(" -> {}", type_str)
375 FunctionRetTy::Default(..) => String::new(),
378 let args = if (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n')
379 || !context.use_block_indent()
381 format!("({})", list_str)
385 offset.to_string_with_newline(context.config),
387 shape.block().indent.to_string_with_newline(context.config),
390 if output.is_empty() || last_line_width(&args) + first_line_width(&output) <= shape.width {
391 Some(format!("{}{}", args, output))
396 offset.to_string(context.config),
402 fn type_bound_colon(context: &RewriteContext) -> &'static str {
404 context.config.space_before_colon(),
405 context.config.space_after_colon(),
409 impl Rewrite for ast::WherePredicate {
410 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
411 // FIXME: dead spans?
412 let result = match *self {
413 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
414 ref bound_generic_params,
419 let type_str = bounded_ty.rewrite(context, shape)?;
420 let colon = type_bound_colon(context).trim_right();
421 let lhs = if let Some(lifetime_str) =
422 rewrite_lifetime_param(context, shape, bound_generic_params)
424 format!("for<{}> {}{}", lifetime_str, type_str, colon)
426 format!("{}{}", type_str, colon)
429 rewrite_assign_rhs(context, lhs, bounds, shape)?
431 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
435 }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
436 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
441 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
442 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
450 impl Rewrite for ast::GenericArg {
451 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
453 ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
454 ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
459 fn rewrite_bounded_lifetime(
461 bounds: &[ast::GenericBound],
462 context: &RewriteContext,
464 ) -> Option<String> {
465 let result = lt.rewrite(context, shape)?;
467 if bounds.is_empty() {
470 let colon = type_bound_colon(context);
471 let overhead = last_line_width(&result) + colon.len();
472 let result = format!(
476 join_bounds(context, shape.sub_width(overhead)?, bounds, true, false)?
482 impl Rewrite for ast::Lifetime {
483 fn rewrite(&self, context: &RewriteContext, _: Shape) -> Option<String> {
484 Some(rewrite_ident(context, self.ident).to_owned())
488 impl Rewrite for ast::GenericBound {
489 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
491 ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
492 match trait_bound_modifier {
493 ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
494 ast::TraitBoundModifier::Maybe => {
495 let rw = poly_trait_ref.rewrite(context, shape.offset_left(1)?)?;
496 Some(format!("?{}", rw))
500 ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
505 impl Rewrite for ast::GenericBounds {
506 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
508 return Some(String::new());
511 let span = mk_sp(self.get(0)?.span().lo(), self.last()?.span().hi());
512 let has_paren = context.snippet(span).starts_with('(');
513 let bounds_shape = if has_paren {
514 shape.offset_left(1)?.sub_width(1)?
518 join_bounds(context, bounds_shape, self, true, has_paren)
522 impl Rewrite for ast::GenericParam {
523 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
524 let mut result = String::with_capacity(128);
525 // FIXME: If there are more than one attributes, this will force multiline.
526 match self.attrs.rewrite(context, shape) {
527 Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
530 result.push_str(rewrite_ident(context, self.ident));
531 if !self.bounds.is_empty() {
532 result.push_str(type_bound_colon(context));
533 result.push_str(&self.bounds.rewrite(context, shape)?)
535 if let ast::GenericParamKind::Type {
536 default: Some(ref def),
539 let eq_str = match context.config.type_punctuation_density() {
540 TypeDensity::Compressed => "=",
541 TypeDensity::Wide => " = ",
543 result.push_str(eq_str);
544 let budget = shape.width.checked_sub(result.len())?;
546 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
547 result.push_str(&rewrite);
554 impl Rewrite for ast::PolyTraitRef {
555 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
556 if let Some(lifetime_str) =
557 rewrite_lifetime_param(context, shape, &self.bound_generic_params)
559 // 6 is "for<> ".len()
560 let extra_offset = lifetime_str.len() + 6;
563 .rewrite(context, shape.offset_left(extra_offset)?)?;
565 Some(format!("for<{}> {}", lifetime_str, path_str))
567 self.trait_ref.rewrite(context, shape)
572 impl Rewrite for ast::TraitRef {
573 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
574 rewrite_path(context, PathContext::Type, None, &self.path, shape)
578 impl Rewrite for ast::Ty {
579 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
581 ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
582 // we have to consider 'dyn' keyword is used or not!!!
583 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
584 // 4 is length of 'dyn '
585 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
586 let res = bounds.rewrite(context, shape)?;
588 Some(format!("dyn {}", res))
593 ast::TyKind::Ptr(ref mt) => {
594 let prefix = match mt.mutbl {
595 Mutability::Mutable => "*mut ",
596 Mutability::Immutable => "*const ",
599 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
601 ast::TyKind::Rptr(ref lifetime, ref mt) => {
602 let mut_str = format_mutability(mt.mutbl);
603 let mut_len = mut_str.len();
604 Some(match *lifetime {
605 Some(ref lifetime) => {
606 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
607 let lt_str = lifetime.rewrite(
609 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
611 let lt_len = lt_str.len();
612 let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
619 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
624 let budget = shape.width.checked_sub(1 + mut_len)?;
630 Shape::legacy(budget, shape.indent + 1 + mut_len)
636 // FIXME: we drop any comments here, even though it's a silly place to put
638 ast::TyKind::Paren(ref ty) => {
639 let budget = shape.width.checked_sub(2)?;
640 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
641 .map(|ty_str| format!("({})", ty_str))
643 ast::TyKind::Slice(ref ty) => {
644 let budget = shape.width.checked_sub(4)?;
645 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
646 .map(|ty_str| format!("[{}]", ty_str))
648 ast::TyKind::Tup(ref items) => {
649 rewrite_tuple(context, items.iter(), self.span, shape, items.len() == 1)
651 ast::TyKind::Path(ref q_self, ref path) => {
652 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
654 ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
657 PairParts::new("[", "; ", "]"),
660 SeparatorPlace::Back,
662 ast::TyKind::Infer => {
663 if shape.width >= 1 {
669 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
670 ast::TyKind::Never => Some(String::from("!")),
671 ast::TyKind::Mac(ref mac) => {
672 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
674 ast::TyKind::ImplicitSelf => Some(String::from("")),
675 ast::TyKind::ImplTrait(_, ref it) => it
676 .rewrite(context, shape)
677 .map(|it_str| format!("impl {}", it_str)),
678 ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
684 bare_fn: &ast::BareFnTy,
686 context: &RewriteContext,
688 ) -> Option<String> {
689 debug!("rewrite_bare_fn {:#?}", shape);
691 let mut result = String::with_capacity(128);
693 if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
695 result.push_str("for<");
696 // 6 = "for<> ".len(), 4 = "for<".
697 // This doesn't work out so nicely for multiline situation with lots of
698 // rightward drift. If that is a problem, we could use the list stuff.
699 result.push_str(lifetime_str);
700 result.push_str("> ");
703 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
705 result.push_str(&format_abi(
707 context.config.force_explicit_abi(),
711 result.push_str("fn");
713 let func_ty_shape = if context.use_block_indent() {
714 shape.offset_left(result.len())?
716 shape.visual_indent(result.len()).sub_width(result.len())?
719 let rewrite = format_function_type(
720 bare_fn.decl.inputs.iter(),
721 &bare_fn.decl.output,
722 bare_fn.decl.variadic,
728 result.push_str(&rewrite);
733 fn is_generic_bounds_in_order(generic_bounds: &[ast::GenericBound]) -> bool {
734 let is_trait = |b: &ast::GenericBound| match b {
735 ast::GenericBound::Outlives(..) => false,
736 ast::GenericBound::Trait(..) => true,
738 let is_lifetime = |b: &ast::GenericBound| !is_trait(b);
739 let last_trait_index = generic_bounds.iter().rposition(is_trait);
740 let first_lifetime_index = generic_bounds.iter().position(is_lifetime);
741 match (last_trait_index, first_lifetime_index) {
742 (Some(last_trait_index), Some(first_lifetime_index)) => {
743 last_trait_index < first_lifetime_index
750 context: &RewriteContext,
752 items: &[ast::GenericBound],
755 ) -> Option<String> {
756 debug_assert!(!items.is_empty());
758 // Try to join types in a single line
759 let joiner = match context.config.type_punctuation_density() {
760 TypeDensity::Compressed => "+",
761 TypeDensity::Wide => " + ",
763 let type_strs = items
769 shape.sub_width(1)?.offset_left(1)?
775 .collect::<Option<Vec<_>>>()?;
776 let mut result = String::with_capacity(128);
777 let mut closing_paren = has_paren;
781 result.push_str(&type_strs[0]);
782 if has_paren && type_strs.len() == 1 {
785 for (i, type_str) in type_strs[1..].iter().enumerate() {
787 if let ast::GenericBound::Outlives(..) = items[i + 1] {
789 closing_paren = false;
792 result.push_str(joiner);
793 result.push_str(type_str);
795 if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
799 // We need to use multiple lines.
800 let (type_strs, offset) = if need_indent {
801 // Rewrite with additional indentation.
802 let nested_shape = shape.block_indent(context.config.tab_spaces());
803 let type_strs = items
805 .map(|item| item.rewrite(context, nested_shape))
806 .collect::<Option<Vec<_>>>()?;
807 (type_strs, nested_shape.indent)
809 (type_strs, shape.indent)
812 let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
813 ast::GenericBound::Outlives(..) => true,
814 ast::GenericBound::Trait(..) => last_line_extendable(s),
816 let mut result = String::with_capacity(128);
817 let mut closing_paren = has_paren;
821 result.push_str(&type_strs[0]);
822 let mut can_be_put_on_the_same_line = is_bound_extendable(&result, &items[0]);
823 let generic_bounds_in_order = is_generic_bounds_in_order(items);
824 for (bound, bound_str) in items[1..].iter().zip(type_strs[1..].iter()) {
826 if let ast::GenericBound::Outlives(..) = bound {
827 closing_paren = false;
831 if generic_bounds_in_order && can_be_put_on_the_same_line {
832 result.push_str(joiner);
834 result.push_str(&offset.to_string_with_newline(context.config));
835 result.push_str("+ ");
837 result.push_str(bound_str);
838 can_be_put_on_the_same_line = is_bound_extendable(bound_str, bound);
844 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
846 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
847 ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
848 can_be_overflowed_type(context, &*mutty.ty, len)
854 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
855 fn rewrite_lifetime_param(
856 context: &RewriteContext,
858 generic_params: &[ast::GenericParam],
859 ) -> Option<String> {
860 let result = generic_params
862 .filter(|p| match p.kind {
863 ast::GenericParamKind::Lifetime => true,
866 .map(|lt| lt.rewrite(context, shape))
867 .collect::<Option<Vec<_>>>()?
869 if result.is_empty() {