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::{extra_offset, span_after, format_mutability, wrap_str};
23 use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
25 // Does not wrap on simple segments.
26 pub fn rewrite_path(context: &RewriteContext,
28 qself: Option<&ast::QSelf>,
33 let skip_count = qself.map_or(0, |x| x.position);
35 let mut result = if path.global {
41 let mut span_lo = path.span.lo;
43 if let Some(ref qself) = qself {
45 let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
46 result.push_str(&fmt_ty);
49 result.push_str(" as ");
51 let extra_offset = extra_offset(&result, offset);
53 let budget = try_opt!(width.checked_sub(extra_offset + 3));
55 result = try_opt!(rewrite_path_segments(expr_context,
57 path.segments.iter().take(skip_count),
62 offset + extra_offset));
65 result.push_str(">::");
66 span_lo = qself.ty.span.hi + BytePos(1);
69 let extra_offset = extra_offset(&result, offset);
70 let budget = try_opt!(width.checked_sub(extra_offset));
71 rewrite_path_segments(expr_context,
73 path.segments.iter().skip(skip_count),
78 offset + extra_offset)
81 fn rewrite_path_segments<'a, I>(expr_context: bool,
86 context: &RewriteContext,
90 where I: Iterator<Item = &'a ast::PathSegment>
98 buffer.push_str("::");
101 let extra_offset = extra_offset(&buffer, offset);
102 let remaining_width = try_opt!(width.checked_sub(extra_offset));
103 let new_offset = offset + extra_offset;
104 let segment_string = try_opt!(rewrite_segment(expr_context,
112 buffer.push_str(&segment_string);
119 enum SegmentParam<'a> {
120 LifeTime(&'a ast::Lifetime),
122 Binding(&'a ast::TypeBinding),
125 impl<'a> SegmentParam<'a> {
126 fn get_span(&self) -> Span {
128 SegmentParam::LifeTime(ref lt) => lt.span,
129 SegmentParam::Type(ref ty) => ty.span,
130 SegmentParam::Binding(ref binding) => binding.span,
135 impl<'a> Rewrite for SegmentParam<'a> {
136 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
138 SegmentParam::LifeTime(ref lt) => lt.rewrite(context, width, offset),
139 SegmentParam::Type(ref ty) => ty.rewrite(context, width, offset),
140 SegmentParam::Binding(ref binding) => {
141 let mut result = format!("{} = ", binding.ident);
142 let budget = try_opt!(width.checked_sub(result.len()));
143 let rewrite = try_opt!(binding.ty.rewrite(context, budget, offset + result.len()));
144 result.push_str(&rewrite);
151 // Formats a path segment. There are some hacks involved to correctly determine
152 // the segment's associated span since it's not part of the AST.
154 // The span_lo is assumed to be greater than the end of any previous segment's
155 // parameters and lesser or equal than the start of current segment.
157 // span_hi is assumed equal to the end of the entire path.
159 // When the segment contains a positive number of parameters, we update span_lo
160 // so that invariants described above will hold for the next segment.
161 fn rewrite_segment(expr_context: bool,
162 segment: &ast::PathSegment,
163 span_lo: &mut BytePos,
165 context: &RewriteContext,
169 let ident_len = segment.identifier.to_string().len();
170 let width = try_opt!(width.checked_sub(ident_len));
171 let offset = offset + ident_len;
173 let params = match segment.parameters {
174 ast::PathParameters::AngleBracketedParameters(ref data) if !data.lifetimes.is_empty() ||
175 !data.types.is_empty() ||
176 !data.bindings.is_empty() => {
177 let param_list = data.lifetimes
179 .map(SegmentParam::LifeTime)
180 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
181 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
182 .collect::<Vec<_>>();
184 let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
185 let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi), "<", context.codemap);
186 let separator = if expr_context {
193 let extra_offset = 1 + separator.len();
195 let list_width = try_opt!(width.checked_sub(extra_offset + 1));
197 let items = itemize_list(context.codemap,
198 param_list.into_iter(),
200 |param| param.get_span().lo,
201 |param| param.get_span().hi,
202 |seg| seg.rewrite(context, list_width, offset + extra_offset),
205 let list_str = try_opt!(format_item_list(items,
207 offset + extra_offset,
210 // Update position of last bracket.
211 *span_lo = next_span_lo;
213 format!("{}<{}>", separator, list_str)
215 ast::PathParameters::ParenthesizedParameters(ref data) => {
216 let output = match data.output {
217 Some(ref ty) => FunctionRetTy::Return(ty.clone()),
218 None => FunctionRetTy::DefaultReturn(codemap::DUMMY_SP),
220 try_opt!(format_function_type(data.inputs.iter().map(|x| &**x),
230 Some(format!("{}{}", segment.identifier, params))
233 fn format_function_type<'a, I>(inputs: I,
234 output: &FunctionRetTy,
236 context: &RewriteContext,
240 where I: ExactSizeIterator,
241 <I as Iterator>::Item: Deref,
242 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
245 let budget = try_opt!(width.checked_sub(2));
247 let offset = offset + 1;
248 let list_lo = span_after(span, "(", context.codemap);
249 let items = itemize_list(context.codemap,
254 |ty| ty.rewrite(context, budget, offset),
258 let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
260 let output = match *output {
261 FunctionRetTy::Return(ref ty) => {
262 let budget = try_opt!(width.checked_sub(4));
263 let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
264 format!(" -> {}", type_str)
266 FunctionRetTy::NoReturn(..) => " -> !".to_owned(),
267 FunctionRetTy::DefaultReturn(..) => String::new(),
270 let infix = if output.len() + list_str.len() > width {
271 format!("\n{}", (offset - 1).to_string(context.config))
276 Some(format!("({}){}{}", list_str, infix, output))
279 impl Rewrite for ast::WherePredicate {
280 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
282 let result = match *self {
283 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
287 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
289 if !bound_lifetimes.is_empty() {
290 let lifetime_str = try_opt!(bound_lifetimes.iter()
296 .collect::<Option<Vec<_>>>())
298 // 8 = "for<> : ".len()
299 let used_width = lifetime_str.len() + type_str.len() + 8;
300 let budget = try_opt!(width.checked_sub(used_width));
301 let bounds_str = try_opt!(bounds.iter()
303 ty_bound.rewrite(context,
307 .collect::<Option<Vec<_>>>())
310 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
313 let used_width = type_str.len() + 2;
314 let budget = try_opt!(width.checked_sub(used_width));
315 let bounds_str = try_opt!(bounds.iter()
317 ty_bound.rewrite(context,
321 .collect::<Option<Vec<_>>>())
324 format!("{}: {}", type_str, bounds_str)
327 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
330 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
332 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
333 let ty_str = try_opt!(ty.rewrite(context, width, offset));
335 let used_width = 3 + ty_str.len();
336 let budget = try_opt!(width.checked_sub(used_width));
337 let path_str = try_opt!(rewrite_path(context,
342 offset + used_width));
343 format!("{} = {}", path_str, ty_str)
347 wrap_str(result, context.config.max_width, width, offset)
351 impl Rewrite for ast::LifetimeDef {
352 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
353 rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
357 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
359 context: &RewriteContext,
363 where I: ExactSizeIterator<Item = &'b ast::Lifetime>
365 let result = try_opt!(lt.rewrite(context, width, offset));
367 if bounds.len() == 0 {
370 let appendix: Vec<_> = try_opt!(bounds.into_iter()
371 .map(|b| b.rewrite(context, width, offset))
373 let result = format!("{}: {}", result, appendix.join(" + "));
374 wrap_str(result, context.config.max_width, width, offset)
378 impl Rewrite for ast::TyParamBound {
379 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
381 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
382 tref.rewrite(context, width, offset)
384 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
385 let budget = try_opt!(width.checked_sub(1));
386 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
388 ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
393 impl Rewrite for ast::Lifetime {
394 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
395 wrap_str(pprust::lifetime_to_string(self),
396 context.config.max_width,
402 impl Rewrite for ast::TyParamBounds {
403 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
404 let strs: Vec<_> = try_opt!(self.iter()
405 .map(|b| b.rewrite(context, width, offset))
407 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
411 impl Rewrite for ast::TyParam {
412 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
413 let mut result = String::with_capacity(128);
414 result.push_str(&self.ident.to_string());
415 if !self.bounds.is_empty() {
416 result.push_str(": ");
418 let bounds = try_opt!(self.bounds
420 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
421 .collect::<Option<Vec<_>>>())
424 result.push_str(&bounds);
426 if let Some(ref def) = self.default {
427 result.push_str(" = ");
428 let budget = try_opt!(width.checked_sub(result.len()));
429 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
430 result.push_str(&rewrite);
433 wrap_str(result, context.config.max_width, width, offset)
437 impl Rewrite for ast::PolyTraitRef {
438 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
439 if !self.bound_lifetimes.is_empty() {
440 let lifetime_str = try_opt!(self.bound_lifetimes
442 .map(|lt| lt.rewrite(context, width, offset))
443 .collect::<Option<Vec<_>>>())
445 // 6 is "for<> ".len()
446 let extra_offset = lifetime_str.len() + 6;
447 let max_path_width = try_opt!(width.checked_sub(extra_offset));
448 let path_str = try_opt!(self.trait_ref
449 .rewrite(context, max_path_width, offset + extra_offset));
451 Some(format!("for<{}> {}", lifetime_str, path_str))
453 self.trait_ref.rewrite(context, width, offset)
458 impl Rewrite for ast::TraitRef {
459 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
460 rewrite_path(context, false, None, &self.path, width, offset)
464 impl Rewrite for ast::Ty {
465 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
467 ast::TyObjectSum(ref ty, ref bounds) => {
468 let ty_str = try_opt!(ty.rewrite(context, width, offset));
469 let overhead = ty_str.len() + 3;
470 Some(format!("{} + {}",
472 try_opt!(bounds.rewrite(context,
473 try_opt!(width.checked_sub(overhead)),
474 offset + overhead))))
476 ast::TyPtr(ref mt) => {
477 let prefix = match mt.mutbl {
478 Mutability::MutMutable => "*mut ",
479 Mutability::MutImmutable => "*const ",
482 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
484 ast::TyRptr(ref lifetime, ref mt) => {
485 let mut_str = format_mutability(mt.mutbl);
486 let mut_len = mut_str.len();
487 Some(match *lifetime {
488 Some(ref lifetime) => {
489 let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
490 let lt_str = try_opt!(lifetime.rewrite(context,
492 offset + 2 + mut_len));
493 let lt_len = lt_str.len();
494 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
498 try_opt!(mt.ty.rewrite(context,
500 offset + 2 + mut_len + lt_len)))
503 let budget = try_opt!(width.checked_sub(1 + mut_len));
506 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
510 // FIXME: we drop any comments here, even though it's a silly place to put
512 ast::TyParen(ref ty) => {
513 let budget = try_opt!(width.checked_sub(2));
514 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
516 ast::TyVec(ref ty) => {
517 let budget = try_opt!(width.checked_sub(2));
518 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
520 ast::TyTup(ref items) => {
521 rewrite_tuple(context,
522 items.iter().map(|x| &**x),
527 ast::TyPolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
528 ast::TyPath(ref q_self, ref path) => {
529 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
531 ast::TyFixedLengthVec(ref ty, ref repeats) => {
532 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
541 ast::TyBareFn(ref bare_fn) => {
542 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
544 ast::TyMac(..) | ast::TyTypeof(..) => unreachable!(),
549 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
551 context: &RewriteContext,
555 let mut result = String::with_capacity(128);
557 result.push_str(&::utils::format_unsafety(bare_fn.unsafety));
559 if bare_fn.abi != abi::Rust {
560 result.push_str(&::utils::format_abi(bare_fn.abi));
563 result.push_str("fn");
565 let budget = try_opt!(width.checked_sub(result.len()));
566 let indent = offset + result.len();
568 let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
569 &bare_fn.decl.output,
575 result.push_str(&rewrite);