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.
12 use std::iter::ExactSizeIterator;
14 use syntax::ast::{self, Mutability, FunctionRetTy};
15 use syntax::print::pprust;
16 use syntax::codemap::{self, Span, BytePos};
19 use {Indent, Spanned};
20 use codemap::SpanUtils;
21 use lists::{format_item_list, itemize_list, format_fn_args};
22 use rewrite::{Rewrite, RewriteContext};
23 use utils::{extra_offset, format_mutability, wrap_str};
24 use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
25 use config::TypeDensity;
26 use itertools::Itertools;
28 // Does not wrap on simple segments.
29 pub fn rewrite_path(context: &RewriteContext,
31 qself: Option<&ast::QSelf>,
36 let skip_count = qself.map_or(0, |x| x.position);
38 let mut result = if path.global && qself.is_none() {
44 let mut span_lo = path.span.lo;
46 if let Some(qself) = qself {
48 if context.config.spaces_within_angle_brackets {
52 let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
53 result.push_str(&fmt_ty);
56 result.push_str(" as ");
58 result.push_str("::");
61 let extra_offset = extra_offset(&result, offset);
63 let budget = try_opt!(width.checked_sub(extra_offset + 3));
65 result = try_opt!(rewrite_path_segments(false,
67 path.segments.iter().take(skip_count),
72 offset + extra_offset));
75 if context.config.spaces_within_angle_brackets {
79 result.push_str(">::");
80 span_lo = qself.ty.span.hi + BytePos(1);
83 let extra_offset = extra_offset(&result, offset);
84 let budget = try_opt!(width.checked_sub(extra_offset));
85 rewrite_path_segments(expr_context,
87 path.segments.iter().skip(skip_count),
92 offset + extra_offset)
95 fn rewrite_path_segments<'a, I>(expr_context: bool,
100 context: &RewriteContext,
104 where I: Iterator<Item = &'a ast::PathSegment>
106 let mut first = true;
108 for segment in iter {
112 buffer.push_str("::");
115 let extra_offset = extra_offset(&buffer, offset);
116 let remaining_width = try_opt!(width.checked_sub(extra_offset));
117 let new_offset = offset + extra_offset;
118 let segment_string = try_opt!(rewrite_segment(expr_context,
126 buffer.push_str(&segment_string);
133 enum SegmentParam<'a> {
134 LifeTime(&'a ast::Lifetime),
136 Binding(&'a ast::TypeBinding),
139 impl<'a> SegmentParam<'a> {
140 fn get_span(&self) -> Span {
142 SegmentParam::LifeTime(lt) => lt.span,
143 SegmentParam::Type(ty) => ty.span,
144 SegmentParam::Binding(binding) => binding.span,
149 impl<'a> Rewrite for SegmentParam<'a> {
150 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
152 SegmentParam::LifeTime(lt) => lt.rewrite(context, width, offset),
153 SegmentParam::Type(ty) => ty.rewrite(context, width, offset),
154 SegmentParam::Binding(binding) => {
155 let mut result = format!("{} = ", binding.ident);
156 let budget = try_opt!(width.checked_sub(result.len()));
157 let rewrite = try_opt!(binding.ty.rewrite(context, budget, offset + result.len()));
158 result.push_str(&rewrite);
165 // Formats a path segment. There are some hacks involved to correctly determine
166 // the segment's associated span since it's not part of the AST.
168 // The span_lo is assumed to be greater than the end of any previous segment's
169 // parameters and lesser or equal than the start of current segment.
171 // span_hi is assumed equal to the end of the entire path.
173 // When the segment contains a positive number of parameters, we update span_lo
174 // so that invariants described above will hold for the next segment.
175 fn rewrite_segment(expr_context: bool,
176 segment: &ast::PathSegment,
177 span_lo: &mut BytePos,
179 context: &RewriteContext,
183 let ident_len = segment.identifier.to_string().len();
184 let width = try_opt!(width.checked_sub(ident_len));
185 let offset = offset + ident_len;
187 let params = match segment.parameters {
188 ast::PathParameters::AngleBracketed(ref data) if !data.lifetimes.is_empty() ||
189 !data.types.is_empty() ||
190 !data.bindings.is_empty() => {
191 let param_list = data.lifetimes
193 .map(SegmentParam::LifeTime)
194 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
195 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
196 .collect::<Vec<_>>();
198 let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
199 let list_lo = context.codemap.span_after(codemap::mk_sp(*span_lo, span_hi), "<");
200 let separator = if expr_context { "::" } else { "" };
203 let extra_offset = 1 + separator.len();
205 let list_width = try_opt!(width.checked_sub(extra_offset + 1));
207 let items = itemize_list(context.codemap,
208 param_list.into_iter(),
210 |param| param.get_span().lo,
211 |param| param.get_span().hi,
212 |seg| seg.rewrite(context, list_width, offset + extra_offset),
215 let list_str = try_opt!(format_item_list(items,
217 offset + extra_offset,
220 // Update position of last bracket.
221 *span_lo = next_span_lo;
223 if context.config.spaces_within_angle_brackets && list_str.len() > 0 {
224 format!("{}< {} >", separator, list_str)
226 format!("{}<{}>", separator, list_str)
229 ast::PathParameters::Parenthesized(ref data) => {
230 let output = match data.output {
231 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
232 None => FunctionRetTy::Default(codemap::DUMMY_SP),
234 try_opt!(format_function_type(data.inputs.iter().map(|x| &**x),
245 Some(format!("{}{}", segment.identifier, params))
248 fn format_function_type<'a, I>(inputs: I,
249 output: &FunctionRetTy,
252 context: &RewriteContext,
256 where I: ExactSizeIterator,
257 <I as Iterator>::Item: Deref,
258 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
260 // Code for handling variadics is somewhat duplicated for items, but they
261 // are different enough to need some serious refactoring to share code.
264 <T as Deref>::Target: Rewrite + Spanned
270 let variadic_arg = if variadic {
271 let variadic_start = context.codemap.span_before(span, "...");
272 Some(ArgumentKind::Variadic(variadic_start))
278 let budget = try_opt!(width.checked_sub(2));
280 let offset = offset + 1;
281 let list_lo = context.codemap.span_after(span, "(");
282 let items = itemize_list(context.codemap,
283 // FIXME Would be nice to avoid this allocation,
284 // but I couldn't get the types to work out.
285 inputs.map(|i| ArgumentKind::Regular(Box::new(i)))
286 .chain(variadic_arg),
290 ArgumentKind::Regular(ref ty) => ty.span().lo,
291 ArgumentKind::Variadic(start) => start,
296 ArgumentKind::Regular(ref ty) => ty.span().hi,
297 ArgumentKind::Variadic(start) => start + BytePos(3),
302 ArgumentKind::Regular(ref ty) => ty.rewrite(context, budget, offset),
303 ArgumentKind::Variadic(_) => Some("...".to_owned()),
309 let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
311 let output = match *output {
312 FunctionRetTy::Ty(ref ty) => {
313 let budget = try_opt!(width.checked_sub(4));
314 let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
315 format!(" -> {}", type_str)
317 FunctionRetTy::Default(..) => String::new(),
320 let infix = if !output.is_empty() && output.len() + list_str.len() > width {
321 format!("\n{}", (offset - 1).to_string(context.config))
326 Some(if context.config.spaces_within_parens {
327 format!("( {} ){}{}", list_str, infix, output)
329 format!("({}){}{}", list_str, infix, output)
333 impl Rewrite for ast::WherePredicate {
334 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
336 let result = match *self {
337 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
341 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
343 if !bound_lifetimes.is_empty() {
344 let lifetime_str: String = try_opt!(bound_lifetimes.iter()
350 .intersperse(Some(", ".to_string()))
353 // 8 = "for<> : ".len()
354 let used_width = lifetime_str.len() + type_str.len() + 8;
355 let budget = try_opt!(width.checked_sub(used_width));
356 let bounds_str: String = try_opt!(bounds.iter()
358 ty_bound.rewrite(context,
362 .intersperse(Some(" + ".to_string()))
365 if context.config.spaces_within_angle_brackets && lifetime_str.len() > 0 {
366 format!("for< {} > {}: {}", lifetime_str, type_str, bounds_str)
368 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
372 let used_width = type_str.len() + 2;
373 let budget = try_opt!(width.checked_sub(used_width));
374 let bounds_str: String = try_opt!(bounds.iter()
376 ty_bound.rewrite(context,
380 .intersperse(Some(" + ".to_string()))
383 format!("{}: {}", type_str, bounds_str)
386 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
389 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
391 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
392 let ty_str = try_opt!(ty.rewrite(context, width, offset));
394 let used_width = 3 + ty_str.len();
395 let budget = try_opt!(width.checked_sub(used_width));
397 try_opt!(rewrite_path(context, false, None, path, budget, offset + used_width));
398 format!("{} = {}", path_str, ty_str)
402 wrap_str(result, context.config.max_width, width, offset)
406 impl Rewrite for ast::LifetimeDef {
407 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
408 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
412 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
414 context: &RewriteContext,
418 where I: ExactSizeIterator<Item = &'b ast::Lifetime>
420 let result = try_opt!(lt.rewrite(context, width, offset));
422 if bounds.len() == 0 {
425 let appendix: Vec<_> = try_opt!(bounds.into_iter()
426 .map(|b| b.rewrite(context, width, offset))
428 let bound_spacing_before = if context.config.space_before_bound {
433 let bound_spacing_after = if context.config.space_after_bound_colon {
438 let result = format!("{}{}:{}{}",
440 bound_spacing_before,
442 appendix.join(" + "));
443 wrap_str(result, context.config.max_width, width, offset)
447 impl Rewrite for ast::TyParamBound {
448 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
450 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
451 tref.rewrite(context, width, offset)
453 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
454 let budget = try_opt!(width.checked_sub(1));
455 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
457 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
462 impl Rewrite for ast::Lifetime {
463 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
464 wrap_str(pprust::lifetime_to_string(self),
465 context.config.max_width,
471 impl Rewrite for ast::TyParamBounds {
472 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
473 let strs: Vec<_> = try_opt!(self.iter()
474 .map(|b| b.rewrite(context, width, offset))
476 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
480 impl Rewrite for ast::TyParam {
481 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
482 let mut result = String::with_capacity(128);
483 result.push_str(&self.ident.to_string());
484 if !self.bounds.is_empty() {
485 if context.config.space_before_bound {
486 result.push_str(" ");
488 result.push_str(":");
489 if context.config.space_after_bound_colon {
490 result.push_str(" ");
493 let bounds: String = try_opt!(self.bounds
495 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
496 .intersperse(Some(" + ".to_string()))
499 result.push_str(&bounds);
501 if let Some(ref def) = self.default {
503 let eq_str = match context.config.type_punctuation_density {
504 TypeDensity::Compressed => "=",
505 TypeDensity::Wide => " = ",
507 result.push_str(eq_str);
508 let budget = try_opt!(width.checked_sub(result.len()));
509 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
510 result.push_str(&rewrite);
513 wrap_str(result, context.config.max_width, width, offset)
517 impl Rewrite for ast::PolyTraitRef {
518 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
519 if !self.bound_lifetimes.is_empty() {
520 let lifetime_str: String = try_opt!(self.bound_lifetimes
522 .map(|lt| lt.rewrite(context, width, offset))
523 .intersperse(Some(", ".to_string()))
526 // 6 is "for<> ".len()
527 let extra_offset = lifetime_str.len() + 6;
528 let max_path_width = try_opt!(width.checked_sub(extra_offset));
529 let path_str = try_opt!(self.trait_ref
530 .rewrite(context, max_path_width, offset + extra_offset));
532 Some(if context.config.spaces_within_angle_brackets && lifetime_str.len() > 0 {
533 format!("for< {} > {}", lifetime_str, path_str)
535 format!("for<{}> {}", lifetime_str, path_str)
538 self.trait_ref.rewrite(context, width, offset)
543 impl Rewrite for ast::TraitRef {
544 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
545 rewrite_path(context, false, None, &self.path, width, offset)
549 impl Rewrite for ast::Ty {
550 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
552 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
553 let ty_str = try_opt!(ty.rewrite(context, width, offset));
554 let overhead = ty_str.len() + 3;
555 let plus_str = match context.config.type_punctuation_density {
556 TypeDensity::Compressed => "+",
557 TypeDensity::Wide => " + ",
559 Some(format!("{}{}{}",
562 try_opt!(bounds.rewrite(context,
563 try_opt!(width.checked_sub(overhead)),
564 offset + overhead))))
566 ast::TyKind::Ptr(ref mt) => {
567 let prefix = match mt.mutbl {
568 Mutability::Mutable => "*mut ",
569 Mutability::Immutable => "*const ",
572 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
574 ast::TyKind::Rptr(ref lifetime, ref mt) => {
575 let mut_str = format_mutability(mt.mutbl);
576 let mut_len = mut_str.len();
577 Some(match *lifetime {
578 Some(ref lifetime) => {
579 let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
581 try_opt!(lifetime.rewrite(context, lt_budget, offset + 2 + mut_len));
582 let lt_len = lt_str.len();
583 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
588 .rewrite(context, budget, offset + 2 + mut_len + lt_len)))
591 let budget = try_opt!(width.checked_sub(1 + mut_len));
594 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
598 // FIXME: we drop any comments here, even though it's a silly place to put
600 ast::TyKind::Paren(ref ty) => {
601 let budget = try_opt!(width.checked_sub(2));
602 ty.rewrite(context, budget, offset + 1)
603 .map(|ty_str| if context.config.spaces_within_parens {
604 format!("( {} )", ty_str)
606 format!("({})", ty_str)
609 ast::TyKind::Vec(ref ty) => {
610 let budget = try_opt!(width.checked_sub(2));
611 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
613 ast::TyKind::Tup(ref items) => {
614 rewrite_tuple(context,
615 items.iter().map(|x| &**x),
620 ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
621 ast::TyKind::Path(ref q_self, ref path) => {
622 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
624 ast::TyKind::FixedLengthVec(ref ty, ref repeats) => {
625 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
627 ast::TyKind::Infer => {
634 ast::TyKind::BareFn(ref bare_fn) => {
635 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
637 ast::TyKind::Never => Some(String::from("!")),
638 ast::TyKind::Mac(..) |
639 ast::TyKind::Typeof(..) => unreachable!(),
640 ast::TyKind::ImplicitSelf => Some(String::from("")),
641 ast::TyKind::ImplTrait(ref it) => {
642 it.rewrite(context, width, offset).map(|it_str| format!("impl {}", it_str))
648 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
650 context: &RewriteContext,
654 let mut result = String::with_capacity(128);
656 if !bare_fn.lifetimes.is_empty() {
657 result.push_str("for<");
658 // 6 = "for<> ".len(), 4 = "for<".
659 // This doesn't work out so nicely for mutliline situation with lots of
660 // rightward drift. If that is a problem, we could use the list stuff.
661 result.push_str(&try_opt!(bare_fn.lifetimes
663 .map(|l| l.rewrite(context, try_opt!(width.checked_sub(6)), offset + 4))
664 .intersperse(Some(", ".to_string()))
665 .collect::<Option<String>>()));
666 result.push_str("> ");
669 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
671 if bare_fn.abi != abi::Abi::Rust {
672 result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi));
675 result.push_str("fn");
677 let budget = try_opt!(width.checked_sub(result.len()));
678 let indent = offset + result.len();
680 let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
681 &bare_fn.decl.output,
682 bare_fn.decl.variadic,
688 result.push_str(&rewrite);