]> git.lizzy.rs Git - rust.git/blob - src/types.rs
Merge pull request #634 from Marwes/block_comment_crlf
[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| {
204                                          seg.rewrite(context,
205                                                      context.config.max_width,
206                                                      offset + extra_offset)
207                                      },
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) => {
223                     let type_str = try_opt!(ty.rewrite(context, width, offset));
224                     format!(" -> {}", type_str)
225                 }
226                 None => String::new(),
227             };
228
229             // 2 for ()
230             let budget = try_opt!(width.checked_sub(output.len() + 2));
231             // 1 for (
232             let offset = offset + 1;
233             let list_lo = span_after(data.span, "(", context.codemap);
234             let items = itemize_list(context.codemap,
235                                      data.inputs.iter(),
236                                      ")",
237                                      |ty| ty.span.lo,
238                                      |ty| ty.span.hi,
239                                      |ty| ty.rewrite(context, budget, offset),
240                                      list_lo,
241                                      span_hi);
242             let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
243
244             format!("({}){}", list_str, output)
245         }
246         _ => String::new(),
247     };
248
249     Some(format!("{}{}", segment.identifier, params))
250 }
251
252 impl Rewrite for ast::WherePredicate {
253     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
254         // TODO: dead spans?
255         let result = match *self {
256             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
257                                                                            ref bounded_ty,
258                                                                            ref bounds,
259                                                                            .. }) => {
260                 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
261
262                 if !bound_lifetimes.is_empty() {
263                     let lifetime_str = try_opt!(bound_lifetimes.iter()
264                                                                .map(|lt| {
265                                                                    lt.rewrite(context,
266                                                                               width,
267                                                                               offset)
268                                                                })
269                                                                .collect::<Option<Vec<_>>>())
270                                            .join(", ");
271                     // 8 = "for<> : ".len()
272                     let used_width = lifetime_str.len() + type_str.len() + 8;
273                     let budget = try_opt!(width.checked_sub(used_width));
274                     let bounds_str = try_opt!(bounds.iter()
275                                                     .map(|ty_bound| {
276                                                         ty_bound.rewrite(context,
277                                                                          budget,
278                                                                          offset + used_width)
279                                                     })
280                                                     .collect::<Option<Vec<_>>>())
281                                          .join(" + ");
282
283                     format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
284                 } else {
285                     // 2 = ": ".len()
286                     let used_width = type_str.len() + 2;
287                     let budget = try_opt!(width.checked_sub(used_width));
288                     let bounds_str = try_opt!(bounds.iter()
289                                                     .map(|ty_bound| {
290                                                         ty_bound.rewrite(context,
291                                                                          budget,
292                                                                          offset + used_width)
293                                                     })
294                                                     .collect::<Option<Vec<_>>>())
295                                          .join(" + ");
296
297                     format!("{}: {}", type_str, bounds_str)
298                 }
299             }
300             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
301                                                                              ref bounds,
302                                                                              .. }) => {
303                 format!("{}: {}",
304                         pprust::lifetime_to_string(lifetime),
305                         bounds.iter()
306                               .map(pprust::lifetime_to_string)
307                               .collect::<Vec<_>>()
308                               .join(" + "))
309             }
310             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
311                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
312                 // 3 = " = ".len()
313                 let used_width = 3 + ty_str.len();
314                 let budget = try_opt!(width.checked_sub(used_width));
315                 let path_str = try_opt!(rewrite_path(context,
316                                                      false,
317                                                      None,
318                                                      path,
319                                                      budget,
320                                                      offset + used_width));
321                 format!("{} = {}", path_str, ty_str)
322             }
323         };
324
325         wrap_str(result, context.config.max_width, width, offset)
326     }
327 }
328
329 impl Rewrite for ast::LifetimeDef {
330     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
331         let result = if self.bounds.is_empty() {
332             pprust::lifetime_to_string(&self.lifetime)
333         } else {
334             format!("{}: {}",
335                     pprust::lifetime_to_string(&self.lifetime),
336                     self.bounds
337                         .iter()
338                         .map(pprust::lifetime_to_string)
339                         .collect::<Vec<_>>()
340                         .join(" + "))
341         };
342
343         wrap_str(result, context.config.max_width, width, offset)
344     }
345 }
346
347 impl Rewrite for ast::TyParamBound {
348     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
349         match *self {
350             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
351                 tref.rewrite(context, width, offset)
352             }
353             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
354                 let budget = try_opt!(width.checked_sub(1));
355                 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
356             }
357             ast::TyParamBound::RegionTyParamBound(ref l) => {
358                 wrap_str(pprust::lifetime_to_string(l),
359                          context.config.max_width,
360                          width,
361                          offset)
362             }
363         }
364     }
365 }
366
367 impl Rewrite for ast::TyParamBounds {
368     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
369         let strs: Vec<_> = try_opt!(self.iter()
370                                         .map(|b| b.rewrite(context, width, offset))
371                                         .collect());
372         wrap_str(strs.join(" + "), context.config.max_width, width, offset)
373     }
374 }
375
376 impl Rewrite for ast::TyParam {
377     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
378         let mut result = String::with_capacity(128);
379         result.push_str(&self.ident.to_string());
380         if !self.bounds.is_empty() {
381             result.push_str(": ");
382
383             let bounds = try_opt!(self.bounds
384                                       .iter()
385                                       .map(|ty_bound| ty_bound.rewrite(context, width, offset))
386                                       .collect::<Option<Vec<_>>>())
387                              .join(" + ");
388
389             result.push_str(&bounds);
390         }
391         if let Some(ref def) = self.default {
392             result.push_str(" = ");
393             let budget = try_opt!(width.checked_sub(result.len()));
394             let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
395             result.push_str(&rewrite);
396         }
397
398         wrap_str(result, context.config.max_width, width, offset)
399     }
400 }
401
402 impl Rewrite for ast::PolyTraitRef {
403     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
404         if !self.bound_lifetimes.is_empty() {
405             let lifetime_str = try_opt!(self.bound_lifetimes
406                                             .iter()
407                                             .map(|lt| lt.rewrite(context, width, offset))
408                                             .collect::<Option<Vec<_>>>())
409                                    .join(", ");
410             // 6 is "for<> ".len()
411             let extra_offset = lifetime_str.len() + 6;
412             let max_path_width = try_opt!(width.checked_sub(extra_offset));
413             let path_str = try_opt!(rewrite_path(context,
414                                                  false,
415                                                  None,
416                                                  &self.trait_ref.path,
417                                                  max_path_width,
418                                                  offset + extra_offset));
419
420             Some(format!("for<{}> {}", lifetime_str, path_str))
421         } else {
422             rewrite_path(context, false, None, &self.trait_ref.path, width, offset)
423         }
424     }
425 }
426
427 impl Rewrite for ast::Ty {
428     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
429         match self.node {
430             ast::TyObjectSum(ref ty, ref bounds) => {
431                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
432                 let overhead = ty_str.len() + 3;
433                 Some(format!("{} + {}",
434                              ty_str,
435                              try_opt!(bounds.rewrite(context,
436                                                      try_opt!(width.checked_sub(overhead)),
437                                                      offset + overhead))))
438             }
439             ast::TyPtr(ref mt) => {
440                 let prefix = match mt.mutbl {
441                     Mutability::MutMutable => "*mut ",
442                     Mutability::MutImmutable => "*const ",
443                 };
444
445                 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
446             }
447             ast::TyRptr(ref lifetime, ref mt) => {
448                 let mut_str = format_mutability(mt.mutbl);
449                 let mut_len = mut_str.len();
450                 Some(match *lifetime {
451                     Some(ref lifetime) => {
452                         let lt_str = pprust::lifetime_to_string(lifetime);
453                         let lt_len = lt_str.len();
454                         let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
455                         format!("&{} {}{}",
456                                 lt_str,
457                                 mut_str,
458                                 try_opt!(mt.ty.rewrite(context,
459                                                        budget,
460                                                        offset + 2 + mut_len + lt_len)))
461                     }
462                     None => {
463                         let budget = try_opt!(width.checked_sub(1 + mut_len));
464                         format!("&{}{}",
465                                 mut_str,
466                                 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
467                     }
468                 })
469             }
470             // FIXME: we drop any comments here, even though it's a silly place to put
471             // comments.
472             ast::TyParen(ref ty) => {
473                 let budget = try_opt!(width.checked_sub(2));
474                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
475             }
476             ast::TyVec(ref ty) => {
477                 let budget = try_opt!(width.checked_sub(2));
478                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
479             }
480             ast::TyTup(ref items) => rewrite_tuple(context, items, self.span, width, offset),
481             ast::TyPolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
482             ast::TyPath(ref q_self, ref path) => {
483                 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
484             }
485             ast::TyFixedLengthVec(ref ty, ref repeats) => {
486                 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
487             }
488             ast::TyInfer => {
489                 if width >= 1 {
490                     Some("_".to_owned())
491                 } else {
492                     None
493                 }
494             }
495             ast::TyBareFn(..) => {
496                 wrap_str(pprust::ty_to_string(self),
497                          context.config.max_width,
498                          width,
499                          offset)
500             }
501             ast::TyMac(..) | ast::TyTypeof(..) => unreachable!(),
502         }
503     }
504 }