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 let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
49 result.push_str(&fmt_ty);
52 result.push_str(" as ");
54 result.push_str("::");
57 let extra_offset = extra_offset(&result, offset);
59 let budget = try_opt!(width.checked_sub(extra_offset + 3));
61 result = try_opt!(rewrite_path_segments(false,
63 path.segments.iter().take(skip_count),
68 offset + extra_offset));
71 result.push_str(">::");
72 span_lo = qself.ty.span.hi + BytePos(1);
75 let extra_offset = extra_offset(&result, offset);
76 let budget = try_opt!(width.checked_sub(extra_offset));
77 rewrite_path_segments(expr_context,
79 path.segments.iter().skip(skip_count),
84 offset + extra_offset)
87 fn rewrite_path_segments<'a, I>(expr_context: bool,
92 context: &RewriteContext,
96 where I: Iterator<Item = &'a ast::PathSegment>
100 for segment in iter {
104 buffer.push_str("::");
107 let extra_offset = extra_offset(&buffer, offset);
108 let remaining_width = try_opt!(width.checked_sub(extra_offset));
109 let new_offset = offset + extra_offset;
110 let segment_string = try_opt!(rewrite_segment(expr_context,
118 buffer.push_str(&segment_string);
125 enum SegmentParam<'a> {
126 LifeTime(&'a ast::Lifetime),
128 Binding(&'a ast::TypeBinding),
131 impl<'a> SegmentParam<'a> {
132 fn get_span(&self) -> Span {
134 SegmentParam::LifeTime(lt) => lt.span,
135 SegmentParam::Type(ty) => ty.span,
136 SegmentParam::Binding(binding) => binding.span,
141 impl<'a> Rewrite for SegmentParam<'a> {
142 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
144 SegmentParam::LifeTime(lt) => lt.rewrite(context, width, offset),
145 SegmentParam::Type(ty) => ty.rewrite(context, width, offset),
146 SegmentParam::Binding(binding) => {
147 let mut result = format!("{} = ", binding.ident);
148 let budget = try_opt!(width.checked_sub(result.len()));
149 let rewrite = try_opt!(binding.ty.rewrite(context, budget, offset + result.len()));
150 result.push_str(&rewrite);
157 // Formats a path segment. There are some hacks involved to correctly determine
158 // the segment's associated span since it's not part of the AST.
160 // The span_lo is assumed to be greater than the end of any previous segment's
161 // parameters and lesser or equal than the start of current segment.
163 // span_hi is assumed equal to the end of the entire path.
165 // When the segment contains a positive number of parameters, we update span_lo
166 // so that invariants described above will hold for the next segment.
167 fn rewrite_segment(expr_context: bool,
168 segment: &ast::PathSegment,
169 span_lo: &mut BytePos,
171 context: &RewriteContext,
175 let ident_len = segment.identifier.to_string().len();
176 let width = try_opt!(width.checked_sub(ident_len));
177 let offset = offset + ident_len;
179 let params = match segment.parameters {
180 ast::PathParameters::AngleBracketed(ref data) if !data.lifetimes.is_empty() ||
181 !data.types.is_empty() ||
182 !data.bindings.is_empty() => {
183 let param_list = data.lifetimes
185 .map(SegmentParam::LifeTime)
186 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
187 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
188 .collect::<Vec<_>>();
190 let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
191 let list_lo = context.codemap.span_after(codemap::mk_sp(*span_lo, span_hi), "<");
192 let separator = if expr_context { "::" } else { "" };
195 let extra_offset = 1 + separator.len();
197 let list_width = try_opt!(width.checked_sub(extra_offset + 1));
199 let items = itemize_list(context.codemap,
200 param_list.into_iter(),
202 |param| param.get_span().lo,
203 |param| param.get_span().hi,
204 |seg| seg.rewrite(context, list_width, offset + extra_offset),
207 let list_str = try_opt!(format_item_list(items,
209 offset + extra_offset,
212 // Update position of last bracket.
213 *span_lo = next_span_lo;
215 format!("{}<{}>", separator, list_str)
217 ast::PathParameters::Parenthesized(ref data) => {
218 let output = match data.output {
219 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
220 None => FunctionRetTy::Default(codemap::DUMMY_SP),
222 try_opt!(format_function_type(data.inputs.iter().map(|x| &**x),
233 Some(format!("{}{}", segment.identifier, params))
236 fn format_function_type<'a, I>(inputs: I,
237 output: &FunctionRetTy,
240 context: &RewriteContext,
244 where I: ExactSizeIterator,
245 <I as Iterator>::Item: Deref,
246 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
248 // Code for handling variadics is somewhat duplicated for items, but they
249 // are different enough to need some serious refactoring to share code.
252 <T as Deref>::Target: Rewrite + Spanned
258 let variadic_arg = if variadic {
259 let variadic_start = context.codemap.span_before(span, "...");
260 Some(ArgumentKind::Variadic(variadic_start))
266 let budget = try_opt!(width.checked_sub(2));
268 let offset = offset + 1;
269 let list_lo = context.codemap.span_after(span, "(");
270 let items = itemize_list(context.codemap,
271 // FIXME Would be nice to avoid this allocation,
272 // but I couldn't get the types to work out.
273 inputs.map(|i| ArgumentKind::Regular(Box::new(i)))
274 .chain(variadic_arg),
278 ArgumentKind::Regular(ref ty) => ty.span().lo,
279 ArgumentKind::Variadic(start) => start,
284 ArgumentKind::Regular(ref ty) => ty.span().hi,
285 ArgumentKind::Variadic(start) => start + BytePos(3),
290 ArgumentKind::Regular(ref ty) => ty.rewrite(context, budget, offset),
291 ArgumentKind::Variadic(_) => Some("...".to_owned()),
297 let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
299 let output = match *output {
300 FunctionRetTy::Ty(ref ty) => {
301 let budget = try_opt!(width.checked_sub(4));
302 let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
303 format!(" -> {}", type_str)
305 FunctionRetTy::Default(..) => String::new(),
308 let infix = if !output.is_empty() && output.len() + list_str.len() > width {
309 format!("\n{}", (offset - 1).to_string(context.config))
314 Some(format!("({}){}{}", list_str, infix, output))
317 impl Rewrite for ast::WherePredicate {
318 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
320 let result = match *self {
321 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
325 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
327 if !bound_lifetimes.is_empty() {
328 let lifetime_str: String = try_opt!(bound_lifetimes.iter()
334 .intersperse(Some(", ".to_string()))
337 // 8 = "for<> : ".len()
338 let used_width = lifetime_str.len() + type_str.len() + 8;
339 let budget = try_opt!(width.checked_sub(used_width));
340 let bounds_str: String = try_opt!(bounds.iter()
342 ty_bound.rewrite(context,
346 .intersperse(Some(" + ".to_string()))
349 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
352 let used_width = type_str.len() + 2;
353 let budget = try_opt!(width.checked_sub(used_width));
354 let bounds_str: String = try_opt!(bounds.iter()
356 ty_bound.rewrite(context,
360 .intersperse(Some(" + ".to_string()))
363 format!("{}: {}", type_str, bounds_str)
366 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
369 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
371 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
372 let ty_str = try_opt!(ty.rewrite(context, width, offset));
374 let used_width = 3 + ty_str.len();
375 let budget = try_opt!(width.checked_sub(used_width));
377 try_opt!(rewrite_path(context, false, None, path, budget, offset + used_width));
378 format!("{} = {}", path_str, ty_str)
382 wrap_str(result, context.config.max_width, width, offset)
386 impl Rewrite for ast::LifetimeDef {
387 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
388 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
392 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
394 context: &RewriteContext,
398 where I: ExactSizeIterator<Item = &'b ast::Lifetime>
400 let result = try_opt!(lt.rewrite(context, width, offset));
402 if bounds.len() == 0 {
405 let appendix: Vec<_> = try_opt!(bounds.into_iter()
406 .map(|b| b.rewrite(context, width, offset))
408 let bound_spacing_before = if context.config.space_before_bound {
413 let bound_spacing_after = if context.config.space_after_bound_colon {
418 let result = format!("{}{}:{}{}",
420 bound_spacing_before,
422 appendix.join(" + "));
423 wrap_str(result, context.config.max_width, width, offset)
427 impl Rewrite for ast::TyParamBound {
428 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
430 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
431 tref.rewrite(context, width, offset)
433 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
434 let budget = try_opt!(width.checked_sub(1));
435 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
437 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
442 impl Rewrite for ast::Lifetime {
443 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
444 wrap_str(pprust::lifetime_to_string(self),
445 context.config.max_width,
451 impl Rewrite for ast::TyParamBounds {
452 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
453 let strs: Vec<_> = try_opt!(self.iter()
454 .map(|b| b.rewrite(context, width, offset))
456 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
460 impl Rewrite for ast::TyParam {
461 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
462 let mut result = String::with_capacity(128);
463 result.push_str(&self.ident.to_string());
464 if !self.bounds.is_empty() {
465 if context.config.space_before_bound {
466 result.push_str(" ");
468 result.push_str(":");
469 if context.config.space_after_bound_colon {
470 result.push_str(" ");
473 let bounds: String = try_opt!(self.bounds
475 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
476 .intersperse(Some(" + ".to_string()))
479 result.push_str(&bounds);
481 if let Some(ref def) = self.default {
483 let eq_str = match context.config.type_punctuation_density {
484 TypeDensity::Compressed => "=",
485 TypeDensity::Wide => " = ",
487 result.push_str(eq_str);
488 let budget = try_opt!(width.checked_sub(result.len()));
489 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
490 result.push_str(&rewrite);
493 wrap_str(result, context.config.max_width, width, offset)
497 impl Rewrite for ast::PolyTraitRef {
498 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
499 if !self.bound_lifetimes.is_empty() {
500 let lifetime_str: String = try_opt!(self.bound_lifetimes
502 .map(|lt| lt.rewrite(context, width, offset))
503 .intersperse(Some(", ".to_string()))
506 // 6 is "for<> ".len()
507 let extra_offset = lifetime_str.len() + 6;
508 let max_path_width = try_opt!(width.checked_sub(extra_offset));
509 let path_str = try_opt!(self.trait_ref
510 .rewrite(context, max_path_width, offset + extra_offset));
512 Some(format!("for<{}> {}", lifetime_str, path_str))
514 self.trait_ref.rewrite(context, width, offset)
519 impl Rewrite for ast::TraitRef {
520 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
521 rewrite_path(context, false, None, &self.path, width, offset)
525 impl Rewrite for ast::Ty {
526 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
528 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
529 let ty_str = try_opt!(ty.rewrite(context, width, offset));
530 let overhead = ty_str.len() + 3;
531 let plus_str = match context.config.type_punctuation_density {
532 TypeDensity::Compressed => "+",
533 TypeDensity::Wide => " + ",
535 Some(format!("{}{}{}",
538 try_opt!(bounds.rewrite(context,
539 try_opt!(width.checked_sub(overhead)),
540 offset + overhead))))
542 ast::TyKind::Ptr(ref mt) => {
543 let prefix = match mt.mutbl {
544 Mutability::Mutable => "*mut ",
545 Mutability::Immutable => "*const ",
548 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
550 ast::TyKind::Rptr(ref lifetime, ref mt) => {
551 let mut_str = format_mutability(mt.mutbl);
552 let mut_len = mut_str.len();
553 Some(match *lifetime {
554 Some(ref lifetime) => {
555 let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
557 try_opt!(lifetime.rewrite(context, lt_budget, offset + 2 + mut_len));
558 let lt_len = lt_str.len();
559 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
564 .rewrite(context, budget, offset + 2 + mut_len + lt_len)))
567 let budget = try_opt!(width.checked_sub(1 + mut_len));
570 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
574 // FIXME: we drop any comments here, even though it's a silly place to put
576 ast::TyKind::Paren(ref ty) => {
577 let budget = try_opt!(width.checked_sub(2));
578 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
580 ast::TyKind::Vec(ref ty) => {
581 let budget = try_opt!(width.checked_sub(2));
582 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
584 ast::TyKind::Tup(ref items) => {
585 rewrite_tuple(context,
586 items.iter().map(|x| &**x),
591 ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
592 ast::TyKind::Path(ref q_self, ref path) => {
593 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
595 ast::TyKind::FixedLengthVec(ref ty, ref repeats) => {
596 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
598 ast::TyKind::Infer => {
605 ast::TyKind::BareFn(ref bare_fn) => {
606 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
608 ast::TyKind::Never => Some(String::from("!")),
609 ast::TyKind::Mac(..) |
610 ast::TyKind::Typeof(..) => unreachable!(),
611 ast::TyKind::ImplicitSelf => Some(String::from("")),
612 ast::TyKind::ImplTrait(..) => {
613 // FIXME(#1154) Implement impl Trait
614 Some(String::from("impl TODO"))
620 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
622 context: &RewriteContext,
626 let mut result = String::with_capacity(128);
628 if !bare_fn.lifetimes.is_empty() {
629 result.push_str("for<");
630 // 6 = "for<> ".len(), 4 = "for<".
631 // This doesn't work out so nicely for mutliline situation with lots of
632 // rightward drift. If that is a problem, we could use the list stuff.
633 result.push_str(&try_opt!(bare_fn.lifetimes
635 .map(|l| l.rewrite(context, try_opt!(width.checked_sub(6)), offset + 4))
636 .intersperse(Some(", ".to_string()))
637 .collect::<Option<String>>()));
638 result.push_str("> ");
641 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
643 if bare_fn.abi != abi::Abi::Rust {
644 result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi));
647 result.push_str("fn");
649 let budget = try_opt!(width.checked_sub(result.len()));
650 let indent = offset + result.len();
652 let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
653 &bare_fn.decl.output,
654 bare_fn.decl.variadic,
660 result.push_str(&rewrite);