]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Handle variadic function types
[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                                           false,
224                                           data.span,
225                                           context,
226                                           width,
227                                           offset))
228         }
229         _ => String::new(),
230     };
231
232     Some(format!("{}{}", segment.identifier, params))
233 }
234
235 fn format_function_type<'a, I>(inputs: I,
236                                output: &FunctionRetTy,
237                                variadic: bool,
238                                span: Span,
239                                context: &RewriteContext,
240                                width: usize,
241                                offset: Indent)
242                                -> Option<String>
243     where I: ExactSizeIterator,
244           <I as Iterator>::Item: Deref,
245           <I::Item as Deref>::Target: Rewrite + Spanned + 'a
246 {
247     // Code for handling variadics is somewhat duplicated for items, but they
248     // are different enough to need some serious refactoring to share code.
249     enum ArgumentKind<T>
250         where T: Deref,
251               <T as Deref>::Target: Rewrite + Spanned
252     {
253         Regular(Box<T>),
254         Variadic(BytePos),
255     }
256
257     let variadic_arg = if variadic {
258         let variadic_start = context.codemap.span_before(span, "...");
259         Some(ArgumentKind::Variadic(variadic_start))
260     } else {
261         None
262     };
263
264     // 2 for ()
265     let budget = try_opt!(width.checked_sub(2));
266     // 1 for (
267     let offset = offset + 1;
268     let list_lo = context.codemap.span_after(span, "(");
269     let items = itemize_list(context.codemap,
270                              // FIXME Would be nice to avoid this allocation,
271                              // but I couldn't get the types to work out.
272                              inputs.map(|i| ArgumentKind::Regular(Box::new(i)))
273                                    .chain(variadic_arg),
274                              ")",
275                              |arg| {
276                                  match *arg {
277                                      ArgumentKind::Regular(ref ty) => ty.span().lo,
278                                      ArgumentKind::Variadic(start) => start,
279                                  }
280                              },
281                              |arg| {
282                                  match *arg {
283                                      ArgumentKind::Regular(ref ty) => ty.span().hi,
284                                      ArgumentKind::Variadic(start) => start + BytePos(3),
285                                  }
286                              },
287                              |arg| {
288                                  match *arg {
289                                      ArgumentKind::Regular(ref ty) => {
290                                          ty.rewrite(context, budget, offset)
291                                      }
292                                      ArgumentKind::Variadic(_) => Some("...".to_owned()),
293                                  }
294                              },
295                              list_lo,
296                              span.hi);
297
298     let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
299
300     let output = match *output {
301         FunctionRetTy::Ty(ref ty) => {
302             let budget = try_opt!(width.checked_sub(4));
303             let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
304             format!(" -> {}", type_str)
305         }
306         FunctionRetTy::None(..) => " -> !".to_owned(),
307         FunctionRetTy::Default(..) => String::new(),
308     };
309
310     let infix = if output.len() > 0 && output.len() + list_str.len() > width {
311         format!("\n{}", (offset - 1).to_string(context.config))
312     } else {
313         String::new()
314     };
315
316     Some(format!("({}){}{}", list_str, infix, output))
317 }
318
319 impl Rewrite for ast::WherePredicate {
320     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
321         // TODO: dead spans?
322         let result = match *self {
323             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
324                                                                            ref bounded_ty,
325                                                                            ref bounds,
326                                                                            .. }) => {
327                 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
328
329                 if !bound_lifetimes.is_empty() {
330                     let lifetime_str = try_opt!(bound_lifetimes.iter()
331                                                                .map(|lt| {
332                                                                    lt.rewrite(context,
333                                                                               width,
334                                                                               offset)
335                                                                })
336                                                                .collect::<Option<Vec<_>>>())
337                                            .join(", ");
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 = try_opt!(bounds.iter()
342                                                     .map(|ty_bound| {
343                                                         ty_bound.rewrite(context,
344                                                                          budget,
345                                                                          offset + used_width)
346                                                     })
347                                                     .collect::<Option<Vec<_>>>())
348                                          .join(" + ");
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 = try_opt!(bounds.iter()
356                                                     .map(|ty_bound| {
357                                                         ty_bound.rewrite(context,
358                                                                          budget,
359                                                                          offset + used_width)
360                                                     })
361                                                     .collect::<Option<Vec<_>>>())
362                                          .join(" + ");
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 = try_opt!(rewrite_path(context,
378                                                      false,
379                                                      None,
380                                                      path,
381                                                      budget,
382                                                      offset + used_width));
383                 format!("{} = {}", path_str, ty_str)
384             }
385         };
386
387         wrap_str(result, context.config.max_width, width, offset)
388     }
389 }
390
391 impl Rewrite for ast::LifetimeDef {
392     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
393         rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
394     }
395 }
396
397 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
398                                    bounds: I,
399                                    context: &RewriteContext,
400                                    width: usize,
401                                    offset: Indent)
402                                    -> Option<String>
403     where I: ExactSizeIterator<Item = &'b ast::Lifetime>
404 {
405     let result = try_opt!(lt.rewrite(context, width, offset));
406
407     if bounds.len() == 0 {
408         Some(result)
409     } else {
410         let appendix: Vec<_> = try_opt!(bounds.into_iter()
411                                               .map(|b| b.rewrite(context, width, offset))
412                                               .collect());
413         let result = format!("{}: {}", result, appendix.join(" + "));
414         wrap_str(result, context.config.max_width, width, offset)
415     }
416 }
417
418 impl Rewrite for ast::TyParamBound {
419     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
420         match *self {
421             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
422                 tref.rewrite(context, width, offset)
423             }
424             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
425                 let budget = try_opt!(width.checked_sub(1));
426                 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
427             }
428             ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
429         }
430     }
431 }
432
433 impl Rewrite for ast::Lifetime {
434     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
435         wrap_str(pprust::lifetime_to_string(self),
436                  context.config.max_width,
437                  width,
438                  offset)
439     }
440 }
441
442 impl Rewrite for ast::TyParamBounds {
443     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
444         let strs: Vec<_> = try_opt!(self.iter()
445                                         .map(|b| b.rewrite(context, width, offset))
446                                         .collect());
447         wrap_str(strs.join(" + "), context.config.max_width, width, offset)
448     }
449 }
450
451 impl Rewrite for ast::TyParam {
452     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
453         let mut result = String::with_capacity(128);
454         result.push_str(&self.ident.to_string());
455         if !self.bounds.is_empty() {
456             result.push_str(": ");
457
458             let bounds = try_opt!(self.bounds
459                                       .iter()
460                                       .map(|ty_bound| ty_bound.rewrite(context, width, offset))
461                                       .collect::<Option<Vec<_>>>())
462                              .join(" + ");
463
464             result.push_str(&bounds);
465         }
466         if let Some(ref def) = self.default {
467
468             let eq_str = match context.config.type_punctuation_density {
469                 TypeDensity::Compressed => "=",
470                 TypeDensity::Wide => " = ",
471             };
472             result.push_str(eq_str);
473             let budget = try_opt!(width.checked_sub(result.len()));
474             let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
475             result.push_str(&rewrite);
476         }
477
478         wrap_str(result, context.config.max_width, width, offset)
479     }
480 }
481
482 impl Rewrite for ast::PolyTraitRef {
483     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
484         if !self.bound_lifetimes.is_empty() {
485             let lifetime_str = try_opt!(self.bound_lifetimes
486                                             .iter()
487                                             .map(|lt| lt.rewrite(context, width, offset))
488                                             .collect::<Option<Vec<_>>>())
489                                    .join(", ");
490             // 6 is "for<> ".len()
491             let extra_offset = lifetime_str.len() + 6;
492             let max_path_width = try_opt!(width.checked_sub(extra_offset));
493             let path_str = try_opt!(self.trait_ref
494                                         .rewrite(context, max_path_width, offset + extra_offset));
495
496             Some(format!("for<{}> {}", lifetime_str, path_str))
497         } else {
498             self.trait_ref.rewrite(context, width, offset)
499         }
500     }
501 }
502
503 impl Rewrite for ast::TraitRef {
504     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
505         rewrite_path(context, false, None, &self.path, width, offset)
506     }
507 }
508
509 impl Rewrite for ast::Ty {
510     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
511         match self.node {
512             ast::TyKind::ObjectSum(ref ty, ref bounds) => {
513                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
514                 let overhead = ty_str.len() + 3;
515                 let plus_str = match context.config.type_punctuation_density {
516                     TypeDensity::Compressed => "+",
517                     TypeDensity::Wide => " + ",
518                 };
519                 Some(format!("{}{}{}",
520                              ty_str,
521                              plus_str,
522                              try_opt!(bounds.rewrite(context,
523                                                      try_opt!(width.checked_sub(overhead)),
524                                                      offset + overhead))))
525             }
526             ast::TyKind::Ptr(ref mt) => {
527                 let prefix = match mt.mutbl {
528                     Mutability::Mutable => "*mut ",
529                     Mutability::Immutable => "*const ",
530                 };
531
532                 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
533             }
534             ast::TyKind::Rptr(ref lifetime, ref mt) => {
535                 let mut_str = format_mutability(mt.mutbl);
536                 let mut_len = mut_str.len();
537                 Some(match *lifetime {
538                     Some(ref lifetime) => {
539                         let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
540                         let lt_str = try_opt!(lifetime.rewrite(context,
541                                                                lt_budget,
542                                                                offset + 2 + mut_len));
543                         let lt_len = lt_str.len();
544                         let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
545                         format!("&{} {}{}",
546                                 lt_str,
547                                 mut_str,
548                                 try_opt!(mt.ty.rewrite(context,
549                                                        budget,
550                                                        offset + 2 + mut_len + lt_len)))
551                     }
552                     None => {
553                         let budget = try_opt!(width.checked_sub(1 + mut_len));
554                         format!("&{}{}",
555                                 mut_str,
556                                 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
557                     }
558                 })
559             }
560             // FIXME: we drop any comments here, even though it's a silly place to put
561             // comments.
562             ast::TyKind::Paren(ref ty) => {
563                 let budget = try_opt!(width.checked_sub(2));
564                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
565             }
566             ast::TyKind::Vec(ref ty) => {
567                 let budget = try_opt!(width.checked_sub(2));
568                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
569             }
570             ast::TyKind::Tup(ref items) => {
571                 rewrite_tuple(context,
572                               items.iter().map(|x| &**x),
573                               self.span,
574                               width,
575                               offset)
576             }
577             ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
578             ast::TyKind::Path(ref q_self, ref path) => {
579                 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
580             }
581             ast::TyKind::FixedLengthVec(ref ty, ref repeats) => {
582                 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
583             }
584             ast::TyKind::Infer => {
585                 if width >= 1 {
586                     Some("_".to_owned())
587                 } else {
588                     None
589                 }
590             }
591             ast::TyKind::BareFn(ref bare_fn) => {
592                 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
593             }
594             ast::TyKind::Mac(..) |
595             ast::TyKind::Typeof(..) => unreachable!(),
596         }
597     }
598 }
599
600 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
601                    span: Span,
602                    context: &RewriteContext,
603                    width: usize,
604                    offset: Indent)
605                    -> Option<String> {
606     let mut result = String::with_capacity(128);
607
608     result.push_str(&::utils::format_unsafety(bare_fn.unsafety));
609
610     if bare_fn.abi != abi::Abi::Rust {
611         result.push_str(&::utils::format_abi(bare_fn.abi));
612     }
613
614     result.push_str("fn");
615
616     let budget = try_opt!(width.checked_sub(result.len()));
617     let indent = offset + result.len();
618
619     let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
620                                                 &bare_fn.decl.output,
621                                                 bare_fn.decl.variadic,
622                                                 span,
623                                                 context,
624                                                 budget,
625                                                 indent));
626
627     result.push_str(&rewrite);
628
629     Some(result)
630 }