]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Fix up indentation of function style paths
[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 syntax::ast::{self, Mutability};
12 use syntax::print::pprust;
13 use syntax::codemap::{self, Span, BytePos};
14
15 use Indent;
16 use lists::{format_item_list, itemize_list, format_fn_args};
17 use rewrite::{Rewrite, RewriteContext};
18 use utils::{extra_offset, span_after, format_mutability, wrap_str};
19 use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
20
21 // Does not wrap on simple segments.
22 pub fn rewrite_path(context: &RewriteContext,
23                     expr_context: bool,
24                     qself: Option<&ast::QSelf>,
25                     path: &ast::Path,
26                     width: usize,
27                     offset: Indent)
28                     -> Option<String> {
29     let skip_count = qself.map(|x| x.position).unwrap_or(0);
30
31     let mut result = if path.global {
32         "::".to_owned()
33     } else {
34         String::new()
35     };
36
37     let mut span_lo = path.span.lo;
38
39     if let Some(ref qself) = qself {
40         result.push('<');
41         let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
42         result.push_str(&fmt_ty);
43
44         if skip_count > 0 {
45             result.push_str(" as ");
46
47             let extra_offset = extra_offset(&result, offset);
48             // 3 = ">::".len()
49             let budget = try_opt!(width.checked_sub(extra_offset + 3));
50
51             result = try_opt!(rewrite_path_segments(expr_context,
52                                                     result,
53                                                     path.segments.iter().take(skip_count),
54                                                     span_lo,
55                                                     path.span.hi,
56                                                     context,
57                                                     budget,
58                                                     offset + extra_offset));
59         }
60
61         result.push_str(">::");
62         span_lo = qself.ty.span.hi + BytePos(1);
63     }
64
65     let extra_offset = extra_offset(&result, offset);
66     let budget = try_opt!(width.checked_sub(extra_offset));
67     rewrite_path_segments(expr_context,
68                           result,
69                           path.segments.iter().skip(skip_count),
70                           span_lo,
71                           path.span.hi,
72                           context,
73                           budget,
74                           offset + extra_offset)
75 }
76
77 fn rewrite_path_segments<'a, I>(expr_context: bool,
78                                 mut buffer: String,
79                                 iter: I,
80                                 mut span_lo: BytePos,
81                                 span_hi: BytePos,
82                                 context: &RewriteContext,
83                                 width: usize,
84                                 offset: Indent)
85                                 -> Option<String>
86     where I: Iterator<Item = &'a ast::PathSegment>
87 {
88     let mut first = true;
89
90     for segment in iter {
91         if first {
92             first = false;
93         } else {
94             buffer.push_str("::");
95         }
96
97         let extra_offset = extra_offset(&buffer, offset);
98         let remaining_width = try_opt!(width.checked_sub(extra_offset));
99         let new_offset = offset + extra_offset;
100         let segment_string = try_opt!(rewrite_segment(expr_context,
101                                                       segment,
102                                                       &mut span_lo,
103                                                       span_hi,
104                                                       context,
105                                                       remaining_width,
106                                                       new_offset));
107
108         buffer.push_str(&segment_string);
109     }
110
111     Some(buffer)
112 }
113
114 #[derive(Debug)]
115 enum SegmentParam<'a> {
116     LifeTime(&'a ast::Lifetime),
117     Type(&'a ast::Ty),
118     Binding(&'a ast::TypeBinding),
119 }
120
121 impl<'a> SegmentParam<'a> {
122     fn get_span(&self) -> Span {
123         match *self {
124             SegmentParam::LifeTime(ref lt) => lt.span,
125             SegmentParam::Type(ref ty) => ty.span,
126             SegmentParam::Binding(ref binding) => binding.span,
127         }
128     }
129 }
130
131 impl<'a> Rewrite for SegmentParam<'a> {
132     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
133         match *self {
134             SegmentParam::LifeTime(ref lt) => {
135                 wrap_str(pprust::lifetime_to_string(lt),
136                          context.config.max_width,
137                          width,
138                          offset)
139             }
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::AngleBracketedParameters(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 = span_after(codemap::mk_sp(*span_lo, span_hi), "<", context.codemap);
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::ParenthesizedParameters(ref data) => {
217             // 2 for ()
218             let budget = try_opt!(width.checked_sub(2));
219             // 1 for (
220             let offset = offset + 1;
221             let list_lo = span_after(data.span, "(", context.codemap);
222             let items = itemize_list(context.codemap,
223                                      data.inputs.iter(),
224                                      ")",
225                                      |ty| ty.span.lo,
226                                      |ty| ty.span.hi,
227                                      |ty| ty.rewrite(context, budget, offset),
228                                      list_lo,
229                                      span_hi);
230             println!("got here");
231
232             let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
233
234             println!("got here 2");
235             let output = match data.output {
236                 Some(ref ty) => {
237                     let budget = try_opt!(width.checked_sub(4));
238                     let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
239                     format!(" -> {}", type_str)
240                 }
241                 None => String::new(),
242             };
243
244             println!("got here 3");
245
246             let infix = if output.len() + list_str.len() > width {
247                 format!("\n{}", (offset - 1).to_string(context.config))
248             } else {
249                 String::new()
250             };
251             println!("({}){}{}", &list_str, &infix, &output);
252
253             format!("({}){}{}", list_str, infix, output)
254         }
255         _ => String::new(),
256     };
257
258     Some(format!("{}{}", segment.identifier, params))
259 }
260
261 impl Rewrite for ast::WherePredicate {
262     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
263         // TODO: dead spans?
264         let result = match *self {
265             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
266                                                                            ref bounded_ty,
267                                                                            ref bounds,
268                                                                            .. }) => {
269                 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
270
271                 if !bound_lifetimes.is_empty() {
272                     let lifetime_str = try_opt!(bound_lifetimes.iter()
273                                                                .map(|lt| {
274                                                                    lt.rewrite(context,
275                                                                               width,
276                                                                               offset)
277                                                                })
278                                                                .collect::<Option<Vec<_>>>())
279                                            .join(", ");
280                     // 8 = "for<> : ".len()
281                     let used_width = lifetime_str.len() + type_str.len() + 8;
282                     let budget = try_opt!(width.checked_sub(used_width));
283                     let bounds_str = try_opt!(bounds.iter()
284                                                     .map(|ty_bound| {
285                                                         ty_bound.rewrite(context,
286                                                                          budget,
287                                                                          offset + used_width)
288                                                     })
289                                                     .collect::<Option<Vec<_>>>())
290                                          .join(" + ");
291
292                     format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
293                 } else {
294                     // 2 = ": ".len()
295                     let used_width = type_str.len() + 2;
296                     let budget = try_opt!(width.checked_sub(used_width));
297                     let bounds_str = try_opt!(bounds.iter()
298                                                     .map(|ty_bound| {
299                                                         ty_bound.rewrite(context,
300                                                                          budget,
301                                                                          offset + used_width)
302                                                     })
303                                                     .collect::<Option<Vec<_>>>())
304                                          .join(" + ");
305
306                     format!("{}: {}", type_str, bounds_str)
307                 }
308             }
309             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
310                                                                              ref bounds,
311                                                                              .. }) => {
312                 format!("{}: {}",
313                         pprust::lifetime_to_string(lifetime),
314                         bounds.iter()
315                               .map(pprust::lifetime_to_string)
316                               .collect::<Vec<_>>()
317                               .join(" + "))
318             }
319             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
320                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
321                 // 3 = " = ".len()
322                 let used_width = 3 + ty_str.len();
323                 let budget = try_opt!(width.checked_sub(used_width));
324                 let path_str = try_opt!(rewrite_path(context,
325                                                      false,
326                                                      None,
327                                                      path,
328                                                      budget,
329                                                      offset + used_width));
330                 format!("{} = {}", path_str, ty_str)
331             }
332         };
333
334         wrap_str(result, context.config.max_width, width, offset)
335     }
336 }
337
338 impl Rewrite for ast::LifetimeDef {
339     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
340         let result = if self.bounds.is_empty() {
341             pprust::lifetime_to_string(&self.lifetime)
342         } else {
343             format!("{}: {}",
344                     pprust::lifetime_to_string(&self.lifetime),
345                     self.bounds
346                         .iter()
347                         .map(pprust::lifetime_to_string)
348                         .collect::<Vec<_>>()
349                         .join(" + "))
350         };
351
352         wrap_str(result, context.config.max_width, width, offset)
353     }
354 }
355
356 impl Rewrite for ast::TyParamBound {
357     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
358         match *self {
359             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
360                 tref.rewrite(context, width, offset)
361             }
362             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
363                 let budget = try_opt!(width.checked_sub(1));
364                 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
365             }
366             ast::TyParamBound::RegionTyParamBound(ref l) => {
367                 wrap_str(pprust::lifetime_to_string(l),
368                          context.config.max_width,
369                          width,
370                          offset)
371             }
372         }
373     }
374 }
375
376 impl Rewrite for ast::TyParamBounds {
377     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
378         let strs: Vec<_> = try_opt!(self.iter()
379                                         .map(|b| b.rewrite(context, width, offset))
380                                         .collect());
381         wrap_str(strs.join(" + "), context.config.max_width, width, offset)
382     }
383 }
384
385 impl Rewrite for ast::TyParam {
386     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
387         let mut result = String::with_capacity(128);
388         result.push_str(&self.ident.to_string());
389         if !self.bounds.is_empty() {
390             result.push_str(": ");
391
392             let bounds = try_opt!(self.bounds
393                                       .iter()
394                                       .map(|ty_bound| ty_bound.rewrite(context, width, offset))
395                                       .collect::<Option<Vec<_>>>())
396                              .join(" + ");
397
398             result.push_str(&bounds);
399         }
400         if let Some(ref def) = self.default {
401             result.push_str(" = ");
402             let budget = try_opt!(width.checked_sub(result.len()));
403             let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
404             result.push_str(&rewrite);
405         }
406
407         wrap_str(result, context.config.max_width, width, offset)
408     }
409 }
410
411 impl Rewrite for ast::PolyTraitRef {
412     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
413         if !self.bound_lifetimes.is_empty() {
414             let lifetime_str = try_opt!(self.bound_lifetimes
415                                             .iter()
416                                             .map(|lt| lt.rewrite(context, width, offset))
417                                             .collect::<Option<Vec<_>>>())
418                                    .join(", ");
419             // 6 is "for<> ".len()
420             let extra_offset = lifetime_str.len() + 6;
421             let max_path_width = try_opt!(width.checked_sub(extra_offset));
422             let path_str = try_opt!(rewrite_path(context,
423                                                  false,
424                                                  None,
425                                                  &self.trait_ref.path,
426                                                  max_path_width,
427                                                  offset + extra_offset));
428
429             Some(format!("for<{}> {}", lifetime_str, path_str))
430         } else {
431             rewrite_path(context, false, None, &self.trait_ref.path, width, offset)
432         }
433     }
434 }
435
436 impl Rewrite for ast::Ty {
437     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
438         match self.node {
439             ast::TyObjectSum(ref ty, ref bounds) => {
440                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
441                 let overhead = ty_str.len() + 3;
442                 Some(format!("{} + {}",
443                              ty_str,
444                              try_opt!(bounds.rewrite(context,
445                                                      try_opt!(width.checked_sub(overhead)),
446                                                      offset + overhead))))
447             }
448             ast::TyPtr(ref mt) => {
449                 let prefix = match mt.mutbl {
450                     Mutability::MutMutable => "*mut ",
451                     Mutability::MutImmutable => "*const ",
452                 };
453
454                 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
455             }
456             ast::TyRptr(ref lifetime, ref mt) => {
457                 let mut_str = format_mutability(mt.mutbl);
458                 let mut_len = mut_str.len();
459                 Some(match *lifetime {
460                     Some(ref lifetime) => {
461                         let lt_str = pprust::lifetime_to_string(lifetime);
462                         let lt_len = lt_str.len();
463                         let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
464                         format!("&{} {}{}",
465                                 lt_str,
466                                 mut_str,
467                                 try_opt!(mt.ty.rewrite(context,
468                                                        budget,
469                                                        offset + 2 + mut_len + lt_len)))
470                     }
471                     None => {
472                         let budget = try_opt!(width.checked_sub(1 + mut_len));
473                         format!("&{}{}",
474                                 mut_str,
475                                 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
476                     }
477                 })
478             }
479             // FIXME: we drop any comments here, even though it's a silly place to put
480             // comments.
481             ast::TyParen(ref ty) => {
482                 let budget = try_opt!(width.checked_sub(2));
483                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
484             }
485             ast::TyVec(ref ty) => {
486                 let budget = try_opt!(width.checked_sub(2));
487                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
488             }
489             ast::TyTup(ref items) => rewrite_tuple(context, items, self.span, width, offset),
490             ast::TyPolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
491             ast::TyPath(ref q_self, ref path) => {
492                 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
493             }
494             ast::TyFixedLengthVec(ref ty, ref repeats) => {
495                 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
496             }
497             ast::TyInfer => {
498                 if width >= 1 {
499                     Some("_".to_owned())
500                 } else {
501                     None
502                 }
503             }
504             ast::TyBareFn(ref bare_fn) => bare_fn.rewrite(context, width, offset),
505             ast::TyMac(..) | ast::TyTypeof(..) => unreachable!(),
506         }
507     }
508 }
509
510 impl Rewrite for ast::BareFnTy {
511     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
512         None
513     }
514 }