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