]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Merge pull request #604 from eefriedman/path-cleanup
[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::{self, Mutability};
12 use syntax::print::pprust;
13 use syntax::codemap::{self, Span, BytePos};
14
15 use Indent;
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};
20
21 // Does not wrap on simple segments.
22 pub fn rewrite_path(context: &RewriteContext,
23                     expr_context: bool,
24                     qself: Option<&ast::QSelf>,
25                     path: &ast::Path,
26                     width: usize,
27                     offset: Indent)
28                     -> Option<String> {
29     let skip_count = qself.map(|x| x.position).unwrap_or(0);
30
31     let mut result = if path.global {
32         "::".to_owned()
33     } else {
34         String::new()
35     };
36
37     let mut span_lo = path.span.lo;
38
39     if let Some(ref qself) = qself {
40         result.push('<');
41         let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
42         result.push_str(&fmt_ty);
43
44         if skip_count > 0 {
45             result.push_str(" as ");
46
47             let extra_offset = extra_offset(&result, offset);
48             // 3 = ">::".len()
49             let budget = try_opt!(width.checked_sub(extra_offset + 3));
50
51             result = try_opt!(rewrite_path_segments(expr_context,
52                                                     result,
53                                                     path.segments.iter().take(skip_count),
54                                                     span_lo,
55                                                     path.span.hi,
56                                                     context,
57                                                     budget,
58                                                     offset + extra_offset));
59         }
60
61         result.push_str(">::");
62         span_lo = qself.ty.span.hi + BytePos(1);
63     }
64
65     let extra_offset = extra_offset(&result, offset);
66     let budget = try_opt!(width.checked_sub(extra_offset));
67     rewrite_path_segments(expr_context,
68                           result,
69                           path.segments.iter().skip(skip_count),
70                           span_lo,
71                           path.span.hi,
72                           context,
73                           budget,
74                           offset + extra_offset)
75 }
76
77 fn rewrite_path_segments<'a, I>(expr_context: bool,
78                                 mut buffer: String,
79                                 iter: I,
80                                 mut span_lo: BytePos,
81                                 span_hi: BytePos,
82                                 context: &RewriteContext,
83                                 width: usize,
84                                 offset: Indent)
85                                 -> Option<String>
86     where I: Iterator<Item = &'a ast::PathSegment>
87 {
88     let mut first = true;
89
90     for segment in iter {
91         if first {
92             first = false;
93         } else {
94             buffer.push_str("::");
95         }
96
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,
101                                                       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     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
133         match *self {
134             SegmentParam::LifeTime(ref lt) => {
135                 wrap_str(pprust::lifetime_to_string(lt),
136                          context.config.max_width,
137                          width,
138                          offset)
139             }
140             SegmentParam::Type(ref ty) => {
141                 ty.rewrite(context, width, offset)
142             }
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);
148                 Some(result)
149             }
150         }
151     }
152 }
153
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.
156 //
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.
159 //
160 // span_hi is assumed equal to the end of the entire path.
161 //
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,
167                    span_hi: BytePos,
168                    context: &RewriteContext,
169                    width: usize,
170                    offset: Indent)
171                    -> Option<String> {
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;
175
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
181                                  .iter()
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<_>>();
186
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 {
190                 "::"
191             } else {
192                 ""
193             };
194
195             // 1 for <
196             let extra_offset = 1 + separator.len();
197             // 1 for >
198             let list_width = try_opt!(width.checked_sub(extra_offset + 1));
199
200             let items = itemize_list(context.codemap,
201                                      param_list.into_iter(),
202                                      ">",
203                                      |param| param.get_span().lo,
204                                      |param| param.get_span().hi,
205                                      |seg| {
206                                          seg.rewrite(context,
207                                                      context.config.max_width,
208                                                      offset + extra_offset)
209                                      },
210                                      list_lo,
211                                      span_hi);
212             let list_str = try_opt!(format_item_list(items,
213                                                      list_width,
214                                                      offset + extra_offset,
215                                                      context.config));
216
217             // Update position of last bracket.
218             *span_lo = next_span_lo;
219
220             format!("{}<{}>", separator, list_str)
221         }
222         ast::PathParameters::ParenthesizedParameters(ref data) => {
223             let output = match data.output {
224                 Some(ref ty) => {
225                     let type_str = try_opt!(ty.rewrite(context, width, offset));
226                     format!(" -> {}", type_str)
227                 }
228                 None => String::new(),
229             };
230
231             // 2 for ()
232             let budget = try_opt!(width.checked_sub(output.len() + 2));
233             // 1 for (
234             let offset = offset + 1;
235             let list_lo = span_after(data.span, "(", context.codemap);
236             let items = itemize_list(context.codemap,
237                                      data.inputs.iter(),
238                                      ")",
239                                      |ty| ty.span.lo,
240                                      |ty| ty.span.hi,
241                                      |ty| ty.rewrite(context, budget, offset),
242                                      list_lo,
243                                      span_hi);
244             let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
245
246             format!("({}){}", list_str, output)
247         }
248         _ => String::new(),
249     };
250
251     Some(format!("{}{}", segment.identifier, params))
252 }
253
254 impl Rewrite for ast::WherePredicate {
255     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
256         // TODO: dead spans?
257         let result = match *self {
258             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
259                                                                            ref bounded_ty,
260                                                                            ref bounds,
261                                                                            .. }) => {
262                 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
263
264                 if !bound_lifetimes.is_empty() {
265                     let lifetime_str = try_opt!(bound_lifetimes.iter()
266                                                                .map(|lt| {
267                                                                    lt.rewrite(context,
268                                                                               width,
269                                                                               offset)
270                                                                })
271                                                                .collect::<Option<Vec<_>>>())
272                                            .join(", ");
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()
277                                                     .map(|ty_bound| {
278                                                         ty_bound.rewrite(context,
279                                                                          budget,
280                                                                          offset + used_width)
281                                                     })
282                                                     .collect::<Option<Vec<_>>>())
283                                          .join(" + ");
284
285                     format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
286                 } else {
287                     // 2 = ": ".len()
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()
291                                                     .map(|ty_bound| {
292                                                         ty_bound.rewrite(context,
293                                                                          budget,
294                                                                          offset + used_width)
295                                                     })
296                                                     .collect::<Option<Vec<_>>>())
297                                          .join(" + ");
298
299                     format!("{}: {}", type_str, bounds_str)
300                 }
301             }
302             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
303                                                                              ref bounds,
304                                                                              .. }) => {
305                 format!("{}: {}",
306                         pprust::lifetime_to_string(lifetime),
307                         bounds.iter()
308                               .map(pprust::lifetime_to_string)
309                               .collect::<Vec<_>>()
310                               .join(" + "))
311             }
312             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
313                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
314                 // 3 = " = ".len()
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,
318                                                      false,
319                                                      None,
320                                                      path,
321                                                      budget,
322                                                      offset + used_width));
323                 format!("{} = {}", path_str, ty_str)
324             }
325         };
326
327         wrap_str(result, context.config.max_width, width, offset)
328     }
329 }
330
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)
335         } else {
336             format!("{}: {}",
337                     pprust::lifetime_to_string(&self.lifetime),
338                     self.bounds
339                         .iter()
340                         .map(pprust::lifetime_to_string)
341                         .collect::<Vec<_>>()
342                         .join(" + "))
343         };
344
345         wrap_str(result, context.config.max_width, width, offset)
346     }
347 }
348
349 impl Rewrite for ast::TyParamBound {
350     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
351         match *self {
352             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
353                 tref.rewrite(context, width, offset)
354             }
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))))
358             }
359             ast::TyParamBound::RegionTyParamBound(ref l) => {
360                 wrap_str(pprust::lifetime_to_string(l),
361                          context.config.max_width,
362                          width,
363                          offset)
364             }
365         }
366     }
367 }
368
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))
373                                         .collect());
374         wrap_str(strs.join(" + "), context.config.max_width, width, offset)
375     }
376 }
377
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(": ");
384
385             let bounds = try_opt!(self.bounds
386                                       .iter()
387                                       .map(|ty_bound| ty_bound.rewrite(context, width, offset))
388                                       .collect::<Option<Vec<_>>>())
389                              .join(" + ");
390
391             result.push_str(&bounds);
392         }
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);
398         }
399
400         wrap_str(result, context.config.max_width, width, offset)
401     }
402 }
403
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
408                                             .iter()
409                                             .map(|lt| lt.rewrite(context, width, offset))
410                                             .collect::<Option<Vec<_>>>())
411                                    .join(", ");
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,
416                                                  false,
417                                                  None,
418                                                  &self.trait_ref.path,
419                                                  max_path_width,
420                                                  offset + extra_offset));
421
422             Some(format!("for<{}> {}", lifetime_str, path_str))
423         } else {
424             rewrite_path(context, false, None, &self.trait_ref.path, width, offset)
425         }
426     }
427 }
428
429 impl Rewrite for ast::Ty {
430     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
431         match self.node {
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!("{} + {}",
436                              ty_str,
437                              try_opt!(bounds.rewrite(context,
438                                                      try_opt!(width.checked_sub(overhead)),
439                                                      offset + overhead))))
440             }
441             ast::TyPtr(ref mt) => {
442                 let prefix = match mt.mutbl {
443                     Mutability::MutMutable => "*mut ",
444                     Mutability::MutImmutable => "*const ",
445                 };
446
447                 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
448             }
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));
457                         format!("&{} {}{}",
458                                 lt_str,
459                                 mut_str,
460                                 try_opt!(mt.ty.rewrite(context,
461                                                        budget,
462                                                        offset + 2 + mut_len + lt_len)))
463                     }
464                     None => {
465                         let budget = try_opt!(width.checked_sub(1 + mut_len));
466                         format!("&{}{}",
467                                 mut_str,
468                                 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
469                     }
470                 })
471             }
472             // FIXME: we drop any comments here, even though it's a silly place to put
473             // comments.
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))
477             }
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))
481             }
482             ast::TyTup(ref items) => {
483                 rewrite_tuple(context, items, self.span, width, offset)
484             }
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)
488             }
489             ast::TyFixedLengthVec(ref ty, ref repeats) => {
490                 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
491             }
492             ast::TyInfer => {
493                 if width >= 1 {
494                     Some("_".to_owned())
495                 } else {
496                     None
497                 }
498             }
499             ast::TyBareFn(..) => {
500                 wrap_str(pprust::ty_to_string(self),
501                          context.config.max_width,
502                          width,
503                          offset)
504             }
505             ast::TyMac(..) | ast::TyTypeof(..) => unreachable!(),
506         }
507     }
508 }