]> git.lizzy.rs Git - rust.git/blob - src/items.rs
ec79040f59cae02d4221baf3d29c58f14b33e5be
[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         let mut budgets = None;
517
518         // Try keeping everything on the same line
519         if !result.contains("\n") {
520             // 3 = `() `, space is before ret_string
521             let mut used_space = indent.width() + result.len() + ret_str_len + 3;
522             if !newline_brace {
523                 used_space += 2;
524             }
525             let one_line_budget = if used_space > self.config.max_width {
526                 0
527             } else {
528                 self.config.max_width - used_space
529             };
530
531             // 2 = `()`
532             let used_space = indent.width() + result.len() + 2;
533             let max_space = self.config.ideal_width + self.config.leeway;
534             debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
535                    used_space,
536                    max_space);
537             if used_space < max_space {
538                 budgets = Some((one_line_budget,
539                                 max_space - used_space,
540                                 indent + result.len() + 1));
541             }
542         }
543
544         // Didn't work. we must force vertical layout and put args on a newline.
545         if let None = budgets {
546             let new_indent = indent.block_indent(self.config);
547             let used_space = new_indent.width() + 2; // account for `(` and `)`
548             let max_space = self.config.ideal_width + self.config.leeway;
549             if used_space > max_space {
550                 // Whoops! bankrupt.
551                 // TODO: take evasive action, perhaps kill the indent or something.
552             } else {
553                 budgets = Some((0, max_space - used_space, new_indent));
554             }
555         }
556
557         budgets.unwrap()
558     }
559
560     fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
561         match self.config.fn_brace_style {
562             BraceStyle::AlwaysNextLine => true,
563             BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
564             _ => false,
565         }
566     }
567
568     pub fn visit_enum(&mut self,
569                       ident: ast::Ident,
570                       vis: ast::Visibility,
571                       enum_def: &ast::EnumDef,
572                       generics: &ast::Generics,
573                       span: Span) {
574         let header_str = self.format_header("enum ", ident, vis);
575         self.buffer.push_str(&header_str);
576
577         let enum_snippet = self.snippet(span);
578         let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
579         let generics_str = self.format_generics(generics,
580                                                 " {",
581                                                 self.block_indent,
582                                                 self.block_indent.block_indent(self.config),
583                                                 codemap::mk_sp(span.lo, body_start))
584                                .unwrap();
585         self.buffer.push_str(&generics_str);
586
587         self.last_pos = body_start;
588         self.block_indent = self.block_indent.block_indent(self.config);
589         for (i, f) in enum_def.variants.iter().enumerate() {
590             let next_span_start: BytePos = if i == enum_def.variants.len() - 1 {
591                 span.hi
592             } else {
593                 enum_def.variants[i + 1].span.lo
594             };
595
596             self.visit_variant(f, i == enum_def.variants.len() - 1, next_span_start);
597         }
598         self.block_indent = self.block_indent.block_unindent(self.config);
599
600         self.format_missing_with_indent(span.hi - BytePos(1));
601         self.buffer.push_str("}");
602     }
603
604     // Variant of an enum.
605     fn visit_variant(&mut self, field: &ast::Variant, last_field: bool, next_span_start: BytePos) {
606         if self.visit_attrs(&field.node.attrs) {
607             return;
608         }
609
610         self.format_missing_with_indent(field.span.lo);
611
612         let result = match field.node.kind {
613             ast::VariantKind::TupleVariantKind(ref types) => {
614                 let name = field.node.name.to_string();
615                 self.buffer.push_str(&name);
616
617                 let mut result = String::new();
618
619                 if !types.is_empty() {
620                     let items = itemize_list(self.codemap,
621                                              types.iter(),
622                                              ")",
623                                              |arg| arg.ty.span.lo,
624                                              |arg| arg.ty.span.hi,
625                                              |arg| {
626                                                  // FIXME silly width, indent
627                                                  arg.ty
628                                                     .rewrite(&self.get_context(),
629                                                              1000,
630                                                              Indent::empty())
631                                                     .unwrap()
632                                              },
633                                              span_after(field.span, "(", self.codemap),
634                                              next_span_start);
635
636                     result.push('(');
637
638                     let indent = self.block_indent + field.node.name.to_string().len() + "(".len();
639
640                     let comma_cost = if self.config.enum_trailing_comma {
641                         1
642                     } else {
643                         0
644                     };
645                     let budget = self.config.ideal_width - indent.width() - comma_cost - 1; // 1 = )
646
647                     let fmt = ListFormatting {
648                         tactic: ListTactic::HorizontalVertical,
649                         separator: ",",
650                         trailing_separator: SeparatorTactic::Never,
651                         indent: indent,
652                         h_width: budget,
653                         v_width: budget,
654                         ends_with_newline: true,
655                         config: self.config,
656                     };
657                     let list_str = match write_list(&items.collect::<Vec<_>>(), &fmt) {
658                         Some(list_str) => list_str,
659                         None => return,
660                     };
661
662                     result.push_str(&list_str);
663                     result.push(')');
664                 }
665
666                 if let Some(ref expr) = field.node.disr_expr {
667                     result.push_str(" = ");
668                     let expr_snippet = self.snippet(expr.span);
669                     result.push_str(&expr_snippet);
670
671                     // Make sure we do not exceed column limit
672                     assert!(self.config.max_width >=
673                             name.len() + expr_snippet.len() + " = ,".len(),
674                             "Enum variant exceeded column limit");
675                 }
676
677                 result
678             }
679             ast::VariantKind::StructVariantKind(ref struct_def) => {
680                 // TODO: Should limit the width, as we have a trailing comma
681                 let struct_rewrite = self.format_struct("",
682                                                         field.node.name,
683                                                         ast::Visibility::Inherited,
684                                                         struct_def,
685                                                         None,
686                                                         field.span,
687                                                         self.block_indent);
688
689                 match struct_rewrite {
690                     Some(struct_str) => struct_str,
691                     None => return,
692                 }
693             }
694         };
695         self.buffer.push_str(&result);
696
697         if !last_field || self.config.enum_trailing_comma {
698             self.buffer.push_str(",");
699         }
700
701         self.last_pos = field.span.hi + BytePos(1);
702     }
703
704     fn format_struct(&self,
705                      item_name: &str,
706                      ident: ast::Ident,
707                      vis: ast::Visibility,
708                      struct_def: &ast::StructDef,
709                      generics: Option<&ast::Generics>,
710                      span: Span,
711                      offset: Indent)
712                      -> Option<String> {
713         let mut result = String::with_capacity(1024);
714
715         let header_str = self.format_header(item_name, ident, vis);
716         result.push_str(&header_str);
717
718         if struct_def.fields.is_empty() {
719             result.push(';');
720             return Some(result);
721         }
722
723         let is_tuple = match struct_def.fields[0].node.kind {
724             ast::StructFieldKind::NamedField(..) => false,
725             ast::StructFieldKind::UnnamedField(..) => true,
726         };
727
728         let (opener, terminator) = if is_tuple {
729             ("(", ")")
730         } else {
731             (" {", "}")
732         };
733
734         let generics_str = match generics {
735             Some(g) => {
736                 try_opt!(self.format_generics(g,
737                                               opener,
738                                               offset,
739                                               offset + header_str.len(),
740                                               codemap::mk_sp(span.lo,
741                                                              struct_def.fields[0].span.lo)))
742             }
743             None => opener.to_owned(),
744         };
745         result.push_str(&generics_str);
746
747         let items = itemize_list(self.codemap,
748                                  struct_def.fields.iter(),
749                                  terminator,
750                                  |field| {
751                                      // Include attributes and doc comments, if present
752                                      if !field.node.attrs.is_empty() {
753                                          field.node.attrs[0].span.lo
754                                      } else {
755                                          field.span.lo
756                                      }
757                                  },
758                                  |field| field.node.ty.span.hi,
759                                  |field| self.format_field(field),
760                                  span_after(span, opener.trim(), self.codemap),
761                                  span.hi);
762
763         // 2 terminators and a semicolon
764         let used_budget = offset.width() + header_str.len() + generics_str.len() + 3;
765
766         // Conservative approximation
767         let single_line_cost = (span.hi - struct_def.fields[0].span.lo).0;
768         let break_line = !is_tuple || generics_str.contains('\n') ||
769                          single_line_cost as usize + used_budget > self.config.max_width;
770
771         let tactic = if break_line {
772             let indentation = offset.block_indent(self.config).to_string(self.config);
773             result.push('\n');
774             result.push_str(&indentation);
775
776             ListTactic::Vertical
777         } else {
778             ListTactic::Horizontal
779         };
780
781         // 1 = ,
782         let budget = self.config.ideal_width - offset.width() + self.config.tab_spaces - 1;
783         let fmt = ListFormatting {
784             tactic: tactic,
785             separator: ",",
786             trailing_separator: self.config.struct_trailing_comma,
787             indent: offset.block_indent(self.config),
788             h_width: self.config.max_width,
789             v_width: budget,
790             ends_with_newline: true,
791             config: self.config,
792         };
793
794         let list_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
795         result.push_str(&list_str);
796
797         if break_line {
798             result.push('\n');
799             result.push_str(&offset.to_string(self.config));
800         }
801
802         result.push_str(terminator);
803
804         if is_tuple {
805             result.push(';');
806         }
807
808         Some(result)
809     }
810
811     pub fn visit_struct(&mut self,
812                         ident: ast::Ident,
813                         vis: ast::Visibility,
814                         struct_def: &ast::StructDef,
815                         generics: &ast::Generics,
816                         span: Span) {
817         let indent = self.block_indent;
818         let result = self.format_struct("struct ",
819                                         ident,
820                                         vis,
821                                         struct_def,
822                                         Some(generics),
823                                         span,
824                                         indent);
825
826         if let Some(rewrite) = result {
827             self.buffer.push_str(&rewrite);
828             self.last_pos = span.hi;
829         }
830     }
831
832     fn format_header(&self, item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
833         format!("{}{}{}", format_visibility(vis), item_name, ident)
834     }
835
836     fn format_generics(&self,
837                        generics: &ast::Generics,
838                        opener: &str,
839                        offset: Indent,
840                        generics_offset: Indent,
841                        span: Span)
842                        -> Option<String> {
843         let mut result = try_opt!(self.rewrite_generics(generics, offset, generics_offset, span));
844
845         if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
846             let where_clause_str = try_opt!(self.rewrite_where_clause(&generics.where_clause,
847                                                                       self.config,
848                                                                       self.block_indent,
849                                                                       Density::Tall,
850                                                                       span.hi));
851             result.push_str(&where_clause_str);
852             result.push_str(&self.block_indent.to_string(self.config));
853             result.push('\n');
854             result.push_str(opener.trim());
855         } else {
856             result.push_str(opener);
857         }
858
859         Some(result)
860     }
861
862     // Field of a struct
863     fn format_field(&self, field: &ast::StructField) -> String {
864         if contains_skip(&field.node.attrs) {
865             return self.snippet(codemap::mk_sp(field.node.attrs[0].span.lo, field.span.hi));
866         }
867
868         let name = match field.node.kind {
869             ast::StructFieldKind::NamedField(ident, _) => Some(ident.to_string()),
870             ast::StructFieldKind::UnnamedField(_) => None,
871         };
872         let vis = match field.node.kind {
873             ast::StructFieldKind::NamedField(_, vis) |
874             ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis),
875         };
876         // FIXME silly width, indent
877         let typ = field.node.ty.rewrite(&self.get_context(), 1000, Indent::empty()).unwrap();
878
879         let indent = self.block_indent.block_indent(self.config);
880         let mut attr_str = field.node
881                                 .attrs
882                                 .rewrite(&self.get_context(),
883                                          self.config.max_width - indent.width(),
884                                          indent)
885                                 .unwrap();
886         if !attr_str.is_empty() {
887             attr_str.push('\n');
888             attr_str.push_str(&indent.to_string(self.config));
889         }
890
891         match name {
892             Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ),
893             None => format!("{}{}{}", attr_str, vis, typ),
894         }
895     }
896
897     fn rewrite_generics(&self,
898                         generics: &ast::Generics,
899                         offset: Indent,
900                         generics_offset: Indent,
901                         span: Span)
902                         -> Option<String> {
903         // FIXME: convert bounds to where clauses where they get too big or if
904         // there is a where clause at all.
905         let lifetimes: &[_] = &generics.lifetimes;
906         let tys: &[_] = &generics.ty_params;
907         if lifetimes.is_empty() && tys.is_empty() {
908             return Some(String::new());
909         }
910
911         let offset = match self.config.generics_indent {
912             BlockIndentStyle::Inherit => offset,
913             BlockIndentStyle::Tabbed => offset.block_indent(self.config),
914             // 1 = <
915             BlockIndentStyle::Visual => generics_offset + 1,
916         };
917
918         let h_budget = self.config.max_width - generics_offset.width() - 2;
919         // TODO: might need to insert a newline if the generics are really long.
920
921         // Strings for the generics.
922         let context = self.get_context();
923         // FIXME: don't unwrap
924         let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset).unwrap());
925         let ty_strs = tys.iter()
926                          .map(|ty_param| ty_param.rewrite(&context, h_budget, offset).unwrap());
927
928         // Extract comments between generics.
929         let lt_spans = lifetimes.iter().map(|l| {
930             let hi = if l.bounds.is_empty() {
931                 l.lifetime.span.hi
932             } else {
933                 l.bounds[l.bounds.len() - 1].span.hi
934             };
935             codemap::mk_sp(l.lifetime.span.lo, hi)
936         });
937         let ty_spans = tys.iter().map(span_for_ty_param);
938
939         let items = itemize_list(self.codemap,
940                                  lt_spans.chain(ty_spans),
941                                  ">",
942                                  |sp| sp.lo,
943                                  |sp| sp.hi,
944                                  |_| String::new(),
945                                  span_after(span, "<", self.codemap),
946                                  span.hi);
947         let mut items = items.collect::<Vec<_>>();
948
949         for (item, ty) in items.iter_mut().zip(lt_strs.chain(ty_strs)) {
950             item.item = ty;
951         }
952
953         let fmt = ListFormatting::for_item(h_budget, offset, self.config);
954         let list_str = try_opt!(write_list(&items, &fmt));
955
956         Some(format!("<{}>", list_str))
957     }
958
959     fn rewrite_where_clause(&self,
960                             where_clause: &ast::WhereClause,
961                             config: &Config,
962                             indent: Indent,
963                             density: Density,
964                             span_end: BytePos)
965                             -> Option<String> {
966         if where_clause.predicates.is_empty() {
967             return Some(String::new());
968         }
969
970         let extra_indent = match self.config.where_indent {
971             BlockIndentStyle::Inherit => Indent::empty(),
972             BlockIndentStyle::Tabbed | BlockIndentStyle::Visual =>
973                 Indent::new(config.tab_spaces, 0),
974         };
975
976         let context = self.get_context();
977
978         let offset = match self.config.where_pred_indent {
979             BlockIndentStyle::Inherit => indent + extra_indent,
980             BlockIndentStyle::Tabbed => indent + extra_indent.block_indent(config),
981             // 6 = "where ".len()
982             BlockIndentStyle::Visual => indent + extra_indent + 6,
983         };
984         // FIXME: if where_pred_indent != Visual, then the budgets below might
985         // be out by a char or two.
986
987         let budget = self.config.ideal_width + self.config.leeway - offset.width();
988         let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
989         let items = itemize_list(self.codemap,
990                                  where_clause.predicates.iter(),
991                                  "{",
992                                  |pred| span_for_where_pred(pred).lo,
993                                  |pred| span_for_where_pred(pred).hi,
994                                  // FIXME: we should handle failure better
995                                  // this will be taken care of when write_list
996                                  // takes Rewrite object: see issue #133
997                                  |pred| pred.rewrite(&context, budget, offset).unwrap(),
998                                  span_start,
999                                  span_end);
1000
1001         let fmt = ListFormatting {
1002             tactic: self.config.where_layout,
1003             separator: ",",
1004             trailing_separator: SeparatorTactic::Never,
1005             indent: offset,
1006             h_width: budget,
1007             v_width: budget,
1008             ends_with_newline: true,
1009             config: self.config,
1010         };
1011         let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
1012
1013         // 9 = " where ".len() + " {".len()
1014         if density == Density::Tall || preds_str.contains('\n') ||
1015            indent.width() + 9 + preds_str.len() > self.config.max_width {
1016             Some(format!("\n{}where {}",
1017                          (indent + extra_indent).to_string(self.config),
1018                          preds_str))
1019         } else {
1020             Some(format!(" where {}", preds_str))
1021         }
1022     }
1023 }
1024
1025 impl Rewrite for ast::FunctionRetTy {
1026     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1027         match *self {
1028             ast::FunctionRetTy::DefaultReturn(_) => Some(String::new()),
1029             ast::FunctionRetTy::NoReturn(_) => {
1030                 if width >= 4 {
1031                     Some("-> !".to_owned())
1032                 } else {
1033                     None
1034                 }
1035             }
1036             ast::FunctionRetTy::Return(ref ty) => {
1037                 let inner_width = try_opt!(width.checked_sub(3));
1038                 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
1039             }
1040         }
1041     }
1042 }
1043
1044 impl Rewrite for ast::Arg {
1045     fn rewrite(&self, context: &RewriteContext, width: usize, offset: Indent) -> Option<String> {
1046         if is_named_arg(self) {
1047             if let ast::Ty_::TyInfer = self.ty.node {
1048                 wrap_str(pprust::pat_to_string(&self.pat),
1049                          context.config.max_width,
1050                          width,
1051                          offset)
1052             } else {
1053                 let mut result = pprust::pat_to_string(&self.pat);
1054                 result.push_str(": ");
1055                 let max_width = try_opt!(width.checked_sub(result.len()));
1056                 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
1057                 result.push_str(&ty_str);
1058                 Some(result)
1059             }
1060         } else {
1061             self.ty.rewrite(context, width, offset)
1062         }
1063     }
1064 }
1065
1066 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf, args: &[ast::Arg]) -> Option<String> {
1067     match explicit_self.node {
1068         ast::ExplicitSelf_::SelfRegion(lt, m, _) => {
1069             let mut_str = format_mutability(m);
1070             match lt {
1071                 Some(ref l) => Some(format!("&{} {}self", pprust::lifetime_to_string(l), mut_str)),
1072                 None => Some(format!("&{}self", mut_str)),
1073             }
1074         }
1075         ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
1076             Some(format!("self: {}", pprust::ty_to_string(ty)))
1077         }
1078         ast::ExplicitSelf_::SelfValue(_) => {
1079             assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
1080
1081             // this hacky solution caused by absence of `Mutability` in `SelfValue`.
1082             let mut_str = {
1083                 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _) =
1084                        args[0].pat.node {
1085                     format_mutability(mutability)
1086                 } else {
1087                     panic!("there is a bug or change in structure of AST, aborting.");
1088                 }
1089             };
1090
1091             Some(format!("{}self", mut_str))
1092         }
1093         _ => None,
1094     }
1095 }
1096
1097 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1098     if is_named_arg(arg) {
1099         arg.pat.span.lo
1100     } else {
1101         arg.ty.span.lo
1102     }
1103 }
1104
1105 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
1106     match arg.ty.node {
1107         ast::Ty_::TyInfer if is_named_arg(arg) => arg.pat.span.hi,
1108         _ => arg.ty.span.hi,
1109     }
1110 }
1111
1112 fn is_named_arg(arg: &ast::Arg) -> bool {
1113     if let ast::Pat_::PatIdent(_, ident, _) = arg.pat.node {
1114         ident.node != token::special_idents::invalid
1115     } else {
1116         true
1117     }
1118 }
1119
1120 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1121     match *ret {
1122         ast::FunctionRetTy::NoReturn(ref span) |
1123         ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
1124         ast::FunctionRetTy::Return(ref ty) => ty.span,
1125     }
1126 }
1127
1128 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1129     // Note that ty.span is the span for ty.ident, not the whole item.
1130     let lo = ty.span.lo;
1131     if let Some(ref def) = ty.default {
1132         return codemap::mk_sp(lo, def.span.hi);
1133     }
1134     if ty.bounds.is_empty() {
1135         return ty.span;
1136     }
1137     let hi = match ty.bounds[ty.bounds.len() - 1] {
1138         ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1139         ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1140     };
1141     codemap::mk_sp(lo, hi)
1142 }
1143
1144 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1145     match *pred {
1146         ast::WherePredicate::BoundPredicate(ref p) => p.span,
1147         ast::WherePredicate::RegionPredicate(ref p) => p.span,
1148         ast::WherePredicate::EqPredicate(ref p) => p.span,
1149     }
1150 }