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::codemap::{self, BytePos, Span};
16 use syntax::print::pprust;
17 use syntax::symbol::keywords;
20 use codemap::SpanUtils;
21 use config::{IndentStyle, TypeDensity};
22 use expr::{rewrite_pair, rewrite_tuple, rewrite_unary_prefix, wrap_args_with_parens, PairParts};
23 use items::{format_generics_item_list, generics_shape_from_config};
24 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListTactic, Separator,
25 SeparatorPlace, SeparatorTactic};
26 use rewrite::{Rewrite, RewriteContext};
28 use utils::{colon_spaces, extra_offset, first_line_width, format_abi, format_mutability,
29 last_line_width, mk_sp};
31 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
32 pub enum PathContext {
38 // Does not wrap on simple segments.
40 context: &RewriteContext,
41 path_context: PathContext,
42 qself: Option<&ast::QSelf>,
46 let skip_count = qself.map_or(0, |x| x.position);
48 let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
54 let mut span_lo = path.span.lo();
56 if let Some(qself) = qself {
58 if context.config.spaces_within_parens_and_brackets() {
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 if context.config.spaces_within_parens_and_brackets() {
89 result.push_str(">::");
90 span_lo = qself.ty.span.hi() + BytePos(1);
93 rewrite_path_segments(
96 path.segments.iter().skip(skip_count),
104 fn rewrite_path_segments<'a, I>(
105 path_context: PathContext,
108 mut span_lo: BytePos,
110 context: &RewriteContext,
114 I: Iterator<Item = &'a ast::PathSegment>,
116 let mut first = true;
117 let shape = shape.visual_indent(0);
119 for segment in iter {
120 // Indicates a global path, shouldn't be rendered.
121 if segment.identifier.name == keywords::CrateRoot.name() {
127 buffer.push_str("::");
130 let extra_offset = extra_offset(&buffer, shape);
131 let new_shape = shape.shrink_left(extra_offset)?;
132 let segment_string = rewrite_segment(
141 buffer.push_str(&segment_string);
148 enum SegmentParam<'a> {
149 LifeTime(&'a ast::Lifetime),
151 Binding(&'a ast::TypeBinding),
154 impl<'a> SegmentParam<'a> {
155 fn get_span(&self) -> Span {
157 SegmentParam::LifeTime(lt) => lt.span,
158 SegmentParam::Type(ty) => ty.span,
159 SegmentParam::Binding(binding) => binding.span,
164 impl<'a> Rewrite for SegmentParam<'a> {
165 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
167 SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
168 SegmentParam::Type(ty) => ty.rewrite(context, shape),
169 SegmentParam::Binding(binding) => {
170 let mut result = match context.config.type_punctuation_density() {
171 TypeDensity::Wide => format!("{} = ", binding.ident),
172 TypeDensity::Compressed => format!("{}=", binding.ident),
174 let budget = shape.width.checked_sub(result.len())?;
175 let rewrite = binding
177 .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
178 result.push_str(&rewrite);
185 // Formats a path segment. There are some hacks involved to correctly determine
186 // the segment's associated span since it's not part of the AST.
188 // The span_lo is assumed to be greater than the end of any previous segment's
189 // parameters and lesser or equal than the start of current segment.
191 // span_hi is assumed equal to the end of the entire path.
193 // When the segment contains a positive number of parameters, we update span_lo
194 // so that invariants described above will hold for the next segment.
196 path_context: PathContext,
197 segment: &ast::PathSegment,
198 span_lo: &mut BytePos,
200 context: &RewriteContext,
202 ) -> Option<String> {
203 let ident_len = segment.identifier.to_string().len();
204 let shape = shape.shrink_left(ident_len)?;
206 let params = if let Some(ref params) = segment.parameters {
208 ast::PathParameters::AngleBracketed(ref data)
209 if !data.lifetimes.is_empty() || !data.types.is_empty()
210 || !data.bindings.is_empty() =>
212 let param_list = data.lifetimes
214 .map(SegmentParam::LifeTime)
215 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
216 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
217 .collect::<Vec<_>>();
219 let next_span_lo = param_list.last().unwrap().get_span().hi() + BytePos(1);
220 let list_lo = context.codemap.span_after(mk_sp(*span_lo, span_hi), "<");
221 let separator = if path_context == PathContext::Expr {
228 generics_shape_from_config(context.config, shape, separator.len())?;
229 let one_line_width = shape.width.checked_sub(separator.len() + 2)?;
230 let items = itemize_list(
232 param_list.into_iter(),
235 |param| param.get_span().lo(),
236 |param| param.get_span().hi(),
237 |seg| seg.rewrite(context, generics_shape),
243 format_generics_item_list(context, items, generics_shape, one_line_width)?;
245 // Update position of last bracket.
246 *span_lo = next_span_lo;
248 format!("{}{}", separator, generics_str)
250 ast::PathParameters::Parenthesized(ref data) => {
251 let output = match data.output {
252 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
253 None => FunctionRetTy::Default(codemap::DUMMY_SP),
255 format_function_type(
256 data.inputs.iter().map(|x| &**x),
270 Some(format!("{}{}", segment.identifier, params))
273 fn format_function_type<'a, I>(
275 output: &FunctionRetTy,
278 context: &RewriteContext,
282 I: ExactSizeIterator,
283 <I as Iterator>::Item: Deref,
284 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
286 // Code for handling variadics is somewhat duplicated for items, but they
287 // are different enough to need some serious refactoring to share code.
291 <T as Deref>::Target: Rewrite + Spanned,
297 let variadic_arg = if variadic {
298 let variadic_start = context.codemap.span_before(span, "...");
299 Some(ArgumentKind::Variadic(variadic_start))
305 let budget = shape.width.checked_sub(2)?;
307 let offset = match context.config.indent_style() {
308 IndentStyle::Block => {
311 .block_indent(context.config.tab_spaces())
314 IndentStyle::Visual => shape.indent + 1,
316 let list_shape = Shape::legacy(budget, offset);
317 let list_lo = context.codemap.span_after(span, "(");
318 let items = itemize_list(
320 // FIXME Would be nice to avoid this allocation,
321 // but I couldn't get the types to work out.
323 .map(|i| ArgumentKind::Regular(Box::new(i)))
324 .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,
353 let fmt = ListFormatting {
356 trailing_separator: if !context.use_block_indent() || variadic {
357 SeparatorTactic::Never
359 context.config.trailing_comma()
361 separator_place: SeparatorPlace::Back,
363 ends_with_newline: tactic.ends_with_newline(context.config.indent_style()),
364 preserve_newline: true,
365 config: context.config,
368 let list_str = write_list(&item_vec, &fmt)?;
370 let ty_shape = match context.config.indent_style() {
372 IndentStyle::Block => shape.offset_left(4)?,
373 IndentStyle::Visual => shape.block_left(4)?,
375 let output = match *output {
376 FunctionRetTy::Ty(ref ty) => {
377 let type_str = ty.rewrite(context, ty_shape)?;
378 format!(" -> {}", type_str)
380 FunctionRetTy::Default(..) => String::new(),
383 let extendable = (!list_str.contains('\n') || list_str.is_empty()) && !output.contains('\n');
384 let args = wrap_args_with_parens(
388 shape.sub_width(first_line_width(&output))?,
389 Shape::indented(offset, context.config),
391 if last_line_width(&args) + first_line_width(&output) <= shape.width {
392 Some(format!("{}{}", args, output))
397 offset.to_string(context.config),
403 fn type_bound_colon(context: &RewriteContext) -> &'static str {
405 context.config.space_before_colon(),
406 context.config.space_after_colon(),
410 impl Rewrite for ast::WherePredicate {
411 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
413 let result = match *self {
414 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
420 let type_str = bounded_ty.rewrite(context, shape)?;
422 let colon = type_bound_colon(context);
424 if !bound_lifetimes.is_empty() {
425 let lifetime_str: String = bound_lifetimes
427 .map(|lt| lt.rewrite(context, shape))
428 .collect::<Option<Vec<_>>>()?
431 // 6 = "for<> ".len()
432 let used_width = lifetime_str.len() + type_str.len() + colon.len() + 6;
433 let ty_shape = shape.offset_left(used_width)?;
436 .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
437 .collect::<Option<Vec<_>>>()?;
438 let bounds_str = join_bounds(context, ty_shape, &bounds);
440 if context.config.spaces_within_parens_and_brackets()
441 && !lifetime_str.is_empty()
451 format!("for<{}> {}{}{}", lifetime_str, type_str, colon, bounds_str)
454 let used_width = type_str.len() + colon.len();
455 let ty_shape = match context.config.indent_style() {
456 IndentStyle::Visual => shape.block_left(used_width)?,
457 IndentStyle::Block => shape,
461 .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
462 .collect::<Option<Vec<_>>>()?;
463 let overhead = type_str.len() + colon.len();
464 let bounds_str = join_bounds(context, ty_shape.sub_width(overhead)?, &bounds);
466 format!("{}{}{}", type_str, colon, bounds_str)
469 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
473 }) => rewrite_bounded_lifetime(lifetime, bounds.iter(), context, shape)?,
474 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
479 let lhs_ty_str = lhs_ty.rewrite(context, shape)?;
481 let used_width = 3 + lhs_ty_str.len();
482 let budget = shape.width.checked_sub(used_width)?;
484 rhs_ty.rewrite(context, Shape::legacy(budget, shape.indent + used_width))?;
485 format!("{} = {}", lhs_ty_str, rhs_ty_str)
493 impl Rewrite for ast::LifetimeDef {
494 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
495 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, shape)
499 fn rewrite_bounded_lifetime<'b, I>(
502 context: &RewriteContext,
506 I: ExactSizeIterator<Item = &'b ast::Lifetime>,
508 let result = lt.rewrite(context, shape)?;
510 if bounds.len() == 0 {
513 let appendix = bounds
515 .map(|b| b.rewrite(context, shape))
516 .collect::<Option<Vec<_>>>()?;
517 let colon = type_bound_colon(context);
518 let overhead = last_line_width(&result) + colon.len();
519 let result = format!(
523 join_bounds(context, shape.sub_width(overhead)?, &appendix)
529 impl Rewrite for ast::TyParamBound {
530 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
532 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
533 tref.rewrite(context, shape)
535 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
538 tref.rewrite(context, shape.offset_left(1)?)?
541 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, shape),
546 impl Rewrite for ast::Lifetime {
547 fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> {
548 Some(pprust::lifetime_to_string(self))
552 impl Rewrite for ast::TyParamBounds {
553 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
554 let strs = self.iter()
555 .map(|b| b.rewrite(context, shape))
556 .collect::<Option<Vec<_>>>()?;
557 Some(join_bounds(context, shape, &strs))
561 impl Rewrite for ast::TyParam {
562 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
563 let mut result = String::with_capacity(128);
564 // FIXME: If there are more than one attributes, this will force multiline.
565 match self.attrs.rewrite(context, shape) {
566 Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
569 result.push_str(&self.ident.to_string());
570 if !self.bounds.is_empty() {
571 result.push_str(type_bound_colon(context));
572 let strs = self.bounds
574 .map(|ty_bound| ty_bound.rewrite(context, shape))
575 .collect::<Option<Vec<_>>>()?;
576 result.push_str(&join_bounds(context, shape, &strs));
578 if let Some(ref def) = self.default {
579 let eq_str = match context.config.type_punctuation_density() {
580 TypeDensity::Compressed => "=",
581 TypeDensity::Wide => " = ",
583 result.push_str(eq_str);
584 let budget = shape.width.checked_sub(result.len())?;
585 let rewrite = def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
586 result.push_str(&rewrite);
593 impl Rewrite for ast::PolyTraitRef {
594 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
595 if !self.bound_lifetimes.is_empty() {
596 let lifetime_str: String = self.bound_lifetimes
598 .map(|lt| lt.rewrite(context, shape))
599 .collect::<Option<Vec<_>>>()?
602 // 6 is "for<> ".len()
603 let extra_offset = lifetime_str.len() + 6;
604 let path_str = self.trait_ref
605 .rewrite(context, shape.offset_left(extra_offset)?)?;
608 if context.config.spaces_within_parens_and_brackets() && !lifetime_str.is_empty() {
609 format!("for< {} > {}", lifetime_str, path_str)
611 format!("for<{}> {}", lifetime_str, path_str)
615 self.trait_ref.rewrite(context, shape)
620 impl Rewrite for ast::TraitRef {
621 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
622 rewrite_path(context, PathContext::Type, None, &self.path, shape)
626 impl Rewrite for ast::Ty {
627 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
629 ast::TyKind::TraitObject(ref bounds, ..) => bounds.rewrite(context, shape),
630 ast::TyKind::Ptr(ref mt) => {
631 let prefix = match mt.mutbl {
632 Mutability::Mutable => "*mut ",
633 Mutability::Immutable => "*const ",
636 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
638 ast::TyKind::Rptr(ref lifetime, ref mt) => {
639 let mut_str = format_mutability(mt.mutbl);
640 let mut_len = mut_str.len();
641 Some(match *lifetime {
642 Some(ref lifetime) => {
643 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
644 let lt_str = lifetime.rewrite(
646 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
648 let lt_len = lt_str.len();
649 let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
656 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
661 let budget = shape.width.checked_sub(1 + mut_len)?;
667 Shape::legacy(budget, shape.indent + 1 + mut_len)
673 // FIXME: we drop any comments here, even though it's a silly place to put
675 ast::TyKind::Paren(ref ty) => {
676 let budget = shape.width.checked_sub(2)?;
677 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
679 if context.config.spaces_within_parens_and_brackets() {
680 format!("( {} )", ty_str)
682 format!("({})", ty_str)
686 ast::TyKind::Slice(ref ty) => {
687 let budget = if context.config.spaces_within_parens_and_brackets() {
688 shape.width.checked_sub(4)?
690 shape.width.checked_sub(2)?
692 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
694 if context.config.spaces_within_parens_and_brackets() {
695 format!("[ {} ]", ty_str)
697 format!("[{}]", ty_str)
701 ast::TyKind::Tup(ref items) => rewrite_tuple(
703 &::utils::ptr_vec_to_ref_vec(items),
707 ast::TyKind::Path(ref q_self, ref path) => {
708 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
710 ast::TyKind::Array(ref ty, ref repeats) => {
711 let use_spaces = context.config.spaces_within_parens_and_brackets();
712 let lbr = if use_spaces { "[ " } else { "[" };
713 let rbr = if use_spaces { " ]" } else { "]" };
717 PairParts::new(lbr, "; ", rbr),
720 SeparatorPlace::Back,
723 ast::TyKind::Infer => {
724 if shape.width >= 1 {
730 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
731 ast::TyKind::Never => Some(String::from("!")),
732 ast::TyKind::Mac(..) => None,
733 ast::TyKind::ImplicitSelf => Some(String::from("")),
734 ast::TyKind::ImplTrait(ref it) => it.rewrite(context, shape)
735 .map(|it_str| format!("impl {}", it_str)),
736 ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
742 bare_fn: &ast::BareFnTy,
744 context: &RewriteContext,
746 ) -> Option<String> {
747 let mut result = String::with_capacity(128);
749 if !bare_fn.lifetimes.is_empty() {
750 result.push_str("for<");
751 // 6 = "for<> ".len(), 4 = "for<".
752 // This doesn't work out so nicely for mutliline situation with lots of
753 // rightward drift. If that is a problem, we could use the list stuff.
754 result.push_str(&bare_fn
760 Shape::legacy(shape.width.checked_sub(6)?, shape.indent + 4),
763 .collect::<Option<Vec<_>>>()?
765 result.push_str("> ");
768 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
770 result.push_str(&format_abi(
772 context.config.force_explicit_abi(),
776 result.push_str("fn");
778 let func_ty_shape = shape.offset_left(result.len())?;
780 let rewrite = format_function_type(
781 bare_fn.decl.inputs.iter(),
782 &bare_fn.decl.output,
783 bare_fn.decl.variadic,
789 result.push_str(&rewrite);
794 pub fn join_bounds(context: &RewriteContext, shape: Shape, type_strs: &[String]) -> String {
795 // Try to join types in a single line
796 let joiner = match context.config.type_punctuation_density() {
797 TypeDensity::Compressed => "+",
798 TypeDensity::Wide => " + ",
800 let result = type_strs.join(joiner);
801 if result.contains('\n') || result.len() > shape.width {
802 let joiner_indent = shape.indent.block_indent(context.config);
803 let joiner = format!("\n{}+ ", joiner_indent.to_string(context.config));
804 type_strs.join(&joiner)
810 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
812 ast::TyKind::Path(..) | 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)