]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Use max width for function decls, etc.
[rust.git] / src / items.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 // Formatting top-level items - functions, structs, enums, traits, impls.
12
13 use Indent;
14 use utils::{format_mutability, format_visibility, contains_skip, span_after, end_typaram, wrap_str};
15 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, ListTactic};
16 use expr::rewrite_assign_rhs;
17 use comment::FindUncommented;
18 use visitor::FmtVisitor;
19 use rewrite::{Rewrite, RewriteContext};
20 use config::{Config, BlockIndentStyle, Density, ReturnIndent, BraceStyle, StructLitStyle};
21
22 use syntax::{ast, abi};
23 use syntax::codemap::{self, Span, BytePos};
24 use syntax::print::pprust;
25 use syntax::parse::token;
26
27 impl<'a> FmtVisitor<'a> {
28     pub fn visit_let(&mut self, local: &ast::Local, span: Span) {
29         self.format_missing_with_indent(span.lo);
30
31         // String that is placed within the assignment pattern and expression.
32         let infix = {
33             let mut infix = String::new();
34
35             if let Some(ref ty) = local.ty {
36                 // 2 = ": ".len()
37                 let offset = self.block_indent + 2;
38                 let width = self.config.max_width - offset.width();
39                 let rewrite = ty.rewrite(&self.get_context(), width, offset);
40
41                 match rewrite {
42                     Some(result) => {
43                         infix.push_str(": ");
44                         infix.push_str(&result);
45                     }
46                     None => return,
47                 }
48             }
49
50             if local.init.is_some() {
51                 infix.push_str(" =");
52             }
53
54             infix
55         };
56
57         // New scope so we drop the borrow of self (context) in time to mutably
58         // borrow self to mutate its buffer.
59         let result = {
60             let context = self.get_context();
61             let mut result = "let ".to_owned();
62             let pattern_offset = self.block_indent + result.len() + infix.len();
63             // 1 = ;
64             let pattern_width = self.config.max_width.checked_sub(pattern_offset.width() + 1);
65             let pattern_width = match pattern_width {
66                 Some(width) => width,
67                 None => return,
68             };
69
70             match local.pat.rewrite(&context, pattern_width, pattern_offset) {
71                 Some(ref pat_string) => result.push_str(pat_string),
72                 None => return,
73             }
74
75             result.push_str(&infix);
76
77             if let Some(ref ex) = local.init {
78                 let max_width = self.config.max_width.checked_sub(context.block_indent.width() + 1);
79                 let max_width = match max_width {
80                     Some(width) => width,
81                     None => return,
82                 };
83
84                 // 1 = trailing semicolon;
85                 let rhs = rewrite_assign_rhs(&context, result, ex, max_width, context.block_indent);
86
87                 match rhs {
88                     Some(result) => result,
89                     None => return,
90                 }
91             } else {
92                 result
93             }
94         };
95
96         self.buffer.push_str(&result);
97         self.buffer.push_str(";");
98         self.last_pos = span.hi;
99     }
100
101     pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
102         self.buffer.push_str("extern ");
103
104         if fm.abi != abi::Abi::C {
105             self.buffer.push_str(&format!("{} ", fm.abi));
106         }
107
108         let snippet = self.snippet(span);
109         let brace_pos = snippet.find_uncommented("{").unwrap() as u32;
110
111         // FIXME: this skips comments between the extern keyword and the opening
112         // brace.
113         self.last_pos = span.lo + BytePos(brace_pos);
114         self.block_indent = self.block_indent.block_indent(self.config);
115
116         for item in &fm.items {
117             self.format_foreign_item(&*item);
118         }
119
120         self.block_indent = self.block_indent.block_unindent(self.config);
121         self.format_missing_with_indent(span.hi - BytePos(1));
122         self.buffer.push_str("}");
123         self.last_pos = span.hi;
124     }
125
126     fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
127         self.format_missing_with_indent(item.span.lo);
128         // Drop semicolon or it will be interpreted as comment.
129         // FIXME: this may be a faulty span from libsyntax.
130         let span = codemap::mk_sp(item.span.lo, item.span.hi - BytePos(1));
131
132         match item.node {
133             ast::ForeignItem_::ForeignItemFn(ref fn_decl, ref generics) => {
134                 let indent = self.block_indent;
135                 let rewrite = self.rewrite_fn_base(indent,
136                                                    item.ident,
137                                                    fn_decl,
138                                                    None,
139                                                    generics,
140                                                    ast::Unsafety::Normal,
141                                                    ast::Constness::NotConst,
142                                                    // These are not actually rust functions,
143                                                    // but we format them as such.
144                                                    abi::Abi::Rust,
145                                                    ast::Visibility::Inherited,
146                                                    span,
147                                                    false);
148
149                 match rewrite {
150                     Some(new_fn) => {
151                         self.buffer.push_str(format_visibility(item.vis));
152                         self.buffer.push_str(&new_fn);
153                         self.buffer.push_str(";");
154                     }
155                     None => self.format_missing(item.span.hi),
156                 }
157             }
158             ast::ForeignItem_::ForeignItemStatic(ref ty, is_mutable) => {
159                 // FIXME(#21): we're dropping potential comments in between the
160                 // function keywords here.
161                 let mut_str = if is_mutable {
162                     "mut "
163                 } else {
164                     ""
165                 };
166                 let prefix = format!("{}static {}{}: ",
167                                      format_visibility(item.vis),
168                                      mut_str,
169                                      item.ident);
170                 let offset = self.block_indent + prefix.len();
171                 // 1 = ;
172                 let width = self.config.max_width - offset.width() - 1;
173                 let rewrite = ty.rewrite(&self.get_context(), width, offset);
174
175                 match rewrite {
176                     Some(result) => {
177                         self.buffer.push_str(&prefix);
178                         self.buffer.push_str(&result);
179                         self.buffer.push_str(";");
180                     }
181                     None => self.format_missing(item.span.hi),
182                 }
183             }
184         }
185
186         self.last_pos = item.span.hi;
187     }
188
189     pub fn rewrite_fn(&mut self,
190                       indent: Indent,
191                       ident: ast::Ident,
192                       fd: &ast::FnDecl,
193                       explicit_self: Option<&ast::ExplicitSelf>,
194                       generics: &ast::Generics,
195                       unsafety: ast::Unsafety,
196                       constness: ast::Constness,
197                       abi: abi::Abi,
198                       vis: ast::Visibility,
199                       span: Span)
200                       -> Option<String> {
201         let mut newline_brace = self.newline_for_brace(&generics.where_clause);
202
203         let mut result = try_opt!(self.rewrite_fn_base(indent,
204                                                        ident,
205                                                        fd,
206                                                        explicit_self,
207                                                        generics,
208                                                        unsafety,
209                                                        constness,
210                                                        abi,
211                                                        vis,
212                                                        span,
213                                                        newline_brace));
214
215         if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
216             newline_brace = false;
217         }
218
219         // Prepare for the function body by possibly adding a newline and
220         // indent.
221         // FIXME we'll miss anything between the end of the signature and the
222         // start of the body, but we need more spans from the compiler to solve
223         // this.
224         if newline_brace {
225             result.push('\n');
226             result.push_str(&indent.to_string(self.config));
227         } else {
228             result.push(' ');
229         }
230
231         Some(result)
232     }
233
234     pub fn rewrite_required_fn(&mut self,
235                                indent: Indent,
236                                ident: ast::Ident,
237                                sig: &ast::MethodSig,
238                                span: Span)
239                                -> Option<String> {
240         // Drop semicolon or it will be interpreted as comment
241         let span = codemap::mk_sp(span.lo, span.hi - BytePos(1));
242
243         let mut result = try_opt!(self.rewrite_fn_base(indent,
244                                                        ident,
245                                                        &sig.decl,
246                                                        Some(&sig.explicit_self),
247                                                        &sig.generics,
248                                                        sig.unsafety,
249                                                        sig.constness,
250                                                        sig.abi,
251                                                        ast::Visibility::Inherited,
252                                                        span,
253                                                        false));
254
255         // Re-attach semicolon
256         result.push(';');
257
258         Some(result)
259     }
260
261     fn rewrite_fn_base(&mut self,
262                        indent: Indent,
263                        ident: ast::Ident,
264                        fd: &ast::FnDecl,
265                        explicit_self: Option<&ast::ExplicitSelf>,
266                        generics: &ast::Generics,
267                        unsafety: ast::Unsafety,
268                        constness: ast::Constness,
269                        abi: abi::Abi,
270                        vis: ast::Visibility,
271                        span: Span,
272                        newline_brace: bool)
273                        -> Option<String> {
274         // FIXME we'll lose any comments in between parts of the function decl, but anyone
275         // who comments there probably deserves what they get.
276
277         let where_clause = &generics.where_clause;
278
279         let mut result = String::with_capacity(1024);
280         // Vis unsafety abi.
281         result.push_str(format_visibility(vis));
282
283         if let ast::Unsafety::Unsafe = unsafety {
284             result.push_str("unsafe ");
285         }
286         if let ast::Constness::Const = constness {
287             result.push_str("const ");
288         }
289         if abi != abi::Rust {
290             result.push_str("extern ");
291             result.push_str(&abi.to_string());
292             result.push(' ');
293         }
294
295         // fn foo
296         result.push_str("fn ");
297         result.push_str(&ident.to_string());
298
299         // Generics.
300         let generics_indent = indent + result.len();
301         let generics_span = codemap::mk_sp(span.lo, span_for_return(&fd.output).lo);
302         let generics_str = try_opt!(self.rewrite_generics(generics,
303                                                           indent,
304                                                           generics_indent,
305                                                           generics_span));
306         result.push_str(&generics_str);
307
308         let context = self.get_context();
309         let ret_str = fd.output
310                         .rewrite(&context,
311                                  self.config.max_width - indent.width(),
312                                  indent)
313                         .unwrap();
314
315         // Args.
316         let (one_line_budget, multi_line_budget, mut arg_indent) =
317             self.compute_budgets_for_args(&result, indent, ret_str.len(), newline_brace);
318
319         debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
320                one_line_budget,
321                multi_line_budget,
322                arg_indent);
323
324         // Check if vertical layout was forced by compute_budget_for_args.
325         if one_line_budget <= 0 {
326             if self.config.fn_args_paren_newline {
327                 result.push('\n');
328                 result.push_str(&arg_indent.to_string(self.config));
329                 arg_indent = arg_indent + 1; // extra space for `(`
330                 result.push('(');
331             } else {
332                 result.push_str("(\n");
333                 result.push_str(&arg_indent.to_string(self.config));
334             }
335         } else if self.config.fn_args_layout == StructLitStyle::Block {
336             arg_indent = indent.block_indent(self.config);
337             result.push_str("(\n");
338             result.push_str(&arg_indent.to_string(self.config));
339         } else {
340             result.push('(');
341         }
342
343         // A conservative estimation, to goal is to be over all parens in generics
344         let args_start = generics.ty_params
345                                  .last()
346                                  .map(|tp| end_typaram(tp))
347                                  .unwrap_or(span.lo);
348         let args_span = codemap::mk_sp(span_after(codemap::mk_sp(args_start, span.hi),
349                                                   "(",
350                                                   self.codemap),
351                                        span_for_return(&fd.output).lo);
352         let arg_str = try_opt!(self.rewrite_args(&fd.inputs,
353                                                  explicit_self,
354                                                  one_line_budget,
355                                                  multi_line_budget,
356                                                  indent,
357                                                  arg_indent,
358                                                  args_span));
359         result.push_str(&arg_str);
360         if self.config.fn_args_layout == StructLitStyle::Block {
361             result.push('\n');
362         }
363         result.push(')');
364
365         // Return type.
366         if !ret_str.is_empty() {
367             // If we've already gone multi-line, or the return type would push
368             // over the max width, then put the return type on a new line.
369             // Unless we are formatting args like a block, in which case there
370             // should always be room for the return type.
371             if (result.contains("\n") ||
372                 result.len() + indent.width() + ret_str.len() > self.config.max_width) &&
373                self.config.fn_args_layout != StructLitStyle::Block {
374                 let indent = match self.config.fn_return_indent {
375                     ReturnIndent::WithWhereClause => indent + 4,
376                     // TODO: we might want to check that using the arg indent
377                     // doesn't blow our budget, and if it does, then fallback to
378                     // the where clause indent.
379                     _ => arg_indent,
380                 };
381
382                 result.push('\n');
383                 result.push_str(&indent.to_string(self.config));
384             } else {
385                 result.push(' ');
386             }
387             result.push_str(&ret_str);
388
389             // Comment between return type and the end of the decl.
390             let snippet_lo = fd.output.span().hi;
391             if where_clause.predicates.is_empty() {
392                 let snippet_hi = span.hi;
393                 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
394                 let snippet = snippet.trim();
395                 if !snippet.is_empty() {
396                     result.push(' ');
397                     result.push_str(snippet);
398                 }
399             } else {
400                 // FIXME it would be nice to catch comments between the return type
401                 // and the where clause, but we don't have a span for the where
402                 // clause.
403             }
404         }
405
406         let where_density = if (self.config.where_density == Density::Compressed &&
407                                 (!result.contains('\n') ||
408                                  self.config.fn_args_layout == StructLitStyle::Block)) ||
409                                (self.config.fn_args_layout == StructLitStyle::Block &&
410                                 ret_str.is_empty()) {
411             Density::Compressed
412         } else {
413             Density::Tall
414         };
415
416         // Where clause.
417         let where_clause_str = try_opt!(self.rewrite_where_clause(where_clause,
418                                                                   self.config,
419                                                                   indent,
420                                                                   where_density,
421                                                                   span.hi));
422         result.push_str(&where_clause_str);
423
424         Some(result)
425     }
426
427     fn rewrite_args(&self,
428                     args: &[ast::Arg],
429                     explicit_self: Option<&ast::ExplicitSelf>,
430                     one_line_budget: usize,
431                     multi_line_budget: usize,
432                     indent: Indent,
433                     arg_indent: Indent,
434                     span: Span)
435                     -> Option<String> {
436         let context = self.get_context();
437         let mut arg_item_strs = try_opt!(args.iter()
438                                              .map(|arg| {
439                                                  arg.rewrite(&context, multi_line_budget, indent)
440                                              })
441                                              .collect::<Option<Vec<_>>>());
442
443         // Account for sugary self.
444         // FIXME: the comment for the self argument is dropped. This is blocked
445         // on rust issue #27522.
446         let min_args = explicit_self.and_then(|explicit_self| {
447                                         rewrite_explicit_self(explicit_self, args)
448                                     })
449                                     .map(|self_str| {
450                                         arg_item_strs[0] = self_str;
451                                         2
452                                     })
453                                     .unwrap_or(1);
454
455         // Comments between args.
456         let mut arg_items = Vec::new();
457         if min_args == 2 {
458             arg_items.push(ListItem::from_str(""));
459         }
460
461         // TODO(#21): if there are no args, there might still be a comment, but
462         // without spans for the comment or parens, there is no chance of
463         // getting it right. You also don't get to put a comment on self, unless
464         // it is explicit.
465         if args.len() >= min_args {
466             let comment_span_start = if min_args == 2 {
467                 span_after(span, ",", self.codemap)
468             } else {
469                 span.lo
470             };
471
472             let more_items = itemize_list(self.codemap,
473                                           args[min_args-1..].iter(),
474                                           ")",
475                                           |arg| span_lo_for_arg(arg),
476                                           |arg| arg.ty.span.hi,
477                                           |_| String::new(),
478                                           comment_span_start,
479                                           span.hi);
480
481             arg_items.extend(more_items);
482         }
483
484         assert_eq!(arg_item_strs.len(), arg_items.len());
485
486         for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
487             item.item = arg;
488         }
489
490         let indent = match self.config.fn_arg_indent {
491             BlockIndentStyle::Inherit => indent,
492             BlockIndentStyle::Tabbed => indent.block_indent(self.config),
493             BlockIndentStyle::Visual => arg_indent,
494         };
495
496         let fmt = ListFormatting {
497             tactic: self.config.fn_args_density.to_list_tactic(),
498             separator: ",",
499             trailing_separator: SeparatorTactic::Never,
500             indent: indent,
501             h_width: one_line_budget,
502             v_width: multi_line_budget,
503             ends_with_newline: false,
504             config: self.config,
505         };
506
507         write_list(&arg_items, &fmt)
508     }
509
510     fn compute_budgets_for_args(&self,
511                                 result: &str,
512                                 indent: Indent,
513                                 ret_str_len: usize,
514                                 newline_brace: bool)
515                                 -> (usize, usize, Indent) {
516         // Try keeping everything on the same line
517         if !result.contains("\n") {
518             // 3 = `() `, space is before ret_string
519             let mut used_space = indent.width() + result.len() + ret_str_len + 3;
520             if !newline_brace {
521                 used_space += 2;
522             }
523             let one_line_budget = if used_space > self.config.max_width {
524                 0
525             } else {
526                 self.config.max_width - used_space
527             };
528
529             // 2 = `()`
530             let used_space = indent.width() + result.len() + 2;
531             let max_space = self.config.max_width;
532             debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
533                    used_space,
534                    max_space);
535             if used_space < max_space {
536                 return (one_line_budget,
537                         max_space - used_space,
538                         indent + result.len() + 1);
539             }
540         }
541
542         // Didn't work. we must force vertical layout and put args on a newline.
543         let new_indent = indent.block_indent(self.config);
544         let used_space = new_indent.width() + 2; // account for `(` and `)`
545         let max_space = self.config.max_width;
546         if used_space <= max_space {
547             (0, max_space - used_space, new_indent)
548         } else {
549             // Whoops! bankrupt.
550             // TODO: take evasive action, perhaps kill the indent or something.
551             panic!("in compute_budgets_for_args");
552         }
553     }
554
555     fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
556         match self.config.fn_brace_style {
557             BraceStyle::AlwaysNextLine => true,
558             BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
559             _ => false,
560         }
561     }
562
563     pub fn visit_enum(&mut self,
564                       ident: ast::Ident,
565                       vis: ast::Visibility,
566                       enum_def: &ast::EnumDef,
567                       generics: &ast::Generics,
568                       span: Span) {
569         let header_str = self.format_header("enum ", ident, vis);
570         self.buffer.push_str(&header_str);
571
572         let enum_snippet = self.snippet(span);
573         let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
574         let generics_str = self.format_generics(generics,
575                                                 " {",
576                                                 self.block_indent,
577                                                 self.block_indent.block_indent(self.config),
578                                                 codemap::mk_sp(span.lo, body_start))
579                                .unwrap();
580         self.buffer.push_str(&generics_str);
581
582         self.last_pos = body_start;
583         self.block_indent = self.block_indent.block_indent(self.config);
584         for (i, f) in enum_def.variants.iter().enumerate() {
585             let next_span_start: BytePos = if i == enum_def.variants.len() - 1 {
586                 span.hi
587             } else {
588                 enum_def.variants[i + 1].span.lo
589             };
590
591             self.visit_variant(f, i == enum_def.variants.len() - 1, next_span_start);
592         }
593         self.block_indent = self.block_indent.block_unindent(self.config);
594
595         self.format_missing_with_indent(span.hi - BytePos(1));
596         self.buffer.push_str("}");
597     }
598
599     // Variant of an enum.
600     fn visit_variant(&mut self, field: &ast::Variant, last_field: bool, next_span_start: BytePos) {
601         if self.visit_attrs(&field.node.attrs) {
602             return;
603         }
604
605         self.format_missing_with_indent(field.span.lo);
606
607         let result = match field.node.kind {
608             ast::VariantKind::TupleVariantKind(ref types) => {
609                 let name = field.node.name.to_string();
610                 self.buffer.push_str(&name);
611
612                 let mut result = String::new();
613
614                 if !types.is_empty() {
615                     let items = itemize_list(self.codemap,
616                                              types.iter(),
617                                              ")",
618                                              |arg| arg.ty.span.lo,
619                                              |arg| arg.ty.span.hi,
620                                              |arg| {
621                                                  // FIXME silly width, indent
622                                                  arg.ty
623                                                     .rewrite(&self.get_context(),
624                                                              1000,
625                                                              Indent::empty())
626                                                     .unwrap()
627                                              },
628                                              span_after(field.span, "(", self.codemap),
629                                              next_span_start);
630
631                     result.push('(');
632
633                     let indent = self.block_indent + field.node.name.to_string().len() + "(".len();
634
635                     let comma_cost = if self.config.enum_trailing_comma {
636                         1
637                     } else {
638                         0
639                     };
640                     let budget = self.config.max_width - indent.width() - comma_cost - 1; // 1 = )
641
642                     let fmt = ListFormatting {
643                         tactic: ListTactic::HorizontalVertical,
644                         separator: ",",
645                         trailing_separator: SeparatorTactic::Never,
646                         indent: indent,
647                         h_width: budget,
648                         v_width: budget,
649                         ends_with_newline: true,
650                         config: self.config,
651                     };
652                     let list_str = match write_list(&items.collect::<Vec<_>>(), &fmt) {
653                         Some(list_str) => list_str,
654                         None => return,
655                     };
656
657                     result.push_str(&list_str);
658                     result.push(')');
659                 }
660
661                 if let Some(ref expr) = field.node.disr_expr {
662                     result.push_str(" = ");
663                     let expr_snippet = self.snippet(expr.span);
664                     result.push_str(&expr_snippet);
665
666                     // Make sure we do not exceed column limit
667                     assert!(self.config.max_width >=
668                             name.len() + expr_snippet.len() + " = ,".len(),
669                             "Enum variant exceeded column limit");
670                 }
671
672                 result
673             }
674             ast::VariantKind::StructVariantKind(ref struct_def) => {
675                 // TODO: Should limit the width, as we have a trailing comma
676                 let struct_rewrite = self.format_struct("",
677                                                         field.node.name,
678                                                         ast::Visibility::Inherited,
679                                                         struct_def,
680                                                         None,
681                                                         field.span,
682                                                         self.block_indent);
683
684                 match struct_rewrite {
685                     Some(struct_str) => struct_str,
686                     None => return,
687                 }
688             }
689         };
690         self.buffer.push_str(&result);
691
692         if !last_field || self.config.enum_trailing_comma {
693             self.buffer.push_str(",");
694         }
695
696         self.last_pos = field.span.hi + BytePos(1);
697     }
698
699     fn format_struct(&self,
700                      item_name: &str,
701                      ident: ast::Ident,
702                      vis: ast::Visibility,
703                      struct_def: &ast::StructDef,
704                      generics: Option<&ast::Generics>,
705                      span: Span,
706                      offset: Indent)
707                      -> Option<String> {
708         let mut result = String::with_capacity(1024);
709
710         let header_str = self.format_header(item_name, ident, vis);
711         result.push_str(&header_str);
712
713         if struct_def.fields.is_empty() {
714             result.push(';');
715             return Some(result);
716         }
717
718         let is_tuple = match struct_def.fields[0].node.kind {
719             ast::StructFieldKind::NamedField(..) => false,
720             ast::StructFieldKind::UnnamedField(..) => true,
721         };
722
723         let (opener, terminator) = if is_tuple {
724             ("(", ")")
725         } else {
726             (" {", "}")
727         };
728
729         let generics_str = match generics {
730             Some(g) => {
731                 try_opt!(self.format_generics(g,
732                                               opener,
733                                               offset,
734                                               offset + header_str.len(),
735                                               codemap::mk_sp(span.lo,
736                                                              struct_def.fields[0].span.lo)))
737             }
738             None => opener.to_owned(),
739         };
740         result.push_str(&generics_str);
741
742         let items = itemize_list(self.codemap,
743                                  struct_def.fields.iter(),
744                                  terminator,
745                                  |field| {
746                                      // Include attributes and doc comments, if present
747                                      if !field.node.attrs.is_empty() {
748                                          field.node.attrs[0].span.lo
749                                      } else {
750                                          field.span.lo
751                                      }
752                                  },
753                                  |field| field.node.ty.span.hi,
754                                  |field| self.format_field(field),
755                                  span_after(span, opener.trim(), self.codemap),
756                                  span.hi);
757
758         // 2 terminators and a semicolon
759         let used_budget = offset.width() + header_str.len() + generics_str.len() + 3;
760
761         // Conservative approximation
762         let single_line_cost = (span.hi - struct_def.fields[0].span.lo).0;
763         let break_line = !is_tuple || generics_str.contains('\n') ||
764                          single_line_cost as usize + used_budget > self.config.max_width;
765
766         let tactic = if break_line {
767             let indentation = offset.block_indent(self.config).to_string(self.config);
768             result.push('\n');
769             result.push_str(&indentation);
770
771             ListTactic::Vertical
772         } else {
773             ListTactic::Horizontal
774         };
775
776         // 1 = ,
777         let budget = self.config.max_width - offset.width() + self.config.tab_spaces - 1;
778         let fmt = ListFormatting {
779             tactic: tactic,
780             separator: ",",
781             trailing_separator: self.config.struct_trailing_comma,
782             indent: offset.block_indent(self.config),
783             h_width: self.config.max_width,
784             v_width: budget,
785             ends_with_newline: true,
786             config: self.config,
787         };
788
789         let list_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
790         result.push_str(&list_str);
791
792         if break_line {
793             result.push('\n');
794             result.push_str(&offset.to_string(self.config));
795         }
796
797         result.push_str(terminator);
798
799         if is_tuple {
800             result.push(';');
801         }
802
803         Some(result)
804     }
805
806     pub fn visit_struct(&mut self,
807                         ident: ast::Ident,
808                         vis: ast::Visibility,
809                         struct_def: &ast::StructDef,
810                         generics: &ast::Generics,
811                         span: Span) {
812         let indent = self.block_indent;
813         let result = self.format_struct("struct ",
814                                         ident,
815                                         vis,
816                                         struct_def,
817                                         Some(generics),
818                                         span,
819                                         indent);
820
821         if let Some(rewrite) = result {
822             self.buffer.push_str(&rewrite);
823             self.last_pos = span.hi;
824         }
825     }
826
827     fn format_header(&self, item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
828         format!("{}{}{}", format_visibility(vis), item_name, ident)
829     }
830
831     fn format_generics(&self,
832                        generics: &ast::Generics,
833                        opener: &str,
834                        offset: Indent,
835                        generics_offset: Indent,
836                        span: Span)
837                        -> Option<String> {
838         let mut result = try_opt!(self.rewrite_generics(generics, offset, generics_offset, span));
839
840         if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
841             let where_clause_str = try_opt!(self.rewrite_where_clause(&generics.where_clause,
842                                                                       self.config,
843                                                                       self.block_indent,
844                                                                       Density::Tall,
845                                                                       span.hi));
846             result.push_str(&where_clause_str);
847             result.push_str(&self.block_indent.to_string(self.config));
848             result.push('\n');
849             result.push_str(opener.trim());
850         } else {
851             result.push_str(opener);
852         }
853
854         Some(result)
855     }
856
857     // Field of a struct
858     fn format_field(&self, field: &ast::StructField) -> String {
859         if contains_skip(&field.node.attrs) {
860             return self.snippet(codemap::mk_sp(field.node.attrs[0].span.lo, field.span.hi));
861         }
862
863         let name = match field.node.kind {
864             ast::StructFieldKind::NamedField(ident, _) => Some(ident.to_string()),
865             ast::StructFieldKind::UnnamedField(_) => None,
866         };
867         let vis = match field.node.kind {
868             ast::StructFieldKind::NamedField(_, vis) |
869             ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis),
870         };
871         // FIXME silly width, indent
872         let typ = field.node.ty.rewrite(&self.get_context(), 1000, Indent::empty()).unwrap();
873
874         let indent = self.block_indent.block_indent(self.config);
875         let mut attr_str = field.node
876                                 .attrs
877                                 .rewrite(&self.get_context(),
878                                          self.config.max_width - indent.width(),
879                                          indent)
880                                 .unwrap();
881         if !attr_str.is_empty() {
882             attr_str.push('\n');
883             attr_str.push_str(&indent.to_string(self.config));
884         }
885
886         match name {
887             Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ),
888             None => format!("{}{}{}", attr_str, vis, typ),
889         }
890     }
891
892     fn rewrite_generics(&self,
893                         generics: &ast::Generics,
894                         offset: Indent,
895                         generics_offset: Indent,
896                         span: Span)
897                         -> Option<String> {
898         // FIXME: convert bounds to where clauses where they get too big or if
899         // there is a where clause at all.
900         let lifetimes: &[_] = &generics.lifetimes;
901         let tys: &[_] = &generics.ty_params;
902         if lifetimes.is_empty() && tys.is_empty() {
903             return Some(String::new());
904         }
905
906         let offset = match self.config.generics_indent {
907             BlockIndentStyle::Inherit => offset,
908             BlockIndentStyle::Tabbed => offset.block_indent(self.config),
909             // 1 = <
910             BlockIndentStyle::Visual => generics_offset + 1,
911         };
912
913         let h_budget = self.config.max_width - generics_offset.width() - 2;
914         // TODO: might need to insert a newline if the generics are really long.
915
916         // Strings for the generics.
917         let context = self.get_context();
918         // FIXME: don't unwrap
919         let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset).unwrap());
920         let ty_strs = tys.iter()
921                          .map(|ty_param| ty_param.rewrite(&context, h_budget, offset).unwrap());
922
923         // Extract comments between generics.
924         let lt_spans = lifetimes.iter().map(|l| {
925             let hi = if l.bounds.is_empty() {
926                 l.lifetime.span.hi
927             } else {
928                 l.bounds[l.bounds.len() - 1].span.hi
929             };
930             codemap::mk_sp(l.lifetime.span.lo, hi)
931         });
932         let ty_spans = tys.iter().map(span_for_ty_param);
933
934         let items = itemize_list(self.codemap,
935                                  lt_spans.chain(ty_spans),
936                                  ">",
937                                  |sp| sp.lo,
938                                  |sp| sp.hi,
939                                  |_| String::new(),
940                                  span_after(span, "<", self.codemap),
941                                  span.hi);
942         let mut items = items.collect::<Vec<_>>();
943
944         for (item, ty) in items.iter_mut().zip(lt_strs.chain(ty_strs)) {
945             item.item = ty;
946         }
947
948         let fmt = ListFormatting::for_item(h_budget, offset, self.config);
949         let list_str = try_opt!(write_list(&items, &fmt));
950
951         Some(format!("<{}>", list_str))
952     }
953
954     fn rewrite_where_clause(&self,
955                             where_clause: &ast::WhereClause,
956                             config: &Config,
957                             indent: Indent,
958                             density: Density,
959                             span_end: BytePos)
960                             -> Option<String> {
961         if where_clause.predicates.is_empty() {
962             return Some(String::new());
963         }
964
965         let extra_indent = match self.config.where_indent {
966             BlockIndentStyle::Inherit => Indent::empty(),
967             BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => Indent::new(config.tab_spaces,
968                                                                                0),
969         };
970
971         let context = self.get_context();
972
973         let offset = match self.config.where_pred_indent {
974             BlockIndentStyle::Inherit => indent + extra_indent,
975             BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
976             // 6 = "where ".len()
977             BlockIndentStyle::Visual => indent + extra_indent + 6,
978         };
979         // FIXME: if where_pred_indent != Visual, then the budgets below might
980         // be out by a char or two.
981
982         let budget = self.config.max_width - offset.width();
983         let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
984         let items = itemize_list(self.codemap,
985                                  where_clause.predicates.iter(),
986                                  "{",
987                                  |pred| span_for_where_pred(pred).lo,
988                                  |pred| span_for_where_pred(pred).hi,
989                                  // FIXME: we should handle failure better
990                                  // this will be taken care of when write_list
991                                  // takes Rewrite object: see issue #133
992                                  |pred| pred.rewrite(&context, budget, offset).unwrap(),
993                                  span_start,
994                                  span_end);
995
996         let fmt = ListFormatting {
997             tactic: self.config.where_layout,
998             separator: ",",
999             trailing_separator: SeparatorTactic::Never,
1000             indent: offset,
1001             h_width: budget,
1002             v_width: budget,
1003             ends_with_newline: true,
1004             config: self.config,
1005         };
1006         let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1007
1008         // 9 = " where ".len() + " {".len()
1009         if density == Density::Tall || preds_str.contains('\n') ||
1010            indent.width() + 9 + preds_str.len() > self.config.max_width {
1011             Some(format!("\n{}where {}",
1012                          (indent + extra_indent).to_string(self.config),
1013                          preds_str))
1014         } else {
1015             Some(format!(" where {}", preds_str))
1016         }
1017     }
1018 }
1019
1020 impl Rewrite for ast::FunctionRetTy {
1021     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1022         match *self {
1023             ast::FunctionRetTy::DefaultReturn(_) => Some(String::new()),
1024             ast::FunctionRetTy::NoReturn(_) => {
1025                 if width >= 4 {
1026                     Some("-> !".to_owned())
1027                 } else {
1028                     None
1029                 }
1030             }
1031             ast::FunctionRetTy::Return(ref ty) => {
1032                 let inner_width = try_opt!(width.checked_sub(3));
1033                 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1034             }
1035         }
1036     }
1037 }
1038
1039 impl Rewrite for ast::Arg {
1040     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1041         if is_named_arg(self) {
1042             if let ast::Ty_::TyInfer = self.ty.node {
1043                 wrap_str(pprust::pat_to_string(&self.pat),
1044                          context.config.max_width,
1045                          width,
1046                          offset)
1047             } else {
1048                 let mut result = pprust::pat_to_string(&self.pat);
1049                 result.push_str(": ");
1050                 let max_width = try_opt!(width.checked_sub(result.len()));
1051                 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1052                 result.push_str(&ty_str);
1053                 Some(result)
1054             }
1055         } else {
1056             self.ty.rewrite(context, width, offset)
1057         }
1058     }
1059 }
1060
1061 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf, args: &[ast::Arg]) -> Option<String> {
1062     match explicit_self.node {
1063         ast::ExplicitSelf_::SelfRegion(lt, m, _) => {
1064             let mut_str = format_mutability(m);
1065             match lt {
1066                 Some(ref l) => Some(format!("&{} {}self", pprust::lifetime_to_string(l), mut_str)),
1067                 None => Some(format!("&{}self", mut_str)),
1068             }
1069         }
1070         ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
1071             Some(format!("self: {}", pprust::ty_to_string(ty)))
1072         }
1073         ast::ExplicitSelf_::SelfValue(_) => {
1074             assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
1075
1076             // this hacky solution caused by absence of `Mutability` in `SelfValue`.
1077             let mut_str = {
1078                 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _) =
1079                        args[0].pat.node {
1080                     format_mutability(mutability)
1081                 } else {
1082                     panic!("there is a bug or change in structure of AST, aborting.");
1083                 }
1084             };
1085
1086             Some(format!("{}self", mut_str))
1087         }
1088         _ => None,
1089     }
1090 }
1091
1092 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1093     if is_named_arg(arg) {
1094         arg.pat.span.lo
1095     } else {
1096         arg.ty.span.lo
1097     }
1098 }
1099
1100 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1101     match arg.ty.node {
1102         ast::Ty_::TyInfer if is_named_arg(arg) => arg.pat.span.hi,
1103         _ => arg.ty.span.hi,
1104     }
1105 }
1106
1107 fn is_named_arg(arg: &ast::Arg) -> bool {
1108     if let ast::Pat_::PatIdent(_, ident, _) = arg.pat.node {
1109         ident.node != token::special_idents::invalid
1110     } else {
1111         true
1112     }
1113 }
1114
1115 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1116     match *ret {
1117         ast::FunctionRetTy::NoReturn(ref span) |
1118         ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
1119         ast::FunctionRetTy::Return(ref ty) => ty.span,
1120     }
1121 }
1122
1123 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1124     // Note that ty.span is the span for ty.ident, not the whole item.
1125     let lo = ty.span.lo;
1126     if let Some(ref def) = ty.default {
1127         return codemap::mk_sp(lo, def.span.hi);
1128     }
1129     if ty.bounds.is_empty() {
1130         return ty.span;
1131     }
1132     let hi = match ty.bounds[ty.bounds.len() - 1] {
1133         ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1134         ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1135     };
1136     codemap::mk_sp(lo, hi)
1137 }
1138
1139 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1140     match *pred {
1141         ast::WherePredicate::BoundPredicate(ref p) => p.span,
1142         ast::WherePredicate::RegionPredicate(ref p) => p.span,
1143         ast::WherePredicate::EqPredicate(ref p) => p.span,
1144     }
1145 }