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 syntax::print::pprust;
13 use syntax::codemap::{self, Span, BytePos, CodeMap};
15 use lists::{itemize_list, write_list, ListFormatting};
16 use rewrite::{Rewrite, RewriteContext};
17 use utils::{extra_offset, span_after};
19 impl Rewrite for ast::Path {
20 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
21 rewrite_path(context, None, self, width, offset)
25 // Does not wrap on simple segments.
26 pub fn rewrite_path(context: &RewriteContext,
27 qself: Option<&ast::QSelf>,
32 let skip_count = qself.map(|x| x.position).unwrap_or(0);
34 let mut result = if path.global {
40 let mut span_lo = path.span.lo;
42 if let Some(ref qself) = qself {
44 result.push_str(&pprust::ty_to_string(&qself.ty));
47 result.push_str(" as ");
49 let extra_offset = extra_offset(&result, offset);
51 let budget = try_opt!(width.checked_sub(extra_offset)) - 3;
53 result = try_opt!(rewrite_path_segments(result,
54 path.segments.iter().take(skip_count),
59 offset + extra_offset));
62 result.push_str(">::");
63 span_lo = qself.ty.span.hi + BytePos(1);
66 let extra_offset = extra_offset(&result, offset);
67 let budget = try_opt!(width.checked_sub(extra_offset));
68 rewrite_path_segments(result,
69 path.segments.iter().skip(skip_count),
74 offset + extra_offset)
77 fn rewrite_path_segments<'a, I>(mut buffer: String,
81 context: &RewriteContext,
85 where I: Iterator<Item = &'a ast::PathSegment>
90 let extra_offset = extra_offset(&buffer, offset);
91 let remaining_width = try_opt!(width.checked_sub(extra_offset));
92 let new_offset = offset + extra_offset;
93 let segment_string = try_opt!(rewrite_segment(segment,
103 buffer.push_str("::");
106 buffer.push_str(&segment_string);
113 enum SegmentParam<'a> {
114 LifeTime(&'a ast::Lifetime),
116 Binding(&'a ast::TypeBinding),
119 impl<'a> SegmentParam<'a> {
120 fn get_span(&self) -> Span {
122 SegmentParam::LifeTime(ref lt) => lt.span,
123 SegmentParam::Type(ref ty) => ty.span,
124 SegmentParam::Binding(ref binding) => binding.span,
129 impl<'a> Rewrite for SegmentParam<'a> {
130 // FIXME doesn't always use width, offset
131 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
133 SegmentParam::LifeTime(ref lt) => {
134 pprust::lifetime_to_string(lt)
136 SegmentParam::Type(ref ty) => {
137 try_opt!(ty.rewrite(context, width, offset))
139 SegmentParam::Binding(ref binding) => {
140 format!("{} = {}", binding.ident, try_opt!(binding.ty.rewrite(context, width, offset)))
146 // This is a dirty hack to determine if we're in an expression or not. Generic
147 // parameters are passed differently in expressions and items. We'd declare
148 // a struct with Foo<A, B>, but call its functions with Foo::<A, B>::f().
149 // We'd really rather not do this, but there doesn't seem to be an alternative
151 // FIXME: fails with spans containing comments with the characters < or :
152 // FIXME #184 skip due to continue.
154 fn get_path_separator(codemap: &CodeMap,
156 segment_start: BytePos)
158 let span = codemap::mk_sp(path_start, segment_start);
159 let snippet = codemap.span_to_snippet(span).unwrap();
161 for c in snippet.chars().rev() {
164 } else if c.is_whitespace() || c == '<' {
174 // Formats a path segment. There are some hacks involved to correctly determine
175 // the segment's associated span since it's not part of the AST.
177 // The span_lo is assumed to be greater than the end of any previous segment's
178 // parameters and lesser or equal than the start of current segment.
180 // span_hi is assumed equal to the end of the entire path.
182 // When the segment contains a positive number of parameters, we update span_lo
183 // so that invariants described above will hold for the next segment.
184 fn rewrite_segment(segment: &ast::PathSegment,
185 span_lo: &mut BytePos,
187 context: &RewriteContext,
191 let ident_len = segment.identifier.to_string().len();
192 let width = try_opt!(width.checked_sub(ident_len));
193 let offset = offset + ident_len;
195 let params = match segment.parameters {
196 ast::PathParameters::AngleBracketedParameters(ref data) if !data.lifetimes.is_empty() ||
197 !data.types.is_empty() ||
198 !data.bindings.is_empty() => {
199 let param_list = data.lifetimes.iter()
200 .map(SegmentParam::LifeTime)
201 .chain(data.types.iter()
202 .map(|x| SegmentParam::Type(&*x)))
203 .chain(data.bindings.iter()
204 .map(|x| SegmentParam::Binding(&*x)))
205 .collect::<Vec<_>>();
207 let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
208 let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi), "<", context.codemap);
209 let separator = get_path_separator(context.codemap, *span_lo, list_lo);
212 let extra_offset = 1 + separator.len();
214 let list_width = try_opt!(width.checked_sub(extra_offset + 1));
216 let items = itemize_list(context.codemap,
217 param_list.into_iter(),
219 |param| param.get_span().lo,
220 |param| param.get_span().hi,
222 seg.rewrite(context, list_width, offset + extra_offset).unwrap()
227 let fmt = ListFormatting::for_fn(list_width, offset + extra_offset);
230 *span_lo = next_span_lo;
232 format!("{}<{}>", separator, write_list(&items.collect::<Vec<_>>(), &fmt))
234 ast::PathParameters::ParenthesizedParameters(ref data) => {
235 let output = match data.output {
236 Some(ref ty) => format!(" -> {}", pprust::ty_to_string(&*ty)),
237 None => String::new(),
240 let list_lo = span_after(data.span, "(", context.codemap);
241 let items = itemize_list(context.codemap,
246 |ty| pprust::ty_to_string(ty),
251 let budget = try_opt!(width.checked_sub(output.len() + 2));
254 let fmt = ListFormatting::for_fn(budget, offset + 1);
257 *span_lo = data.span.hi + BytePos(1);
259 format!("({}){}", write_list(&items.collect::<Vec<_>>(), &fmt), output)
264 Some(format!("{}{}", segment.identifier, params))
267 impl Rewrite for ast::WherePredicate {
268 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
270 // TODO assumes we'll always fit on one line...
272 ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate{ref bound_lifetimes,
276 if !bound_lifetimes.is_empty() {
277 let lifetime_str = bound_lifetimes.iter().map(|lt| {
278 lt.rewrite(context, width, offset).unwrap()
279 }).collect::<Vec<_>>().join(", ");
280 let type_str = pprust::ty_to_string(bounded_ty);
281 // 8 = "for<> : ".len()
282 let used_width = lifetime_str.len() + type_str.len() + 8;
283 let bounds_str = bounds.iter().map(|ty_bound| {
284 ty_bound.rewrite(context,
288 }).collect::<Vec<_>>().join(" + ");
290 format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
292 let type_str = pprust::ty_to_string(bounded_ty);
294 let used_width = type_str.len() + 2;
295 let bounds_str = bounds.iter().map(|ty_bound| {
296 ty_bound.rewrite(context,
300 }).collect::<Vec<_>>().join(" + ");
302 format!("{}: {}", type_str, bounds_str)
305 ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate{ref lifetime,
309 pprust::lifetime_to_string(lifetime),
310 bounds.iter().map(pprust::lifetime_to_string)
311 .collect::<Vec<_>>().join(" + "))
313 ast::WherePredicate::EqPredicate(ast::WhereEqPredicate{ref path, ref ty, ..}) => {
314 let ty_str = pprust::ty_to_string(ty);
316 let used_width = 3 + ty_str.len();
317 let path_str = try_opt!(path.rewrite(context,
319 offset + used_width));
320 format!("{} = {}", path_str, ty_str)
326 impl Rewrite for ast::LifetimeDef {
327 fn rewrite(&self, _: &RewriteContext, _: usize, _: usize) -> Option<String> {
328 if self.bounds.is_empty() {
329 Some(pprust::lifetime_to_string(&self.lifetime))
331 Some(format!("{}: {}",
332 pprust::lifetime_to_string(&self.lifetime),
333 self.bounds.iter().map(pprust::lifetime_to_string)
334 .collect::<Vec<_>>().join(" + ")))
339 impl Rewrite for ast::TyParamBound {
340 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
342 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
343 tref.rewrite(context, width, offset)
345 ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
346 Some(format!("?{}", try_opt!(tref.rewrite(context, width - 1, offset + 1))))
348 ast::TyParamBound::RegionTyParamBound(ref l) => {
349 Some(pprust::lifetime_to_string(l))
355 impl Rewrite for ast::TyParamBounds {
356 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
357 let strs: Vec<_> = self.iter().map(|b| b.rewrite(context, width, offset).unwrap()).collect();
358 Some(strs.join(" + "))
362 // FIXME: this assumes everything will fit on one line
363 impl Rewrite for ast::TyParam {
364 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
365 let mut result = String::with_capacity(128);
366 result.push_str(&self.ident.to_string());
367 if !self.bounds.is_empty() {
368 result.push_str(": ");
370 let bounds = self.bounds.iter().map(|ty_bound| {
371 ty_bound.rewrite(context, width, offset).unwrap()
372 }).collect::<Vec<_>>().join(" + ");
374 result.push_str(&bounds);
376 if let Some(ref def) = self.default {
377 result.push_str(" = ");
378 result.push_str(&pprust::ty_to_string(&def));
385 // FIXME: this assumes everything will fit on one line
386 impl Rewrite for ast::PolyTraitRef {
387 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
388 if !self.bound_lifetimes.is_empty() {
389 let lifetime_str = self.bound_lifetimes.iter().map(|lt| {
390 lt.rewrite(context, width, offset).unwrap()
391 }).collect::<Vec<_>>().join(", ");
392 // 6 is "for<> ".len()
393 let extra_offset = lifetime_str.len() + 6;
394 let max_path_width = try_opt!(width.checked_sub(extra_offset));
395 let path_str = try_opt!(self.trait_ref.path.rewrite(context,
397 offset + extra_offset));
399 Some(format!("for<{}> {}", lifetime_str, path_str))
401 self.trait_ref.path.rewrite(context, width, offset)
406 impl Rewrite for ast::Ty {
407 // FIXME doesn't always use width, offset
408 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
410 ast::TyPath(None, ref p) => {
411 p.rewrite(context, width, offset)
413 ast::TyObjectSum(ref ty, ref bounds) => {
414 Some(format!("{} + {}",
415 try_opt!(ty.rewrite(context, width, offset)),
416 try_opt!(bounds.rewrite(context, width, offset))))
418 _ => Some(pprust::ty_to_string(self)),