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 lists::{format_item_list, itemize_list, format_fn_args};
21 use rewrite::{Rewrite, RewriteContext};
22 use utils::{CodeMapSpanUtils, extra_offset, format_mutability, wrap_str};
23 use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
24 use config::TypeDensity;
26 // Does not wrap on simple segments.
27 pub fn rewrite_path(context: &RewriteContext,
29 qself: Option<&ast::QSelf>,
34 let skip_count = qself.map_or(0, |x| x.position);
36 let mut result = if path.global {
42 let mut span_lo = path.span.lo;
44 if let Some(ref qself) = qself {
46 let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
47 result.push_str(&fmt_ty);
50 result.push_str(" as ");
52 let extra_offset = extra_offset(&result, offset);
54 let budget = try_opt!(width.checked_sub(extra_offset + 3));
56 result = try_opt!(rewrite_path_segments(false,
58 path.segments.iter().take(skip_count),
63 offset + extra_offset));
66 result.push_str(">::");
67 span_lo = qself.ty.span.hi + BytePos(1);
70 let extra_offset = extra_offset(&result, offset);
71 let budget = try_opt!(width.checked_sub(extra_offset));
72 rewrite_path_segments(expr_context,
74 path.segments.iter().skip(skip_count),
79 offset + extra_offset)
82 fn rewrite_path_segments<'a, I>(expr_context: bool,
87 context: &RewriteContext,
91 where I: Iterator<Item = &'a ast::PathSegment>
99 buffer.push_str("::");
102 let extra_offset = extra_offset(&buffer, offset);
103 let remaining_width = try_opt!(width.checked_sub(extra_offset));
104 let new_offset = offset + extra_offset;
105 let segment_string = try_opt!(rewrite_segment(expr_context,
113 buffer.push_str(&segment_string);
120 enum SegmentParam<'a> {
121 LifeTime(&'a ast::Lifetime),
123 Binding(&'a ast::TypeBinding),
126 impl<'a> SegmentParam<'a> {
127 fn get_span(&self) -> Span {
129 SegmentParam::LifeTime(ref lt) => lt.span,
130 SegmentParam::Type(ref ty) => ty.span,
131 SegmentParam::Binding(ref binding) => binding.span,
136 impl<'a> Rewrite for SegmentParam<'a> {
137 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
139 SegmentParam::LifeTime(ref lt) => lt.rewrite(context, width, offset),
140 SegmentParam::Type(ref ty) => ty.rewrite(context, width, offset),
141 SegmentParam::Binding(ref binding) => {
142 let mut result = format!("{} = ", binding.ident);
143 let budget = try_opt!(width.checked_sub(result.len()));
144 let rewrite = try_opt!(binding.ty.rewrite(context, budget, offset + result.len()));
145 result.push_str(&rewrite);
152 // Formats a path segment. There are some hacks involved to correctly determine
153 // the segment's associated span since it's not part of the AST.
155 // The span_lo is assumed to be greater than the end of any previous segment's
156 // parameters and lesser or equal than the start of current segment.
158 // span_hi is assumed equal to the end of the entire path.
160 // When the segment contains a positive number of parameters, we update span_lo
161 // so that invariants described above will hold for the next segment.
162 fn rewrite_segment(expr_context: bool,
163 segment: &ast::PathSegment,
164 span_lo: &mut BytePos,
166 context: &RewriteContext,
170 let ident_len = segment.identifier.to_string().len();
171 let width = try_opt!(width.checked_sub(ident_len));
172 let offset = offset + ident_len;
174 let params = match segment.parameters {
175 ast::PathParameters::AngleBracketed(ref data) if !data.lifetimes.is_empty() ||
176 !data.types.is_empty() ||
177 !data.bindings.is_empty() => {
178 let param_list = data.lifetimes
180 .map(SegmentParam::LifeTime)
181 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
182 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
183 .collect::<Vec<_>>();
185 let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
186 let list_lo = context.codemap.span_after(codemap::mk_sp(*span_lo, span_hi), "<");
187 let separator = if expr_context {
194 let extra_offset = 1 + separator.len();
196 let list_width = try_opt!(width.checked_sub(extra_offset + 1));
198 let items = itemize_list(context.codemap,
199 param_list.into_iter(),
201 |param| param.get_span().lo,
202 |param| param.get_span().hi,
203 |seg| seg.rewrite(context, list_width, offset + extra_offset),
206 let list_str = try_opt!(format_item_list(items,
208 offset + extra_offset,
211 // Update position of last bracket.
212 *span_lo = next_span_lo;
214 format!("{}<{}>", separator, list_str)
216 ast::PathParameters::Parenthesized(ref data) => {
217 let output = match data.output {
218 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
219 None => FunctionRetTy::Default(codemap::DUMMY_SP),
221 try_opt!(format_function_type(data.inputs.iter().map(|x| &**x),
232 Some(format!("{}{}", segment.identifier, params))
235 fn format_function_type<'a, I>(inputs: I,
236 output: &FunctionRetTy,
239 context: &RewriteContext,
243 where I: ExactSizeIterator,
244 <I as Iterator>::Item: Deref,
245 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
247 // Code for handling variadics is somewhat duplicated for items, but they
248 // are different enough to need some serious refactoring to share code.
251 <T as Deref>::Target: Rewrite + Spanned
257 let variadic_arg = if variadic {
258 let variadic_start = context.codemap.span_before(span, "...");
259 Some(ArgumentKind::Variadic(variadic_start))
265 let budget = try_opt!(width.checked_sub(2));
267 let offset = offset + 1;
268 let list_lo = context.codemap.span_after(span, "(");
269 let items = itemize_list(context.codemap,
270 // FIXME Would be nice to avoid this allocation,
271 // but I couldn't get the types to work out.
272 inputs.map(|i| ArgumentKind::Regular(Box::new(i)))
273 .chain(variadic_arg),
277 ArgumentKind::Regular(ref ty) => ty.span().lo,
278 ArgumentKind::Variadic(start) => start,
283 ArgumentKind::Regular(ref ty) => ty.span().hi,
284 ArgumentKind::Variadic(start) => start + BytePos(3),
289 ArgumentKind::Regular(ref ty) => ty.rewrite(context, budget, offset),
290 ArgumentKind::Variadic(_) => Some("...".to_owned()),
296 let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
298 let output = match *output {
299 FunctionRetTy::Ty(ref ty) => {
300 let budget = try_opt!(width.checked_sub(4));
301 let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
302 format!(" -> {}", type_str)
304 FunctionRetTy::None(..) => " -> !".to_owned(),
305 FunctionRetTy::Default(..) => String::new(),
308 let infix = if output.len() > 0 && 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 = try_opt!(bound_lifetimes.iter()
334 .collect::<Option<Vec<_>>>())
336 // 8 = "for<> : ".len()
337 let used_width = lifetime_str.len() + type_str.len() + 8;
338 let budget = try_opt!(width.checked_sub(used_width));
339 let bounds_str = try_opt!(bounds.iter()
341 ty_bound.rewrite(context,
345 .collect::<Option<Vec<_>>>())
348 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
351 let used_width = type_str.len() + 2;
352 let budget = try_opt!(width.checked_sub(used_width));
353 let bounds_str = try_opt!(bounds.iter()
355 ty_bound.rewrite(context,
359 .collect::<Option<Vec<_>>>())
362 format!("{}: {}", type_str, bounds_str)
365 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
368 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
370 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
371 let ty_str = try_opt!(ty.rewrite(context, width, offset));
373 let used_width = 3 + ty_str.len();
374 let budget = try_opt!(width.checked_sub(used_width));
375 let path_str = try_opt!(rewrite_path(context,
380 offset + used_width));
381 format!("{} = {}", path_str, ty_str)
385 wrap_str(result, context.config.max_width, width, offset)
389 impl Rewrite for ast::LifetimeDef {
390 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
391 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
395 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
397 context: &RewriteContext,
401 where I: ExactSizeIterator<Item = &'b ast::Lifetime>
403 let result = try_opt!(lt.rewrite(context, width, offset));
405 if bounds.len() == 0 {
408 let appendix: Vec<_> = try_opt!(bounds.into_iter()
409 .map(|b| b.rewrite(context, width, offset))
411 let result = format!("{}: {}", result, appendix.join(" + "));
412 wrap_str(result, context.config.max_width, width, offset)
416 impl Rewrite for ast::TyParamBound {
417 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
419 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
420 tref.rewrite(context, width, offset)
422 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
423 let budget = try_opt!(width.checked_sub(1));
424 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
426 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
431 impl Rewrite for ast::Lifetime {
432 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
433 wrap_str(pprust::lifetime_to_string(self),
434 context.config.max_width,
440 impl Rewrite for ast::TyParamBounds {
441 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
442 let strs: Vec<_> = try_opt!(self.iter()
443 .map(|b| b.rewrite(context, width, offset))
445 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
449 impl Rewrite for ast::TyParam {
450 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
451 let mut result = String::with_capacity(128);
452 result.push_str(&self.ident.to_string());
453 if !self.bounds.is_empty() {
454 result.push_str(": ");
456 let bounds = try_opt!(self.bounds
458 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
459 .collect::<Option<Vec<_>>>())
462 result.push_str(&bounds);
464 if let Some(ref def) = self.default {
466 let eq_str = match context.config.type_punctuation_density {
467 TypeDensity::Compressed => "=",
468 TypeDensity::Wide => " = ",
470 result.push_str(eq_str);
471 let budget = try_opt!(width.checked_sub(result.len()));
472 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
473 result.push_str(&rewrite);
476 wrap_str(result, context.config.max_width, width, offset)
480 impl Rewrite for ast::PolyTraitRef {
481 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
482 if !self.bound_lifetimes.is_empty() {
483 let lifetime_str = try_opt!(self.bound_lifetimes
485 .map(|lt| lt.rewrite(context, width, offset))
486 .collect::<Option<Vec<_>>>())
488 // 6 is "for<> ".len()
489 let extra_offset = lifetime_str.len() + 6;
490 let max_path_width = try_opt!(width.checked_sub(extra_offset));
491 let path_str = try_opt!(self.trait_ref
492 .rewrite(context, max_path_width, offset + extra_offset));
494 Some(format!("for<{}> {}", lifetime_str, path_str))
496 self.trait_ref.rewrite(context, width, offset)
501 impl Rewrite for ast::TraitRef {
502 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
503 rewrite_path(context, false, None, &self.path, width, offset)
507 impl Rewrite for ast::Ty {
508 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
510 ast::TyKind::ObjectSum(ref ty, ref bounds) => {
511 let ty_str = try_opt!(ty.rewrite(context, width, offset));
512 let overhead = ty_str.len() + 3;
513 let plus_str = match context.config.type_punctuation_density {
514 TypeDensity::Compressed => "+",
515 TypeDensity::Wide => " + ",
517 Some(format!("{}{}{}",
520 try_opt!(bounds.rewrite(context,
521 try_opt!(width.checked_sub(overhead)),
522 offset + overhead))))
524 ast::TyKind::Ptr(ref mt) => {
525 let prefix = match mt.mutbl {
526 Mutability::Mutable => "*mut ",
527 Mutability::Immutable => "*const ",
530 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
532 ast::TyKind::Rptr(ref lifetime, ref mt) => {
533 let mut_str = format_mutability(mt.mutbl);
534 let mut_len = mut_str.len();
535 Some(match *lifetime {
536 Some(ref lifetime) => {
537 let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
538 let lt_str = try_opt!(lifetime.rewrite(context,
540 offset + 2 + mut_len));
541 let lt_len = lt_str.len();
542 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
547 .rewrite(context, budget, offset + 2 + mut_len + lt_len)))
550 let budget = try_opt!(width.checked_sub(1 + mut_len));
553 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
557 // FIXME: we drop any comments here, even though it's a silly place to put
559 ast::TyKind::Paren(ref ty) => {
560 let budget = try_opt!(width.checked_sub(2));
561 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
563 ast::TyKind::Vec(ref ty) => {
564 let budget = try_opt!(width.checked_sub(2));
565 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
567 ast::TyKind::Tup(ref items) => {
568 rewrite_tuple(context,
569 items.iter().map(|x| &**x),
574 ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
575 ast::TyKind::Path(ref q_self, ref path) => {
576 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
578 ast::TyKind::FixedLengthVec(ref ty, ref repeats) => {
579 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
581 ast::TyKind::Infer => {
588 ast::TyKind::BareFn(ref bare_fn) => {
589 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
591 ast::TyKind::Mac(..) |
592 ast::TyKind::Typeof(..) => unreachable!(),
597 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
599 context: &RewriteContext,
603 let mut result = String::with_capacity(128);
605 result.push_str(&::utils::format_unsafety(bare_fn.unsafety));
607 if bare_fn.abi != abi::Abi::Rust {
608 result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi));
611 result.push_str("fn");
613 let budget = try_opt!(width.checked_sub(result.len()));
614 let indent = offset + result.len();
616 let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
617 &bare_fn.decl.output,
618 bare_fn.decl.variadic,
624 result.push_str(&rewrite);