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.
11 use syntax::ast::{self, Mutability};
12 use syntax::print::pprust;
13 use syntax::codemap::{self, Span, BytePos};
16 use lists::{format_item_list, itemize_list, format_fn_args};
17 use rewrite::{Rewrite, RewriteContext};
18 use utils::{extra_offset, span_after, format_mutability, wrap_str};
19 use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
21 // Does not wrap on simple segments.
22 pub fn rewrite_path(context: &RewriteContext,
24 qself: Option<&ast::QSelf>,
29 let skip_count = qself.map(|x| x.position).unwrap_or(0);
31 let mut result = if path.global {
37 let mut span_lo = path.span.lo;
39 if let Some(ref qself) = qself {
41 let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
42 result.push_str(&fmt_ty);
45 result.push_str(" as ");
47 let extra_offset = extra_offset(&result, offset);
49 let budget = try_opt!(width.checked_sub(extra_offset + 3));
51 result = try_opt!(rewrite_path_segments(expr_context,
53 path.segments.iter().take(skip_count),
58 offset + extra_offset));
61 result.push_str(">::");
62 span_lo = qself.ty.span.hi + BytePos(1);
65 let extra_offset = extra_offset(&result, offset);
66 let budget = try_opt!(width.checked_sub(extra_offset));
67 rewrite_path_segments(expr_context,
69 path.segments.iter().skip(skip_count),
74 offset + extra_offset)
77 fn rewrite_path_segments<'a, I>(expr_context: bool,
82 context: &RewriteContext,
86 where I: Iterator<Item = &'a ast::PathSegment>
94 buffer.push_str("::");
97 let extra_offset = extra_offset(&buffer, offset);
98 let remaining_width = try_opt!(width.checked_sub(extra_offset));
99 let new_offset = offset + extra_offset;
100 let segment_string = try_opt!(rewrite_segment(expr_context,
108 buffer.push_str(&segment_string);
115 enum SegmentParam<'a> {
116 LifeTime(&'a ast::Lifetime),
118 Binding(&'a ast::TypeBinding),
121 impl<'a> SegmentParam<'a> {
122 fn get_span(&self) -> Span {
124 SegmentParam::LifeTime(ref lt) => lt.span,
125 SegmentParam::Type(ref ty) => ty.span,
126 SegmentParam::Binding(ref binding) => binding.span,
131 impl<'a> Rewrite for SegmentParam<'a> {
132 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
134 SegmentParam::LifeTime(ref lt) => {
135 wrap_str(pprust::lifetime_to_string(lt),
136 context.config.max_width,
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::AngleBracketedParameters(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 = span_after(codemap::mk_sp(*span_lo, span_hi), "<", context.codemap);
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,
205 context.config.max_width,
206 offset + extra_offset)
210 let list_str = try_opt!(format_item_list(items,
212 offset + extra_offset,
215 // Update position of last bracket.
216 *span_lo = next_span_lo;
218 format!("{}<{}>", separator, list_str)
220 ast::PathParameters::ParenthesizedParameters(ref data) => {
221 let output = match data.output {
223 let type_str = try_opt!(ty.rewrite(context, width, offset));
224 format!(" -> {}", type_str)
226 None => String::new(),
230 let budget = try_opt!(width.checked_sub(output.len() + 2));
232 let offset = offset + 1;
233 let list_lo = span_after(data.span, "(", context.codemap);
234 let items = itemize_list(context.codemap,
239 |ty| ty.rewrite(context, budget, offset),
242 let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
244 format!("({}){}", list_str, output)
249 Some(format!("{}{}", segment.identifier, params))
252 impl Rewrite for ast::WherePredicate {
253 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
255 let result = match *self {
256 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
260 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
262 if !bound_lifetimes.is_empty() {
263 let lifetime_str = try_opt!(bound_lifetimes.iter()
269 .collect::<Option<Vec<_>>>())
271 // 8 = "for<> : ".len()
272 let used_width = lifetime_str.len() + type_str.len() + 8;
273 let budget = try_opt!(width.checked_sub(used_width));
274 let bounds_str = try_opt!(bounds.iter()
276 ty_bound.rewrite(context,
280 .collect::<Option<Vec<_>>>())
283 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
286 let used_width = type_str.len() + 2;
287 let budget = try_opt!(width.checked_sub(used_width));
288 let bounds_str = try_opt!(bounds.iter()
290 ty_bound.rewrite(context,
294 .collect::<Option<Vec<_>>>())
297 format!("{}: {}", type_str, bounds_str)
300 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
304 pprust::lifetime_to_string(lifetime),
306 .map(pprust::lifetime_to_string)
310 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
311 let ty_str = try_opt!(ty.rewrite(context, width, offset));
313 let used_width = 3 + ty_str.len();
314 let budget = try_opt!(width.checked_sub(used_width));
315 let path_str = try_opt!(rewrite_path(context,
320 offset + used_width));
321 format!("{} = {}", path_str, ty_str)
325 wrap_str(result, context.config.max_width, width, offset)
329 impl Rewrite for ast::LifetimeDef {
330 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
331 let result = if self.bounds.is_empty() {
332 pprust::lifetime_to_string(&self.lifetime)
335 pprust::lifetime_to_string(&self.lifetime),
338 .map(pprust::lifetime_to_string)
343 wrap_str(result, context.config.max_width, width, offset)
347 impl Rewrite for ast::TyParamBound {
348 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
350 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
351 tref.rewrite(context, width, offset)
353 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
354 let budget = try_opt!(width.checked_sub(1));
355 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
357 ast::TyParamBound::RegionTyParamBound(ref l) => {
358 wrap_str(pprust::lifetime_to_string(l),
359 context.config.max_width,
367 impl Rewrite for ast::TyParamBounds {
368 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
369 let strs: Vec<_> = try_opt!(self.iter()
370 .map(|b| b.rewrite(context, width, offset))
372 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
376 impl Rewrite for ast::TyParam {
377 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
378 let mut result = String::with_capacity(128);
379 result.push_str(&self.ident.to_string());
380 if !self.bounds.is_empty() {
381 result.push_str(": ");
383 let bounds = try_opt!(self.bounds
385 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
386 .collect::<Option<Vec<_>>>())
389 result.push_str(&bounds);
391 if let Some(ref def) = self.default {
392 result.push_str(" = ");
393 let budget = try_opt!(width.checked_sub(result.len()));
394 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
395 result.push_str(&rewrite);
398 wrap_str(result, context.config.max_width, width, offset)
402 impl Rewrite for ast::PolyTraitRef {
403 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
404 if !self.bound_lifetimes.is_empty() {
405 let lifetime_str = try_opt!(self.bound_lifetimes
407 .map(|lt| lt.rewrite(context, width, offset))
408 .collect::<Option<Vec<_>>>())
410 // 6 is "for<> ".len()
411 let extra_offset = lifetime_str.len() + 6;
412 let max_path_width = try_opt!(width.checked_sub(extra_offset));
413 let path_str = try_opt!(rewrite_path(context,
416 &self.trait_ref.path,
418 offset + extra_offset));
420 Some(format!("for<{}> {}", lifetime_str, path_str))
422 rewrite_path(context, false, None, &self.trait_ref.path, width, offset)
427 impl Rewrite for ast::Ty {
428 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
430 ast::TyObjectSum(ref ty, ref bounds) => {
431 let ty_str = try_opt!(ty.rewrite(context, width, offset));
432 let overhead = ty_str.len() + 3;
433 Some(format!("{} + {}",
435 try_opt!(bounds.rewrite(context,
436 try_opt!(width.checked_sub(overhead)),
437 offset + overhead))))
439 ast::TyPtr(ref mt) => {
440 let prefix = match mt.mutbl {
441 Mutability::MutMutable => "*mut ",
442 Mutability::MutImmutable => "*const ",
445 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
447 ast::TyRptr(ref lifetime, ref mt) => {
448 let mut_str = format_mutability(mt.mutbl);
449 let mut_len = mut_str.len();
450 Some(match *lifetime {
451 Some(ref lifetime) => {
452 let lt_str = pprust::lifetime_to_string(lifetime);
453 let lt_len = lt_str.len();
454 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
458 try_opt!(mt.ty.rewrite(context,
460 offset + 2 + mut_len + lt_len)))
463 let budget = try_opt!(width.checked_sub(1 + mut_len));
466 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
470 // FIXME: we drop any comments here, even though it's a silly place to put
472 ast::TyParen(ref ty) => {
473 let budget = try_opt!(width.checked_sub(2));
474 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
476 ast::TyVec(ref ty) => {
477 let budget = try_opt!(width.checked_sub(2));
478 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
480 ast::TyTup(ref items) => rewrite_tuple(context, items, self.span, width, offset),
481 ast::TyPolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
482 ast::TyPath(ref q_self, ref path) => {
483 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
485 ast::TyFixedLengthVec(ref ty, ref repeats) => {
486 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
495 ast::TyBareFn(..) => {
496 wrap_str(pprust::ty_to_string(self),
497 context.config.max_width,
501 ast::TyMac(..) | ast::TyTypeof(..) => unreachable!(),