]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Refactoring exsisting filter_maps to maps
[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 std::ops::Deref;
12 use std::iter::ExactSizeIterator;
13
14 use syntax::ast::{self, Mutability, FunctionRetTy};
15 use syntax::print::pprust;
16 use syntax::codemap::{self, Span, BytePos};
17 use syntax::abi;
18
19 use {Indent, Spanned};
20 use codemap::SpanUtils;
21 use lists::{format_item_list, itemize_list, format_fn_args};
22 use rewrite::{Rewrite, RewriteContext};
23 use utils::{extra_offset, format_mutability, wrap_str};
24 use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
25 use config::TypeDensity;
26 use itertools::Itertools;
27
28 // Does not wrap on simple segments.
29 pub fn rewrite_path(context: &RewriteContext,
30                     expr_context: bool,
31                     qself: Option<&ast::QSelf>,
32                     path: &ast::Path,
33                     width: usize,
34                     offset: Indent)
35                     -> Option<String> {
36     let skip_count = qself.map_or(0, |x| x.position);
37
38     let mut result = if path.global && qself.is_none() {
39         "::".to_owned()
40     } else {
41         String::new()
42     };
43
44     let mut span_lo = path.span.lo;
45
46     if let Some(ref qself) = qself {
47         result.push('<');
48         let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
49         result.push_str(&fmt_ty);
50
51         if skip_count > 0 {
52             result.push_str(" as ");
53             if path.global {
54                 result.push_str("::");
55             }
56
57             let extra_offset = extra_offset(&result, offset);
58             // 3 = ">::".len()
59             let budget = try_opt!(width.checked_sub(extra_offset + 3));
60
61             result = try_opt!(rewrite_path_segments(false,
62                                                     result,
63                                                     path.segments.iter().take(skip_count),
64                                                     span_lo,
65                                                     path.span.hi,
66                                                     context,
67                                                     budget,
68                                                     offset + extra_offset));
69         }
70
71         result.push_str(">::");
72         span_lo = qself.ty.span.hi + BytePos(1);
73     }
74
75     let extra_offset = extra_offset(&result, offset);
76     let budget = try_opt!(width.checked_sub(extra_offset));
77     rewrite_path_segments(expr_context,
78                           result,
79                           path.segments.iter().skip(skip_count),
80                           span_lo,
81                           path.span.hi,
82                           context,
83                           budget,
84                           offset + extra_offset)
85 }
86
87 fn rewrite_path_segments<'a, I>(expr_context: bool,
88                                 mut buffer: String,
89                                 iter: I,
90                                 mut span_lo: BytePos,
91                                 span_hi: BytePos,
92                                 context: &RewriteContext,
93                                 width: usize,
94                                 offset: Indent)
95                                 -> Option<String>
96     where I: Iterator<Item = &'a ast::PathSegment>
97 {
98     let mut first = true;
99
100     for segment in iter {
101         if first {
102             first = false;
103         } else {
104             buffer.push_str("::");
105         }
106
107         let extra_offset = extra_offset(&buffer, offset);
108         let remaining_width = try_opt!(width.checked_sub(extra_offset));
109         let new_offset = offset + extra_offset;
110         let segment_string = try_opt!(rewrite_segment(expr_context,
111                                                       segment,
112                                                       &mut span_lo,
113                                                       span_hi,
114                                                       context,
115                                                       remaining_width,
116                                                       new_offset));
117
118         buffer.push_str(&segment_string);
119     }
120
121     Some(buffer)
122 }
123
124 #[derive(Debug)]
125 enum SegmentParam<'a> {
126     LifeTime(&'a ast::Lifetime),
127     Type(&'a ast::Ty),
128     Binding(&'a ast::TypeBinding),
129 }
130
131 impl<'a> SegmentParam<'a> {
132     fn get_span(&self) -> Span {
133         match *self {
134             SegmentParam::LifeTime(ref lt) => lt.span,
135             SegmentParam::Type(ref ty) => ty.span,
136             SegmentParam::Binding(ref binding) => binding.span,
137         }
138     }
139 }
140
141 impl<'a> Rewrite for SegmentParam<'a> {
142     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
143         match *self {
144             SegmentParam::LifeTime(ref lt) => lt.rewrite(context, width, offset),
145             SegmentParam::Type(ref ty) => ty.rewrite(context, width, offset),
146             SegmentParam::Binding(ref binding) => {
147                 let mut result = format!("{} = ", binding.ident);
148                 let budget = try_opt!(width.checked_sub(result.len()));
149                 let rewrite = try_opt!(binding.ty.rewrite(context, budget, offset + result.len()));
150                 result.push_str(&rewrite);
151                 Some(result)
152             }
153         }
154     }
155 }
156
157 // Formats a path segment. There are some hacks involved to correctly determine
158 // the segment's associated span since it's not part of the AST.
159 //
160 // The span_lo is assumed to be greater than the end of any previous segment's
161 // parameters and lesser or equal than the start of current segment.
162 //
163 // span_hi is assumed equal to the end of the entire path.
164 //
165 // When the segment contains a positive number of parameters, we update span_lo
166 // so that invariants described above will hold for the next segment.
167 fn rewrite_segment(expr_context: bool,
168                    segment: &ast::PathSegment,
169                    span_lo: &mut BytePos,
170                    span_hi: BytePos,
171                    context: &RewriteContext,
172                    width: usize,
173                    offset: Indent)
174                    -> Option<String> {
175     let ident_len = segment.identifier.to_string().len();
176     let width = try_opt!(width.checked_sub(ident_len));
177     let offset = offset + ident_len;
178
179     let params = match segment.parameters {
180         ast::PathParameters::AngleBracketed(ref data) if !data.lifetimes.is_empty() ||
181                                                          !data.types.is_empty() ||
182                                                          !data.bindings.is_empty() => {
183             let param_list = data.lifetimes
184                 .iter()
185                 .map(SegmentParam::LifeTime)
186                 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
187                 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
188                 .collect::<Vec<_>>();
189
190             let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
191             let list_lo = context.codemap.span_after(codemap::mk_sp(*span_lo, span_hi), "<");
192             let separator = if expr_context { "::" } else { "" };
193
194             // 1 for <
195             let extra_offset = 1 + separator.len();
196             // 1 for >
197             let list_width = try_opt!(width.checked_sub(extra_offset + 1));
198
199             let items = itemize_list(context.codemap,
200                                      param_list.into_iter(),
201                                      ">",
202                                      |param| param.get_span().lo,
203                                      |param| param.get_span().hi,
204                                      |seg| seg.rewrite(context, list_width, offset + extra_offset),
205                                      list_lo,
206                                      span_hi);
207             let list_str = try_opt!(format_item_list(items,
208                                                      list_width,
209                                                      offset + extra_offset,
210                                                      context.config));
211
212             // Update position of last bracket.
213             *span_lo = next_span_lo;
214
215             format!("{}<{}>", separator, list_str)
216         }
217         ast::PathParameters::Parenthesized(ref data) => {
218             let output = match data.output {
219                 Some(ref ty) => FunctionRetTy::Ty(ty.clone()),
220                 None => FunctionRetTy::Default(codemap::DUMMY_SP),
221             };
222             try_opt!(format_function_type(data.inputs.iter().map(|x| &**x),
223                                           &output,
224                                           false,
225                                           data.span,
226                                           context,
227                                           width,
228                                           offset))
229         }
230         _ => String::new(),
231     };
232
233     Some(format!("{}{}", segment.identifier, params))
234 }
235
236 fn format_function_type<'a, I>(inputs: I,
237                                output: &FunctionRetTy,
238                                variadic: bool,
239                                span: Span,
240                                context: &RewriteContext,
241                                width: usize,
242                                offset: Indent)
243                                -> Option<String>
244     where I: ExactSizeIterator,
245           <I as Iterator>::Item: Deref,
246           <I::Item as Deref>::Target: Rewrite + Spanned + 'a
247 {
248     // Code for handling variadics is somewhat duplicated for items, but they
249     // are different enough to need some serious refactoring to share code.
250     enum ArgumentKind<T>
251         where T: Deref,
252               <T as Deref>::Target: Rewrite + Spanned
253     {
254         Regular(Box<T>),
255         Variadic(BytePos),
256     }
257
258     let variadic_arg = if variadic {
259         let variadic_start = context.codemap.span_before(span, "...");
260         Some(ArgumentKind::Variadic(variadic_start))
261     } else {
262         None
263     };
264
265     // 2 for ()
266     let budget = try_opt!(width.checked_sub(2));
267     // 1 for (
268     let offset = offset + 1;
269     let list_lo = context.codemap.span_after(span, "(");
270     let items = itemize_list(context.codemap,
271                              // FIXME Would be nice to avoid this allocation,
272                              // but I couldn't get the types to work out.
273                              inputs.map(|i| ArgumentKind::Regular(Box::new(i)))
274                                  .chain(variadic_arg),
275                              ")",
276                              |arg| {
277                                  match *arg {
278                                      ArgumentKind::Regular(ref ty) => ty.span().lo,
279                                      ArgumentKind::Variadic(start) => start,
280                                  }
281                              },
282                              |arg| {
283                                  match *arg {
284                                      ArgumentKind::Regular(ref ty) => ty.span().hi,
285                                      ArgumentKind::Variadic(start) => start + BytePos(3),
286                                  }
287                              },
288                              |arg| {
289         match *arg {
290             ArgumentKind::Regular(ref ty) => ty.rewrite(context, budget, offset),
291             ArgumentKind::Variadic(_) => Some("...".to_owned()),
292         }
293     },
294                              list_lo,
295                              span.hi);
296
297     let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
298
299     let output = match *output {
300         FunctionRetTy::Ty(ref ty) => {
301             let budget = try_opt!(width.checked_sub(4));
302             let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
303             format!(" -> {}", type_str)
304         }
305         FunctionRetTy::None(..) => " -> !".to_owned(),
306         FunctionRetTy::Default(..) => String::new(),
307     };
308
309     let infix = if output.len() > 0 && output.len() + list_str.len() > width {
310         format!("\n{}", (offset - 1).to_string(context.config))
311     } else {
312         String::new()
313     };
314
315     Some(format!("({}){}{}", list_str, infix, output))
316 }
317
318 impl Rewrite for ast::WherePredicate {
319     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
320         // TODO: dead spans?
321         let result = match *self {
322             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
323                                                                            ref bounded_ty,
324                                                                            ref bounds,
325                                                                            .. }) => {
326                 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
327
328                 if !bound_lifetimes.is_empty() {
329                     let lifetime_str: String = try_opt!(bound_lifetimes.iter()
330                                                                .map(|lt| {
331                                                                    lt.rewrite(context,
332                                                                               width,
333                                                                               offset)
334                                                                })
335                                                                .intersperse(Some(", ".to_string()))
336                                                                .collect());
337
338                     // 8 = "for<> : ".len()
339                     let used_width = lifetime_str.len() + type_str.len() + 8;
340                     let budget = try_opt!(width.checked_sub(used_width));
341                     let bounds_str: String = try_opt!(bounds.iter()
342                                                     .map(|ty_bound| {
343                                                         ty_bound.rewrite(context,
344                                                                          budget,
345                                                                          offset + used_width)
346                                                     })
347                                                     .intersperse(Some(" + ".to_string()))
348                                                     .collect());
349
350                     format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
351                 } else {
352                     // 2 = ": ".len()
353                     let used_width = type_str.len() + 2;
354                     let budget = try_opt!(width.checked_sub(used_width));
355                     let bounds_str: String = try_opt!(bounds.iter()
356                                                     .map(|ty_bound| {
357                                                         ty_bound.rewrite(context,
358                                                                          budget,
359                                                                          offset + used_width)
360                                                     })
361                                                     .intersperse(Some(" + ".to_string()))
362                                                     .collect());
363
364                     format!("{}: {}", type_str, bounds_str)
365                 }
366             }
367             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
368                                                                              ref bounds,
369                                                                              .. }) => {
370                 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
371             }
372             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
373                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
374                 // 3 = " = ".len()
375                 let used_width = 3 + ty_str.len();
376                 let budget = try_opt!(width.checked_sub(used_width));
377                 let path_str =
378                     try_opt!(rewrite_path(context, false, None, path, budget, offset + used_width));
379                 format!("{} = {}", path_str, ty_str)
380             }
381         };
382
383         wrap_str(result, context.config.max_width, width, offset)
384     }
385 }
386
387 impl Rewrite for ast::LifetimeDef {
388     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
389         rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
390     }
391 }
392
393 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
394                                    bounds: I,
395                                    context: &RewriteContext,
396                                    width: usize,
397                                    offset: Indent)
398                                    -> Option<String>
399     where I: ExactSizeIterator<Item = &'b ast::Lifetime>
400 {
401     let result = try_opt!(lt.rewrite(context, width, offset));
402
403     if bounds.len() == 0 {
404         Some(result)
405     } else {
406         let appendix: Vec<_> = try_opt!(bounds.into_iter()
407             .map(|b| b.rewrite(context, width, offset))
408             .collect());
409         let result = format!("{}: {}", result, appendix.join(" + "));
410         wrap_str(result, context.config.max_width, width, offset)
411     }
412 }
413
414 impl Rewrite for ast::TyParamBound {
415     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
416         match *self {
417             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
418                 tref.rewrite(context, width, offset)
419             }
420             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
421                 let budget = try_opt!(width.checked_sub(1));
422                 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
423             }
424             ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
425         }
426     }
427 }
428
429 impl Rewrite for ast::Lifetime {
430     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
431         wrap_str(pprust::lifetime_to_string(self),
432                  context.config.max_width,
433                  width,
434                  offset)
435     }
436 }
437
438 impl Rewrite for ast::TyParamBounds {
439     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
440         let strs: Vec<_> = try_opt!(self.iter()
441             .map(|b| b.rewrite(context, width, offset))
442             .collect());
443         wrap_str(strs.join(" + "), context.config.max_width, width, offset)
444     }
445 }
446
447 impl Rewrite for ast::TyParam {
448     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
449         let mut result = String::with_capacity(128);
450         result.push_str(&self.ident.to_string());
451         if !self.bounds.is_empty() {
452             result.push_str(": ");
453
454             let bounds: String = try_opt!(self.bounds
455                 .iter()
456                 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
457                 .intersperse(Some(" + ".to_string()))
458                 .collect());
459
460             result.push_str(&bounds);
461         }
462         if let Some(ref def) = self.default {
463
464             let eq_str = match context.config.type_punctuation_density {
465                 TypeDensity::Compressed => "=",
466                 TypeDensity::Wide => " = ",
467             };
468             result.push_str(eq_str);
469             let budget = try_opt!(width.checked_sub(result.len()));
470             let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
471             result.push_str(&rewrite);
472         }
473
474         wrap_str(result, context.config.max_width, width, offset)
475     }
476 }
477
478 impl Rewrite for ast::PolyTraitRef {
479     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
480         if !self.bound_lifetimes.is_empty() {
481             let lifetime_str: String = try_opt!(self.bound_lifetimes
482                 .iter()
483                 .map(|lt| lt.rewrite(context, width, offset))
484                 .intersperse(Some(", ".to_string()))
485                 .collect());
486
487             // 6 is "for<> ".len()
488             let extra_offset = lifetime_str.len() + 6;
489             let max_path_width = try_opt!(width.checked_sub(extra_offset));
490             let path_str = try_opt!(self.trait_ref
491                 .rewrite(context, max_path_width, offset + extra_offset));
492
493             Some(format!("for<{}> {}", lifetime_str, path_str))
494         } else {
495             self.trait_ref.rewrite(context, width, offset)
496         }
497     }
498 }
499
500 impl Rewrite for ast::TraitRef {
501     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
502         rewrite_path(context, false, None, &self.path, width, offset)
503     }
504 }
505
506 impl Rewrite for ast::Ty {
507     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
508         match self.node {
509             ast::TyKind::ObjectSum(ref ty, ref bounds) => {
510                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
511                 let overhead = ty_str.len() + 3;
512                 let plus_str = match context.config.type_punctuation_density {
513                     TypeDensity::Compressed => "+",
514                     TypeDensity::Wide => " + ",
515                 };
516                 Some(format!("{}{}{}",
517                              ty_str,
518                              plus_str,
519                              try_opt!(bounds.rewrite(context,
520                                                      try_opt!(width.checked_sub(overhead)),
521                                                      offset + overhead))))
522             }
523             ast::TyKind::Ptr(ref mt) => {
524                 let prefix = match mt.mutbl {
525                     Mutability::Mutable => "*mut ",
526                     Mutability::Immutable => "*const ",
527                 };
528
529                 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
530             }
531             ast::TyKind::Rptr(ref lifetime, ref mt) => {
532                 let mut_str = format_mutability(mt.mutbl);
533                 let mut_len = mut_str.len();
534                 Some(match *lifetime {
535                     Some(ref lifetime) => {
536                         let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
537                         let lt_str =
538                             try_opt!(lifetime.rewrite(context, lt_budget, offset + 2 + mut_len));
539                         let lt_len = lt_str.len();
540                         let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
541                         format!("&{} {}{}",
542                                 lt_str,
543                                 mut_str,
544                                 try_opt!(mt.ty
545                                     .rewrite(context, budget, offset + 2 + mut_len + lt_len)))
546                     }
547                     None => {
548                         let budget = try_opt!(width.checked_sub(1 + mut_len));
549                         format!("&{}{}",
550                                 mut_str,
551                                 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
552                     }
553                 })
554             }
555             // FIXME: we drop any comments here, even though it's a silly place to put
556             // comments.
557             ast::TyKind::Paren(ref ty) => {
558                 let budget = try_opt!(width.checked_sub(2));
559                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
560             }
561             ast::TyKind::Vec(ref ty) => {
562                 let budget = try_opt!(width.checked_sub(2));
563                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
564             }
565             ast::TyKind::Tup(ref items) => {
566                 rewrite_tuple(context,
567                               items.iter().map(|x| &**x),
568                               self.span,
569                               width,
570                               offset)
571             }
572             ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
573             ast::TyKind::Path(ref q_self, ref path) => {
574                 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
575             }
576             ast::TyKind::FixedLengthVec(ref ty, ref repeats) => {
577                 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
578             }
579             ast::TyKind::Infer => {
580                 if width >= 1 {
581                     Some("_".to_owned())
582                 } else {
583                     None
584                 }
585             }
586             ast::TyKind::BareFn(ref bare_fn) => {
587                 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
588             }
589             ast::TyKind::Mac(..) |
590             ast::TyKind::Typeof(..) => unreachable!(),
591             ast::TyKind::ImplicitSelf => Some(String::from("")),
592         }
593     }
594 }
595
596 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
597                    span: Span,
598                    context: &RewriteContext,
599                    width: usize,
600                    offset: Indent)
601                    -> Option<String> {
602     let mut result = String::with_capacity(128);
603
604     if !bare_fn.lifetimes.is_empty() {
605         result.push_str("for<");
606         // 6 = "for<> ".len(), 4 = "for<".
607         // This doesn't work out so nicely for mutliline situation with lots of
608         // rightward drift. If that is a problem, we could use the list stuff.
609         result.push_str(&try_opt!(bare_fn.lifetimes
610             .iter()
611             .map(|l| l.rewrite(context, try_opt!(width.checked_sub(6)), offset + 4))
612             .intersperse(Some(", ".to_string()))
613             .collect::<Option<String>>()));
614         result.push_str("> ");
615     }
616
617     result.push_str(&::utils::format_unsafety(bare_fn.unsafety));
618
619     if bare_fn.abi != abi::Abi::Rust {
620         result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi));
621     }
622
623     result.push_str("fn");
624
625     let budget = try_opt!(width.checked_sub(result.len()));
626     let indent = offset + result.len();
627
628     let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
629                                                 &bare_fn.decl.output,
630                                                 bare_fn.decl.variadic,
631                                                 span,
632                                                 context,
633                                                 budget,
634                                                 indent));
635
636     result.push_str(&rewrite);
637
638     Some(result)
639 }