]> git.lizzy.rs Git - rust.git/blob - src/types.rs
utils: Move codemap related utilities to a dedicated module
[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 codemap::SpanUtils;
21 use lists::{format_item_list, itemize_list, format_fn_args};
22 use rewrite::{Rewrite, RewriteContext};
23 use utils::{extra_offset, format_mutability, wrap_str};
24 use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
25 use config::TypeDensity;
26
27 // Does not wrap on simple segments.
28 pub fn rewrite_path(context: &RewriteContext,
29                     expr_context: bool,
30                     qself: Option<&ast::QSelf>,
31                     path: &ast::Path,
32                     width: usize,
33                     offset: Indent)
34                     -> Option<String> {
35     let skip_count = qself.map_or(0, |x| x.position);
36
37     let mut result = if path.global && qself.is_none() {
38         "::".to_owned()
39     } else {
40         String::new()
41     };
42
43     let mut span_lo = path.span.lo;
44
45     if let Some(ref qself) = qself {
46         result.push('<');
47         let fmt_ty = try_opt!(qself.ty.rewrite(context, width, offset));
48         result.push_str(&fmt_ty);
49
50         if skip_count > 0 {
51             result.push_str(" as ");
52             if path.global {
53                 result.push_str("::");
54             }
55
56             let extra_offset = extra_offset(&result, offset);
57             // 3 = ">::".len()
58             let budget = try_opt!(width.checked_sub(extra_offset + 3));
59
60             result = try_opt!(rewrite_path_segments(false,
61                                                     result,
62                                                     path.segments.iter().take(skip_count),
63                                                     span_lo,
64                                                     path.span.hi,
65                                                     context,
66                                                     budget,
67                                                     offset + extra_offset));
68         }
69
70         result.push_str(">::");
71         span_lo = qself.ty.span.hi + BytePos(1);
72     }
73
74     let extra_offset = extra_offset(&result, offset);
75     let budget = try_opt!(width.checked_sub(extra_offset));
76     rewrite_path_segments(expr_context,
77                           result,
78                           path.segments.iter().skip(skip_count),
79                           span_lo,
80                           path.span.hi,
81                           context,
82                           budget,
83                           offset + extra_offset)
84 }
85
86 fn rewrite_path_segments<'a, I>(expr_context: bool,
87                                 mut buffer: String,
88                                 iter: I,
89                                 mut span_lo: BytePos,
90                                 span_hi: BytePos,
91                                 context: &RewriteContext,
92                                 width: usize,
93                                 offset: Indent)
94                                 -> Option<String>
95     where I: Iterator<Item = &'a ast::PathSegment>
96 {
97     let mut first = true;
98
99     for segment in iter {
100         if first {
101             first = false;
102         } else {
103             buffer.push_str("::");
104         }
105
106         let extra_offset = extra_offset(&buffer, offset);
107         let remaining_width = try_opt!(width.checked_sub(extra_offset));
108         let new_offset = offset + extra_offset;
109         let segment_string = try_opt!(rewrite_segment(expr_context,
110                                                       segment,
111                                                       &mut span_lo,
112                                                       span_hi,
113                                                       context,
114                                                       remaining_width,
115                                                       new_offset));
116
117         buffer.push_str(&segment_string);
118     }
119
120     Some(buffer)
121 }
122
123 #[derive(Debug)]
124 enum SegmentParam<'a> {
125     LifeTime(&'a ast::Lifetime),
126     Type(&'a ast::Ty),
127     Binding(&'a ast::TypeBinding),
128 }
129
130 impl<'a> SegmentParam<'a> {
131     fn get_span(&self) -> Span {
132         match *self {
133             SegmentParam::LifeTime(ref lt) => lt.span,
134             SegmentParam::Type(ref ty) => ty.span,
135             SegmentParam::Binding(ref binding) => binding.span,
136         }
137     }
138 }
139
140 impl<'a> Rewrite for SegmentParam<'a> {
141     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
142         match *self {
143             SegmentParam::LifeTime(ref lt) => lt.rewrite(context, width, offset),
144             SegmentParam::Type(ref ty) => ty.rewrite(context, width, offset),
145             SegmentParam::Binding(ref binding) => {
146                 let mut result = format!("{} = ", binding.ident);
147                 let budget = try_opt!(width.checked_sub(result.len()));
148                 let rewrite = try_opt!(binding.ty.rewrite(context, budget, offset + result.len()));
149                 result.push_str(&rewrite);
150                 Some(result)
151             }
152         }
153     }
154 }
155
156 // Formats a path segment. There are some hacks involved to correctly determine
157 // the segment's associated span since it's not part of the AST.
158 //
159 // The span_lo is assumed to be greater than the end of any previous segment's
160 // parameters and lesser or equal than the start of current segment.
161 //
162 // span_hi is assumed equal to the end of the entire path.
163 //
164 // When the segment contains a positive number of parameters, we update span_lo
165 // so that invariants described above will hold for the next segment.
166 fn rewrite_segment(expr_context: bool,
167                    segment: &ast::PathSegment,
168                    span_lo: &mut BytePos,
169                    span_hi: BytePos,
170                    context: &RewriteContext,
171                    width: usize,
172                    offset: Indent)
173                    -> Option<String> {
174     let ident_len = segment.identifier.to_string().len();
175     let width = try_opt!(width.checked_sub(ident_len));
176     let offset = offset + ident_len;
177
178     let params = match segment.parameters {
179         ast::PathParameters::AngleBracketed(ref data) if !data.lifetimes.is_empty() ||
180                                                          !data.types.is_empty() ||
181                                                          !data.bindings.is_empty() => {
182             let param_list = data.lifetimes
183                 .iter()
184                 .map(SegmentParam::LifeTime)
185                 .chain(data.types.iter().map(|x| SegmentParam::Type(&*x)))
186                 .chain(data.bindings.iter().map(|x| SegmentParam::Binding(&*x)))
187                 .collect::<Vec<_>>();
188
189             let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
190             let list_lo = context.codemap.span_after(codemap::mk_sp(*span_lo, span_hi), "<");
191             let separator = if expr_context { "::" } else { "" };
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) => ty.rewrite(context, budget, offset),
290             ArgumentKind::Variadic(_) => Some("...".to_owned()),
291         }
292     },
293                              list_lo,
294                              span.hi);
295
296     let list_str = try_opt!(format_fn_args(items, budget, offset, context.config));
297
298     let output = match *output {
299         FunctionRetTy::Ty(ref ty) => {
300             let budget = try_opt!(width.checked_sub(4));
301             let type_str = try_opt!(ty.rewrite(context, budget, offset + 4));
302             format!(" -> {}", type_str)
303         }
304         FunctionRetTy::None(..) => " -> !".to_owned(),
305         FunctionRetTy::Default(..) => String::new(),
306     };
307
308     let infix = if output.len() > 0 && output.len() + list_str.len() > width {
309         format!("\n{}", (offset - 1).to_string(context.config))
310     } else {
311         String::new()
312     };
313
314     Some(format!("({}){}{}", list_str, infix, output))
315 }
316
317 impl Rewrite for ast::WherePredicate {
318     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
319         // TODO: dead spans?
320         let result = match *self {
321             ast::WherePredicate::BoundPredicate(ast::WhereBoundPredicate { ref bound_lifetimes,
322                                                                            ref bounded_ty,
323                                                                            ref bounds,
324                                                                            .. }) => {
325                 let type_str = try_opt!(bounded_ty.rewrite(context, width, offset));
326
327                 if !bound_lifetimes.is_empty() {
328                     let lifetime_str = try_opt!(bound_lifetimes.iter()
329                                                                .map(|lt| {
330                                                                    lt.rewrite(context,
331                                                                               width,
332                                                                               offset)
333                                                                })
334                                                                .collect::<Option<Vec<_>>>())
335                                            .join(", ");
336                     // 8 = "for<> : ".len()
337                     let used_width = lifetime_str.len() + type_str.len() + 8;
338                     let budget = try_opt!(width.checked_sub(used_width));
339                     let bounds_str = try_opt!(bounds.iter()
340                                                     .map(|ty_bound| {
341                                                         ty_bound.rewrite(context,
342                                                                          budget,
343                                                                          offset + used_width)
344                                                     })
345                                                     .collect::<Option<Vec<_>>>())
346                                          .join(" + ");
347
348                     format!("for<{}> {}: {}", lifetime_str, type_str, bounds_str)
349                 } else {
350                     // 2 = ": ".len()
351                     let used_width = type_str.len() + 2;
352                     let budget = try_opt!(width.checked_sub(used_width));
353                     let bounds_str = try_opt!(bounds.iter()
354                                                     .map(|ty_bound| {
355                                                         ty_bound.rewrite(context,
356                                                                          budget,
357                                                                          offset + used_width)
358                                                     })
359                                                     .collect::<Option<Vec<_>>>())
360                                          .join(" + ");
361
362                     format!("{}: {}", type_str, bounds_str)
363                 }
364             }
365             ast::WherePredicate::RegionPredicate(ast::WhereRegionPredicate { ref lifetime,
366                                                                              ref bounds,
367                                                                              .. }) => {
368                 try_opt!(rewrite_bounded_lifetime(lifetime, bounds.iter(), context, width, offset))
369             }
370             ast::WherePredicate::EqPredicate(ast::WhereEqPredicate { ref path, ref ty, .. }) => {
371                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
372                 // 3 = " = ".len()
373                 let used_width = 3 + ty_str.len();
374                 let budget = try_opt!(width.checked_sub(used_width));
375                 let path_str =
376                     try_opt!(rewrite_path(context, false, None, path, budget, offset + used_width));
377                 format!("{} = {}", path_str, ty_str)
378             }
379         };
380
381         wrap_str(result, context.config.max_width, width, offset)
382     }
383 }
384
385 impl Rewrite for ast::LifetimeDef {
386     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
387         rewrite_bounded_lifetime(&self.lifetime, self.bounds.iter(), context, width, offset)
388     }
389 }
390
391 fn rewrite_bounded_lifetime<'b, I>(lt: &ast::Lifetime,
392                                    bounds: I,
393                                    context: &RewriteContext,
394                                    width: usize,
395                                    offset: Indent)
396                                    -> Option<String>
397     where I: ExactSizeIterator<Item = &'b ast::Lifetime>
398 {
399     let result = try_opt!(lt.rewrite(context, width, offset));
400
401     if bounds.len() == 0 {
402         Some(result)
403     } else {
404         let appendix: Vec<_> = try_opt!(bounds.into_iter()
405             .map(|b| b.rewrite(context, width, offset))
406             .collect());
407         let result = format!("{}: {}", result, appendix.join(" + "));
408         wrap_str(result, context.config.max_width, width, offset)
409     }
410 }
411
412 impl Rewrite for ast::TyParamBound {
413     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
414         match *self {
415             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::None) => {
416                 tref.rewrite(context, width, offset)
417             }
418             ast::TyParamBound::TraitTyParamBound(ref tref, ast::TraitBoundModifier::Maybe) => {
419                 let budget = try_opt!(width.checked_sub(1));
420                 Some(format!("?{}", try_opt!(tref.rewrite(context, budget, offset + 1))))
421             }
422             ast::TyParamBound::RegionTyParamBound(ref l) => l.rewrite(context, width, offset),
423         }
424     }
425 }
426
427 impl Rewrite for ast::Lifetime {
428     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
429         wrap_str(pprust::lifetime_to_string(self),
430                  context.config.max_width,
431                  width,
432                  offset)
433     }
434 }
435
436 impl Rewrite for ast::TyParamBounds {
437     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
438         let strs: Vec<_> = try_opt!(self.iter()
439             .map(|b| b.rewrite(context, width, offset))
440             .collect());
441         wrap_str(strs.join(" + "), context.config.max_width, width, offset)
442     }
443 }
444
445 impl Rewrite for ast::TyParam {
446     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
447         let mut result = String::with_capacity(128);
448         result.push_str(&self.ident.to_string());
449         if !self.bounds.is_empty() {
450             result.push_str(": ");
451
452             let bounds = try_opt!(self.bounds
453                     .iter()
454                     .map(|ty_bound| ty_bound.rewrite(context, width, offset))
455                     .collect::<Option<Vec<_>>>())
456                 .join(" + ");
457
458             result.push_str(&bounds);
459         }
460         if let Some(ref def) = self.default {
461
462             let eq_str = match context.config.type_punctuation_density {
463                 TypeDensity::Compressed => "=",
464                 TypeDensity::Wide => " = ",
465             };
466             result.push_str(eq_str);
467             let budget = try_opt!(width.checked_sub(result.len()));
468             let rewrite = try_opt!(def.rewrite(context, budget, offset + result.len()));
469             result.push_str(&rewrite);
470         }
471
472         wrap_str(result, context.config.max_width, width, offset)
473     }
474 }
475
476 impl Rewrite for ast::PolyTraitRef {
477     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
478         if !self.bound_lifetimes.is_empty() {
479             let lifetime_str = try_opt!(self.bound_lifetimes
480                     .iter()
481                     .map(|lt| lt.rewrite(context, width, offset))
482                     .collect::<Option<Vec<_>>>())
483                 .join(", ");
484             // 6 is "for<> ".len()
485             let extra_offset = lifetime_str.len() + 6;
486             let max_path_width = try_opt!(width.checked_sub(extra_offset));
487             let path_str = try_opt!(self.trait_ref
488                 .rewrite(context, max_path_width, offset + extra_offset));
489
490             Some(format!("for<{}> {}", lifetime_str, path_str))
491         } else {
492             self.trait_ref.rewrite(context, width, offset)
493         }
494     }
495 }
496
497 impl Rewrite for ast::TraitRef {
498     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
499         rewrite_path(context, false, None, &self.path, width, offset)
500     }
501 }
502
503 impl Rewrite for ast::Ty {
504     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
505         match self.node {
506             ast::TyKind::ObjectSum(ref ty, ref bounds) => {
507                 let ty_str = try_opt!(ty.rewrite(context, width, offset));
508                 let overhead = ty_str.len() + 3;
509                 let plus_str = match context.config.type_punctuation_density {
510                     TypeDensity::Compressed => "+",
511                     TypeDensity::Wide => " + ",
512                 };
513                 Some(format!("{}{}{}",
514                              ty_str,
515                              plus_str,
516                              try_opt!(bounds.rewrite(context,
517                                                      try_opt!(width.checked_sub(overhead)),
518                                                      offset + overhead))))
519             }
520             ast::TyKind::Ptr(ref mt) => {
521                 let prefix = match mt.mutbl {
522                     Mutability::Mutable => "*mut ",
523                     Mutability::Immutable => "*const ",
524                 };
525
526                 rewrite_unary_prefix(context, prefix, &*mt.ty, width, offset)
527             }
528             ast::TyKind::Rptr(ref lifetime, ref mt) => {
529                 let mut_str = format_mutability(mt.mutbl);
530                 let mut_len = mut_str.len();
531                 Some(match *lifetime {
532                     Some(ref lifetime) => {
533                         let lt_budget = try_opt!(width.checked_sub(2 + mut_len));
534                         let lt_str =
535                             try_opt!(lifetime.rewrite(context, lt_budget, offset + 2 + mut_len));
536                         let lt_len = lt_str.len();
537                         let budget = try_opt!(width.checked_sub(2 + mut_len + lt_len));
538                         format!("&{} {}{}",
539                                 lt_str,
540                                 mut_str,
541                                 try_opt!(mt.ty
542                                     .rewrite(context, budget, offset + 2 + mut_len + lt_len)))
543                     }
544                     None => {
545                         let budget = try_opt!(width.checked_sub(1 + mut_len));
546                         format!("&{}{}",
547                                 mut_str,
548                                 try_opt!(mt.ty.rewrite(context, budget, offset + 1 + mut_len)))
549                     }
550                 })
551             }
552             // FIXME: we drop any comments here, even though it's a silly place to put
553             // comments.
554             ast::TyKind::Paren(ref ty) => {
555                 let budget = try_opt!(width.checked_sub(2));
556                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("({})", ty_str))
557             }
558             ast::TyKind::Vec(ref ty) => {
559                 let budget = try_opt!(width.checked_sub(2));
560                 ty.rewrite(context, budget, offset + 1).map(|ty_str| format!("[{}]", ty_str))
561             }
562             ast::TyKind::Tup(ref items) => {
563                 rewrite_tuple(context,
564                               items.iter().map(|x| &**x),
565                               self.span,
566                               width,
567                               offset)
568             }
569             ast::TyKind::PolyTraitRef(ref trait_ref) => trait_ref.rewrite(context, width, offset),
570             ast::TyKind::Path(ref q_self, ref path) => {
571                 rewrite_path(context, false, q_self.as_ref(), path, width, offset)
572             }
573             ast::TyKind::FixedLengthVec(ref ty, ref repeats) => {
574                 rewrite_pair(&**ty, &**repeats, "[", "; ", "]", context, width, offset)
575             }
576             ast::TyKind::Infer => {
577                 if width >= 1 {
578                     Some("_".to_owned())
579                 } else {
580                     None
581                 }
582             }
583             ast::TyKind::BareFn(ref bare_fn) => {
584                 rewrite_bare_fn(bare_fn, self.span, context, width, offset)
585             }
586             ast::TyKind::Mac(..) |
587             ast::TyKind::Typeof(..) => unreachable!(),
588             ast::TyKind::ImplicitSelf => Some(String::from("")),
589         }
590     }
591 }
592
593 fn rewrite_bare_fn(bare_fn: &ast::BareFnTy,
594                    span: Span,
595                    context: &RewriteContext,
596                    width: usize,
597                    offset: Indent)
598                    -> Option<String> {
599     let mut result = String::with_capacity(128);
600
601     if !bare_fn.lifetimes.is_empty() {
602         result.push_str("for<");
603         // 6 = "for<> ".len(), 4 = "for<".
604         // This doesn't work out so nicely for mutliline situation with lots of
605         // rightward drift. If that is a problem, we could use the list stuff.
606         result.push_str(&try_opt!(bare_fn.lifetimes
607                 .iter()
608                 .map(|l| l.rewrite(context, try_opt!(width.checked_sub(6)), offset + 4))
609                 .collect::<Option<Vec<_>>>())
610             .join(", "));
611         result.push_str("> ");
612     }
613
614     result.push_str(&::utils::format_unsafety(bare_fn.unsafety));
615
616     if bare_fn.abi != abi::Abi::Rust {
617         result.push_str(&::utils::format_abi(bare_fn.abi, context.config.force_explicit_abi));
618     }
619
620     result.push_str("fn");
621
622     let budget = try_opt!(width.checked_sub(result.len()));
623     let indent = offset + result.len();
624
625     let rewrite = try_opt!(format_function_type(bare_fn.decl.inputs.iter(),
626                                                 &bare_fn.decl.output,
627                                                 bare_fn.decl.variadic,
628                                                 span,
629                                                 context,
630                                                 budget,
631                                                 indent));
632
633     result.push_str(&rewrite);
634
635     Some(result)
636 }