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(|x| x.position).unwrap_or(0);
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) => {
139 wrap_str(pprust::lifetime_to_string(lt),
140 context.config.max_width,
144 SegmentParam::Type(ref ty) => ty.rewrite(context, width, offset),
145 SegmentParam::Binding(ref binding) => {
146 let mut result = format!("{} = ", binding.ident);
147 let budget = try_opt!(width.checked_sub(result.len()));
148 let rewrite = try_opt!(binding.ty.rewrite(context, budget, offset + result.len()));
149 result.push_str(&rewrite);
156 // Formats a path segment. There are some hacks involved to correctly determine
157 // the segment's associated span since it's not part of the AST.
159 // The span_lo is assumed to be greater than the end of any previous segment's
160 // parameters and lesser or equal than the start of current segment.
162 // span_hi is assumed equal to the end of the entire path.
164 // When the segment contains a positive number of parameters, we update span_lo
165 // so that invariants described above will hold for the next segment.
166 fn rewrite_segment(expr_context: bool,
167 segment: &ast::PathSegment,
168 span_lo: &mut BytePos,
170 context: &RewriteContext,
174 let ident_len = segment.identifier.to_string().len();
175 let width = try_opt!(width.checked_sub(ident_len));
176 let offset = offset + ident_len;
178 let params = match segment.parameters {
179 ast::PathParameters::AngleBracketedParameters(ref data) if !data.lifetimes.is_empty() ||
180 !data.types.is_empty() ||
181 !data.bindings.is_empty() => {
182 let param_list = data.lifetimes
184 .map(SegmentParam::LifeTime)
185 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
186 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
187 .collect::<Vec<_>>();
189 let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
190 let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi), "<", context.codemap);
191 let separator = if expr_context {
198 let extra_offset = 1 + separator.len();
200 let list_width = try_opt!(width.checked_sub(extra_offset + 1));
202 let items = itemize_list(context.codemap,
203 param_list.into_iter(),
205 |param| param.get_span().lo,
206 |param| param.get_span().hi,
207 |seg| seg.rewrite(context, list_width, 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 {
222 Some(ref ty) => FunctionRetTy::Return(ty.clone()),
223 None => FunctionRetTy::DefaultReturn(codemap::DUMMY_SP),
225 try_opt!(format_function_type(data.inputs.iter().map(|x| &**x),
235 Some(format!("{}{}", segment.identifier, params))
238 fn format_function_type<'a, I>(inputs: I,
239 output: &FunctionRetTy,
241 context: &RewriteContext,
245 where I: ExactSizeIterator,
246 <I as Iterator>::Item: Deref,
247 <I::Item as Deref>::Target: Rewrite + Spanned + 'a
250 let budget = try_opt!(width.checked_sub(2));
252 let offset = offset + 1;
253 let list_lo = span_after(span, "(", context.codemap);
254 let items = itemize_list(context.codemap,
259 |ty| ty.rewrite(context, budget, offset),
263 let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
265 let output = match *output {
266 FunctionRetTy::Return(ref ty) => {
267 let budget = try_opt!(width.checked_sub(4));
268 let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
269 format!(" -> {}", type_str)
271 FunctionRetTy::NoReturn(..) => " -> !".to_owned(),
272 FunctionRetTy::DefaultReturn(..) => String::new(),
275 let infix = if output.len() + list_str.len() > width {
276 format!("\n{}", (offset - 1).to_string(context.config))
281 Some(format!("({}){}{}", list_str, infix, output))
284 impl Rewrite for ast::WherePredicate {
285 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
287 let result = match *self {
288 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
292 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
294 if !bound_lifetimes.is_empty() {
295 let lifetime_str = try_opt!(bound_lifetimes.iter()
301 .collect::<Option<Vec<_>>>())
303 // 8 = "for<> : ".len()
304 let used_width = lifetime_str.len() + type_str.len() + 8;
305 let budget = try_opt!(width.checked_sub(used_width));
306 let bounds_str = try_opt!(bounds.iter()
308 ty_bound.rewrite(context,
312 .collect::<Option<Vec<_>>>())
315 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
318 let used_width = type_str.len() + 2;
319 let budget = try_opt!(width.checked_sub(used_width));
320 let bounds_str = try_opt!(bounds.iter()
322 ty_bound.rewrite(context,
326 .collect::<Option<Vec<_>>>())
329 format!("{}: {}", type_str, bounds_str)
332 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
336 pprust::lifetime_to_string(lifetime),
338 .map(pprust::lifetime_to_string)
342 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
343 let ty_str = try_opt!(ty.rewrite(context, width, offset));
345 let used_width = 3 + ty_str.len();
346 let budget = try_opt!(width.checked_sub(used_width));
347 let path_str = try_opt!(rewrite_path(context,
352 offset + used_width));
353 format!("{} = {}", path_str, ty_str)
357 wrap_str(result, context.config.max_width, width, offset)
361 impl Rewrite for ast::LifetimeDef {
362 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
363 let result = if self.bounds.is_empty() {
364 pprust::lifetime_to_string(&self.lifetime)
367 pprust::lifetime_to_string(&self.lifetime),
370 .map(pprust::lifetime_to_string)
375 wrap_str(result, context.config.max_width, width, offset)
379 impl Rewrite for ast::TyParamBound {
380 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
382 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
383 tref.rewrite(context, width, offset)
385 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
386 let budget = try_opt!(width.checked_sub(1));
387 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
389 ast::TyParamBound::RegionTyParamBound(ref l) => {
390 wrap_str(pprust::lifetime_to_string(l),
391 context.config.max_width,
399 impl Rewrite for ast::TyParamBounds {
400 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
401 let strs: Vec<_> = try_opt!(self.iter()
402 .map(|b| b.rewrite(context, width, offset))
404 wrap_str(strs.join(" + "), context.config.max_width, width, offset)
408 impl Rewrite for ast::TyParam {
409 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
410 let mut result = String::with_capacity(128);
411 result.push_str(&self.ident.to_string());
412 if !self.bounds.is_empty() {
413 result.push_str(": ");
415 let bounds = try_opt!(self.bounds
417 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
418 .collect::<Option<Vec<_>>>())
421 result.push_str(&bounds);
423 if let Some(ref def) = self.default {
424 result.push_str(" = ");
425 let budget = try_opt!(width.checked_sub(result.len()));
426 let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
427 result.push_str(&rewrite);
430 wrap_str(result, context.config.max_width, width, offset)
434 impl Rewrite for ast::PolyTraitRef {
435 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
436 if !self.bound_lifetimes.is_empty() {
437 let lifetime_str = try_opt!(self.bound_lifetimes
439 .map(|lt| lt.rewrite(context, width, offset))
440 .collect::<Option<Vec<_>>>())
442 // 6 is "for<> ".len()
443 let extra_offset = lifetime_str.len() + 6;
444 let max_path_width = try_opt!(width.checked_sub(extra_offset));
445 let path_str = try_opt!(self.trait_ref
446 .rewrite(context, max_path_width, offset + extra_offset));
448 Some(format!("for<{}> {}", lifetime_str, path_str))
450 self.trait_ref.rewrite(context, width, offset)
455 impl Rewrite for ast::TraitRef {
456 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
457 rewrite_path(context, false, None, &self.path, width, offset)
461 impl Rewrite for ast::Ty {
462 fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
464 ast::TyObjectSum(ref ty, ref bounds) => {
465 let ty_str = try_opt!(ty.rewrite(context, width, offset));
466 let overhead = ty_str.len() + 3;
467 Some(format!("{} + {}",
469 try_opt!(bounds.rewrite(context,
470 try_opt!(width.checked_sub(overhead)),
471 offset + overhead))))
473 ast::TyPtr(ref mt) => {
474 let prefix = match mt.mutbl {
475 Mutability::MutMutable => "*mut ",
476 Mutability::MutImmutable => "*const ",
479 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
481 ast::TyRptr(ref lifetime, ref mt) => {
482 let mut_str = format_mutability(mt.mutbl);
483 let mut_len = mut_str.len();
484 Some(match *lifetime {
485 Some(ref lifetime) => {
486 let lt_str = pprust::lifetime_to_string(lifetime);
487 let lt_len = lt_str.len();
488 let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
492 try_opt!(mt.ty.rewrite(context,
494 offset + 2 + mut_len + lt_len)))
497 let budget = try_opt!(width.checked_sub(1 + mut_len));
500 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
504 // FIXME: we drop any comments here, even though it's a silly place to put
506 ast::TyParen(ref ty) => {
507 let budget = try_opt!(width.checked_sub(2));
508 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
510 ast::TyVec(ref ty) => {
511 let budget = try_opt!(width.checked_sub(2));
512 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
514 ast::TyTup(ref items) => {
515 rewrite_tuple(context,
516 items.iter().map(|x| &**x),
521 ast::TyPolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
522 ast::TyPath(ref q_self, ref path) => {
523 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
525 ast::TyFixedLengthVec(ref ty, ref repeats) => {
526 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
535 ast::TyBareFn(ref bare_fn) => {
536 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
538 ast::TyMac(..) | ast::TyTypeof(..) => unreachable!(),
543 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
545 context: &RewriteContext,
549 let mut result = String::with_capacity(128);
551 result.push_str(&::utils::format_unsafety(bare_fn.unsafety));
553 if bare_fn.abi != abi::Rust {
554 result.push_str(&::utils::format_abi(bare_fn.abi));
557 result.push_str("fn");
559 let budget = try_opt!(width.checked_sub(result.len()));
560 let indent = offset + result.len();
562 let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
563 &bare_fn.decl.output,
569 result.push_str(&rewrite);