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(ref 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(ref lt) => lt.span,
135 SegmentParam::Type(ref ty) => ty.span,
136 SegmentParam::Binding(ref 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(ref lt) => lt.rewrite(context, width, offset),
145 SegmentParam::Type(ref ty) => ty.rewrite(context, width, offset),
146 SegmentParam::Binding(ref 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::None(..) => " -> !".to_owned(),
306 FunctionRetTy::Default(..) => String::new(),
309 let infix = if output.len() > 0 && output.len() + list_str.len() > width {
310 format!("\n{}", (offset - 1).to_string(context.config))
315 Some(format!("({}){}{}", list_str, infix, output))
318 impl Rewrite for ast::WherePredicate {
319 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
321 let result = match *self {
322 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
326 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
328 if !bound_lifetimes.is_empty() {
329 let lifetime_str: String = try_opt!(bound_lifetimes.iter()
335 .intersperse(Some(", ".to_string()))
338 // 8 = "for<> : ".len()
339 let used_width = lifetime_str.len() + type_str.len() + 8;
340 let budget = try_opt!(width.checked_sub(used_width));
341 let bounds_str: String = try_opt!(bounds.iter()
343 ty_bound.rewrite(context,
347 .intersperse(Some(" + ".to_string()))
350 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
353 let used_width = type_str.len() + 2;
354 let budget = try_opt!(width.checked_sub(used_width));
355 let bounds_str: String = try_opt!(bounds.iter()
357 ty_bound.rewrite(context,
361 .intersperse(Some(" + ".to_string()))
364 format!("{}: {}", type_str, bounds_str)
367 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
370 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
372 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
373 let ty_str = try_opt!(ty.rewrite(context, width, offset));
375 let used_width = 3 + ty_str.len();
376 let budget = try_opt!(width.checked_sub(used_width));
378 try_opt!(rewrite_path(context, false, None, path, budget, offset + used_width));
379 format!("{} = {}", path_str, ty_str)
383 wrap_str(result, context.config.max_width, width, offset)
387 impl Rewrite for ast::LifetimeDef {
388 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
389 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
393 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
395 context: &RewriteContext,
399 where I: ExactSizeIterator<Item = &'b ast::Lifetime>
401 let result = try_opt!(lt.rewrite(context, width, offset));
403 if bounds.len() == 0 {
406 let appendix: Vec<_> = try_opt!(bounds.into_iter()
407 .map(|b| b.rewrite(context, width, offset))
409 let bound_spacing = if context.config.space_before_bound {
414 let result = format!("{}{}: {}", result, bound_spacing, appendix.join(" + "));
415 wrap_str(result, context.config.max_width, width, offset)
419 impl Rewrite for ast::TyParamBound {
420 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
422 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
423 tref.rewrite(context, width, offset)
425 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
426 let budget = try_opt!(width.checked_sub(1));
427 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
429 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
434 impl Rewrite for ast::Lifetime {
435 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
436 wrap_str(pprust::lifetime_to_string(self),
437 context.config.max_width,
443 impl Rewrite for ast::TyParamBounds {
444 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
445 let strs: Vec<_> = try_opt!(self.iter()
446 .map(|b| b.rewrite(context, width, offset))
448 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
452 impl Rewrite for ast::TyParam {
453 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
454 let mut result = String::with_capacity(128);
455 result.push_str(&self.ident.to_string());
456 if !self.bounds.is_empty() {
457 if context.config.space_before_bound {
458 result.push_str(" ");
460 result.push_str(": ");
462 let bounds: String = try_opt!(self.bounds
464 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
465 .intersperse(Some(" + ".to_string()))
468 result.push_str(&bounds);
470 if let Some(ref def) = self.default {
472 let eq_str = match context.config.type_punctuation_density {
473 TypeDensity::Compressed => "=",
474 TypeDensity::Wide => " = ",
476 result.push_str(eq_str);
477 let budget = try_opt!(width.checked_sub(result.len()));
478 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
479 result.push_str(&rewrite);
482 wrap_str(result, context.config.max_width, width, offset)
486 impl Rewrite for ast::PolyTraitRef {
487 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
488 if !self.bound_lifetimes.is_empty() {
489 let lifetime_str: String = try_opt!(self.bound_lifetimes
491 .map(|lt| lt.rewrite(context, width, offset))
492 .intersperse(Some(", ".to_string()))
495 // 6 is "for<> ".len()
496 let extra_offset = lifetime_str.len() + 6;
497 let max_path_width = try_opt!(width.checked_sub(extra_offset));
498 let path_str = try_opt!(self.trait_ref
499 .rewrite(context, max_path_width, offset + extra_offset));
501 Some(format!("for<{}> {}", lifetime_str, path_str))
503 self.trait_ref.rewrite(context, width, offset)
508 impl Rewrite for ast::TraitRef {
509 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
510 rewrite_path(context, false, None, &self.path, width, offset)
514 impl Rewrite for ast::Ty {
515 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
517 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
518 let ty_str = try_opt!(ty.rewrite(context, width, offset));
519 let overhead = ty_str.len() + 3;
520 let plus_str = match context.config.type_punctuation_density {
521 TypeDensity::Compressed => "+",
522 TypeDensity::Wide => " + ",
524 Some(format!("{}{}{}",
527 try_opt!(bounds.rewrite(context,
528 try_opt!(width.checked_sub(overhead)),
529 offset + overhead))))
531 ast::TyKind::Ptr(ref mt) => {
532 let prefix = match mt.mutbl {
533 Mutability::Mutable => "*mut ",
534 Mutability::Immutable => "*const ",
537 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
539 ast::TyKind::Rptr(ref lifetime, ref mt) => {
540 let mut_str = format_mutability(mt.mutbl);
541 let mut_len = mut_str.len();
542 Some(match *lifetime {
543 Some(ref lifetime) => {
544 let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
546 try_opt!(lifetime.rewrite(context, lt_budget, offset + 2 + mut_len));
547 let lt_len = lt_str.len();
548 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
553 .rewrite(context, budget, offset + 2 + mut_len + lt_len)))
556 let budget = try_opt!(width.checked_sub(1 + mut_len));
559 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
563 // FIXME: we drop any comments here, even though it's a silly place to put
565 ast::TyKind::Paren(ref ty) => {
566 let budget = try_opt!(width.checked_sub(2));
567 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
569 ast::TyKind::Vec(ref ty) => {
570 let budget = try_opt!(width.checked_sub(2));
571 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
573 ast::TyKind::Tup(ref items) => {
574 rewrite_tuple(context,
575 items.iter().map(|x| &**x),
580 ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
581 ast::TyKind::Path(ref q_self, ref path) => {
582 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
584 ast::TyKind::FixedLengthVec(ref ty, ref repeats) => {
585 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
587 ast::TyKind::Infer => {
594 ast::TyKind::BareFn(ref bare_fn) => {
595 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
597 ast::TyKind::Mac(..) |
598 ast::TyKind::Typeof(..) => unreachable!(),
599 ast::TyKind::ImplicitSelf => Some(String::from("")),
604 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
606 context: &RewriteContext,
610 let mut result = String::with_capacity(128);
612 if !bare_fn.lifetimes.is_empty() {
613 result.push_str("for<");
614 // 6 = "for<> ".len(), 4 = "for<".
615 // This doesn't work out so nicely for mutliline situation with lots of
616 // rightward drift. If that is a problem, we could use the list stuff.
617 result.push_str(&try_opt!(bare_fn.lifetimes
619 .map(|l| l.rewrite(context, try_opt!(width.checked_sub(6)), offset + 4))
620 .intersperse(Some(", ".to_string()))
621 .collect::<Option<String>>()));
622 result.push_str("> ");
625 result.push_str(&::utils::format_unsafety(bare_fn.unsafety));
627 if bare_fn.abi != abi::Abi::Rust {
628 result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi));
631 result.push_str("fn");
633 let budget = try_opt!(width.checked_sub(result.len()));
634 let indent = offset + result.len();
636 let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
637 &bare_fn.decl.output,
638 bare_fn.decl.variadic,
644 result.push_str(&rewrite);