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, Style, TypeDensity};
22 use expr::{rewrite_pair, rewrite_tuple, rewrite_unary_prefix, wrap_args_with_parens};
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, format_abi, format_mutability, last_line_width, mk_sp};
30 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
31 pub enum PathContext {
37 // Does not wrap on simple segments.
39 context: &RewriteContext,
40 path_context: PathContext,
41 qself: Option<&ast::QSelf>,
45 let skip_count = qself.map_or(0, |x| x.position);
47 let mut result = if path.is_global() && qself.is_none() && path_context != PathContext::Import {
53 let mut span_lo = path.span.lo();
55 if let Some(qself) = qself {
57 if context.config.spaces_within_angle_brackets() {
61 let fmt_ty = qself.ty.rewrite(context, shape)?;
62 result.push_str(&fmt_ty);
65 result.push_str(" as ");
66 if path.is_global() && path_context != PathContext::Import {
67 result.push_str("::");
70 let extra_offset = extra_offset(&result, shape);
72 let shape = shape.shrink_left(extra_offset)?.sub_width(3)?;
74 result = rewrite_path_segments(
77 path.segments.iter().take(skip_count),
85 if context.config.spaces_within_angle_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(),
234 |param| param.get_span().lo(),
235 |param| param.get_span().hi(),
236 |seg| seg.rewrite(context, generics_shape),
242 format_generics_item_list(context, items, generics_shape, one_line_width)?;
244 // Update position of last bracket.
245 *span_lo = next_span_lo;
247 format!("{}{}", separator, generics_str)
249 ast::PathParameters::Parenthesized(ref data) => {
250 let output = match data.output {
251 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
252 None => FunctionRetTy::Default(codemap::DUMMY_SP),
254 format_function_type(
255 data.inputs.iter().map(|x| &**x),
269 Some(format!("{}{}", segment.identifier, params))
272 fn format_function_type<'a, I>(
274 output: &FunctionRetTy,
277 context: &RewriteContext,
281 I: ExactSizeIterator,
282 <I as Iterator>::Item: Deref,
283 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
285 // Code for handling variadics is somewhat duplicated for items, but they
286 // are different enough to need some serious refactoring to share code.
290 <T as Deref>::Target: Rewrite + Spanned,
296 let variadic_arg = if variadic {
297 let variadic_start = context.codemap.span_before(span, "...");
298 Some(ArgumentKind::Variadic(variadic_start))
304 let budget = shape.width.checked_sub(2)?;
306 let offset = match context.config.fn_args_layout() {
307 IndentStyle::Block => {
310 .block_indent(context.config.tab_spaces())
313 IndentStyle::Visual => shape.indent + 1,
315 let list_shape = Shape::legacy(budget, offset);
316 let list_lo = context.codemap.span_after(span, "(");
317 let items = itemize_list(
319 // FIXME Would be nice to avoid this allocation,
320 // but I couldn't get the types to work out.
322 .map(|i| ArgumentKind::Regular(Box::new(i)))
323 .chain(variadic_arg),
326 ArgumentKind::Regular(ref ty) => ty.span().lo(),
327 ArgumentKind::Variadic(start) => start,
330 ArgumentKind::Regular(ref ty) => ty.span().hi(),
331 ArgumentKind::Variadic(start) => start + BytePos(3),
334 ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
335 ArgumentKind::Variadic(_) => Some("...".to_owned()),
342 let item_vec: Vec<_> = items.collect();
344 let tactic = definitive_tactic(
346 ListTactic::HorizontalVertical,
351 let fmt = ListFormatting {
354 trailing_separator: if !context.use_block_indent() || variadic {
355 SeparatorTactic::Never
357 context.config.trailing_comma()
359 separator_place: SeparatorPlace::Back,
361 ends_with_newline: tactic.ends_with_newline(context.config.fn_call_style()),
362 preserve_newline: true,
363 config: context.config,
366 let list_str = write_list(&item_vec, &fmt)?;
368 let ty_shape = match context.config.fn_args_layout() {
369 IndentStyle::Block => shape.block().block_indent(context.config.tab_spaces()),
370 IndentStyle::Visual => shape.block_left(4)?,
372 let output = match *output {
373 FunctionRetTy::Ty(ref ty) => {
374 let type_str = ty.rewrite(context, ty_shape)?;
375 format!(" -> {}", type_str)
377 FunctionRetTy::Default(..) => String::new(),
380 let shape = shape.sub_width(output.len())?;
381 let extendable = !list_str.contains('\n') || list_str.is_empty();
382 let args = wrap_args_with_parens(
387 Shape::indented(offset, context.config),
389 if last_line_width(&args) + output.len() > shape.width {
393 offset.to_string(context.config),
397 Some(format!("{}{}", args, output))
401 fn type_bound_colon(context: &RewriteContext) -> &'static str {
403 context.config.space_before_bound(),
404 context.config.space_after_bound_colon(),
408 impl Rewrite for ast::WherePredicate {
409 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
411 let result = match *self {
412 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
418 let type_str = bounded_ty.rewrite(context, shape)?;
420 let colon = type_bound_colon(context);
422 if !bound_lifetimes.is_empty() {
423 let lifetime_str: String = bound_lifetimes
425 .map(|lt| lt.rewrite(context, shape))
426 .collect::<Option<Vec<_>>>()?
429 // 6 = "for<> ".len()
430 let used_width = lifetime_str.len() + type_str.len() + colon.len() + 6;
431 let ty_shape = shape.offset_left(used_width)?;
434 .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
435 .collect::<Option<Vec<_>>>()?;
436 let bounds_str = join_bounds(context, ty_shape, &bounds);
438 if context.config.spaces_within_angle_brackets() && !lifetime_str.is_empty() {
447 format!("for<{}> {}{}{}", lifetime_str, type_str, colon, bounds_str)
450 let used_width = type_str.len() + colon.len();
451 let ty_shape = match context.config.where_style() {
452 Style::Legacy => shape.block_left(used_width)?,
457 .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
458 .collect::<Option<Vec<_>>>()?;
459 let overhead = type_str.len() + colon.len();
460 let bounds_str = join_bounds(context, ty_shape.sub_width(overhead)?, &bounds);
462 format!("{}{}{}", type_str, colon, bounds_str)
465 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
469 }) => rewrite_bounded_lifetime(lifetime, bounds.iter(), context, shape)?,
470 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
475 let lhs_ty_str = lhs_ty.rewrite(context, shape)?;
477 let used_width = 3 + lhs_ty_str.len();
478 let budget = shape.width.checked_sub(used_width)?;
480 rhs_ty.rewrite(context, Shape::legacy(budget, shape.indent + used_width))?;
481 format!("{} = {}", lhs_ty_str, rhs_ty_str)
489 impl Rewrite for ast::LifetimeDef {
490 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
491 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, shape)
495 fn rewrite_bounded_lifetime<'b, I>(
498 context: &RewriteContext,
502 I: ExactSizeIterator<Item = &'b ast::Lifetime>,
504 let result = lt.rewrite(context, shape)?;
506 if bounds.len() == 0 {
509 let appendix = bounds
511 .map(|b| b.rewrite(context, shape))
512 .collect::<Option<Vec<_>>>()?;
513 let colon = type_bound_colon(context);
514 let overhead = last_line_width(&result) + colon.len();
515 let result = format!(
519 join_bounds(context, shape.sub_width(overhead)?, &appendix)
525 impl Rewrite for ast::TyParamBound {
526 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
528 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
529 tref.rewrite(context, shape)
531 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
534 tref.rewrite(context, shape.offset_left(1)?)?
537 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, shape),
542 impl Rewrite for ast::Lifetime {
543 fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> {
544 Some(pprust::lifetime_to_string(self))
548 impl Rewrite for ast::TyParamBounds {
549 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
550 let strs = self.iter()
551 .map(|b| b.rewrite(context, shape))
552 .collect::<Option<Vec<_>>>()?;
553 Some(join_bounds(context, shape, &strs))
557 impl Rewrite for ast::TyParam {
558 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
559 let mut result = String::with_capacity(128);
560 // FIXME: If there are more than one attributes, this will force multiline.
561 match self.attrs.rewrite(context, shape) {
562 Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
565 result.push_str(&self.ident.to_string());
566 if !self.bounds.is_empty() {
567 result.push_str(type_bound_colon(context));
568 let strs = self.bounds
570 .map(|ty_bound| ty_bound.rewrite(context, shape))
571 .collect::<Option<Vec<_>>>()?;
572 result.push_str(&join_bounds(context, shape, &strs));
574 if let Some(ref def) = self.default {
575 let eq_str = match context.config.type_punctuation_density() {
576 TypeDensity::Compressed => "=",
577 TypeDensity::Wide => " = ",
579 result.push_str(eq_str);
580 let budget = shape.width.checked_sub(result.len())?;
581 let rewrite = def.rewrite(context, Shape::legacy(budget, shape.indent + result.len()))?;
582 result.push_str(&rewrite);
589 impl Rewrite for ast::PolyTraitRef {
590 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
591 if !self.bound_lifetimes.is_empty() {
592 let lifetime_str: String = self.bound_lifetimes
594 .map(|lt| lt.rewrite(context, shape))
595 .collect::<Option<Vec<_>>>()?
598 // 6 is "for<> ".len()
599 let extra_offset = lifetime_str.len() + 6;
600 let path_str = self.trait_ref
601 .rewrite(context, shape.offset_left(extra_offset)?)?;
604 if context.config.spaces_within_angle_brackets() && !lifetime_str.is_empty() {
605 format!("for< {} > {}", lifetime_str, path_str)
607 format!("for<{}> {}", lifetime_str, path_str)
611 self.trait_ref.rewrite(context, shape)
616 impl Rewrite for ast::TraitRef {
617 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
618 rewrite_path(context, PathContext::Type, None, &self.path, shape)
622 impl Rewrite for ast::Ty {
623 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
625 ast::TyKind::TraitObject(ref bounds) => bounds.rewrite(context, shape),
626 ast::TyKind::Ptr(ref mt) => {
627 let prefix = match mt.mutbl {
628 Mutability::Mutable => "*mut ",
629 Mutability::Immutable => "*const ",
632 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
634 ast::TyKind::Rptr(ref lifetime, ref mt) => {
635 let mut_str = format_mutability(mt.mutbl);
636 let mut_len = mut_str.len();
637 Some(match *lifetime {
638 Some(ref lifetime) => {
639 let lt_budget = shape.width.checked_sub(2 + mut_len)?;
640 let lt_str = lifetime.rewrite(
642 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
644 let lt_len = lt_str.len();
645 let budget = shape.width.checked_sub(2 + mut_len + lt_len)?;
652 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len)
657 let budget = shape.width.checked_sub(1 + mut_len)?;
663 Shape::legacy(budget, shape.indent + 1 + mut_len),
669 // FIXME: we drop any comments here, even though it's a silly place to put
671 ast::TyKind::Paren(ref ty) => {
672 let budget = shape.width.checked_sub(2)?;
673 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
674 .map(|ty_str| if context.config.spaces_within_parens() {
675 format!("( {} )", ty_str)
677 format!("({})", ty_str)
680 ast::TyKind::Slice(ref ty) => {
681 let budget = if context.config.spaces_within_square_brackets() {
682 shape.width.checked_sub(4)?
684 shape.width.checked_sub(2)?
686 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
687 .map(|ty_str| if context.config.spaces_within_square_brackets() {
688 format!("[ {} ]", ty_str)
690 format!("[{}]", ty_str)
693 ast::TyKind::Tup(ref items) => rewrite_tuple(
695 &::utils::ptr_vec_to_ref_vec(&items),
699 ast::TyKind::Path(ref q_self, ref path) => {
700 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
702 ast::TyKind::Array(ref ty, ref repeats) => {
703 let use_spaces = context.config.spaces_within_square_brackets();
704 let lbr = if use_spaces { "[ " } else { "[" };
705 let rbr = if use_spaces { " ]" } else { "]" };
714 SeparatorPlace::Back,
717 ast::TyKind::Infer => if shape.width >= 1 {
722 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
723 ast::TyKind::Never => Some(String::from("!")),
724 ast::TyKind::Mac(..) => None,
725 ast::TyKind::ImplicitSelf => Some(String::from("")),
726 ast::TyKind::ImplTrait(ref it) => it.rewrite(context, shape)
727 .map(|it_str| format!("impl {}", it_str)),
728 ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
734 bare_fn: &ast::BareFnTy,
736 context: &RewriteContext,
738 ) -> Option<String> {
739 let mut result = String::with_capacity(128);
741 if !bare_fn.lifetimes.is_empty() {
742 result.push_str("for<");
743 // 6 = "for<> ".len(), 4 = "for<".
744 // This doesn't work out so nicely for mutliline situation with lots of
745 // rightward drift. If that is a problem, we could use the list stuff.
746 result.push_str(&bare_fn
752 Shape::legacy(shape.width.checked_sub(6)?, shape.indent + 4),
755 .collect::<Option<Vec<_>>>()?
757 result.push_str("> ");
760 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
762 result.push_str(&format_abi(
764 context.config.force_explicit_abi(),
768 result.push_str("fn");
770 let func_ty_shape = shape.offset_left(result.len())?;
772 let rewrite = format_function_type(
773 bare_fn.decl.inputs.iter(),
774 &bare_fn.decl.output,
775 bare_fn.decl.variadic,
781 result.push_str(&rewrite);
786 pub fn join_bounds(context: &RewriteContext, shape: Shape, type_strs: &[String]) -> String {
787 // Try to join types in a single line
788 let joiner = match context.config.type_punctuation_density() {
789 TypeDensity::Compressed => "+",
790 TypeDensity::Wide => " + ",
792 let result = type_strs.join(joiner);
793 if result.contains('\n') || result.len() > shape.width {
794 let joiner_indent = shape.indent.block_indent(context.config);
795 let joiner = format!("\n{}+ ", joiner_indent.to_string(context.config));
796 type_strs.join(&joiner)
802 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
804 ast::TyKind::Path(..) | ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
805 ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
806 can_be_overflowed_type(context, &*mutty.ty, len)