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};
21 use expr::{rewrite_assign_rhs, rewrite_tuple, rewrite_unary_prefix, ToExpr};
22 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
23 use macros::{rewrite_macro, MacroPosition};
25 use pairs::{rewrite_pair, PairParts};
26 use rewrite::{Rewrite, RewriteContext};
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 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> ToExpr for SegmentParam<'a> {
170 fn to_expr(&self) -> Option<&ast::Expr> {
174 fn can_be_overflowed(&self, context: &RewriteContext, len: usize) -> bool {
176 SegmentParam::Type(ty) => ty.can_be_overflowed(context, len),
182 impl<'a> Rewrite for SegmentParam<'a> {
183 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
185 SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
186 SegmentParam::Type(ty) => ty.rewrite(context, shape),
187 SegmentParam::Binding(binding) => {
188 let mut result = match context.config.type_punctuation_density() {
189 TypeDensity::Wide => format!("{} = ", rewrite_ident(context, binding.ident)),
190 TypeDensity::Compressed => {
191 format!("{}=", rewrite_ident(context, binding.ident))
194 let budget = shape.width.checked_sub(result.len())?;
195 let rewrite = binding
197 .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
198 result.push_str(&rewrite);
205 // Formats a path segment. There are some hacks involved to correctly determine
206 // the segment's associated span since it's not part of the AST.
208 // The span_lo is assumed to be greater than the end of any previous segment's
209 // parameters and lesser or equal than the start of current segment.
211 // span_hi is assumed equal to the end of the entire path.
213 // When the segment contains a positive number of parameters, we update span_lo
214 // so that invariants described above will hold for the next segment.
216 path_context: PathContext,
217 segment: &ast::PathSegment,
218 span_lo: &mut BytePos,
220 context: &RewriteContext,
222 ) -> Option<String> {
223 let mut result = String::with_capacity(128);
224 result.push_str(rewrite_ident(context, segment.ident));
226 let ident_len = result.len();
227 let shape = if context.use_block_indent() {
228 shape.offset_left(ident_len)?
230 shape.shrink_left(ident_len)?
233 if let Some(ref args) = segment.args {
235 ast::GenericArgs::AngleBracketed(ref data)
236 if !data.args.is_empty() || !data.bindings.is_empty() =>
238 let param_list = data
241 .map(SegmentParam::from_generic_arg)
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::GenericArgs::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,
363 let trailing_separator = if !context.use_block_indent() || variadic {
364 SeparatorTactic::Never
366 context.config.trailing_comma()
369 let fmt = ListFormatting::new(list_shape, context.config)
371 .trailing_separator(trailing_separator)
372 .ends_with_newline(tactic.ends_with_newline(context.config.indent_style()))
373 .preserve_newline(true);
374 let list_str = write_list(&item_vec, &fmt)?;
376 let ty_shape = match context.config.indent_style() {
378 IndentStyle::Block => shape.offset_left(4)?,
379 IndentStyle::Visual => shape.block_left(4)?,
381 let output = match *output {
382 FunctionRetTy::Ty(ref ty) => {
383 let type_str = ty.rewrite(context, ty_shape)?;
384 format!(" -> {}", type_str)
386 FunctionRetTy::Default(..) => String::new(),
389 let args = if (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n')
390 || !context.use_block_indent()
392 format!("({})", list_str)
396 offset.to_string_with_newline(context.config),
398 shape.block().indent.to_string_with_newline(context.config),
401 if last_line_width(&args) + first_line_width(&output) <= shape.width {
402 Some(format!("{}{}", args, output))
407 offset.to_string(context.config),
413 fn type_bound_colon(context: &RewriteContext) -> &'static str {
415 context.config.space_before_colon(),
416 context.config.space_after_colon(),
420 impl Rewrite for ast::WherePredicate {
421 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
422 // FIXME: dead spans?
423 let result = match *self {
424 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
425 ref bound_generic_params,
430 let type_str = bounded_ty.rewrite(context, shape)?;
431 let colon = type_bound_colon(context).trim_right();
432 let lhs = if let Some(lifetime_str) =
433 rewrite_lifetime_param(context, shape, bound_generic_params)
435 format!("for<{}> {}{}", lifetime_str, type_str, colon)
437 format!("{}{}", type_str, colon)
440 rewrite_assign_rhs(context, lhs, bounds, shape)?
442 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
446 }) => rewrite_bounded_lifetime(lifetime, bounds, context, shape)?,
447 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
452 let lhs_ty_str = lhs_ty.rewrite(context, shape).map(|lhs| lhs + " =")?;
453 rewrite_assign_rhs(context, lhs_ty_str, &**rhs_ty, shape)?
461 impl Rewrite for ast::GenericArg {
462 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
464 ast::GenericArg::Lifetime(ref lt) => lt.rewrite(context, shape),
465 ast::GenericArg::Type(ref ty) => ty.rewrite(context, shape),
470 fn rewrite_bounded_lifetime(
472 bounds: &[ast::GenericBound],
473 context: &RewriteContext,
475 ) -> Option<String> {
476 let result = lt.rewrite(context, shape)?;
478 if bounds.is_empty() {
481 let colon = type_bound_colon(context);
482 let overhead = last_line_width(&result) + colon.len();
483 let result = format!(
487 join_bounds(context, shape.sub_width(overhead)?, bounds, true)?
493 impl Rewrite for ast::Lifetime {
494 fn rewrite(&self, context: &RewriteContext, _: Shape) -> Option<String> {
495 Some(rewrite_ident(context, self.ident).to_owned())
499 impl Rewrite for ast::GenericBound {
500 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
502 ast::GenericBound::Trait(ref poly_trait_ref, trait_bound_modifier) => {
503 match trait_bound_modifier {
504 ast::TraitBoundModifier::None => poly_trait_ref.rewrite(context, shape),
505 ast::TraitBoundModifier::Maybe => {
506 let rw = poly_trait_ref.rewrite(context, shape.offset_left(1)?)?;
507 Some(format!("?{}", rw))
511 ast::GenericBound::Outlives(ref lifetime) => lifetime.rewrite(context, shape),
516 impl Rewrite for ast::GenericBounds {
517 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
519 return Some(String::new());
522 let span = mk_sp(self.get(0)?.span().lo(), self.last()?.span().hi());
523 let has_paren = context.snippet(span).starts_with("(");
524 let bounds_shape = if has_paren {
525 shape.offset_left(1)?.sub_width(1)?
529 join_bounds(context, bounds_shape, self, true).map(|s| {
539 impl Rewrite for ast::GenericParam {
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(rewrite_ident(context, self.ident));
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 ast::GenericParamKind::Type {
553 default: Some(ref def),
556 let eq_str = match context.config.type_punctuation_density() {
557 TypeDensity::Compressed => "=",
558 TypeDensity::Wide => " = ",
560 result.push_str(eq_str);
561 let budget = shape.width.checked_sub(result.len())?;
563 def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
564 result.push_str(&rewrite);
571 impl Rewrite for ast::PolyTraitRef {
572 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
573 if let Some(lifetime_str) =
574 rewrite_lifetime_param(context, shape, &self.bound_generic_params)
576 // 6 is "for<> ".len()
577 let extra_offset = lifetime_str.len() + 6;
580 .rewrite(context, shape.offset_left(extra_offset)?)?;
582 Some(format!("for<{}> {}", lifetime_str, path_str))
584 self.trait_ref.rewrite(context, shape)
589 impl Rewrite for ast::TraitRef {
590 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
591 rewrite_path(context, PathContext::Type, None, &self.path, shape)
595 impl Rewrite for ast::Ty {
596 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
598 ast::TyKind::TraitObject(ref bounds, tobj_syntax) => {
599 // we have to consider 'dyn' keyword is used or not!!!
600 let is_dyn = tobj_syntax == ast::TraitObjectSyntax::Dyn;
601 // 4 is length of 'dyn '
602 let shape = if is_dyn { shape.offset_left(4)? } else { shape };
603 let res = bounds.rewrite(context, shape)?;
605 Some(format!("dyn {}", res))
610 ast::TyKind::Ptr(ref mt) => {
611 let prefix = match mt.mutbl {
612 Mutability::Mutable => "*mut ",
613 Mutability::Immutable => "*const ",
616 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
618 ast::TyKind::Rptr(ref lifetime, ref mt) => {
619 let mut_str = format_mutability(mt.mutbl);
620 let mut_len = mut_str.len();
621 Some(match *lifetime {
622 Some(ref lifetime) => {
623 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
624 let lt_str = lifetime.rewrite(
626 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
628 let lt_len = lt_str.len();
629 let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
636 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
641 let budget = shape.width.checked_sub(1 + mut_len)?;
647 Shape::legacy(budget, shape.indent + 1 + mut_len)
653 // FIXME: we drop any comments here, even though it's a silly place to put
655 ast::TyKind::Paren(ref ty) => {
656 let budget = shape.width.checked_sub(2)?;
657 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
658 .map(|ty_str| format!("({})", ty_str))
660 ast::TyKind::Slice(ref ty) => {
661 let budget = shape.width.checked_sub(4)?;
662 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
663 .map(|ty_str| format!("[{}]", ty_str))
665 ast::TyKind::Tup(ref items) => rewrite_tuple(
667 &::utils::ptr_vec_to_ref_vec(items),
671 ast::TyKind::Path(ref q_self, ref path) => {
672 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
674 ast::TyKind::Array(ref ty, ref repeats) => rewrite_pair(
677 PairParts::new("[", "; ", "]"),
680 SeparatorPlace::Back,
682 ast::TyKind::Infer => {
683 if shape.width >= 1 {
689 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
690 ast::TyKind::Never => Some(String::from("!")),
691 ast::TyKind::Mac(ref mac) => {
692 rewrite_macro(mac, None, context, shape, MacroPosition::Expression)
694 ast::TyKind::ImplicitSelf => Some(String::from("")),
695 ast::TyKind::ImplTrait(_, ref it) => it
696 .rewrite(context, shape)
697 .map(|it_str| format!("impl {}", it_str)),
698 ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
704 bare_fn: &ast::BareFnTy,
706 context: &RewriteContext,
708 ) -> Option<String> {
709 let mut result = String::with_capacity(128);
711 if let Some(ref lifetime_str) = rewrite_lifetime_param(context, shape, &bare_fn.generic_params)
713 result.push_str("for<");
714 // 6 = "for<> ".len(), 4 = "for<".
715 // This doesn't work out so nicely for multiline situation with lots of
716 // rightward drift. If that is a problem, we could use the list stuff.
717 result.push_str(lifetime_str);
718 result.push_str("> ");
721 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
723 result.push_str(&format_abi(
725 context.config.force_explicit_abi(),
729 result.push_str("fn");
731 let func_ty_shape = shape.offset_left(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 // Try to join types in a single line
770 let joiner = match context.config.type_punctuation_density() {
771 TypeDensity::Compressed => "+",
772 TypeDensity::Wide => " + ",
774 let type_strs = items
776 .map(|item| item.rewrite(context, shape))
777 .collect::<Option<Vec<_>>>()?;
778 let result = type_strs.join(joiner);
779 if items.len() <= 1 || (!result.contains('\n') && result.len() <= shape.width) {
783 // We need to use multiple lines.
784 let (type_strs, offset) = if need_indent {
785 // Rewrite with additional indentation.
786 let nested_shape = shape.block_indent(context.config.tab_spaces());
787 let type_strs = items
789 .map(|item| item.rewrite(context, nested_shape))
790 .collect::<Option<Vec<_>>>()?;
791 (type_strs, nested_shape.indent)
793 (type_strs, shape.indent)
796 let is_bound_extendable = |s: &str, b: &ast::GenericBound| match b {
797 ast::GenericBound::Outlives(..) => true,
798 ast::GenericBound::Trait(..) => last_line_extendable(s),
800 let mut result = String::with_capacity(128);
801 result.push_str(&type_strs[0]);
802 let mut can_be_put_on_the_same_line = is_bound_extendable(&result, &items[0]);
803 let generic_bounds_in_order = is_generic_bounds_in_order(items);
804 for (bound, bound_str) in items[1..].iter().zip(type_strs[1..].iter()) {
805 if generic_bounds_in_order && can_be_put_on_the_same_line {
806 result.push_str(joiner);
808 result.push_str(&offset.to_string_with_newline(context.config));
809 result.push_str("+ ");
811 result.push_str(bound_str);
812 can_be_put_on_the_same_line = is_bound_extendable(bound_str, bound);
818 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
820 ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
821 ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
822 can_be_overflowed_type(context, &*mutty.ty, len)
828 /// Returns `None` if there is no `LifetimeDef` in the given generic parameters.
829 fn rewrite_lifetime_param(
830 context: &RewriteContext,
832 generic_params: &[ast::GenericParam],
833 ) -> Option<String> {
834 let result = generic_params
836 .filter(|p| match p.kind {
837 ast::GenericParamKind::Lifetime => true,
839 }).map(|lt| lt.rewrite(context, shape))
840 .collect::<Option<Vec<_>>>()?
842 if result.is_empty() {