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) => {
141 ty.rewrite(context, width, offset)
143 SegmentParam::Binding(ref binding) => {
144 let mut result = format!("{} = ", binding.ident);
145 let budget = try_opt!(width.checked_sub(result.len()));
146 let rewrite = try_opt!(binding.ty.rewrite(context, budget, offset + result.len()));
147 result.push_str(&rewrite);
154 // Formats a path segment. There are some hacks involved to correctly determine
155 // the segment's associated span since it's not part of the AST.
157 // The span_lo is assumed to be greater than the end of any previous segment's
158 // parameters and lesser or equal than the start of current segment.
160 // span_hi is assumed equal to the end of the entire path.
162 // When the segment contains a positive number of parameters, we update span_lo
163 // so that invariants described above will hold for the next segment.
164 fn rewrite_segment(expr_context: bool,
165 segment: &ast::PathSegment,
166 span_lo: &mut BytePos,
168 context: &RewriteContext,
172 let ident_len = segment.identifier.to_string().len();
173 let width = try_opt!(width.checked_sub(ident_len));
174 let offset = offset + ident_len;
176 let params = match segment.parameters {
177 ast::PathParameters::AngleBracketedParameters(ref data) if !data.lifetimes.is_empty() ||
178 !data.types.is_empty() ||
179 !data.bindings.is_empty() => {
180 let param_list = data.lifetimes
182 .map(SegmentParam::LifeTime)
183 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
184 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
185 .collect::<Vec<_>>();
187 let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
188 let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi), "<", context.codemap);
189 let separator = if expr_context {
196 let extra_offset = 1 + separator.len();
198 let list_width = try_opt!(width.checked_sub(extra_offset + 1));
200 let items = itemize_list(context.codemap,
201 param_list.into_iter(),
203 |param| param.get_span().lo,
204 |param| param.get_span().hi,
207 context.config.max_width,
208 offset + extra_offset)
212 let list_str = try_opt!(format_item_list(items,
214 offset + extra_offset,
217 // Update position of last bracket.
218 *span_lo = next_span_lo;
220 format!("{}<{}>", separator, list_str)
222 ast::PathParameters::ParenthesizedParameters(ref data) => {
223 let output = match data.output {
225 let type_str = try_opt!(ty.rewrite(context, width, offset));
226 format!(" -> {}", type_str)
228 None => String::new(),
232 let budget = try_opt!(width.checked_sub(output.len() + 2));
234 let offset = offset + 1;
235 let list_lo = span_after(data.span, "(", context.codemap);
236 let items = itemize_list(context.codemap,
241 |ty| ty.rewrite(context, budget, offset),
244 let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
246 format!("({}){}", list_str, output)
251 Some(format!("{}{}", segment.identifier, params))
254 impl Rewrite for ast::WherePredicate {
255 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
257 let result = match *self {
258 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
262 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
264 if !bound_lifetimes.is_empty() {
265 let lifetime_str = try_opt!(bound_lifetimes.iter()
271 .collect::<Option<Vec<_>>>())
273 // 8 = "for<> : ".len()
274 let used_width = lifetime_str.len() + type_str.len() + 8;
275 let budget = try_opt!(width.checked_sub(used_width));
276 let bounds_str = try_opt!(bounds.iter()
278 ty_bound.rewrite(context,
282 .collect::<Option<Vec<_>>>())
285 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
288 let used_width = type_str.len() + 2;
289 let budget = try_opt!(width.checked_sub(used_width));
290 let bounds_str = try_opt!(bounds.iter()
292 ty_bound.rewrite(context,
296 .collect::<Option<Vec<_>>>())
299 format!("{}: {}", type_str, bounds_str)
302 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
306 pprust::lifetime_to_string(lifetime),
308 .map(pprust::lifetime_to_string)
312 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
313 let ty_str = try_opt!(ty.rewrite(context, width, offset));
315 let used_width = 3 + ty_str.len();
316 let budget = try_opt!(width.checked_sub(used_width));
317 let path_str = try_opt!(rewrite_path(context,
322 offset + used_width));
323 format!("{} = {}", path_str, ty_str)
327 wrap_str(result, context.config.max_width, width, offset)
331 impl Rewrite for ast::LifetimeDef {
332 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
333 let result = if self.bounds.is_empty() {
334 pprust::lifetime_to_string(&self.lifetime)
337 pprust::lifetime_to_string(&self.lifetime),
340 .map(pprust::lifetime_to_string)
345 wrap_str(result, context.config.max_width, width, offset)
349 impl Rewrite for ast::TyParamBound {
350 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
352 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
353 tref.rewrite(context, width, offset)
355 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
356 let budget = try_opt!(width.checked_sub(1));
357 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
359 ast::TyParamBound::RegionTyParamBound(ref l) => {
360 wrap_str(pprust::lifetime_to_string(l),
361 context.config.max_width,
369 impl Rewrite for ast::TyParamBounds {
370 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
371 let strs: Vec<_> = try_opt!(self.iter()
372 .map(|b| b.rewrite(context, width, offset))
374 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
378 impl Rewrite for ast::TyParam {
379 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
380 let mut result = String::with_capacity(128);
381 result.push_str(&self.ident.to_string());
382 if !self.bounds.is_empty() {
383 result.push_str(": ");
385 let bounds = try_opt!(self.bounds
387 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
388 .collect::<Option<Vec<_>>>())
391 result.push_str(&bounds);
393 if let Some(ref def) = self.default {
394 result.push_str(" = ");
395 let budget = try_opt!(width.checked_sub(result.len()));
396 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
397 result.push_str(&rewrite);
400 wrap_str(result, context.config.max_width, width, offset)
404 impl Rewrite for ast::PolyTraitRef {
405 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
406 if !self.bound_lifetimes.is_empty() {
407 let lifetime_str = try_opt!(self.bound_lifetimes
409 .map(|lt| lt.rewrite(context, width, offset))
410 .collect::<Option<Vec<_>>>())
412 // 6 is "for<> ".len()
413 let extra_offset = lifetime_str.len() + 6;
414 let max_path_width = try_opt!(width.checked_sub(extra_offset));
415 let path_str = try_opt!(rewrite_path(context,
418 &self.trait_ref.path,
420 offset + extra_offset));
422 Some(format!("for<{}> {}", lifetime_str, path_str))
424 rewrite_path(context, false, None, &self.trait_ref.path, width, offset)
429 impl Rewrite for ast::Ty {
430 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
432 ast::TyObjectSum(ref ty, ref bounds) => {
433 let ty_str = try_opt!(ty.rewrite(context, width, offset));
434 let overhead = ty_str.len() + 3;
435 Some(format!("{} + {}",
437 try_opt!(bounds.rewrite(context,
438 try_opt!(width.checked_sub(overhead)),
439 offset + overhead))))
441 ast::TyPtr(ref mt) => {
442 let prefix = match mt.mutbl {
443 Mutability::MutMutable => "*mut ",
444 Mutability::MutImmutable => "*const ",
447 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
449 ast::TyRptr(ref lifetime, ref mt) => {
450 let mut_str = format_mutability(mt.mutbl);
451 let mut_len = mut_str.len();
452 Some(match *lifetime {
453 Some(ref lifetime) => {
454 let lt_str = pprust::lifetime_to_string(lifetime);
455 let lt_len = lt_str.len();
456 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
460 try_opt!(mt.ty.rewrite(context,
462 offset + 2 + mut_len + lt_len)))
465 let budget = try_opt!(width.checked_sub(1 + mut_len));
468 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
472 // FIXME: we drop any comments here, even though it's a silly place to put
474 ast::TyParen(ref ty) => {
475 let budget = try_opt!(width.checked_sub(2));
476 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
478 ast::TyVec(ref ty) => {
479 let budget = try_opt!(width.checked_sub(2));
480 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
482 ast::TyTup(ref items) => {
483 rewrite_tuple(context, items, self.span, width, offset)
485 ast::TyPolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
486 ast::TyPath(ref q_self, ref path) => {
487 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
489 ast::TyFixedLengthVec(ref ty, ref repeats) => {
490 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
499 ast::TyBareFn(..) => {
500 wrap_str(pprust::ty_to_string(self),
501 context.config.max_width,
505 ast::TyMac(..) | ast::TyTypeof(..) => unreachable!(),