]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Run clippy
[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(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(lt) => lt.span,
135             SegmentParam::Type(ty) => ty.span,
136             SegmentParam::Binding(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(lt) => lt.rewrite(context, width, offset),
145             SegmentParam::Type(ty) => ty.rewrite(context, width, offset),
146             SegmentParam::Binding(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.is_empty() && 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 bound_spacing = if context.config.space_before_bound {
410             " "
411         } else {
412             ""
413         };
414         let result = format!("{}{}: {}", result, bound_spacing, appendix.join(" + "));
415         wrap_str(result, context.config.max_width, width, offset)
416     }
417 }
418
419 impl Rewrite for ast::TyParamBound {
420     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
421         match *self {
422             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
423                 tref.rewrite(context, width, offset)
424             }
425             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
426                 let budget = try_opt!(width.checked_sub(1));
427                 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
428             }
429             ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
430         }
431     }
432 }
433
434 impl Rewrite for ast::Lifetime {
435     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
436         wrap_str(pprust::lifetime_to_string(self),
437                  context.config.max_width,
438                  width,
439                  offset)
440     }
441 }
442
443 impl Rewrite for ast::TyParamBounds {
444     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
445         let strs: Vec<_> = try_opt!(self.iter()
446             .map(|b| b.rewrite(context, width, offset))
447             .collect());
448         wrap_str(strs.join(" + "), context.config.max_width, width, offset)
449     }
450 }
451
452 impl Rewrite for ast::TyParam {
453     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
454         let mut result = String::with_capacity(128);
455         result.push_str(&self.ident.to_string());
456         if !self.bounds.is_empty() {
457             if context.config.space_before_bound {
458                 result.push_str(" ");
459             }
460             result.push_str(": ");
461
462             let bounds: String = try_opt!(self.bounds
463                 .iter()
464                 .map(|ty_bound| ty_bound.rewrite(context, width, offset))
465                 .intersperse(Some(" + ".to_string()))
466                 .collect());
467
468             result.push_str(&bounds);
469         }
470         if let Some(ref def) = self.default {
471
472             let eq_str = match context.config.type_punctuation_density {
473                 TypeDensity::Compressed => "=",
474                 TypeDensity::Wide => " = ",
475             };
476             result.push_str(eq_str);
477             let budget = try_opt!(width.checked_sub(result.len()));
478             let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
479             result.push_str(&rewrite);
480         }
481
482         wrap_str(result, context.config.max_width, width, offset)
483     }
484 }
485
486 impl Rewrite for ast::PolyTraitRef {
487     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
488         if !self.bound_lifetimes.is_empty() {
489             let lifetime_str: String = try_opt!(self.bound_lifetimes
490                 .iter()
491                 .map(|lt| lt.rewrite(context, width, offset))
492                 .intersperse(Some(", ".to_string()))
493                 .collect());
494
495             // 6 is "for<> ".len()
496             let extra_offset = lifetime_str.len() + 6;
497             let max_path_width = try_opt!(width.checked_sub(extra_offset));
498             let path_str = try_opt!(self.trait_ref
499                 .rewrite(context, max_path_width, offset + extra_offset));
500
501             Some(format!("for<{}> {}", lifetime_str, path_str))
502         } else {
503             self.trait_ref.rewrite(context, width, offset)
504         }
505     }
506 }
507
508 impl Rewrite for ast::TraitRef {
509     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
510         rewrite_path(context, false, None, &self.path, width, offset)
511     }
512 }
513
514 impl Rewrite for ast::Ty {
515     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
516         match self.node {
517             ast::TyKind::ObjectSum(ref ty, ref bounds) => {
518                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
519                 let overhead = ty_str.len() + 3;
520                 let plus_str = match context.config.type_punctuation_density {
521                     TypeDensity::Compressed => "+",
522                     TypeDensity::Wide => " + ",
523                 };
524                 Some(format!("{}{}{}",
525                              ty_str,
526                              plus_str,
527                              try_opt!(bounds.rewrite(context,
528                                                      try_opt!(width.checked_sub(overhead)),
529                                                      offset + overhead))))
530             }
531             ast::TyKind::Ptr(ref mt) => {
532                 let prefix = match mt.mutbl {
533                     Mutability::Mutable => "*mut ",
534                     Mutability::Immutable => "*const ",
535                 };
536
537                 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
538             }
539             ast::TyKind::Rptr(ref lifetime, ref mt) => {
540                 let mut_str = format_mutability(mt.mutbl);
541                 let mut_len = mut_str.len();
542                 Some(match *lifetime {
543                     Some(ref lifetime) => {
544                         let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
545                         let lt_str =
546                             try_opt!(lifetime.rewrite(context, lt_budget, offset + 2 + mut_len));
547                         let lt_len = lt_str.len();
548                         let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
549                         format!("&{} {}{}",
550                                 lt_str,
551                                 mut_str,
552                                 try_opt!(mt.ty
553                                     .rewrite(context, budget, offset + 2 + mut_len + lt_len)))
554                     }
555                     None => {
556                         let budget = try_opt!(width.checked_sub(1 + mut_len));
557                         format!("&{}{}",
558                                 mut_str,
559                                 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
560                     }
561                 })
562             }
563             // FIXME: we drop any comments here, even though it's a silly place to put
564             // comments.
565             ast::TyKind::Paren(ref ty) => {
566                 let budget = try_opt!(width.checked_sub(2));
567                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
568             }
569             ast::TyKind::Vec(ref ty) => {
570                 let budget = try_opt!(width.checked_sub(2));
571                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
572             }
573             ast::TyKind::Tup(ref items) => {
574                 rewrite_tuple(context,
575                               items.iter().map(|x| &**x),
576                               self.span,
577                               width,
578                               offset)
579             }
580             ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
581             ast::TyKind::Path(ref q_self, ref path) => {
582                 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
583             }
584             ast::TyKind::FixedLengthVec(ref ty, ref repeats) => {
585                 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
586             }
587             ast::TyKind::Infer => {
588                 if width >= 1 {
589                     Some("_".to_owned())
590                 } else {
591                     None
592                 }
593             }
594             ast::TyKind::BareFn(ref bare_fn) => {
595                 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
596             }
597             ast::TyKind::Mac(..) |
598             ast::TyKind::Typeof(..) => unreachable!(),
599             ast::TyKind::ImplicitSelf => Some(String::from("")),
600         }
601     }
602 }
603
604 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
605                    span: Span,
606                    context: &RewriteContext,
607                    width: usize,
608                    offset: Indent)
609                    -> Option<String> {
610     let mut result = String::with_capacity(128);
611
612     if !bare_fn.lifetimes.is_empty() {
613         result.push_str("for<");
614         // 6 = "for<> ".len(), 4 = "for<".
615         // This doesn't work out so nicely for mutliline situation with lots of
616         // rightward drift. If that is a problem, we could use the list stuff.
617         result.push_str(&try_opt!(bare_fn.lifetimes
618             .iter()
619             .map(|l| l.rewrite(context, try_opt!(width.checked_sub(6)), offset + 4))
620             .intersperse(Some(", ".to_string()))
621             .collect::<Option<String>>()));
622         result.push_str("> ");
623     }
624
625     result.push_str(::utils::format_unsafety(bare_fn.unsafety));
626
627     if bare_fn.abi != abi::Abi::Rust {
628         result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi));
629     }
630
631     result.push_str("fn");
632
633     let budget = try_opt!(width.checked_sub(result.len()));
634     let indent = offset + result.len();
635
636     let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
637                                                 &bare_fn.decl.output,
638                                                 bare_fn.decl.variadic,
639                                                 span,
640                                                 context,
641                                                 budget,
642                                                 indent));
643
644     result.push_str(&rewrite);
645
646     Some(result)
647 }