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