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(if context.config.spaces_within_parens {
315 format!("( {} ){}{}", list_str, infix, output)
317 format!("({}){}{}", list_str, infix, output)
321 impl Rewrite for ast::WherePredicate {
322 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
324 let result = match *self {
325 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
329 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
331 if !bound_lifetimes.is_empty() {
332 let lifetime_str: String = try_opt!(bound_lifetimes.iter()
338 .intersperse(Some(", ".to_string()))
341 // 8 = "for<> : ".len()
342 let used_width = lifetime_str.len() + type_str.len() + 8;
343 let budget = try_opt!(width.checked_sub(used_width));
344 let bounds_str: String = try_opt!(bounds.iter()
346 ty_bound.rewrite(context,
350 .intersperse(Some(" + ".to_string()))
353 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
356 let used_width = type_str.len() + 2;
357 let budget = try_opt!(width.checked_sub(used_width));
358 let bounds_str: String = try_opt!(bounds.iter()
360 ty_bound.rewrite(context,
364 .intersperse(Some(" + ".to_string()))
367 format!("{}: {}", type_str, bounds_str)
370 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
373 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
375 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
376 let ty_str = try_opt!(ty.rewrite(context, width, offset));
378 let used_width = 3 + ty_str.len();
379 let budget = try_opt!(width.checked_sub(used_width));
381 try_opt!(rewrite_path(context, false, None, path, budget, offset + used_width));
382 format!("{} = {}", path_str, ty_str)
386 wrap_str(result, context.config.max_width, width, offset)
390 impl Rewrite for ast::LifetimeDef {
391 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
392 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
396 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
398 context: &RewriteContext,
402 where I: ExactSizeIterator<Item = &'b ast::Lifetime>
404 let result = try_opt!(lt.rewrite(context, width, offset));
406 if bounds.len() == 0 {
409 let appendix: Vec<_> = try_opt!(bounds.into_iter()
410 .map(|b| b.rewrite(context, width, offset))
412 let bound_spacing_before = if context.config.space_before_bound {
417 let bound_spacing_after = if context.config.space_after_bound_colon {
422 let result = format!("{}{}:{}{}",
424 bound_spacing_before,
426 appendix.join(" + "));
427 wrap_str(result, context.config.max_width, width, offset)
431 impl Rewrite for ast::TyParamBound {
432 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
434 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
435 tref.rewrite(context, width, offset)
437 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
438 let budget = try_opt!(width.checked_sub(1));
439 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
441 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
446 impl Rewrite for ast::Lifetime {
447 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
448 wrap_str(pprust::lifetime_to_string(self),
449 context.config.max_width,
455 impl Rewrite for ast::TyParamBounds {
456 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
457 let strs: Vec<_> = try_opt!(self.iter()
458 .map(|b| b.rewrite(context, width, offset))
460 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
464 impl Rewrite for ast::TyParam {
465 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
466 let mut result = String::with_capacity(128);
467 result.push_str(&self.ident.to_string());
468 if !self.bounds.is_empty() {
469 if context.config.space_before_bound {
470 result.push_str(" ");
472 result.push_str(":");
473 if context.config.space_after_bound_colon {
474 result.push_str(" ");
477 let bounds: String = try_opt!(self.bounds
479 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
480 .intersperse(Some(" + ".to_string()))
483 result.push_str(&bounds);
485 if let Some(ref def) = self.default {
487 let eq_str = match context.config.type_punctuation_density {
488 TypeDensity::Compressed => "=",
489 TypeDensity::Wide => " = ",
491 result.push_str(eq_str);
492 let budget = try_opt!(width.checked_sub(result.len()));
493 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
494 result.push_str(&rewrite);
497 wrap_str(result, context.config.max_width, width, offset)
501 impl Rewrite for ast::PolyTraitRef {
502 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
503 if !self.bound_lifetimes.is_empty() {
504 let lifetime_str: String = try_opt!(self.bound_lifetimes
506 .map(|lt| lt.rewrite(context, width, offset))
507 .intersperse(Some(", ".to_string()))
510 // 6 is "for<> ".len()
511 let extra_offset = lifetime_str.len() + 6;
512 let max_path_width = try_opt!(width.checked_sub(extra_offset));
513 let path_str = try_opt!(self.trait_ref
514 .rewrite(context, max_path_width, offset + extra_offset));
516 Some(format!("for<{}> {}", lifetime_str, path_str))
518 self.trait_ref.rewrite(context, width, offset)
523 impl Rewrite for ast::TraitRef {
524 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
525 rewrite_path(context, false, None, &self.path, width, offset)
529 impl Rewrite for ast::Ty {
530 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
532 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
533 let ty_str = try_opt!(ty.rewrite(context, width, offset));
534 let overhead = ty_str.len() + 3;
535 let plus_str = match context.config.type_punctuation_density {
536 TypeDensity::Compressed => "+",
537 TypeDensity::Wide => " + ",
539 Some(format!("{}{}{}",
542 try_opt!(bounds.rewrite(context,
543 try_opt!(width.checked_sub(overhead)),
544 offset + overhead))))
546 ast::TyKind::Ptr(ref mt) => {
547 let prefix = match mt.mutbl {
548 Mutability::Mutable => "*mut ",
549 Mutability::Immutable => "*const ",
552 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
554 ast::TyKind::Rptr(ref lifetime, ref mt) => {
555 let mut_str = format_mutability(mt.mutbl);
556 let mut_len = mut_str.len();
557 Some(match *lifetime {
558 Some(ref lifetime) => {
559 let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
561 try_opt!(lifetime.rewrite(context, lt_budget, offset + 2 + mut_len));
562 let lt_len = lt_str.len();
563 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
568 .rewrite(context, budget, offset + 2 + mut_len + lt_len)))
571 let budget = try_opt!(width.checked_sub(1 + mut_len));
574 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
578 // FIXME: we drop any comments here, even though it's a silly place to put
580 ast::TyKind::Paren(ref ty) => {
581 let budget = try_opt!(width.checked_sub(2));
582 ty.rewrite(context, budget, offset + 1)
583 .map(|ty_str| if context.config.spaces_within_parens {
584 format!("( {} )", ty_str)
586 format!("({})", ty_str)
589 ast::TyKind::Vec(ref ty) => {
590 let budget = try_opt!(width.checked_sub(2));
591 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
593 ast::TyKind::Tup(ref items) => {
594 rewrite_tuple(context,
595 items.iter().map(|x| &**x),
600 ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
601 ast::TyKind::Path(ref q_self, ref path) => {
602 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
604 ast::TyKind::FixedLengthVec(ref ty, ref repeats) => {
605 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
607 ast::TyKind::Infer => {
614 ast::TyKind::BareFn(ref bare_fn) => {
615 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
617 ast::TyKind::Never => Some(String::from("!")),
618 ast::TyKind::Mac(..) |
619 ast::TyKind::Typeof(..) => unreachable!(),
620 ast::TyKind::ImplicitSelf => Some(String::from("")),
621 ast::TyKind::ImplTrait(ref it) => {
622 it.rewrite(context, width, offset).map(|it_str| format!("impl {}", it_str))
628 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
630 context: &RewriteContext,
634 let mut result = String::with_capacity(128);
636 if !bare_fn.lifetimes.is_empty() {
637 result.push_str("for<");
638 // 6 = "for<> ".len(), 4 = "for<".
639 // This doesn't work out so nicely for mutliline situation with lots of
640 // rightward drift. If that is a problem, we could use the list stuff.
641 result.push_str(&try_opt!(bare_fn.lifetimes
643 .map(|l| l.rewrite(context, try_opt!(width.checked_sub(6)), offset + 4))
644 .intersperse(Some(", ".to_string()))
645 .collect::<Option<String>>()));
646 result.push_str("> ");
649 result.push_str(::utils::format_unsafety(bare_fn.unsafety));
651 if bare_fn.abi != abi::Abi::Rust {
652 result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi));
655 result.push_str("fn");
657 let budget = try_opt!(width.checked_sub(result.len()));
658 let indent = offset + result.len();
660 let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
661 &bare_fn.decl.output,
662 bare_fn.decl.variadic,
668 result.push_str(&rewrite);