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, "(");
283 itemize_list(context.codemap,
284 // FIXME Would be nice to avoid this allocation,
285 // but I couldn't get the types to work out.
286 inputs.map(|i| ArgumentKind::Regular(Box::new(i)))
287 .chain(variadic_arg),
290 ArgumentKind::Regular(ref ty) => ty.span().lo,
291 ArgumentKind::Variadic(start) => start,
294 ArgumentKind::Regular(ref ty) => ty.span().hi,
295 ArgumentKind::Variadic(start) => start + BytePos(3),
298 ArgumentKind::Regular(ref ty) => ty.rewrite(context, budget, offset),
299 ArgumentKind::Variadic(_) => Some("...".to_owned()),
304 let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
306 let output = match *output {
307 FunctionRetTy::Ty(ref ty) => {
308 let budget = try_opt!(width.checked_sub(4));
309 let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
310 format!(" -> {}", type_str)
312 FunctionRetTy::Default(..) => String::new(),
315 let infix = if !output.is_empty() && output.len() + list_str.len() > width {
316 format!("\n{}", (offset - 1).to_string(context.config))
321 Some(if context.config.spaces_within_parens {
322 format!("( {} ){}{}", list_str, infix, output)
324 format!("({}){}{}", list_str, infix, output)
328 impl Rewrite for ast::WherePredicate {
329 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
331 let result = match *self {
332 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
336 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
338 if !bound_lifetimes.is_empty() {
339 let lifetime_str: String = try_opt!(bound_lifetimes.iter()
345 .intersperse(Some(", ".to_string()))
348 // 8 = "for<> : ".len()
349 let used_width = lifetime_str.len() + type_str.len() + 8;
350 let budget = try_opt!(width.checked_sub(used_width));
351 let bounds_str: String = try_opt!(bounds.iter()
353 ty_bound.rewrite(context,
357 .intersperse(Some(" + ".to_string()))
360 if context.config.spaces_within_angle_brackets && lifetime_str.len() > 0 {
361 format!("for< {} > {}: {}", lifetime_str, type_str, bounds_str)
363 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
367 let used_width = type_str.len() + 2;
368 let budget = try_opt!(width.checked_sub(used_width));
369 let bounds_str: String = try_opt!(bounds.iter()
371 ty_bound.rewrite(context,
375 .intersperse(Some(" + ".to_string()))
378 format!("{}: {}", type_str, bounds_str)
381 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
384 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
386 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
387 let ty_str = try_opt!(ty.rewrite(context, width, offset));
389 let used_width = 3 + ty_str.len();
390 let budget = try_opt!(width.checked_sub(used_width));
392 try_opt!(rewrite_path(context, false, None, path, budget, offset + used_width));
393 format!("{} = {}", path_str, ty_str)
397 wrap_str(result, context.config.max_width, width, offset)
401 impl Rewrite for ast::LifetimeDef {
402 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
403 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
407 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
409 context: &RewriteContext,
413 where I: ExactSizeIterator<Item = &'b ast::Lifetime>
415 let result = try_opt!(lt.rewrite(context, width, offset));
417 if bounds.len() == 0 {
420 let appendix: Vec<_> = try_opt!(bounds.into_iter()
421 .map(|b| b.rewrite(context, width, offset))
423 let bound_spacing_before = if context.config.space_before_bound {
428 let bound_spacing_after = if context.config.space_after_bound_colon {
433 let result = format!("{}{}:{}{}",
435 bound_spacing_before,
437 appendix.join(" + "));
438 wrap_str(result, context.config.max_width, width, offset)
442 impl Rewrite for ast::TyParamBound {
443 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
445 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
446 tref.rewrite(context, width, offset)
448 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
449 let budget = try_opt!(width.checked_sub(1));
450 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
452 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
457 impl Rewrite for ast::Lifetime {
458 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
459 wrap_str(pprust::lifetime_to_string(self),
460 context.config.max_width,
466 impl Rewrite for ast::TyParamBounds {
467 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
468 let strs: Vec<_> = try_opt!(self.iter()
469 .map(|b| b.rewrite(context, width, offset))
471 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
475 impl Rewrite for ast::TyParam {
476 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
477 let mut result = String::with_capacity(128);
478 result.push_str(&self.ident.to_string());
479 if !self.bounds.is_empty() {
480 if context.config.space_before_bound {
481 result.push_str(" ");
483 result.push_str(":");
484 if context.config.space_after_bound_colon {
485 result.push_str(" ");
488 let bounds: String = try_opt!(self.bounds
490 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
491 .intersperse(Some(" + ".to_string()))
494 result.push_str(&bounds);
496 if let Some(ref def) = self.default {
498 let eq_str = match context.config.type_punctuation_density {
499 TypeDensity::Compressed => "=",
500 TypeDensity::Wide => " = ",
502 result.push_str(eq_str);
503 let budget = try_opt!(width.checked_sub(result.len()));
504 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
505 result.push_str(&rewrite);
508 wrap_str(result, context.config.max_width, width, offset)
512 impl Rewrite for ast::PolyTraitRef {
513 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
514 if !self.bound_lifetimes.is_empty() {
515 let lifetime_str: String = try_opt!(self.bound_lifetimes
517 .map(|lt| lt.rewrite(context, width, offset))
518 .intersperse(Some(", ".to_string()))
521 // 6 is "for<> ".len()
522 let extra_offset = lifetime_str.len() + 6;
523 let max_path_width = try_opt!(width.checked_sub(extra_offset));
524 let path_str = try_opt!(self.trait_ref
525 .rewrite(context, max_path_width, offset + extra_offset));
527 Some(if context.config.spaces_within_angle_brackets && lifetime_str.len() > 0 {
528 format!("for< {} > {}", lifetime_str, path_str)
530 format!("for<{}> {}", lifetime_str, path_str)
533 self.trait_ref.rewrite(context, width, offset)
538 impl Rewrite for ast::TraitRef {
539 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
540 rewrite_path(context, false, None, &self.path, width, offset)
544 impl Rewrite for ast::Ty {
545 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
547 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
548 let ty_str = try_opt!(ty.rewrite(context, width, offset));
549 let overhead = ty_str.len() + 3;
550 let plus_str = match context.config.type_punctuation_density {
551 TypeDensity::Compressed => "+",
552 TypeDensity::Wide => " + ",
554 Some(format!("{}{}{}",
557 try_opt!(bounds.rewrite(context,
558 try_opt!(width.checked_sub(overhead)),
559 offset + overhead))))
561 ast::TyKind::Ptr(ref mt) => {
562 let prefix = match mt.mutbl {
563 Mutability::Mutable => "*mut ",
564 Mutability::Immutable => "*const ",
567 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
569 ast::TyKind::Rptr(ref lifetime, ref mt) => {
570 let mut_str = format_mutability(mt.mutbl);
571 let mut_len = mut_str.len();
572 Some(match *lifetime {
573 Some(ref lifetime) => {
574 let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
576 try_opt!(lifetime.rewrite(context, lt_budget, offset + 2 + mut_len));
577 let lt_len = lt_str.len();
578 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
583 .rewrite(context, budget, offset + 2 + mut_len + lt_len)))
586 let budget = try_opt!(width.checked_sub(1 + mut_len));
589 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
593 // FIXME: we drop any comments here, even though it's a silly place to put
595 ast::TyKind::Paren(ref ty) => {
596 let budget = try_opt!(width.checked_sub(2));
597 ty.rewrite(context, budget, offset + 1)
598 .map(|ty_str| if context.config.spaces_within_parens {
599 format!("( {} )", ty_str)
601 format!("({})", ty_str)
604 ast::TyKind::Slice(ref ty) => {
605 let budget = if context.config.spaces_within_square_brackets {
606 try_opt!(width.checked_sub(4))
608 try_opt!(width.checked_sub(2))
610 ty.rewrite(context, budget, offset + 1)
611 .map(|ty_str| if context.config.spaces_within_square_brackets {
612 format!("[ {} ]", ty_str)
614 format!("[{}]", ty_str)
617 ast::TyKind::Tup(ref items) => {
618 rewrite_tuple(context,
619 items.iter().map(|x| &**x),
624 ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
625 ast::TyKind::Path(ref q_self, ref path) => {
626 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
628 ast::TyKind::Array(ref ty, ref repeats) => {
629 let use_spaces = context.config.spaces_within_square_brackets;
630 let lbr = if use_spaces { "[ " } else { "[" };
631 let rbr = if use_spaces { " ]" } else { "]" };
632 rewrite_pair(&**ty, &**repeats, lbr, "; ", rbr, context, width, offset)
634 ast::TyKind::Infer => {
641 ast::TyKind::BareFn(ref bare_fn) => {
642 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
644 ast::TyKind::Never => Some(String::from("!")),
645 ast::TyKind::Mac(..) |
646 ast::TyKind::Typeof(..) => unreachable!(),
647 ast::TyKind::ImplicitSelf => Some(String::from("")),
648 ast::TyKind::ImplTrait(ref it) => {
649 it.rewrite(context, width, offset).map(|it_str| format!("impl {}", it_str))
655 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
657 context: &RewriteContext,
661 let mut result = String::with_capacity(128);
663 if !bare_fn.lifetimes.is_empty() {
664 result.push_str("for<");
665 // 6 = "for<> ".len(), 4 = "for<".
666 // This doesn't work out so nicely for mutliline situation with lots of
667 // rightward drift. If that is a problem, we could use the list stuff.
668 result.push_str(&try_opt!(bare_fn.lifetimes
670 .map(|l| l.rewrite(context, try_opt!(width.checked_sub(6)), offset + 4))
671 .intersperse(Some(", ".to_string()))
672 .collect::<Option<String>>()));
673 result.push_str("> ");
676 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
678 if bare_fn.abi != abi::Abi::Rust {
679 result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi));
682 result.push_str("fn");
684 let budget = try_opt!(width.checked_sub(result.len()));
685 let indent = offset + result.len();
687 let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
688 &bare_fn.decl.output,
689 bare_fn.decl.variadic,
695 result.push_str(&rewrite);