]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Fix https://github.com/nrc/rustfmt/issues/376
[rust.git] / src / types.rs
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.
4 //
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.
10
11 use syntax::ast;
12 use syntax::print::pprust;
13 use syntax::codemap::{self, Span, BytePos, CodeMap};
14
15 use Indent;
16 use lists::{itemize_list, write_list, ListFormatting};
17 use rewrite::{Rewrite, RewriteContext};
18 use utils::{extra_offset, span_after, format_mutability};
19
20 impl Rewrite for ast::Path {
21     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
22         rewrite_path(context, None, self, width, offset)
23     }
24 }
25
26 // Does not wrap on simple segments.
27 pub fn rewrite_path(context: &RewriteContext,
28                     qself: Option<&ast::QSelf>,
29                     path: &ast::Path,
30                     width: usize,
31                     offset: Indent)
32                     -> Option<String> {
33     let skip_count = qself.map(|x| x.position).unwrap_or(0);
34
35     let mut result = if path.global {
36         "::".to_owned()
37     } else {
38         String::new()
39     };
40
41     let mut span_lo = path.span.lo;
42
43     if let Some(ref qself) = qself {
44         result.push('<');
45         let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
46         result.push_str(&fmt_ty);
47
48         if skip_count > 0 {
49             result.push_str(" as ");
50
51             let extra_offset = extra_offset(&result, offset);
52             // 3 = ">::".len()
53             let budget = try_opt!(width.checked_sub(extra_offset)) - 3;
54
55             result = try_opt!(rewrite_path_segments(result,
56                                                     path.segments.iter().take(skip_count),
57                                                     span_lo,
58                                                     path.span.hi,
59                                                     context,
60                                                     budget,
61                                                     offset + extra_offset));
62         }
63
64         result.push_str(">::");
65         span_lo = qself.ty.span.hi + BytePos(1);
66     }
67
68     let extra_offset = extra_offset(&result, offset);
69     let budget = try_opt!(width.checked_sub(extra_offset));
70     rewrite_path_segments(result,
71                           path.segments.iter().skip(skip_count),
72                           span_lo,
73                           path.span.hi,
74                           context,
75                           budget,
76                           offset + extra_offset)
77 }
78
79 fn rewrite_path_segments<'a, I>(mut buffer: String,
80                                 iter: I,
81                                 mut span_lo: BytePos,
82                                 span_hi: BytePos,
83                                 context: &RewriteContext,
84                                 width: usize,
85                                 offset: Indent)
86                                 -> Option<String>
87     where I: Iterator<Item = &'a ast::PathSegment>
88 {
89     let mut first = true;
90
91     for segment in iter {
92         if first {
93             first = false;
94         } else {
95             buffer.push_str("::");
96         }
97
98         let extra_offset = extra_offset(&buffer, offset);
99         let remaining_width = try_opt!(width.checked_sub(extra_offset));
100         let new_offset = offset + extra_offset;
101         let segment_string = try_opt!(rewrite_segment(segment,
102                                                       &mut span_lo,
103                                                       span_hi,
104                                                       context,
105                                                       remaining_width,
106                                                       new_offset));
107
108         buffer.push_str(&segment_string);
109     }
110
111     Some(buffer)
112 }
113
114 #[derive(Debug)]
115 enum SegmentParam<'a> {
116     LifeTime(&'a ast::Lifetime),
117     Type(&'a ast::Ty),
118     Binding(&'a ast::TypeBinding),
119 }
120
121 impl<'a> SegmentParam<'a> {
122     fn get_span(&self) -> Span {
123         match *self {
124             SegmentParam::LifeTime(ref lt) => lt.span,
125             SegmentParam::Type(ref ty) => ty.span,
126             SegmentParam::Binding(ref binding) => binding.span,
127         }
128     }
129 }
130
131 impl<'a> Rewrite for SegmentParam<'a> {
132     // FIXME: doesn't always use width, offset.
133     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
134         Some(match *self {
135             SegmentParam::LifeTime(ref lt) => {
136                 pprust::lifetime_to_string(lt)
137             }
138             SegmentParam::Type(ref ty) => {
139                 try_opt!(ty.rewrite(context, width, offset))
140             }
141             SegmentParam::Binding(ref binding) => {
142                 format!("{} = {}",
143                         binding.ident,
144                         try_opt!(binding.ty.rewrite(context, width, offset)))
145             }
146         })
147     }
148 }
149
150 // This is a dirty hack to determine if we're in an expression or not. Generic
151 // parameters are passed differently in expressions and items. We'd declare
152 // a struct with Foo<A, B>, but call its functions with Foo::<A, B>::f().
153 // We'd really rather not do this, but there doesn't seem to be an alternative
154 // at this point.
155 // FIXME: fails with spans containing comments with the characters < or :
156 fn get_path_separator(codemap: &CodeMap,
157                       path_start: BytePos,
158                       segment_start: BytePos)
159                       -> &'static str {
160     let span = codemap::mk_sp(path_start, segment_start);
161     let snippet = codemap.span_to_snippet(span).unwrap();
162
163     for c in snippet.chars().rev() {
164         if c == ':' {
165             return "::";
166         } else if c.is_whitespace() || c == '<' {
167             continue;
168         } else {
169             return "";
170         }
171     }
172
173     unreachable!();
174 }
175
176 // Formats a path segment. There are some hacks involved to correctly determine
177 // the segment's associated span since it's not part of the AST.
178 //
179 // The span_lo is assumed to be greater than the end of any previous segment's
180 // parameters and lesser or equal than the start of current segment.
181 //
182 // span_hi is assumed equal to the end of the entire path.
183 //
184 // When the segment contains a positive number of parameters, we update span_lo
185 // so that invariants described above will hold for the next segment.
186 fn rewrite_segment(segment: &ast::PathSegment,
187                    span_lo: &mut BytePos,
188                    span_hi: BytePos,
189                    context: &RewriteContext,
190                    width: usize,
191                    offset: Indent)
192                    -> Option<String> {
193     let ident_len = segment.identifier.to_string().len();
194     let width = try_opt!(width.checked_sub(ident_len));
195     let offset = offset + ident_len;
196
197     let params = match segment.parameters {
198         ast::PathParameters::AngleBracketedParameters(ref data) if !data.lifetimes.is_empty() ||
199                                                                    !data.types.is_empty() ||
200                                                                    !data.bindings.is_empty() => {
201             let param_list = data.lifetimes
202                                  .iter()
203                                  .map(SegmentParam::LifeTime)
204                                  .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
205                                  .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
206                                  .collect::<Vec<_>>();
207
208             let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
209             let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi),
210                                      "<",
211                                      context.codemap);
212             let separator = get_path_separator(context.codemap, *span_lo, list_lo);
213
214             // 1 for <
215             let extra_offset = 1 + separator.len();
216             // 1 for >
217             let list_width = try_opt!(width.checked_sub(extra_offset + 1));
218
219             let items = itemize_list(context.codemap,
220                                      param_list.into_iter(),
221                                      ">",
222                                      |param| param.get_span().lo,
223                                      |param| param.get_span().hi,
224                                      // FIXME(#133): write_list should call
225                                      // rewrite itself, because it has a better
226                                      // context.
227                                      |seg| {
228                                          seg.rewrite(context,
229                                                      context.config.max_width,
230                                                      offset + extra_offset)
231                                             .unwrap()
232                                      },
233                                      list_lo,
234                                      span_hi);
235
236             let fmt = ListFormatting::for_item(list_width, offset + extra_offset, context.config);
237             let list_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
238
239             // Update position of last bracket.
240             *span_lo = next_span_lo;
241
242             format!("{}<{}>", separator, list_str)
243         }
244         ast::PathParameters::ParenthesizedParameters(ref data) => {
245             let output = match data.output {
246                 Some(ref ty) => format!(" -> {}", pprust::ty_to_string(&*ty)),
247                 None => String::new(),
248             };
249
250             let list_lo = span_after(data.span, "(", context.codemap);
251             let items = itemize_list(context.codemap,
252                                      data.inputs.iter(),
253                                      ")",
254                                      |ty| ty.span.lo,
255                                      |ty| ty.span.hi,
256                                      |ty| pprust::ty_to_string(ty),
257                                      list_lo,
258                                      span_hi);
259
260             // 2 for ()
261             let budget = try_opt!(width.checked_sub(output.len() + 2));
262
263             // 1 for (
264             let fmt = ListFormatting::for_fn(budget, offset + 1, context.config);
265             let list_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
266
267             format!("({}){}", list_str, output)
268         }
269         _ => String::new(),
270     };
271
272     Some(format!("{}{}", segment.identifier, params))
273 }
274
275 impl Rewrite for ast::WherePredicate {
276     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
277         // TODO: dead spans?
278         // TODO: don't assume we'll always fit on one line...
279         Some(match *self {
280             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
281                                                                            ref bounded_ty,
282                                                                            ref bounds,
283                                                                            .. }) => {
284                 if !bound_lifetimes.is_empty() {
285                     let lifetime_str = bound_lifetimes.iter()
286                                                       .map(|lt| {
287                                                           lt.rewrite(context, width, offset)
288                                                             .unwrap()
289                                                       })
290                                                       .collect::<Vec<_>>()
291                                                       .join(", ");
292                     let type_str = pprust::ty_to_string(bounded_ty);
293                     // 8 = "for<> : ".len()
294                     let used_width = lifetime_str.len() + type_str.len() + 8;
295                     let bounds_str = bounds.iter()
296                                            .map(|ty_bound| {
297                                                ty_bound.rewrite(context,
298                                                                 width - used_width,
299                                                                 offset + used_width)
300                                                        .unwrap()
301                                            })
302                                            .collect::<Vec<_>>()
303                                            .join(" + ");
304
305                     format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
306                 } else {
307                     let type_str = pprust::ty_to_string(bounded_ty);
308                     // 2 = ": ".len()
309                     let used_width = type_str.len() + 2;
310                     let bounds_str = bounds.iter()
311                                            .map(|ty_bound| {
312                                                ty_bound.rewrite(context,
313                                                                 width - used_width,
314                                                                 offset + used_width)
315                                                        .unwrap()
316                                            })
317                                            .collect::<Vec<_>>()
318                                            .join(" + ");
319
320                     format!("{}: {}", type_str, bounds_str)
321                 }
322             }
323             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
324                                                                              ref bounds,
325                                                                              .. }) => {
326                 format!("{}: {}",
327                         pprust::lifetime_to_string(lifetime),
328                         bounds.iter()
329                               .map(pprust::lifetime_to_string)
330                               .collect::<Vec<_>>()
331                               .join(" + "))
332             }
333             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
334                 let ty_str = pprust::ty_to_string(ty);
335                 // 3 = " = ".len()
336                 let used_width = 3 + ty_str.len();
337                 let path_str = try_opt!(path.rewrite(context,
338                                                      width - used_width,
339                                                      offset + used_width));
340                 format!("{} = {}", path_str, ty_str)
341             }
342         })
343     }
344 }
345
346 impl Rewrite for ast::LifetimeDef {
347     fn rewrite(&self, _: &RewriteContext, _: usize, _: Indent) -> Option<String> {
348         if self.bounds.is_empty() {
349             Some(pprust::lifetime_to_string(&self.lifetime))
350         } else {
351             Some(format!("{}: {}",
352                          pprust::lifetime_to_string(&self.lifetime),
353                          self.bounds
354                              .iter()
355                              .map(pprust::lifetime_to_string)
356                              .collect::<Vec<_>>()
357                              .join(" + ")))
358         }
359     }
360 }
361
362 impl Rewrite for ast::TyParamBound {
363     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
364         match *self {
365             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
366                 tref.rewrite(context, width, offset)
367             }
368             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
369                 Some(format!("?{}",
370                              try_opt!(tref.rewrite(context, width - 1, offset + 1))))
371             }
372             ast::TyParamBound::RegionTyParamBound(ref l) => {
373                 Some(pprust::lifetime_to_string(l))
374             }
375         }
376     }
377 }
378
379 impl Rewrite for ast::TyParamBounds {
380     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
381         let strs: Vec<_> = self.iter()
382                                .map(|b| b.rewrite(context, width, offset).unwrap())
383                                .collect();
384         Some(strs.join(" + "))
385     }
386 }
387
388 // FIXME: this assumes everything will fit on one line
389 impl Rewrite for ast::TyParam {
390     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
391         let mut result = String::with_capacity(128);
392         result.push_str(&self.ident.to_string());
393         if !self.bounds.is_empty() {
394             result.push_str(": ");
395
396             let bounds = self.bounds
397                              .iter()
398                              .map(|ty_bound| ty_bound.rewrite(context, width, offset).unwrap())
399                              .collect::<Vec<_>>()
400                              .join(" + ");
401
402             result.push_str(&bounds);
403         }
404         if let Some(ref def) = self.default {
405             result.push_str(" = ");
406             result.push_str(&pprust::ty_to_string(&def));
407         }
408
409         Some(result)
410     }
411 }
412
413 // FIXME: this assumes everything will fit on one line
414 impl Rewrite for ast::PolyTraitRef {
415     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
416         if !self.bound_lifetimes.is_empty() {
417             let lifetime_str = self.bound_lifetimes
418                                    .iter()
419                                    .map(|lt| lt.rewrite(context, width, offset).unwrap())
420                                    .collect::<Vec<_>>()
421                                    .join(", ");
422             // 6 is "for<> ".len()
423             let extra_offset = lifetime_str.len() + 6;
424             let max_path_width = try_opt!(width.checked_sub(extra_offset));
425             let path_str = try_opt!(self.trait_ref
426                                         .path
427                                         .rewrite(context, max_path_width, offset + extra_offset));
428
429             Some(format!("for<{}> {}", lifetime_str, path_str))
430         } else {
431             self.trait_ref.path.rewrite(context, width, offset)
432         }
433     }
434 }
435
436 impl Rewrite for ast::Ty {
437     // FIXME doesn't always use width, offset
438     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
439         match self.node {
440             ast::TyPath(None, ref p) => {
441                 p.rewrite(context, width, offset)
442             }
443             ast::TyObjectSum(ref ty, ref bounds) => {
444                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
445                 let overhead = ty_str.len() + 3;
446                 Some(format!("{} + {}",
447                              ty_str,
448                              try_opt!(bounds.rewrite(context,
449                                                      try_opt!(width.checked_sub(overhead)),
450                                                      offset + overhead))))
451             }
452             ast::TyRptr(ref lifetime, ref mt) => {
453                 let mut_str = format_mutability(mt.mutbl);
454                 let mut_len = mut_str.len();
455                 Some(match lifetime {
456                     &Some(ref lifetime) => {
457                         let lt_str = pprust::lifetime_to_string(lifetime);
458                         let lt_len = lt_str.len();
459                         format!("&{} {}{}",
460                                 lt_str,
461                                 mut_str,
462                                 try_opt!(mt.ty.rewrite(context,
463                                                        width - (2 + mut_len + lt_len),
464                                                        offset + 2 + mut_len + lt_len)))
465                     }
466                     &None => {
467                         format!("&{}{}",
468                                 mut_str,
469                                 try_opt!(mt.ty.rewrite(context,
470                                                        width - (1 + mut_len),
471                                                        offset + 1 + mut_len)))
472                     }
473                 })
474             }
475             ast::TyParen(ref ty) => {
476                 ty.rewrite(context, width - 2, offset + 1).map(|ty_str| format!("({})", ty_str))
477             }
478             _ => Some(pprust::ty_to_string(self)),
479         }
480     }
481 }