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::print::pprust;
18 use syntax::symbol::keywords;
21 use codemap::SpanUtils;
22 use config::{IndentStyle, Style, TypeDensity};
23 use expr::{rewrite_pair, rewrite_tuple, rewrite_unary_prefix, wrap_args_with_parens};
24 use items::{format_generics_item_list, generics_shape_from_config};
25 use lists::{definitive_tactic, itemize_list, write_list, ListFormatting, ListTactic, Separator,
26 SeparatorPlace, SeparatorTactic};
27 use rewrite::{Rewrite, RewriteContext};
29 use utils::{colon_spaces, extra_offset, format_mutability, 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_angle_brackets() {
62 let fmt_ty = try_opt!(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("::");
71 let extra_offset = extra_offset(&result, shape);
73 let shape = try_opt!(try_opt!(shape.shrink_left(extra_offset)).sub_width(3));
75 result = try_opt!(rewrite_path_segments(
78 path.segments.iter().take(skip_count),
86 if context.config.spaces_within_angle_brackets() {
90 result.push_str(">::");
91 span_lo = qself.ty.span.hi() + BytePos(1);
94 rewrite_path_segments(
97 path.segments.iter().skip(skip_count),
105 fn rewrite_path_segments<'a, I>(
106 path_context: PathContext,
109 mut span_lo: BytePos,
111 context: &RewriteContext,
115 I: Iterator<Item = &'a ast::PathSegment>,
117 let mut first = true;
118 let shape = shape.visual_indent(0);
120 for segment in iter {
121 // Indicates a global path, shouldn't be rendered.
122 if segment.identifier.name == keywords::CrateRoot.name() {
128 buffer.push_str("::");
131 let extra_offset = extra_offset(&buffer, shape);
132 let new_shape = try_opt!(shape.shrink_left(extra_offset));
133 let segment_string = try_opt!(rewrite_segment(
142 buffer.push_str(&segment_string);
149 enum SegmentParam<'a> {
150 LifeTime(&'a ast::Lifetime),
152 Binding(&'a ast::TypeBinding),
155 impl<'a> SegmentParam<'a> {
156 fn get_span(&self) -> Span {
158 SegmentParam::LifeTime(lt) => lt.span,
159 SegmentParam::Type(ty) => ty.span,
160 SegmentParam::Binding(binding) => binding.span,
165 impl<'a> Rewrite for SegmentParam<'a> {
166 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
168 SegmentParam::LifeTime(lt) => lt.rewrite(context, shape),
169 SegmentParam::Type(ty) => ty.rewrite(context, shape),
170 SegmentParam::Binding(binding) => {
171 let mut result = match context.config.type_punctuation_density() {
172 TypeDensity::Wide => format!("{} = ", binding.ident),
173 TypeDensity::Compressed => format!("{}=", binding.ident),
175 let budget = try_opt!(shape.width.checked_sub(result.len()));
176 let rewrite = try_opt!(
179 .rewrite(context, Shape::legacy(budget, shape.indent + result.len()))
181 result.push_str(&rewrite);
188 // Formats a path segment. There are some hacks involved to correctly determine
189 // the segment's associated span since it's not part of the AST.
191 // The span_lo is assumed to be greater than the end of any previous segment's
192 // parameters and lesser or equal than the start of current segment.
194 // span_hi is assumed equal to the end of the entire path.
196 // When the segment contains a positive number of parameters, we update span_lo
197 // so that invariants described above will hold for the next segment.
199 path_context: PathContext,
200 segment: &ast::PathSegment,
201 span_lo: &mut BytePos,
203 context: &RewriteContext,
205 ) -> Option<String> {
206 let ident_len = segment.identifier.to_string().len();
207 let shape = try_opt!(shape.shrink_left(ident_len));
209 let params = if let Some(ref params) = segment.parameters {
211 ast::PathParameters::AngleBracketed(ref data)
212 if !data.lifetimes.is_empty() || !data.types.is_empty()
213 || !data.bindings.is_empty() =>
215 let param_list = data.lifetimes
217 .map(SegmentParam::LifeTime)
218 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
219 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
220 .collect::<Vec<_>>();
222 let next_span_lo = param_list.last().unwrap().get_span().hi() + BytePos(1);
223 let list_lo = context.codemap.span_after(mk_sp(*span_lo, span_hi), "<");
224 let separator = if path_context == PathContext::Expr {
230 let generics_shape = try_opt!(generics_shape_from_config(
235 let one_line_width = try_opt!(shape.width.checked_sub(separator.len() + 2));
236 let items = itemize_list(
238 param_list.into_iter(),
240 |param| param.get_span().lo(),
241 |param| param.get_span().hi(),
242 |seg| seg.rewrite(context, generics_shape),
247 let generics_str = try_opt!(format_generics_item_list(
254 // Update position of last bracket.
255 *span_lo = next_span_lo;
257 format!("{}{}", separator, generics_str)
259 ast::PathParameters::Parenthesized(ref data) => {
260 let output = match data.output {
261 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
262 None => FunctionRetTy::Default(codemap::DUMMY_SP),
264 try_opt!(format_function_type(
265 data.inputs.iter().map(|x| &**x),
279 Some(format!("{}{}", segment.identifier, params))
282 fn format_function_type<'a, I>(
284 output: &FunctionRetTy,
287 context: &RewriteContext,
291 I: ExactSizeIterator,
292 <I as Iterator>::Item: Deref,
293 <I::Item as Deref>::Target: Rewrite + Spanned + 'a,
295 // Code for handling variadics is somewhat duplicated for items, but they
296 // are different enough to need some serious refactoring to share code.
300 <T as Deref>::Target: Rewrite + Spanned,
306 let variadic_arg = if variadic {
307 let variadic_start = context.codemap.span_before(span, "...");
308 Some(ArgumentKind::Variadic(variadic_start))
314 let budget = try_opt!(shape.width.checked_sub(2));
316 let offset = match context.config.fn_args_layout() {
317 IndentStyle::Block => {
320 .block_indent(context.config.tab_spaces())
323 IndentStyle::Visual => shape.indent + 1,
325 let list_shape = Shape::legacy(budget, offset);
326 let list_lo = context.codemap.span_after(span, "(");
327 let items = itemize_list(
329 // FIXME Would be nice to avoid this allocation,
330 // but I couldn't get the types to work out.
332 .map(|i| ArgumentKind::Regular(Box::new(i)))
333 .chain(variadic_arg),
336 ArgumentKind::Regular(ref ty) => ty.span().lo(),
337 ArgumentKind::Variadic(start) => start,
340 ArgumentKind::Regular(ref ty) => ty.span().hi(),
341 ArgumentKind::Variadic(start) => start + BytePos(3),
344 ArgumentKind::Regular(ref ty) => ty.rewrite(context, list_shape),
345 ArgumentKind::Variadic(_) => Some("...".to_owned()),
352 let item_vec: Vec<_> = items.collect();
354 let tactic = definitive_tactic(
356 ListTactic::HorizontalVertical,
361 let fmt = ListFormatting {
364 trailing_separator: if !context.use_block_indent() || variadic {
365 SeparatorTactic::Never
367 context.config.trailing_comma()
369 separator_place: SeparatorPlace::Back,
371 ends_with_newline: tactic.ends_with_newline(context.config.fn_call_style()),
372 preserve_newline: true,
373 config: context.config,
376 let list_str = try_opt!(write_list(&item_vec, &fmt));
378 let ty_shape = match context.config.fn_args_layout() {
379 IndentStyle::Block => shape.block().block_indent(context.config.tab_spaces()),
380 IndentStyle::Visual => try_opt!(shape.block_left(4)),
382 let output = match *output {
383 FunctionRetTy::Ty(ref ty) => {
384 let type_str = try_opt!(ty.rewrite(context, ty_shape));
385 format!(" -> {}", type_str)
387 FunctionRetTy::Default(..) => String::new(),
390 let shape = try_opt!(shape.sub_width(output.len()));
391 let extendable = !list_str.contains('\n') || list_str.is_empty();
392 let args = wrap_args_with_parens(
397 Shape::indented(offset, context.config),
399 if last_line_width(&args) + output.len() > shape.width {
403 offset.to_string(context.config),
407 Some(format!("{}{}", args, output))
411 fn type_bound_colon(context: &RewriteContext) -> &'static str {
413 context.config.space_before_bound(),
414 context.config.space_after_bound_colon(),
418 impl Rewrite for ast::WherePredicate {
419 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
421 let result = match *self {
422 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate {
428 let type_str = try_opt!(bounded_ty.rewrite(context, shape));
430 let colon = type_bound_colon(context);
432 if !bound_lifetimes.is_empty() {
433 let lifetime_str: String = try_opt!(
436 .map(|lt| lt.rewrite(context, shape))
437 .collect::<Option<Vec<_>>>()
440 // 6 = "for<> ".len()
441 let used_width = lifetime_str.len() + type_str.len() + colon.len() + 6;
442 let ty_shape = try_opt!(shape.block_left(used_width));
443 let bounds: Vec<_> = try_opt!(
446 .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
449 let bounds_str = join_bounds(context, ty_shape, &bounds);
451 if context.config.spaces_within_angle_brackets() && !lifetime_str.is_empty() {
460 format!("for<{}> {}{}{}", lifetime_str, type_str, colon, bounds_str)
463 let used_width = type_str.len() + colon.len();
464 let ty_shape = match context.config.where_style() {
465 Style::Legacy => try_opt!(shape.block_left(used_width)),
466 Style::Rfc => shape.block_indent(context.config.tab_spaces()),
468 let bounds: Vec<_> = try_opt!(
471 .map(|ty_bound| ty_bound.rewrite(context, ty_shape))
474 let overhead = type_str.len() + colon.len();
476 join_bounds(context, try_opt!(ty_shape.sub_width(overhead)), &bounds);
478 format!("{}{}{}", type_str, colon, bounds_str)
481 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate {
485 }) => try_opt!(rewrite_bounded_lifetime(
491 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate {
496 let lhs_ty_str = try_opt!(lhs_ty.rewrite(context, shape));
498 let used_width = 3 + lhs_ty_str.len();
499 let budget = try_opt!(shape.width.checked_sub(used_width));
500 let rhs_ty_str = try_opt!(
501 rhs_ty.rewrite(context, Shape::legacy(budget, shape.indent + used_width))
503 format!("{} = {}", lhs_ty_str, rhs_ty_str)
511 impl Rewrite for ast::LifetimeDef {
512 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
513 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, shape)
517 fn rewrite_bounded_lifetime<'b, I>(
520 context: &RewriteContext,
524 I: ExactSizeIterator<Item = &'b ast::Lifetime>,
526 let result = try_opt!(lt.rewrite(context, shape));
528 if bounds.len() == 0 {
531 let appendix: Vec<_> = try_opt!(
534 .map(|b| b.rewrite(context, shape))
537 let colon = type_bound_colon(context);
538 let overhead = last_line_width(&result) + colon.len();
539 let result = format!(
543 join_bounds(context, try_opt!(shape.sub_width(overhead)), &appendix)
549 impl Rewrite for ast::TyParamBound {
550 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
552 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
553 tref.rewrite(context, shape)
555 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
556 let budget = try_opt!(shape.width.checked_sub(1));
559 try_opt!(tref.rewrite(context, Shape::legacy(budget, shape.indent + 1)))
562 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, shape),
567 impl Rewrite for ast::Lifetime {
568 fn rewrite(&self, _: &RewriteContext, _: Shape) -> Option<String> {
569 Some(pprust::lifetime_to_string(self))
573 impl Rewrite for ast::TyParamBounds {
574 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
575 let strs: Vec<_> = try_opt!(self.iter().map(|b| b.rewrite(context, shape)).collect());
576 join_bounds(context, shape, &strs).rewrite(context, shape)
580 impl Rewrite for ast::TyParam {
581 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
582 let mut result = String::with_capacity(128);
583 // FIXME: If there are more than one attributes, this will force multiline.
584 match self.attrs.rewrite(context, shape) {
585 Some(ref rw) if !rw.is_empty() => result.push_str(&format!("{} ", rw)),
588 result.push_str(&self.ident.to_string());
589 if !self.bounds.is_empty() {
590 result.push_str(type_bound_colon(context));
591 let strs: Vec<_> = try_opt!(
594 .map(|ty_bound| ty_bound.rewrite(context, shape))
597 result.push_str(&join_bounds(context, shape, &strs));
599 if let Some(ref def) = self.default {
600 let eq_str = match context.config.type_punctuation_density() {
601 TypeDensity::Compressed => "=",
602 TypeDensity::Wide => " = ",
604 result.push_str(eq_str);
605 let budget = try_opt!(shape.width.checked_sub(result.len()));
607 try_opt!(def.rewrite(context, Shape::legacy(budget, shape.indent + result.len())));
608 result.push_str(&rewrite);
615 impl Rewrite for ast::PolyTraitRef {
616 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
617 if !self.bound_lifetimes.is_empty() {
618 let lifetime_str: String = try_opt!(
621 .map(|lt| lt.rewrite(context, shape))
622 .collect::<Option<Vec<_>>>()
625 // 6 is "for<> ".len()
626 let extra_offset = lifetime_str.len() + 6;
627 let max_path_width = try_opt!(shape.width.checked_sub(extra_offset));
628 let path_str = try_opt!(self.trait_ref.rewrite(
630 Shape::legacy(max_path_width, shape.indent + extra_offset),
634 if context.config.spaces_within_angle_brackets() && !lifetime_str.is_empty() {
635 format!("for< {} > {}", lifetime_str, path_str)
637 format!("for<{}> {}", lifetime_str, path_str)
641 self.trait_ref.rewrite(context, shape)
646 impl Rewrite for ast::TraitRef {
647 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
648 rewrite_path(context, PathContext::Type, None, &self.path, shape)
652 impl Rewrite for ast::Ty {
653 fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
655 ast::TyKind::TraitObject(ref bounds) => bounds.rewrite(context, shape),
656 ast::TyKind::Ptr(ref mt) => {
657 let prefix = match mt.mutbl {
658 Mutability::Mutable => "*mut ",
659 Mutability::Immutable => "*const ",
662 rewrite_unary_prefix(context, prefix, &*mt.ty, shape)
664 ast::TyKind::Rptr(ref lifetime, ref mt) => {
665 let mut_str = format_mutability(mt.mutbl);
666 let mut_len = mut_str.len();
667 Some(match *lifetime {
668 Some(ref lifetime) => {
669 let lt_budget = try_opt!(shape.width.checked_sub(2 + mut_len));
670 let lt_str = try_opt!(lifetime.rewrite(
672 Shape::legacy(lt_budget, shape.indent + 2 + mut_len),
674 let lt_len = lt_str.len();
675 let budget = try_opt!(shape.width.checked_sub(2 + mut_len + lt_len));
680 try_opt!(mt.ty.rewrite(
682 Shape::legacy(budget, shape.indent + 2 + mut_len + lt_len),
687 let budget = try_opt!(shape.width.checked_sub(1 + mut_len));
694 Shape::legacy(budget, shape.indent + 1 + mut_len),
701 // FIXME: we drop any comments here, even though it's a silly place to put
703 ast::TyKind::Paren(ref ty) => {
704 let budget = try_opt!(shape.width.checked_sub(2));
705 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
706 .map(|ty_str| if context.config.spaces_within_parens() {
707 format!("( {} )", ty_str)
709 format!("({})", ty_str)
712 ast::TyKind::Slice(ref ty) => {
713 let budget = if context.config.spaces_within_square_brackets() {
714 try_opt!(shape.width.checked_sub(4))
716 try_opt!(shape.width.checked_sub(2))
718 ty.rewrite(context, Shape::legacy(budget, shape.indent + 1))
719 .map(|ty_str| if context.config.spaces_within_square_brackets() {
720 format!("[ {} ]", ty_str)
722 format!("[{}]", ty_str)
725 ast::TyKind::Tup(ref items) => rewrite_tuple(
727 &::utils::ptr_vec_to_ref_vec(&items),
731 ast::TyKind::Path(ref q_self, ref path) => {
732 rewrite_path(context, PathContext::Type, q_self.as_ref(), path, shape)
734 ast::TyKind::Array(ref ty, ref repeats) => {
735 let use_spaces = context.config.spaces_within_square_brackets();
736 let lbr = if use_spaces { "[ " } else { "[" };
737 let rbr = if use_spaces { " ]" } else { "]" };
746 SeparatorPlace::Back,
749 ast::TyKind::Infer => if shape.width >= 1 {
754 ast::TyKind::BareFn(ref bare_fn) => rewrite_bare_fn(bare_fn, self.span, context, shape),
755 ast::TyKind::Never => Some(String::from("!")),
756 ast::TyKind::Mac(..) => None,
757 ast::TyKind::ImplicitSelf => Some(String::from("")),
758 ast::TyKind::ImplTrait(ref it) => it.rewrite(context, shape)
759 .map(|it_str| format!("impl {}", it_str)),
760 ast::TyKind::Err | ast::TyKind::Typeof(..) => unreachable!(),
766 bare_fn: &ast::BareFnTy,
768 context: &RewriteContext,
770 ) -> Option<String> {
771 let mut result = String::with_capacity(128);
773 if !bare_fn.lifetimes.is_empty() {
774 result.push_str("for<");
775 // 6 = "for<> ".len(), 4 = "for<".
776 // This doesn't work out so nicely for mutliline situation with lots of
777 // rightward drift. If that is a problem, we could use the list stuff.
778 result.push_str(&try_opt!(
785 Shape::legacy(try_opt!(shape.width.checked_sub(6)), shape.indent + 4),
788 .collect::<Option<Vec<_>>>()
790 result.push_str("> ");
793 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
795 if bare_fn.abi != abi::Abi::Rust {
796 result.push_str(&::utils::format_abi(
798 context.config.force_explicit_abi(),
802 result.push_str("fn");
804 let func_ty_shape = try_opt!(shape.offset_left(result.len()));
806 let rewrite = try_opt!(format_function_type(
807 bare_fn.decl.inputs.iter(),
808 &bare_fn.decl.output,
809 bare_fn.decl.variadic,
815 result.push_str(&rewrite);
820 pub fn join_bounds(context: &RewriteContext, shape: Shape, type_strs: &[String]) -> String {
821 // Try to join types in a single line
822 let joiner = match context.config.type_punctuation_density() {
823 TypeDensity::Compressed => "+",
824 TypeDensity::Wide => " + ",
826 let result = type_strs.join(joiner);
827 if result.contains('\n') || result.len() > shape.width {
828 let joiner_indent = shape.indent.block_indent(context.config);
829 let joiner = format!("\n{}+ ", joiner_indent.to_string(context.config));
830 type_strs.join(&joiner)
836 pub fn can_be_overflowed_type(context: &RewriteContext, ty: &ast::Ty, len: usize) -> bool {
838 ast::TyKind::Path(..) | ast::TyKind::Tup(..) => context.use_block_indent() && len == 1,
839 ast::TyKind::Rptr(_, ref mutty) | ast::TyKind::Ptr(ref mutty) => {
840 can_be_overflowed_type(context, &*mutty.ty, len)