]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Merge pull request #740 from svmnotn/less_tmp_files
[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_or(0, |x| x.position);
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) => lt.rewrite(context, width, offset),
139             SegmentParam::Type(ref ty) => ty.rewrite(context, width, offset),
140             SegmentParam::Binding(ref binding) => {
141                 let mut result = format!("{} = ", binding.ident);
142                 let budget = try_opt!(width.checked_sub(result.len()));
143                 let rewrite = try_opt!(binding.ty.rewrite(context, budget, offset + result.len()));
144                 result.push_str(&rewrite);
145                 Some(result)
146             }
147         }
148     }
149 }
150
151 // Formats a path segment. There are some hacks involved to correctly determine
152 // the segment's associated span since it's not part of the AST.
153 //
154 // The span_lo is assumed to be greater than the end of any previous segment's
155 // parameters and lesser or equal than the start of current segment.
156 //
157 // span_hi is assumed equal to the end of the entire path.
158 //
159 // When the segment contains a positive number of parameters, we update span_lo
160 // so that invariants described above will hold for the next segment.
161 fn rewrite_segment(expr_context: bool,
162                    segment: &ast::PathSegment,
163                    span_lo: &mut BytePos,
164                    span_hi: BytePos,
165                    context: &RewriteContext,
166                    width: usize,
167                    offset: Indent)
168                    -> Option<String> {
169     let ident_len = segment.identifier.to_string().len();
170     let width = try_opt!(width.checked_sub(ident_len));
171     let offset = offset + ident_len;
172
173     let params = match segment.parameters {
174         ast::PathParameters::AngleBracketedParameters(ref data) if !data.lifetimes.is_empty() ||
175                                                                    !data.types.is_empty() ||
176                                                                    !data.bindings.is_empty() => {
177             let param_list = data.lifetimes
178                                  .iter()
179                                  .map(SegmentParam::LifeTime)
180                                  .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
181                                  .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
182                                  .collect::<Vec<_>>();
183
184             let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
185             let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi), "<", context.codemap);
186             let separator = if expr_context {
187                 "::"
188             } else {
189                 ""
190             };
191
192             // 1 for <
193             let extra_offset = 1 + separator.len();
194             // 1 for >
195             let list_width = try_opt!(width.checked_sub(extra_offset + 1));
196
197             let items = itemize_list(context.codemap,
198                                      param_list.into_iter(),
199                                      ">",
200                                      |param| param.get_span().lo,
201                                      |param| param.get_span().hi,
202                                      |seg| seg.rewrite(context, list_width, offset + extra_offset),
203                                      list_lo,
204                                      span_hi);
205             let list_str = try_opt!(format_item_list(items,
206                                                      list_width,
207                                                      offset + extra_offset,
208                                                      context.config));
209
210             // Update position of last bracket.
211             *span_lo = next_span_lo;
212
213             format!("{}<{}>", separator, list_str)
214         }
215         ast::PathParameters::ParenthesizedParameters(ref data) => {
216             let output = match data.output {
217                 Some(ref ty) => FunctionRetTy::Return(ty.clone()),
218                 None => FunctionRetTy::DefaultReturn(codemap::DUMMY_SP),
219             };
220             try_opt!(format_function_type(data.inputs.iter().map(|x| &**x),
221                                           &output,
222                                           data.span,
223                                           context,
224                                           width,
225                                           offset))
226         }
227         _ => String::new(),
228     };
229
230     Some(format!("{}{}", segment.identifier, params))
231 }
232
233 fn format_function_type<'a, I>(inputs: I,
234                                output: &FunctionRetTy,
235                                span: Span,
236                                context: &RewriteContext,
237                                width: usize,
238                                offset: Indent)
239                                -> Option<String>
240     where I: ExactSizeIterator,
241           <I as Iterator>::Item: Deref,
242           <I::Item as Deref>::Target: Rewrite + Spanned + 'a
243 {
244     // 2 for ()
245     let budget = try_opt!(width.checked_sub(2));
246     // 1 for (
247     let offset = offset + 1;
248     let list_lo = span_after(span, "(", context.codemap);
249     let items = itemize_list(context.codemap,
250                              inputs,
251                              ")",
252                              |ty| ty.span().lo,
253                              |ty| ty.span().hi,
254                              |ty| ty.rewrite(context, budget, offset),
255                              list_lo,
256                              span.hi);
257
258     let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
259
260     let output = match *output {
261         FunctionRetTy::Return(ref ty) => {
262             let budget = try_opt!(width.checked_sub(4));
263             let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
264             format!(" -> {}", type_str)
265         }
266         FunctionRetTy::NoReturn(..) => " -> !".to_owned(),
267         FunctionRetTy::DefaultReturn(..) => String::new(),
268     };
269
270     let infix = if output.len() + list_str.len() > width {
271         format!("\n{}", (offset - 1).to_string(context.config))
272     } else {
273         String::new()
274     };
275
276     Some(format!("({}){}{}", list_str, infix, output))
277 }
278
279 impl Rewrite for ast::WherePredicate {
280     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
281         // TODO: dead spans?
282         let result = match *self {
283             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
284                                                                            ref bounded_ty,
285                                                                            ref bounds,
286                                                                            .. }) => {
287                 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
288
289                 if !bound_lifetimes.is_empty() {
290                     let lifetime_str = try_opt!(bound_lifetimes.iter()
291                                                                .map(|lt| {
292                                                                    lt.rewrite(context,
293                                                                               width,
294                                                                               offset)
295                                                                })
296                                                                .collect::<Option<Vec<_>>>())
297                                            .join(", ");
298                     // 8 = "for<> : ".len()
299                     let used_width = lifetime_str.len() + type_str.len() + 8;
300                     let budget = try_opt!(width.checked_sub(used_width));
301                     let bounds_str = try_opt!(bounds.iter()
302                                                     .map(|ty_bound| {
303                                                         ty_bound.rewrite(context,
304                                                                          budget,
305                                                                          offset + used_width)
306                                                     })
307                                                     .collect::<Option<Vec<_>>>())
308                                          .join(" + ");
309
310                     format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
311                 } else {
312                     // 2 = ": ".len()
313                     let used_width = type_str.len() + 2;
314                     let budget = try_opt!(width.checked_sub(used_width));
315                     let bounds_str = try_opt!(bounds.iter()
316                                                     .map(|ty_bound| {
317                                                         ty_bound.rewrite(context,
318                                                                          budget,
319                                                                          offset + used_width)
320                                                     })
321                                                     .collect::<Option<Vec<_>>>())
322                                          .join(" + ");
323
324                     format!("{}: {}", type_str, bounds_str)
325                 }
326             }
327             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
328                                                                              ref bounds,
329                                                                              .. }) => {
330                 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
331             }
332             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
333                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
334                 // 3 = " = ".len()
335                 let used_width = 3 + ty_str.len();
336                 let budget = try_opt!(width.checked_sub(used_width));
337                 let path_str = try_opt!(rewrite_path(context,
338                                                      false,
339                                                      None,
340                                                      path,
341                                                      budget,
342                                                      offset + used_width));
343                 format!("{} = {}", path_str, ty_str)
344             }
345         };
346
347         wrap_str(result, context.config.max_width, width, offset)
348     }
349 }
350
351 impl Rewrite for ast::LifetimeDef {
352     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
353         rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
354     }
355 }
356
357 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
358                                    bounds: I,
359                                    context: &RewriteContext,
360                                    width: usize,
361                                    offset: Indent)
362                                    -> Option<String>
363     where I: ExactSizeIterator<Item = &'b ast::Lifetime>
364 {
365     let result = try_opt!(lt.rewrite(context, width, offset));
366
367     if bounds.len() == 0 {
368         Some(result)
369     } else {
370         let appendix: Vec<_> = try_opt!(bounds.into_iter()
371                                               .map(|b| b.rewrite(context, width, offset))
372                                               .collect());
373         let result = format!("{}: {}", result, appendix.join(" + "));
374         wrap_str(result, context.config.max_width, width, offset)
375     }
376 }
377
378 impl Rewrite for ast::TyParamBound {
379     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
380         match *self {
381             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
382                 tref.rewrite(context, width, offset)
383             }
384             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
385                 let budget = try_opt!(width.checked_sub(1));
386                 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
387             }
388             ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
389         }
390     }
391 }
392
393 impl Rewrite for ast::Lifetime {
394     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
395         wrap_str(pprust::lifetime_to_string(self),
396                  context.config.max_width,
397                  width,
398                  offset)
399     }
400 }
401
402 impl Rewrite for ast::TyParamBounds {
403     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
404         let strs: Vec<_> = try_opt!(self.iter()
405                                         .map(|b| b.rewrite(context, width, offset))
406                                         .collect());
407         wrap_str(strs.join(" + "), context.config.max_width, width, offset)
408     }
409 }
410
411 impl Rewrite for ast::TyParam {
412     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
413         let mut result = String::with_capacity(128);
414         result.push_str(&self.ident.to_string());
415         if !self.bounds.is_empty() {
416             result.push_str(": ");
417
418             let bounds = try_opt!(self.bounds
419                                       .iter()
420                                       .map(|ty_bound| ty_bound.rewrite(context, width, offset))
421                                       .collect::<Option<Vec<_>>>())
422                              .join(" + ");
423
424             result.push_str(&bounds);
425         }
426         if let Some(ref def) = self.default {
427             result.push_str(" = ");
428             let budget = try_opt!(width.checked_sub(result.len()));
429             let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
430             result.push_str(&rewrite);
431         }
432
433         wrap_str(result, context.config.max_width, width, offset)
434     }
435 }
436
437 impl Rewrite for ast::PolyTraitRef {
438     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
439         if !self.bound_lifetimes.is_empty() {
440             let lifetime_str = try_opt!(self.bound_lifetimes
441                                             .iter()
442                                             .map(|lt| lt.rewrite(context, width, offset))
443                                             .collect::<Option<Vec<_>>>())
444                                    .join(", ");
445             // 6 is "for<> ".len()
446             let extra_offset = lifetime_str.len() + 6;
447             let max_path_width = try_opt!(width.checked_sub(extra_offset));
448             let path_str = try_opt!(self.trait_ref
449                                         .rewrite(context, max_path_width, offset + extra_offset));
450
451             Some(format!("for<{}> {}", lifetime_str, path_str))
452         } else {
453             self.trait_ref.rewrite(context, width, offset)
454         }
455     }
456 }
457
458 impl Rewrite for ast::TraitRef {
459     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
460         rewrite_path(context, false, None, &self.path, width, offset)
461     }
462 }
463
464 impl Rewrite for ast::Ty {
465     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
466         match self.node {
467             ast::TyObjectSum(ref ty, ref bounds) => {
468                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
469                 let overhead = ty_str.len() + 3;
470                 Some(format!("{} + {}",
471                              ty_str,
472                              try_opt!(bounds.rewrite(context,
473                                                      try_opt!(width.checked_sub(overhead)),
474                                                      offset + overhead))))
475             }
476             ast::TyPtr(ref mt) => {
477                 let prefix = match mt.mutbl {
478                     Mutability::MutMutable => "*mut ",
479                     Mutability::MutImmutable => "*const ",
480                 };
481
482                 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
483             }
484             ast::TyRptr(ref lifetime, ref mt) => {
485                 let mut_str = format_mutability(mt.mutbl);
486                 let mut_len = mut_str.len();
487                 Some(match *lifetime {
488                     Some(ref lifetime) => {
489                         let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
490                         let lt_str = try_opt!(lifetime.rewrite(context,
491                                                                lt_budget,
492                                                                offset + 2 + mut_len));
493                         let lt_len = lt_str.len();
494                         let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
495                         format!("&{} {}{}",
496                                 lt_str,
497                                 mut_str,
498                                 try_opt!(mt.ty.rewrite(context,
499                                                        budget,
500                                                        offset + 2 + mut_len + lt_len)))
501                     }
502                     None => {
503                         let budget = try_opt!(width.checked_sub(1 + mut_len));
504                         format!("&{}{}",
505                                 mut_str,
506                                 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
507                     }
508                 })
509             }
510             // FIXME: we drop any comments here, even though it's a silly place to put
511             // comments.
512             ast::TyParen(ref ty) => {
513                 let budget = try_opt!(width.checked_sub(2));
514                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
515             }
516             ast::TyVec(ref ty) => {
517                 let budget = try_opt!(width.checked_sub(2));
518                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
519             }
520             ast::TyTup(ref items) => {
521                 rewrite_tuple(context,
522                               items.iter().map(|x| &**x),
523                               self.span,
524                               width,
525                               offset)
526             }
527             ast::TyPolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
528             ast::TyPath(ref q_self, ref path) => {
529                 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
530             }
531             ast::TyFixedLengthVec(ref ty, ref repeats) => {
532                 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
533             }
534             ast::TyInfer => {
535                 if width >= 1 {
536                     Some("_".to_owned())
537                 } else {
538                     None
539                 }
540             }
541             ast::TyBareFn(ref bare_fn) => {
542                 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
543             }
544             ast::TyMac(..) | ast::TyTypeof(..) => unreachable!(),
545         }
546     }
547 }
548
549 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
550                    span: Span,
551                    context: &RewriteContext,
552                    width: usize,
553                    offset: Indent)
554                    -> Option<String> {
555     let mut result = String::with_capacity(128);
556
557     result.push_str(&::utils::format_unsafety(bare_fn.unsafety));
558
559     if bare_fn.abi != abi::Rust {
560         result.push_str(&::utils::format_abi(bare_fn.abi));
561     }
562
563     result.push_str("fn");
564
565     let budget = try_opt!(width.checked_sub(result.len()));
566     let indent = offset + result.len();
567
568     let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
569                                                 &bare_fn.decl.output,
570                                                 span,
571                                                 context,
572                                                 budget,
573                                                 indent));
574
575     result.push_str(&rewrite);
576
577     Some(result)
578 }