]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Merge pull request #2115 from topecongiro/chain_width
[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 std::borrow::Cow;
14 use std::cmp::min;
15
16 use syntax::{abi, ast, ptr, symbol};
17 use syntax::ast::{CrateSugar, ImplItem};
18 use syntax::codemap::{BytePos, Span};
19 use syntax::visit;
20
21 use spanned::Spanned;
22 use codemap::{LineRangeUtils, SpanUtils};
23 use comment::{combine_strs_with_missing_comments, contains_comment, recover_comment_removed,
24               recover_missing_comment_in_span, rewrite_missing_comment, FindUncommented};
25 use config::{BraceStyle, Config, Density, IndentStyle, ReturnIndent, Style};
26 use expr::{format_expr, is_empty_block, is_simple_block_stmt, rewrite_assign_rhs,
27            rewrite_call_inner, ExprType};
28 use lists::{definitive_tactic, itemize_list, write_list, DefinitiveListTactic, ListFormatting,
29             ListItem, ListTactic, Separator, SeparatorPlace, SeparatorTactic};
30 use rewrite::{Rewrite, RewriteContext};
31 use shape::{Indent, Shape};
32 use types::join_bounds;
33 use utils::{colon_spaces, contains_skip, end_typaram, first_line_width, format_abi,
34             format_constness, format_defaultness, format_mutability, format_unsafety,
35             format_visibility, is_attributes_extendable, last_line_contains_single_line_comment,
36             last_line_used_width, last_line_width, mk_sp, semicolon_for_expr, starts_with_newline,
37             stmt_expr, trim_newlines, trimmed_last_line_width};
38 use vertical::rewrite_with_alignment;
39 use visitor::FmtVisitor;
40
41 fn type_annotation_separator(config: &Config) -> &str {
42     colon_spaces(
43         config.space_before_type_annotation(),
44         config.space_after_type_annotation_colon(),
45     )
46 }
47
48 // Statements of the form
49 // let pat: ty = init;
50 impl Rewrite for ast::Local {
51     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
52         debug!(
53             "Local::rewrite {:?} {} {:?}",
54             self,
55             shape.width,
56             shape.indent
57         );
58
59         skip_out_of_file_lines_range!(context, self.span);
60
61         if contains_skip(&self.attrs) {
62             return None;
63         }
64
65         let attrs_str = self.attrs.rewrite(context, shape)?;
66         let mut result = if attrs_str.is_empty() {
67             "let ".to_owned()
68         } else {
69             combine_strs_with_missing_comments(
70                 context,
71                 &attrs_str,
72                 "let ",
73                 mk_sp(
74                     self.attrs.last().map(|a| a.span.hi()).unwrap(),
75                     self.span.lo(),
76                 ),
77                 shape,
78                 false,
79             )?
80         };
81
82         // 4 = "let ".len()
83         let pat_shape = shape.offset_left(4)?;
84         // 1 = ;
85         let pat_shape = pat_shape.sub_width(1)?;
86         let pat_str = self.pat.rewrite(context, pat_shape)?;
87         result.push_str(&pat_str);
88
89         // String that is placed within the assignment pattern and expression.
90         let infix = {
91             let mut infix = String::with_capacity(32);
92
93             if let Some(ref ty) = self.ty {
94                 let separator = type_annotation_separator(context.config);
95                 let indent = shape.indent + last_line_width(&result) + separator.len();
96                 // 1 = ;
97                 let budget = shape.width.checked_sub(indent.width() + 1)?;
98                 let rewrite = ty.rewrite(context, Shape::legacy(budget, indent))?;
99
100                 infix.push_str(separator);
101                 infix.push_str(&rewrite);
102             }
103
104             if self.init.is_some() {
105                 infix.push_str(" =");
106             }
107
108             infix
109         };
110
111         result.push_str(&infix);
112
113         if let Some(ref ex) = self.init {
114             // 1 = trailing semicolon;
115             let nested_shape = shape.sub_width(1)?;
116
117             result = rewrite_assign_rhs(context, result, ex, nested_shape)?;
118         }
119
120         result.push(';');
121         Some(result)
122     }
123 }
124
125 // TODO convert to using rewrite style rather than visitor
126 // TODO format modules in this style
127 #[allow(dead_code)]
128 struct Item<'a> {
129     keyword: &'static str,
130     abi: Cow<'static, str>,
131     vis: Option<&'a ast::Visibility>,
132     body: Vec<BodyElement<'a>>,
133     span: Span,
134 }
135
136 impl<'a> Item<'a> {
137     fn from_foreign_mod(fm: &'a ast::ForeignMod, span: Span, config: &Config) -> Item<'a> {
138         Item {
139             keyword: "",
140             abi: format_abi(fm.abi, config.force_explicit_abi(), true),
141             vis: None,
142             body: fm.items
143                 .iter()
144                 .map(|i| BodyElement::ForeignItem(i))
145                 .collect(),
146             span: span,
147         }
148     }
149 }
150
151 enum BodyElement<'a> {
152     // Stmt(&'a ast::Stmt),
153     // Field(&'a ast::Field),
154     // Variant(&'a ast::Variant),
155     // Item(&'a ast::Item),
156     ForeignItem(&'a ast::ForeignItem),
157 }
158
159 /// Represents a fn's signature.
160 pub struct FnSig<'a> {
161     decl: &'a ast::FnDecl,
162     generics: &'a ast::Generics,
163     abi: abi::Abi,
164     constness: ast::Constness,
165     defaultness: ast::Defaultness,
166     unsafety: ast::Unsafety,
167     visibility: ast::Visibility,
168 }
169
170 impl<'a> FnSig<'a> {
171     pub fn new(
172         decl: &'a ast::FnDecl,
173         generics: &'a ast::Generics,
174         vis: ast::Visibility,
175     ) -> FnSig<'a> {
176         FnSig {
177             decl: decl,
178             generics: generics,
179             abi: abi::Abi::Rust,
180             constness: ast::Constness::NotConst,
181             defaultness: ast::Defaultness::Final,
182             unsafety: ast::Unsafety::Normal,
183             visibility: vis,
184         }
185     }
186
187     pub fn from_method_sig(
188         method_sig: &'a ast::MethodSig,
189         generics: &'a ast::Generics,
190     ) -> FnSig<'a> {
191         FnSig {
192             unsafety: method_sig.unsafety,
193             constness: method_sig.constness.node,
194             defaultness: ast::Defaultness::Final,
195             abi: method_sig.abi,
196             decl: &*method_sig.decl,
197             generics: generics,
198             visibility: ast::Visibility::Inherited,
199         }
200     }
201
202     pub fn from_fn_kind(
203         fn_kind: &'a visit::FnKind,
204         generics: &'a ast::Generics,
205         decl: &'a ast::FnDecl,
206         defualtness: ast::Defaultness,
207     ) -> FnSig<'a> {
208         match *fn_kind {
209             visit::FnKind::ItemFn(_, unsafety, constness, abi, visibility, _) => FnSig {
210                 decl: decl,
211                 generics: generics,
212                 abi: abi,
213                 constness: constness.node,
214                 defaultness: defualtness,
215                 unsafety: unsafety,
216                 visibility: visibility.clone(),
217             },
218             visit::FnKind::Method(_, ref method_sig, vis, _) => {
219                 let mut fn_sig = FnSig::from_method_sig(method_sig, generics);
220                 fn_sig.defaultness = defualtness;
221                 if let Some(vis) = vis {
222                     fn_sig.visibility = vis.clone();
223                 }
224                 fn_sig
225             }
226             _ => unreachable!(),
227         }
228     }
229
230     fn to_str(&self, context: &RewriteContext) -> String {
231         let mut result = String::with_capacity(128);
232         // Vis defaultness constness unsafety abi.
233         result.push_str(&*format_visibility(&self.visibility));
234         result.push_str(format_defaultness(self.defaultness));
235         result.push_str(format_constness(self.constness));
236         result.push_str(format_unsafety(self.unsafety));
237         result.push_str(&format_abi(
238             self.abi,
239             context.config.force_explicit_abi(),
240             false,
241         ));
242         result
243     }
244 }
245
246 impl<'a> FmtVisitor<'a> {
247     fn format_item(&mut self, item: Item) {
248         self.buffer.push_str(&item.abi);
249
250         let snippet = self.snippet(item.span);
251         let brace_pos = snippet.find_uncommented("{").unwrap();
252
253         self.buffer.push_str("{");
254         if !item.body.is_empty() || contains_comment(&snippet[brace_pos..]) {
255             // FIXME: this skips comments between the extern keyword and the opening
256             // brace.
257             self.last_pos = item.span.lo() + BytePos(brace_pos as u32 + 1);
258             self.block_indent = self.block_indent.block_indent(self.config);
259
260             if item.body.is_empty() {
261                 self.format_missing_no_indent(item.span.hi() - BytePos(1));
262                 self.block_indent = self.block_indent.block_unindent(self.config);
263
264                 self.buffer
265                     .push_str(&self.block_indent.to_string(self.config));
266             } else {
267                 for item in &item.body {
268                     self.format_body_element(item);
269                 }
270
271                 self.block_indent = self.block_indent.block_unindent(self.config);
272                 self.format_missing_with_indent(item.span.hi() - BytePos(1));
273             }
274         }
275
276         self.buffer.push_str("}");
277         self.last_pos = item.span.hi();
278     }
279
280     fn format_body_element(&mut self, element: &BodyElement) {
281         match *element {
282             BodyElement::ForeignItem(item) => self.format_foreign_item(item),
283         }
284     }
285
286     pub fn format_foreign_mod(&mut self, fm: &ast::ForeignMod, span: Span) {
287         let item = Item::from_foreign_mod(fm, span, self.config);
288         self.format_item(item);
289     }
290
291
292     fn format_foreign_item(&mut self, item: &ast::ForeignItem) {
293         let rewrite = item.rewrite(&self.get_context(), self.shape());
294         self.push_rewrite(item.span(), rewrite);
295         self.last_pos = item.span.hi();
296     }
297
298     pub fn rewrite_fn(
299         &mut self,
300         indent: Indent,
301         ident: ast::Ident,
302         fn_sig: &FnSig,
303         span: Span,
304         block: &ast::Block,
305     ) -> Option<String> {
306         let context = self.get_context();
307
308         let has_body =
309             !is_empty_block(block, self.codemap) || !context.config.fn_empty_single_line();
310         let mut newline_brace =
311             newline_for_brace(self.config, &fn_sig.generics.where_clause, has_body);
312
313         let (mut result, force_newline_brace) =
314             rewrite_fn_base(&context, indent, ident, fn_sig, span, newline_brace, true)?;
315
316         if self.config.fn_brace_style() == BraceStyle::AlwaysNextLine || force_newline_brace {
317             newline_brace = true;
318         } else if last_line_width(&result) + 2 > self.shape().width {
319             // 2 = ` {`
320             newline_brace = true;
321         } else if !result.contains('\n') {
322             newline_brace = false;
323         }
324
325         // Prepare for the function body by possibly adding a newline and
326         // indent.
327         // FIXME we'll miss anything between the end of the signature and the
328         // start of the body, but we need more spans from the compiler to solve
329         // this.
330         if newline_brace {
331             result.push('\n');
332             result.push_str(&indent.to_string(self.config));
333         } else {
334             result.push(' ');
335         }
336
337         self.single_line_fn(&result, block).or_else(|| Some(result))
338     }
339
340     pub fn rewrite_required_fn(
341         &mut self,
342         indent: Indent,
343         ident: ast::Ident,
344         sig: &ast::MethodSig,
345         generics: &ast::Generics,
346         span: Span,
347     ) -> Option<String> {
348         // Drop semicolon or it will be interpreted as comment.
349         let span = mk_sp(span.lo(), span.hi() - BytePos(1));
350         let context = self.get_context();
351
352         let (mut result, _) = rewrite_fn_base(
353             &context,
354             indent,
355             ident,
356             &FnSig::from_method_sig(sig, generics),
357             span,
358             false,
359             false,
360         )?;
361
362         // Re-attach semicolon
363         result.push(';');
364
365         Some(result)
366     }
367
368     fn single_line_fn(&self, fn_str: &str, block: &ast::Block) -> Option<String> {
369         if fn_str.contains('\n') {
370             return None;
371         }
372
373         let codemap = self.get_context().codemap;
374
375         if self.config.fn_empty_single_line() && is_empty_block(block, codemap)
376             && self.block_indent.width() + fn_str.len() + 2 <= self.config.max_width()
377         {
378             return Some(format!("{}{{}}", fn_str));
379         }
380
381         if self.config.fn_single_line() && is_simple_block_stmt(block, codemap) {
382             let rewrite = {
383                 if let Some(stmt) = block.stmts.first() {
384                     match stmt_expr(stmt) {
385                         Some(e) => {
386                             let suffix = if semicolon_for_expr(&self.get_context(), e) {
387                                 ";"
388                             } else {
389                                 ""
390                             };
391
392                             format_expr(e, ExprType::Statement, &self.get_context(), self.shape())
393                                 .map(|s| s + suffix)
394                                 .or_else(|| Some(self.snippet(e.span)))
395                         }
396                         None => stmt.rewrite(&self.get_context(), self.shape()),
397                     }
398                 } else {
399                     None
400                 }
401             };
402
403             if let Some(res) = rewrite {
404                 let width = self.block_indent.width() + fn_str.len() + res.len() + 4;
405                 if !res.contains('\n') && width <= self.config.max_width() {
406                     return Some(format!("{}{{ {} }}", fn_str, res));
407                 }
408             }
409         }
410
411         None
412     }
413
414     pub fn visit_enum(
415         &mut self,
416         ident: ast::Ident,
417         vis: &ast::Visibility,
418         enum_def: &ast::EnumDef,
419         generics: &ast::Generics,
420         span: Span,
421     ) {
422         let enum_header = format_header("enum ", ident, vis);
423         self.buffer.push_str(&enum_header);
424
425         let enum_snippet = self.snippet(span);
426         let brace_pos = enum_snippet.find_uncommented("{").unwrap();
427         let body_start = span.lo() + BytePos(brace_pos as u32 + 1);
428         let generics_str = format_generics(
429             &self.get_context(),
430             generics,
431             "{",
432             "{",
433             self.config.item_brace_style(),
434             enum_def.variants.is_empty(),
435             self.block_indent,
436             mk_sp(span.lo(), body_start),
437             last_line_width(&enum_header),
438         ).unwrap();
439         self.buffer.push_str(&generics_str);
440
441         self.last_pos = body_start;
442
443         self.block_indent = self.block_indent.block_indent(self.config);
444         let variant_list = self.format_variant_list(enum_def, body_start, span.hi() - BytePos(1));
445         match variant_list {
446             Some(ref body_str) => self.buffer.push_str(body_str),
447             None => if contains_comment(&enum_snippet[brace_pos..]) {
448                 self.format_missing_no_indent(span.hi() - BytePos(1))
449             },
450         }
451         self.block_indent = self.block_indent.block_unindent(self.config);
452
453         if variant_list.is_some() || contains_comment(&enum_snippet[brace_pos..]) {
454             self.buffer
455                 .push_str(&self.block_indent.to_string(self.config));
456         }
457         self.buffer.push_str("}");
458         self.last_pos = span.hi();
459     }
460
461     // Format the body of an enum definition
462     fn format_variant_list(
463         &self,
464         enum_def: &ast::EnumDef,
465         body_lo: BytePos,
466         body_hi: BytePos,
467     ) -> Option<String> {
468         if enum_def.variants.is_empty() {
469             return None;
470         }
471         let mut result = String::with_capacity(1024);
472         result.push('\n');
473         let indentation = self.block_indent.to_string(self.config);
474         result.push_str(&indentation);
475
476         let items = itemize_list(
477             self.codemap,
478             enum_def.variants.iter(),
479             "}",
480             |f| if !f.node.attrs.is_empty() {
481                 f.node.attrs[0].span.lo()
482             } else {
483                 f.span.lo()
484             },
485             |f| f.span.hi(),
486             |f| self.format_variant(f),
487             body_lo,
488             body_hi,
489             false,
490         );
491
492         let shape = self.shape().sub_width(2).unwrap();
493         let fmt = ListFormatting {
494             tactic: DefinitiveListTactic::Vertical,
495             separator: ",",
496             trailing_separator: self.config.trailing_comma(),
497             separator_place: SeparatorPlace::Back,
498             shape: shape,
499             ends_with_newline: true,
500             preserve_newline: true,
501             config: self.config,
502         };
503
504         let list = write_list(&items.collect::<Vec<_>>(), &fmt)?;
505         result.push_str(&list);
506         result.push('\n');
507         Some(result)
508     }
509
510     // Variant of an enum.
511     fn format_variant(&self, field: &ast::Variant) -> Option<String> {
512         if contains_skip(&field.node.attrs) {
513             let lo = field.node.attrs[0].span.lo();
514             let span = mk_sp(lo, field.span.hi());
515             return Some(self.snippet(span));
516         }
517
518         let context = self.get_context();
519         let indent = self.block_indent;
520         let shape = self.shape();
521         let attrs_str = field.node.attrs.rewrite(&context, shape)?;
522         let lo = field
523             .node
524             .attrs
525             .last()
526             .map_or(field.span.lo(), |attr| attr.span.hi());
527         let span = mk_sp(lo, field.span.lo());
528
529         let variant_body = match field.node.data {
530             ast::VariantData::Tuple(..) | ast::VariantData::Struct(..) => {
531                 // FIXME: Should limit the width, as we have a trailing comma
532                 format_struct(
533                     &context,
534                     "",
535                     field.node.name,
536                     &ast::Visibility::Inherited,
537                     &field.node.data,
538                     None,
539                     field.span,
540                     indent,
541                     Some(self.config.struct_variant_width()),
542                 )?
543             }
544             ast::VariantData::Unit(..) => if let Some(ref expr) = field.node.disr_expr {
545                 let lhs = format!("{} =", field.node.name);
546                 // 1 = ','
547                 rewrite_assign_rhs(&context, lhs, expr, shape.sub_width(1)?)?
548             } else {
549                 String::from(field.node.name.to_string())
550             },
551         };
552
553         let attrs_extendable = attrs_str.is_empty()
554             || (context.config.attributes_on_same_line_as_variant()
555                 && is_attributes_extendable(&attrs_str));
556         combine_strs_with_missing_comments(
557             &context,
558             &attrs_str,
559             &variant_body,
560             span,
561             shape,
562             attrs_extendable,
563         )
564     }
565 }
566
567 pub fn format_impl(
568     context: &RewriteContext,
569     item: &ast::Item,
570     offset: Indent,
571     where_span_end: Option<BytePos>,
572 ) -> Option<String> {
573     if let ast::ItemKind::Impl(_, _, _, ref generics, _, ref self_ty, ref items) = item.node {
574         let mut result = String::with_capacity(128);
575         let ref_and_type = format_impl_ref_and_type(context, item, offset)?;
576         let indent_str = offset.to_string(context.config);
577         let sep = format!("\n{}", &indent_str);
578         result.push_str(&ref_and_type);
579
580         let where_budget = if result.contains('\n') {
581             context.config.max_width()
582         } else {
583             context.budget(last_line_width(&result))
584         };
585         let option = WhereClauseOption::snuggled(&ref_and_type);
586         let where_clause_str = rewrite_where_clause(
587             context,
588             &generics.where_clause,
589             context.config.item_brace_style(),
590             Shape::legacy(where_budget, offset.block_only()),
591             context.config.where_density(),
592             "{",
593             where_span_end,
594             self_ty.span.hi(),
595             option,
596         )?;
597
598         // If there is no where clause, we may have missing comments between the trait name and
599         // the opening brace.
600         if generics.where_clause.predicates.is_empty() {
601             if let Some(hi) = where_span_end {
602                 match recover_missing_comment_in_span(
603                     mk_sp(self_ty.span.hi(), hi),
604                     Shape::indented(offset, context.config),
605                     context,
606                     last_line_width(&result),
607                 ) {
608                     Some(ref missing_comment) if !missing_comment.is_empty() => {
609                         result.push_str(missing_comment);
610                     }
611                     _ => (),
612                 }
613             }
614         }
615
616         if is_impl_single_line(context, items, &result, &where_clause_str, item)? {
617             result.push_str(&where_clause_str);
618             if where_clause_str.contains('\n') || last_line_contains_single_line_comment(&result) {
619                 result.push_str(&format!("{}{{{}}}", &sep, &sep));
620             } else {
621                 result.push_str(" {}");
622             }
623             return Some(result);
624         }
625
626         if !where_clause_str.is_empty() && !where_clause_str.contains('\n') {
627             result.push('\n');
628             let width = offset.block_indent + context.config.tab_spaces() - 1;
629             let where_indent = Indent::new(0, width);
630             result.push_str(&where_indent.to_string(context.config));
631         }
632         result.push_str(&where_clause_str);
633
634         match context.config.item_brace_style() {
635             _ if last_line_contains_single_line_comment(&result) => result.push_str(&sep),
636             BraceStyle::AlwaysNextLine => result.push_str(&sep),
637             BraceStyle::PreferSameLine => result.push(' '),
638             BraceStyle::SameLineWhere => if !where_clause_str.is_empty() {
639                 result.push_str(&sep);
640             } else {
641                 result.push(' ');
642             },
643         }
644
645         result.push('{');
646
647         let snippet = context.snippet(item.span);
648         let open_pos = snippet.find_uncommented("{")? + 1;
649
650         if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
651             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
652             visitor.block_indent = offset.block_only().block_indent(context.config);
653             visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
654
655             visitor.visit_attrs(&item.attrs, ast::AttrStyle::Inner);
656             for item in items {
657                 visitor.visit_impl_item(item);
658             }
659
660             visitor.format_missing(item.span.hi() - BytePos(1));
661
662             let inner_indent_str = visitor.block_indent.to_string(context.config);
663             let outer_indent_str = offset.block_only().to_string(context.config);
664
665             result.push('\n');
666             result.push_str(&inner_indent_str);
667             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
668             result.push('\n');
669             result.push_str(&outer_indent_str);
670         }
671
672         if result.chars().last().unwrap() == '{' {
673             result.push_str(&sep);
674         }
675         result.push('}');
676
677         Some(result)
678     } else {
679         unreachable!();
680     }
681 }
682
683 fn is_impl_single_line(
684     context: &RewriteContext,
685     items: &[ImplItem],
686     result: &str,
687     where_clause_str: &str,
688     item: &ast::Item,
689 ) -> Option<bool> {
690     let snippet = context.snippet(item.span);
691     let open_pos = snippet.find_uncommented("{")? + 1;
692
693     Some(
694         context.config.impl_empty_single_line() && items.is_empty() && !result.contains('\n')
695             && result.len() + where_clause_str.len() <= context.config.max_width()
696             && !contains_comment(&snippet[open_pos..]),
697     )
698 }
699
700 fn format_impl_ref_and_type(
701     context: &RewriteContext,
702     item: &ast::Item,
703     offset: Indent,
704 ) -> Option<String> {
705     if let ast::ItemKind::Impl(
706         unsafety,
707         polarity,
708         defaultness,
709         ref generics,
710         ref trait_ref,
711         ref self_ty,
712         _,
713     ) = item.node
714     {
715         let mut result = String::with_capacity(128);
716
717         result.push_str(&format_visibility(&item.vis));
718         result.push_str(format_defaultness(defaultness));
719         result.push_str(format_unsafety(unsafety));
720         result.push_str("impl");
721
722         let lo = context.codemap.span_after(item.span, "impl");
723         let hi = match *trait_ref {
724             Some(ref tr) => tr.path.span.lo(),
725             None => self_ty.span.lo(),
726         };
727         let shape = generics_shape_from_config(
728             context.config,
729             Shape::indented(offset + last_line_width(&result), context.config),
730             0,
731         )?;
732         let one_line_budget = shape.width.checked_sub(last_line_width(&result) + 2)?;
733         let generics_str =
734             rewrite_generics_inner(context, generics, shape, one_line_budget, mk_sp(lo, hi))?;
735
736         let polarity_str = if polarity == ast::ImplPolarity::Negative {
737             "!"
738         } else {
739             ""
740         };
741
742         if let Some(ref trait_ref) = *trait_ref {
743             let result_len = result.len();
744             if let Some(trait_ref_str) = rewrite_trait_ref(
745                 context,
746                 trait_ref,
747                 offset,
748                 &generics_str,
749                 true,
750                 polarity_str,
751                 result_len,
752             ) {
753                 result.push_str(&trait_ref_str);
754             } else {
755                 let generics_str =
756                     rewrite_generics_inner(context, generics, shape, 0, mk_sp(lo, hi))?;
757                 result.push_str(&rewrite_trait_ref(
758                     context,
759                     trait_ref,
760                     offset,
761                     &generics_str,
762                     false,
763                     polarity_str,
764                     result_len,
765                 )?);
766             }
767         } else {
768             result.push_str(&generics_str);
769         }
770
771         // Try to put the self type in a single line.
772         // ` for`
773         let trait_ref_overhead = if trait_ref.is_some() { 4 } else { 0 };
774         let curly_brace_overhead = if generics.where_clause.predicates.is_empty() {
775             // If there is no where clause adapt budget for type formatting to take space and curly
776             // brace into account.
777             match context.config.item_brace_style() {
778                 BraceStyle::AlwaysNextLine => 0,
779                 _ => 2,
780             }
781         } else {
782             0
783         };
784         let used_space = last_line_width(&result) + trait_ref_overhead + curly_brace_overhead;
785         // 1 = space before the type.
786         let budget = context.budget(used_space + 1);
787         if let Some(self_ty_str) = self_ty.rewrite(context, Shape::legacy(budget, offset)) {
788             if !self_ty_str.contains('\n') {
789                 if trait_ref.is_some() {
790                     result.push_str(" for ");
791                 } else {
792                     result.push(' ');
793                 }
794                 result.push_str(&self_ty_str);
795                 return Some(result);
796             }
797         }
798
799         // Couldn't fit the self type on a single line, put it on a new line.
800         result.push('\n');
801         // Add indentation of one additional tab.
802         let new_line_offset = offset.block_indent(context.config);
803         result.push_str(&new_line_offset.to_string(context.config));
804         if trait_ref.is_some() {
805             result.push_str("for ");
806         }
807         let budget = context.budget(last_line_width(&result));
808         let type_offset = match context.config.where_style() {
809             Style::Legacy => new_line_offset + trait_ref_overhead,
810             Style::Rfc => new_line_offset,
811         };
812         result.push_str(&*self_ty
813             .rewrite(context, Shape::legacy(budget, type_offset))?);
814         Some(result)
815     } else {
816         unreachable!();
817     }
818 }
819
820 fn rewrite_trait_ref(
821     context: &RewriteContext,
822     trait_ref: &ast::TraitRef,
823     offset: Indent,
824     generics_str: &str,
825     retry: bool,
826     polarity_str: &str,
827     result_len: usize,
828 ) -> Option<String> {
829     // 1 = space between generics and trait_ref
830     let used_space = 1 + polarity_str.len() + last_line_used_width(generics_str, result_len);
831     let shape = Shape::indented(offset + used_space, context.config);
832     if let Some(trait_ref_str) = trait_ref.rewrite(context, shape) {
833         if !(retry && trait_ref_str.contains('\n')) {
834             return Some(format!(
835                 "{} {}{}",
836                 generics_str,
837                 polarity_str,
838                 &trait_ref_str
839             ));
840         }
841     }
842     // We could not make enough space for trait_ref, so put it on new line.
843     if !retry {
844         let offset = offset.block_indent(context.config);
845         let shape = Shape::indented(offset, context.config);
846         let trait_ref_str = trait_ref.rewrite(context, shape)?;
847         Some(format!(
848             "{}\n{}{}{}",
849             generics_str,
850             &offset.to_string(context.config),
851             polarity_str,
852             &trait_ref_str
853         ))
854     } else {
855         None
856     }
857 }
858
859 pub fn format_struct(
860     context: &RewriteContext,
861     item_name: &str,
862     ident: ast::Ident,
863     vis: &ast::Visibility,
864     struct_def: &ast::VariantData,
865     generics: Option<&ast::Generics>,
866     span: Span,
867     offset: Indent,
868     one_line_width: Option<usize>,
869 ) -> Option<String> {
870     match *struct_def {
871         ast::VariantData::Unit(..) => Some(format_unit_struct(item_name, ident, vis)),
872         ast::VariantData::Tuple(ref fields, _) => format_tuple_struct(
873             context,
874             item_name,
875             ident,
876             vis,
877             fields,
878             generics,
879             span,
880             offset,
881         ),
882         ast::VariantData::Struct(ref fields, _) => format_struct_struct(
883             context,
884             item_name,
885             ident,
886             vis,
887             fields,
888             generics,
889             span,
890             offset,
891             one_line_width,
892         ),
893     }
894 }
895
896 pub fn format_trait(context: &RewriteContext, item: &ast::Item, offset: Indent) -> Option<String> {
897     if let ast::ItemKind::Trait(_, unsafety, ref generics, ref type_param_bounds, ref trait_items) =
898         item.node
899     {
900         let mut result = String::with_capacity(128);
901         let header = format!(
902             "{}{}trait {}",
903             format_visibility(&item.vis),
904             format_unsafety(unsafety),
905             item.ident
906         );
907
908         result.push_str(&header);
909
910         let body_lo = context.codemap.span_after(item.span, "{");
911
912         let shape = Shape::indented(offset + last_line_width(&result), context.config);
913         let generics_str =
914             rewrite_generics(context, generics, shape, mk_sp(item.span.lo(), body_lo))?;
915         result.push_str(&generics_str);
916
917         let trait_bound_str = rewrite_trait_bounds(
918             context,
919             type_param_bounds,
920             Shape::indented(offset, context.config),
921         )?;
922         // If the trait, generics, and trait bound cannot fit on the same line,
923         // put the trait bounds on an indented new line
924         if offset.width() + last_line_width(&result) + trait_bound_str.len()
925             > context.config.comment_width()
926         {
927             result.push('\n');
928             let trait_indent = offset.block_only().block_indent(context.config);
929             result.push_str(&trait_indent.to_string(context.config));
930         }
931         result.push_str(&trait_bound_str);
932
933         let has_body = !trait_items.is_empty();
934
935         let where_density = if (context.config.where_density() == Density::Compressed
936             && (!result.contains('\n') || context.config.fn_args_layout() == IndentStyle::Block))
937             || (context.config.fn_args_layout() == IndentStyle::Block && result.is_empty())
938             || (context.config.where_density() == Density::CompressedIfEmpty && !has_body
939                 && !result.contains('\n'))
940         {
941             Density::Compressed
942         } else {
943             Density::Tall
944         };
945
946         let where_budget = context.budget(last_line_width(&result));
947         let pos_before_where = if type_param_bounds.is_empty() {
948             generics.where_clause.span.lo()
949         } else {
950             type_param_bounds[type_param_bounds.len() - 1].span().hi()
951         };
952         let option = WhereClauseOption::snuggled(&generics_str);
953         let where_clause_str = rewrite_where_clause(
954             context,
955             &generics.where_clause,
956             context.config.item_brace_style(),
957             Shape::legacy(where_budget, offset.block_only()),
958             where_density,
959             "{",
960             None,
961             pos_before_where,
962             option,
963         )?;
964         // If the where clause cannot fit on the same line,
965         // put the where clause on a new line
966         if !where_clause_str.contains('\n')
967             && last_line_width(&result) + where_clause_str.len() + offset.width()
968                 > context.config.comment_width()
969         {
970             result.push('\n');
971             let width = offset.block_indent + context.config.tab_spaces() - 1;
972             let where_indent = Indent::new(0, width);
973             result.push_str(&where_indent.to_string(context.config));
974         }
975         result.push_str(&where_clause_str);
976
977         if generics.where_clause.predicates.is_empty() {
978             let item_snippet = context.snippet(item.span);
979             if let Some(lo) = item_snippet.chars().position(|c| c == '/') {
980                 // 1 = `{`
981                 let comment_hi = body_lo - BytePos(1);
982                 let comment_lo = item.span.lo() + BytePos(lo as u32);
983                 if comment_lo < comment_hi {
984                     match recover_missing_comment_in_span(
985                         mk_sp(comment_lo, comment_hi),
986                         Shape::indented(offset, context.config),
987                         context,
988                         last_line_width(&result),
989                     ) {
990                         Some(ref missing_comment) if !missing_comment.is_empty() => {
991                             result.push_str(missing_comment);
992                         }
993                         _ => (),
994                     }
995                 }
996             }
997         }
998
999         match context.config.item_brace_style() {
1000             _ if last_line_contains_single_line_comment(&result) => {
1001                 result.push('\n');
1002                 result.push_str(&offset.to_string(context.config));
1003             }
1004             BraceStyle::AlwaysNextLine => {
1005                 result.push('\n');
1006                 result.push_str(&offset.to_string(context.config));
1007             }
1008             BraceStyle::PreferSameLine => result.push(' '),
1009             BraceStyle::SameLineWhere => if !where_clause_str.is_empty()
1010                 && (!trait_items.is_empty() || result.contains('\n'))
1011             {
1012                 result.push('\n');
1013                 result.push_str(&offset.to_string(context.config));
1014             } else {
1015                 result.push(' ');
1016             },
1017         }
1018         result.push('{');
1019
1020         let snippet = context.snippet(item.span);
1021         let open_pos = snippet.find_uncommented("{")? + 1;
1022
1023         if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
1024             let mut visitor = FmtVisitor::from_codemap(context.parse_session, context.config);
1025             visitor.block_indent = offset.block_only().block_indent(context.config);
1026             visitor.last_pos = item.span.lo() + BytePos(open_pos as u32);
1027
1028             for item in trait_items {
1029                 visitor.visit_trait_item(item);
1030             }
1031
1032             visitor.format_missing(item.span.hi() - BytePos(1));
1033
1034             let inner_indent_str = visitor.block_indent.to_string(context.config);
1035             let outer_indent_str = offset.block_only().to_string(context.config);
1036
1037             result.push('\n');
1038             result.push_str(&inner_indent_str);
1039             result.push_str(trim_newlines(visitor.buffer.to_string().trim()));
1040             result.push('\n');
1041             result.push_str(&outer_indent_str);
1042         } else if result.contains('\n') {
1043             result.push('\n');
1044         }
1045
1046         result.push('}');
1047         Some(result)
1048     } else {
1049         unreachable!();
1050     }
1051 }
1052
1053 fn format_unit_struct(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
1054     format!("{};", format_header(item_name, ident, vis))
1055 }
1056
1057 pub fn format_struct_struct(
1058     context: &RewriteContext,
1059     item_name: &str,
1060     ident: ast::Ident,
1061     vis: &ast::Visibility,
1062     fields: &[ast::StructField],
1063     generics: Option<&ast::Generics>,
1064     span: Span,
1065     offset: Indent,
1066     one_line_width: Option<usize>,
1067 ) -> Option<String> {
1068     let mut result = String::with_capacity(1024);
1069
1070     let header_str = format_header(item_name, ident, vis);
1071     result.push_str(&header_str);
1072
1073     let header_hi = span.lo() + BytePos(header_str.len() as u32);
1074     let body_lo = context.codemap.span_after(span, "{");
1075
1076     let generics_str = match generics {
1077         Some(g) => format_generics(
1078             context,
1079             g,
1080             "{",
1081             "{",
1082             context.config.item_brace_style(),
1083             fields.is_empty(),
1084             offset,
1085             mk_sp(header_hi, body_lo),
1086             last_line_width(&result),
1087         )?,
1088         None => {
1089             // 3 = ` {}`, 2 = ` {`.
1090             let overhead = if fields.is_empty() { 3 } else { 2 };
1091             if (context.config.item_brace_style() == BraceStyle::AlwaysNextLine
1092                 && !fields.is_empty())
1093                 || context.config.max_width() < overhead + result.len()
1094             {
1095                 format!("\n{}{{", offset.block_only().to_string(context.config))
1096             } else {
1097                 " {".to_owned()
1098             }
1099         }
1100     };
1101     // 1 = `}`
1102     let overhead = if fields.is_empty() { 1 } else { 0 };
1103     let total_width = result.len() + generics_str.len() + overhead;
1104     if !generics_str.is_empty() && !generics_str.contains('\n')
1105         && total_width > context.config.max_width()
1106     {
1107         result.push('\n');
1108         result.push_str(&offset.to_string(context.config));
1109         result.push_str(generics_str.trim_left());
1110     } else {
1111         result.push_str(&generics_str);
1112     }
1113
1114     if fields.is_empty() {
1115         let snippet = context.snippet(mk_sp(body_lo, span.hi() - BytePos(1)));
1116         if snippet.trim().is_empty() {
1117             // `struct S {}`
1118         } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1119             // fix indent
1120             result.push_str(snippet.trim_right());
1121             result.push('\n');
1122             result.push_str(&offset.to_string(context.config));
1123         } else {
1124             result.push_str(&snippet);
1125         }
1126         result.push('}');
1127         return Some(result);
1128     }
1129
1130     // 3 = ` ` and ` }`
1131     let one_line_budget = context.budget(result.len() + 3 + offset.width());
1132     let one_line_budget =
1133         one_line_width.map_or(0, |one_line_width| min(one_line_width, one_line_budget));
1134
1135     let items_str = rewrite_with_alignment(
1136         fields,
1137         context,
1138         Shape::indented(offset, context.config),
1139         mk_sp(body_lo, span.hi()),
1140         one_line_budget,
1141     )?;
1142
1143     if !items_str.contains('\n') && !result.contains('\n') && items_str.len() <= one_line_budget {
1144         Some(format!("{} {} }}", result, items_str))
1145     } else {
1146         Some(format!(
1147             "{}\n{}{}\n{}}}",
1148             result,
1149             offset
1150                 .block_indent(context.config)
1151                 .to_string(context.config),
1152             items_str,
1153             offset.to_string(context.config)
1154         ))
1155     }
1156 }
1157
1158 /// Returns a bytepos that is after that of `(` in `pub(..)`. If the given visibility does not
1159 /// contain `pub(..)`, then return the `lo` of the `defualt_span`. Yeah, but for what? Well, we need
1160 /// to bypass the `(` in the visibility when creating a span of tuple's body or fn's args.
1161 fn get_bytepos_after_visibility(
1162     context: &RewriteContext,
1163     vis: &ast::Visibility,
1164     default_span: Span,
1165     terminator: &str,
1166 ) -> BytePos {
1167     match *vis {
1168         ast::Visibility::Crate(s, CrateSugar::PubCrate) => context
1169             .codemap
1170             .span_after(mk_sp(s.hi(), default_span.hi()), terminator),
1171         ast::Visibility::Crate(s, CrateSugar::JustCrate) => s.hi(),
1172         ast::Visibility::Restricted { ref path, .. } => path.span.hi(),
1173         _ => default_span.lo(),
1174     }
1175 }
1176
1177 fn format_tuple_struct(
1178     context: &RewriteContext,
1179     item_name: &str,
1180     ident: ast::Ident,
1181     vis: &ast::Visibility,
1182     fields: &[ast::StructField],
1183     generics: Option<&ast::Generics>,
1184     span: Span,
1185     offset: Indent,
1186 ) -> Option<String> {
1187     let mut result = String::with_capacity(1024);
1188
1189     let header_str = format_header(item_name, ident, vis);
1190     result.push_str(&header_str);
1191
1192     let body_lo = if fields.is_empty() {
1193         let lo = get_bytepos_after_visibility(context, vis, span, ")");
1194         context.codemap.span_after(mk_sp(lo, span.hi()), "(")
1195     } else {
1196         fields[0].span.lo()
1197     };
1198     let body_hi = if fields.is_empty() {
1199         context.codemap.span_after(mk_sp(body_lo, span.hi()), ")")
1200     } else {
1201         // This is a dirty hack to work around a missing `)` from the span of the last field.
1202         let last_arg_span = fields[fields.len() - 1].span;
1203         if context.snippet(last_arg_span).ends_with(')') {
1204             last_arg_span.hi()
1205         } else {
1206             context
1207                 .codemap
1208                 .span_after(mk_sp(last_arg_span.hi(), span.hi()), ")")
1209         }
1210     };
1211
1212     let where_clause_str = match generics {
1213         Some(generics) => {
1214             let budget = context.budget(last_line_width(&header_str));
1215             let shape = Shape::legacy(budget, offset);
1216             let g_span = mk_sp(span.lo(), body_lo);
1217             let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1218             result.push_str(&generics_str);
1219
1220             let where_budget = context.budget(last_line_width(&result));
1221             let option = WhereClauseOption::new(true, false);
1222             rewrite_where_clause(
1223                 context,
1224                 &generics.where_clause,
1225                 context.config.item_brace_style(),
1226                 Shape::legacy(where_budget, offset.block_only()),
1227                 Density::Compressed,
1228                 ";",
1229                 None,
1230                 body_hi,
1231                 option,
1232             )?
1233         }
1234         None => "".to_owned(),
1235     };
1236
1237     if fields.is_empty() {
1238         // 3 = `();`
1239         let used_width = last_line_used_width(&result, offset.width()) + 3;
1240         if used_width > context.config.max_width() {
1241             result.push('\n');
1242             result.push_str(&offset
1243                 .block_indent(context.config)
1244                 .to_string(context.config))
1245         }
1246         result.push('(');
1247         let snippet = context.snippet(mk_sp(
1248             body_lo,
1249             context.codemap.span_before(mk_sp(body_lo, span.hi()), ")"),
1250         ));
1251         if snippet.is_empty() {
1252             // `struct S ()`
1253         } else if snippet.trim_right_matches(&[' ', '\t'][..]).ends_with('\n') {
1254             result.push_str(snippet.trim_right());
1255             result.push('\n');
1256             result.push_str(&offset.to_string(context.config));
1257         } else {
1258             result.push_str(&snippet);
1259         }
1260         result.push(')');
1261     } else {
1262         // 1 = ","
1263         let body = rewrite_call_inner(
1264             context,
1265             "",
1266             &fields.iter().map(|field| field).collect::<Vec<_>>()[..],
1267             span,
1268             Shape::indented(offset, context.config).sub_width(1)?,
1269             context.config.fn_call_width(),
1270             false,
1271         )?;
1272         result.push_str(&body);
1273     }
1274
1275     if !where_clause_str.is_empty() && !where_clause_str.contains('\n')
1276         && (result.contains('\n')
1277             || offset.block_indent + result.len() + where_clause_str.len() + 1
1278                 > context.config.max_width())
1279     {
1280         // We need to put the where clause on a new line, but we didn't
1281         // know that earlier, so the where clause will not be indented properly.
1282         result.push('\n');
1283         result.push_str(&(offset.block_only() + (context.config.tab_spaces() - 1))
1284             .to_string(context.config));
1285     }
1286     result.push_str(&where_clause_str);
1287
1288     Some(result)
1289 }
1290
1291 pub fn rewrite_type_alias(
1292     context: &RewriteContext,
1293     indent: Indent,
1294     ident: ast::Ident,
1295     ty: &ast::Ty,
1296     generics: &ast::Generics,
1297     vis: &ast::Visibility,
1298     span: Span,
1299 ) -> Option<String> {
1300     let mut result = String::with_capacity(128);
1301
1302     result.push_str(&format_visibility(vis));
1303     result.push_str("type ");
1304     result.push_str(&ident.to_string());
1305
1306     // 2 = `= `
1307     let shape = Shape::indented(indent + result.len(), context.config).sub_width(2)?;
1308     let g_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo());
1309     let generics_str = rewrite_generics(context, generics, shape, g_span)?;
1310     result.push_str(&generics_str);
1311
1312     let where_budget = context.budget(last_line_width(&result));
1313     let option = WhereClauseOption::snuggled(&result);
1314     let where_clause_str = rewrite_where_clause(
1315         context,
1316         &generics.where_clause,
1317         context.config.item_brace_style(),
1318         Shape::legacy(where_budget, indent),
1319         context.config.where_density(),
1320         "=",
1321         Some(span.hi()),
1322         generics.span.hi(),
1323         option,
1324     )?;
1325     result.push_str(&where_clause_str);
1326     if where_clause_str.is_empty() {
1327         result.push_str(" = ");
1328     } else {
1329         result.push_str(&format!("\n{}= ", indent.to_string(context.config)));
1330     }
1331
1332     let line_width = last_line_width(&result);
1333     // This checked_sub may fail as the extra space after '=' is not taken into account
1334     // In that case the budget is set to 0 which will make ty.rewrite retry on a new line
1335     let budget = context.budget(indent.width() + line_width + ";".len());
1336     let type_indent = indent + line_width;
1337     // Try to fit the type on the same line
1338     let ty_str = ty.rewrite(context, Shape::legacy(budget, type_indent))
1339         .or_else(|| {
1340             // The line was too short, try to put the type on the next line
1341
1342             // Remove the space after '='
1343             result.pop();
1344             let type_indent = indent.block_indent(context.config);
1345             result.push('\n');
1346             result.push_str(&type_indent.to_string(context.config));
1347             let budget = context.budget(type_indent.width() + ";".len());
1348             ty.rewrite(context, Shape::legacy(budget, type_indent))
1349         })?;
1350     result.push_str(&ty_str);
1351     result.push_str(";");
1352     Some(result)
1353 }
1354
1355 fn type_annotation_spacing(config: &Config) -> (&str, &str) {
1356     (
1357         if config.space_before_type_annotation() {
1358             " "
1359         } else {
1360             ""
1361         },
1362         if config.space_after_type_annotation_colon() {
1363             " "
1364         } else {
1365             ""
1366         },
1367     )
1368 }
1369
1370 pub fn rewrite_struct_field_prefix(
1371     context: &RewriteContext,
1372     field: &ast::StructField,
1373 ) -> Option<String> {
1374     let vis = format_visibility(&field.vis);
1375     let type_annotation_spacing = type_annotation_spacing(context.config);
1376     Some(match field.ident {
1377         Some(name) => format!("{}{}{}:", vis, name, type_annotation_spacing.0),
1378         None => format!("{}", vis),
1379     })
1380 }
1381
1382 impl Rewrite for ast::StructField {
1383     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1384         rewrite_struct_field(context, self, shape, 0)
1385     }
1386 }
1387
1388 pub fn rewrite_struct_field(
1389     context: &RewriteContext,
1390     field: &ast::StructField,
1391     shape: Shape,
1392     lhs_max_width: usize,
1393 ) -> Option<String> {
1394     if contains_skip(&field.attrs) {
1395         return Some(context.snippet(mk_sp(field.attrs[0].span.lo(), field.span.hi())));
1396     }
1397
1398     let type_annotation_spacing = type_annotation_spacing(context.config);
1399     let prefix = rewrite_struct_field_prefix(context, field)?;
1400
1401     let attrs_str = field.attrs.rewrite(context, shape)?;
1402     let attrs_extendable = attrs_str.is_empty()
1403         || (context.config.attributes_on_same_line_as_field()
1404             && is_attributes_extendable(&attrs_str));
1405     let missing_span = if field.attrs.is_empty() {
1406         mk_sp(field.span.lo(), field.span.lo())
1407     } else {
1408         mk_sp(field.attrs.last().unwrap().span.hi(), field.span.lo())
1409     };
1410     let mut spacing = String::from(if field.ident.is_some() {
1411         type_annotation_spacing.1
1412     } else {
1413         ""
1414     });
1415     // Try to put everything on a single line.
1416     let attr_prefix = combine_strs_with_missing_comments(
1417         context,
1418         &attrs_str,
1419         &prefix,
1420         missing_span,
1421         shape,
1422         attrs_extendable,
1423     )?;
1424     let overhead = last_line_width(&attr_prefix);
1425     let lhs_offset = lhs_max_width.checked_sub(overhead).unwrap_or(0);
1426     for _ in 0..lhs_offset {
1427         spacing.push(' ');
1428     }
1429     // In this extreme case we will be missing a space betweeen an attribute and a field.
1430     if prefix.is_empty() && !attrs_str.is_empty() && attrs_extendable && spacing.is_empty() {
1431         spacing.push(' ');
1432     }
1433     let ty_shape = shape.offset_left(overhead + spacing.len())?;
1434     if let Some(ref ty) = field.ty.rewrite(context, ty_shape) {
1435         if !ty.contains('\n') {
1436             return Some(attr_prefix + &spacing + ty);
1437         }
1438     }
1439
1440     // We must use multiline.
1441     let new_shape = shape.with_max_width(context.config);
1442     let ty_rewritten = field.ty.rewrite(context, new_shape)?;
1443
1444     let field_str = if prefix.is_empty() {
1445         ty_rewritten
1446     } else if prefix.len() + first_line_width(&ty_rewritten) + 1 <= shape.width {
1447         prefix + " " + &ty_rewritten
1448     } else {
1449         let type_offset = shape.indent.block_indent(context.config);
1450         let nested_shape = Shape::indented(type_offset, context.config);
1451         let nested_ty = field.ty.rewrite(context, nested_shape)?;
1452         prefix + "\n" + &type_offset.to_string(context.config) + &nested_ty
1453     };
1454     combine_strs_with_missing_comments(
1455         context,
1456         &attrs_str,
1457         &field_str,
1458         missing_span,
1459         shape,
1460         attrs_extendable,
1461     )
1462 }
1463
1464 pub fn rewrite_static(
1465     prefix: &str,
1466     vis: &ast::Visibility,
1467     ident: ast::Ident,
1468     ty: &ast::Ty,
1469     mutability: ast::Mutability,
1470     expr_opt: Option<&ptr::P<ast::Expr>>,
1471     offset: Indent,
1472     span: Span,
1473     context: &RewriteContext,
1474 ) -> Option<String> {
1475     let colon = colon_spaces(
1476         context.config.space_before_type_annotation(),
1477         context.config.space_after_type_annotation_colon(),
1478     );
1479     let prefix = format!(
1480         "{}{} {}{}{}",
1481         format_visibility(vis),
1482         prefix,
1483         format_mutability(mutability),
1484         ident,
1485         colon,
1486     );
1487     // 2 = " =".len()
1488     let ty_str = ty.rewrite(
1489         context,
1490         Shape::indented(offset.block_only(), context.config).offset_left(prefix.len() + 2)?,
1491     )?;
1492
1493     if let Some(expr) = expr_opt {
1494         let lhs = format!("{}{} =", prefix, ty_str);
1495         // 1 = ;
1496         let remaining_width = context.budget(offset.block_indent + 1);
1497         rewrite_assign_rhs(
1498             context,
1499             lhs,
1500             expr,
1501             Shape::legacy(remaining_width, offset.block_only()),
1502         ).and_then(|res| recover_comment_removed(res, span, context))
1503             .map(|s| if s.ends_with(';') { s } else { s + ";" })
1504     } else {
1505         Some(format!("{}{};", prefix, ty_str))
1506     }
1507 }
1508
1509 pub fn rewrite_associated_type(
1510     ident: ast::Ident,
1511     ty_opt: Option<&ptr::P<ast::Ty>>,
1512     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1513     context: &RewriteContext,
1514     indent: Indent,
1515 ) -> Option<String> {
1516     let prefix = format!("type {}", ident);
1517
1518     let type_bounds_str = if let Some(ty_param_bounds) = ty_param_bounds_opt {
1519         // 2 = ": ".len()
1520         let shape = Shape::indented(indent, context.config).offset_left(prefix.len() + 2)?;
1521         let bounds: &[_] = ty_param_bounds;
1522         let bound_str = bounds
1523             .iter()
1524             .map(|ty_bound| ty_bound.rewrite(context, shape))
1525             .collect::<Option<Vec<_>>>()?;
1526         if !bounds.is_empty() {
1527             format!(": {}", join_bounds(context, shape, &bound_str))
1528         } else {
1529             String::new()
1530         }
1531     } else {
1532         String::new()
1533     };
1534
1535     if let Some(ty) = ty_opt {
1536         let ty_str = ty.rewrite(
1537             context,
1538             Shape::legacy(
1539                 context.budget(indent.block_indent + prefix.len() + 2),
1540                 indent.block_only(),
1541             ),
1542         )?;
1543         Some(format!("{}{} = {};", prefix, type_bounds_str, ty_str))
1544     } else {
1545         Some(format!("{}{};", prefix, type_bounds_str))
1546     }
1547 }
1548
1549 pub fn rewrite_associated_impl_type(
1550     ident: ast::Ident,
1551     defaultness: ast::Defaultness,
1552     ty_opt: Option<&ptr::P<ast::Ty>>,
1553     ty_param_bounds_opt: Option<&ast::TyParamBounds>,
1554     context: &RewriteContext,
1555     indent: Indent,
1556 ) -> Option<String> {
1557     let result = rewrite_associated_type(ident, ty_opt, ty_param_bounds_opt, context, indent)?;
1558
1559     match defaultness {
1560         ast::Defaultness::Default => Some(format!("default {}", result)),
1561         _ => Some(result),
1562     }
1563 }
1564
1565 impl Rewrite for ast::FunctionRetTy {
1566     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1567         match *self {
1568             ast::FunctionRetTy::Default(_) => Some(String::new()),
1569             ast::FunctionRetTy::Ty(ref ty) => {
1570                 let inner_width = shape.width.checked_sub(3)?;
1571                 ty.rewrite(context, Shape::legacy(inner_width, shape.indent + 3))
1572                     .map(|r| format!("-> {}", r))
1573             }
1574         }
1575     }
1576 }
1577
1578 fn is_empty_infer(context: &RewriteContext, ty: &ast::Ty) -> bool {
1579     match ty.node {
1580         ast::TyKind::Infer => {
1581             let original = context.snippet(ty.span);
1582             original != "_"
1583         }
1584         _ => false,
1585     }
1586 }
1587
1588 impl Rewrite for ast::Arg {
1589     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
1590         if is_named_arg(self) {
1591             let mut result = self.pat
1592                 .rewrite(context, Shape::legacy(shape.width, shape.indent))?;
1593
1594             if !is_empty_infer(context, &*self.ty) {
1595                 if context.config.space_before_type_annotation() {
1596                     result.push_str(" ");
1597                 }
1598                 result.push_str(":");
1599                 if context.config.space_after_type_annotation_colon() {
1600                     result.push_str(" ");
1601                 }
1602                 let overhead = last_line_width(&result);
1603                 let max_width = shape.width.checked_sub(overhead)?;
1604                 let ty_str = self.ty
1605                     .rewrite(context, Shape::legacy(max_width, shape.indent))?;
1606                 result.push_str(&ty_str);
1607             }
1608
1609             Some(result)
1610         } else {
1611             self.ty.rewrite(context, shape)
1612         }
1613     }
1614 }
1615
1616 fn rewrite_explicit_self(
1617     explicit_self: &ast::ExplicitSelf,
1618     args: &[ast::Arg],
1619     context: &RewriteContext,
1620 ) -> Option<String> {
1621     match explicit_self.node {
1622         ast::SelfKind::Region(lt, m) => {
1623             let mut_str = format_mutability(m);
1624             match lt {
1625                 Some(ref l) => {
1626                     let lifetime_str = l.rewrite(
1627                         context,
1628                         Shape::legacy(context.config.max_width(), Indent::empty()),
1629                     )?;
1630                     Some(format!("&{} {}self", lifetime_str, mut_str))
1631                 }
1632                 None => Some(format!("&{}self", mut_str)),
1633             }
1634         }
1635         ast::SelfKind::Explicit(ref ty, _) => {
1636             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1637
1638             let mutability = explicit_self_mutability(&args[0]);
1639             let type_str = ty.rewrite(
1640                 context,
1641                 Shape::legacy(context.config.max_width(), Indent::empty()),
1642             )?;
1643
1644             Some(format!(
1645                 "{}self: {}",
1646                 format_mutability(mutability),
1647                 type_str
1648             ))
1649         }
1650         ast::SelfKind::Value(_) => {
1651             assert!(!args.is_empty(), "&[ast::Arg] shouldn't be empty.");
1652
1653             let mutability = explicit_self_mutability(&args[0]);
1654
1655             Some(format!("{}self", format_mutability(mutability)))
1656         }
1657     }
1658 }
1659
1660 // Hacky solution caused by absence of `Mutability` in `SelfValue` and
1661 // `SelfExplicit` variants of `ast::ExplicitSelf_`.
1662 fn explicit_self_mutability(arg: &ast::Arg) -> ast::Mutability {
1663     if let ast::PatKind::Ident(ast::BindingMode::ByValue(mutability), _, _) = arg.pat.node {
1664         mutability
1665     } else {
1666         unreachable!()
1667     }
1668 }
1669
1670 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
1671     if is_named_arg(arg) {
1672         arg.pat.span.lo()
1673     } else {
1674         arg.ty.span.lo()
1675     }
1676 }
1677
1678 pub fn span_hi_for_arg(context: &RewriteContext, arg: &ast::Arg) -> BytePos {
1679     match arg.ty.node {
1680         ast::TyKind::Infer if context.snippet(arg.ty.span) == "_" => arg.ty.span.hi(),
1681         ast::TyKind::Infer if is_named_arg(arg) => arg.pat.span.hi(),
1682         _ => arg.ty.span.hi(),
1683     }
1684 }
1685
1686 pub fn is_named_arg(arg: &ast::Arg) -> bool {
1687     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
1688         ident.node != symbol::keywords::Invalid.ident()
1689     } else {
1690         true
1691     }
1692 }
1693
1694 // Return type is (result, force_new_line_for_brace)
1695 fn rewrite_fn_base(
1696     context: &RewriteContext,
1697     indent: Indent,
1698     ident: ast::Ident,
1699     fn_sig: &FnSig,
1700     span: Span,
1701     newline_brace: bool,
1702     has_body: bool,
1703 ) -> Option<(String, bool)> {
1704     let mut force_new_line_for_brace = false;
1705
1706     let where_clause = &fn_sig.generics.where_clause;
1707
1708     let mut result = String::with_capacity(1024);
1709     result.push_str(&fn_sig.to_str(context));
1710
1711     // fn foo
1712     result.push_str("fn ");
1713     result.push_str(&ident.to_string());
1714
1715     // Generics.
1716     let overhead = if has_body && !newline_brace {
1717         // 4 = `() {`
1718         4
1719     } else {
1720         // 2 = `()`
1721         2
1722     };
1723     let used_width = last_line_used_width(&result, indent.width());
1724     let one_line_budget = context.budget(used_width + overhead);
1725     let shape = Shape {
1726         width: one_line_budget,
1727         indent: indent,
1728         offset: used_width,
1729     };
1730     let fd = fn_sig.decl;
1731     let g_span = mk_sp(span.lo(), fd.output.span().lo());
1732     let generics_str = rewrite_generics(context, fn_sig.generics, shape, g_span)?;
1733     result.push_str(&generics_str);
1734
1735     let snuggle_angle_bracket = generics_str
1736         .lines()
1737         .last()
1738         .map_or(false, |l| l.trim_left().len() == 1);
1739
1740     // Note that the width and indent don't really matter, we'll re-layout the
1741     // return type later anyway.
1742     let ret_str = fd.output
1743         .rewrite(context, Shape::indented(indent, context.config))?;
1744
1745     let multi_line_ret_str = ret_str.contains('\n');
1746     let ret_str_len = if multi_line_ret_str { 0 } else { ret_str.len() };
1747
1748     // Args.
1749     let (one_line_budget, multi_line_budget, mut arg_indent) = compute_budgets_for_args(
1750         context,
1751         &result,
1752         indent,
1753         ret_str_len,
1754         newline_brace,
1755         has_body,
1756         multi_line_ret_str,
1757     )?;
1758
1759     debug!(
1760         "rewrite_fn_base: one_line_budget: {}, multi_line_budget: {}, arg_indent: {:?}",
1761         one_line_budget,
1762         multi_line_budget,
1763         arg_indent
1764     );
1765
1766     // Check if vertical layout was forced.
1767     if one_line_budget == 0 {
1768         if snuggle_angle_bracket {
1769             result.push('(');
1770         } else if context.config.fn_args_paren_newline() {
1771             result.push('\n');
1772             result.push_str(&arg_indent.to_string(context.config));
1773             if context.config.fn_args_layout() == IndentStyle::Visual {
1774                 arg_indent = arg_indent + 1; // extra space for `(`
1775             }
1776             result.push('(');
1777         } else {
1778             result.push_str("(");
1779             if context.config.fn_args_layout() == IndentStyle::Visual {
1780                 result.push('\n');
1781                 result.push_str(&arg_indent.to_string(context.config));
1782             }
1783         }
1784     } else {
1785         result.push('(');
1786     }
1787     if context.config.spaces_within_parens() && !fd.inputs.is_empty() && result.ends_with('(') {
1788         result.push(' ')
1789     }
1790
1791     // Skip `pub(crate)`.
1792     let lo_after_visibility = get_bytepos_after_visibility(context, &fn_sig.visibility, span, ")");
1793     // A conservative estimation, to goal is to be over all parens in generics
1794     let args_start = fn_sig
1795         .generics
1796         .ty_params
1797         .last()
1798         .map_or(lo_after_visibility, |tp| end_typaram(tp));
1799     let args_end = if fd.inputs.is_empty() {
1800         context
1801             .codemap
1802             .span_after(mk_sp(args_start, span.hi()), ")")
1803     } else {
1804         let last_span = mk_sp(fd.inputs[fd.inputs.len() - 1].span().hi(), span.hi());
1805         context.codemap.span_after(last_span, ")")
1806     };
1807     let args_span = mk_sp(
1808         context
1809             .codemap
1810             .span_after(mk_sp(args_start, span.hi()), "("),
1811         args_end,
1812     );
1813     let arg_str = rewrite_args(
1814         context,
1815         &fd.inputs,
1816         fd.get_self().as_ref(),
1817         one_line_budget,
1818         multi_line_budget,
1819         indent,
1820         arg_indent,
1821         args_span,
1822         fd.variadic,
1823         generics_str.contains('\n'),
1824     )?;
1825
1826     let put_args_in_block = match context.config.fn_args_layout() {
1827         IndentStyle::Block => arg_str.contains('\n') || arg_str.len() > one_line_budget,
1828         _ => false,
1829     } && !fd.inputs.is_empty();
1830
1831     let mut args_last_line_contains_comment = false;
1832     if put_args_in_block {
1833         arg_indent = indent.block_indent(context.config);
1834         result.push('\n');
1835         result.push_str(&arg_indent.to_string(context.config));
1836         result.push_str(&arg_str);
1837         result.push('\n');
1838         result.push_str(&indent.to_string(context.config));
1839         result.push(')');
1840     } else {
1841         result.push_str(&arg_str);
1842         let used_width = last_line_used_width(&result, indent.width()) + first_line_width(&ret_str);
1843         // Put the closing brace on the next line if it overflows the max width.
1844         // 1 = `)`
1845         if fd.inputs.is_empty() && used_width + 1 > context.config.max_width() {
1846             result.push('\n');
1847         }
1848         if context.config.spaces_within_parens() && !fd.inputs.is_empty() {
1849             result.push(' ')
1850         }
1851         // If the last line of args contains comment, we cannot put the closing paren
1852         // on the same line.
1853         if arg_str
1854             .lines()
1855             .last()
1856             .map_or(false, |last_line| last_line.contains("//"))
1857         {
1858             args_last_line_contains_comment = true;
1859             result.push('\n');
1860             result.push_str(&arg_indent.to_string(context.config));
1861         }
1862         result.push(')');
1863     }
1864
1865     // Return type.
1866     if let ast::FunctionRetTy::Ty(..) = fd.output {
1867         let ret_should_indent = match context.config.fn_args_layout() {
1868             // If our args are block layout then we surely must have space.
1869             IndentStyle::Block if put_args_in_block || fd.inputs.is_empty() => false,
1870             _ if args_last_line_contains_comment => false,
1871             _ if result.contains('\n') || multi_line_ret_str => true,
1872             _ => {
1873                 // If the return type would push over the max width, then put the return type on
1874                 // a new line. With the +1 for the signature length an additional space between
1875                 // the closing parenthesis of the argument and the arrow '->' is considered.
1876                 let mut sig_length = result.len() + indent.width() + ret_str_len + 1;
1877
1878                 // If there is no where clause, take into account the space after the return type
1879                 // and the brace.
1880                 if where_clause.predicates.is_empty() {
1881                     sig_length += 2;
1882                 }
1883
1884                 sig_length > context.config.max_width()
1885             }
1886         };
1887         let ret_indent = if ret_should_indent {
1888             let indent = match context.config.fn_return_indent() {
1889                 ReturnIndent::WithWhereClause => indent + 4,
1890                 // Aligning with non-existent args looks silly.
1891                 _ if arg_str.is_empty() => {
1892                     force_new_line_for_brace = true;
1893                     indent + 4
1894                 }
1895                 // FIXME: we might want to check that using the arg indent
1896                 // doesn't blow our budget, and if it does, then fallback to
1897                 // the where clause indent.
1898                 _ => arg_indent,
1899             };
1900
1901             result.push('\n');
1902             result.push_str(&indent.to_string(context.config));
1903             indent
1904         } else {
1905             result.push(' ');
1906             Indent::new(indent.block_indent, last_line_width(&result))
1907         };
1908
1909         if multi_line_ret_str || ret_should_indent {
1910             // Now that we know the proper indent and width, we need to
1911             // re-layout the return type.
1912             let ret_str = fd.output
1913                 .rewrite(context, Shape::indented(ret_indent, context.config))?;
1914             result.push_str(&ret_str);
1915         } else {
1916             result.push_str(&ret_str);
1917         }
1918
1919         // Comment between return type and the end of the decl.
1920         let snippet_lo = fd.output.span().hi();
1921         if where_clause.predicates.is_empty() {
1922             let snippet_hi = span.hi();
1923             let snippet = context.snippet(mk_sp(snippet_lo, snippet_hi));
1924             // Try to preserve the layout of the original snippet.
1925             let original_starts_with_newline = snippet
1926                 .find(|c| c != ' ')
1927                 .map_or(false, |i| starts_with_newline(&snippet[i..]));
1928             let original_ends_with_newline = snippet
1929                 .rfind(|c| c != ' ')
1930                 .map_or(false, |i| snippet[i..].ends_with('\n'));
1931             let snippet = snippet.trim();
1932             if !snippet.is_empty() {
1933                 result.push(if original_starts_with_newline {
1934                     '\n'
1935                 } else {
1936                     ' '
1937                 });
1938                 result.push_str(snippet);
1939                 if original_ends_with_newline {
1940                     force_new_line_for_brace = true;
1941                 }
1942             }
1943         }
1944     }
1945
1946     let should_compress_where = match context.config.where_density() {
1947         Density::Compressed => !result.contains('\n'),
1948         Density::CompressedIfEmpty => !has_body && !result.contains('\n'),
1949         _ => false,
1950     };
1951
1952     let pos_before_where = match fd.output {
1953         ast::FunctionRetTy::Default(..) => args_span.hi(),
1954         ast::FunctionRetTy::Ty(ref ty) => ty.span.hi(),
1955     };
1956
1957     if where_clause.predicates.len() == 1 && should_compress_where {
1958         let budget = context.budget(last_line_used_width(&result, indent.width()));
1959         if let Some(where_clause_str) = rewrite_where_clause(
1960             context,
1961             where_clause,
1962             context.config.fn_brace_style(),
1963             Shape::legacy(budget, indent),
1964             Density::Compressed,
1965             "{",
1966             Some(span.hi()),
1967             pos_before_where,
1968             WhereClauseOption::compressed(),
1969         ) {
1970             result.push_str(&where_clause_str);
1971             force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
1972             return Some((result, force_new_line_for_brace));
1973         }
1974     }
1975
1976     let option = WhereClauseOption::new(!has_body, put_args_in_block && ret_str.is_empty());
1977     let where_clause_str = rewrite_where_clause(
1978         context,
1979         where_clause,
1980         context.config.fn_brace_style(),
1981         Shape::indented(indent, context.config),
1982         Density::Tall,
1983         "{",
1984         Some(span.hi()),
1985         pos_before_where,
1986         option,
1987     )?;
1988     // If there are neither where clause nor return type, we may be missing comments between
1989     // args and `{`.
1990     if where_clause_str.is_empty() {
1991         if let ast::FunctionRetTy::Default(ret_span) = fd.output {
1992             match recover_missing_comment_in_span(
1993                 mk_sp(args_span.hi(), ret_span.hi()),
1994                 shape,
1995                 context,
1996                 last_line_width(&result),
1997             ) {
1998                 Some(ref missing_comment) if !missing_comment.is_empty() => {
1999                     result.push_str(missing_comment);
2000                     force_new_line_for_brace = true;
2001                 }
2002                 _ => (),
2003             }
2004         }
2005     }
2006
2007     result.push_str(&where_clause_str);
2008
2009     force_new_line_for_brace |= last_line_contains_single_line_comment(&result);
2010     Some((result, force_new_line_for_brace))
2011 }
2012
2013 #[derive(Copy, Clone)]
2014 struct WhereClauseOption {
2015     suppress_comma: bool, // Force no trailing comma
2016     snuggle: bool,        // Do not insert newline before `where`
2017     compress_where: bool, // Try single line where clause instead of vertical layout
2018 }
2019
2020 impl WhereClauseOption {
2021     pub fn new(suppress_comma: bool, snuggle: bool) -> WhereClauseOption {
2022         WhereClauseOption {
2023             suppress_comma: suppress_comma,
2024             snuggle: snuggle,
2025             compress_where: false,
2026         }
2027     }
2028
2029     pub fn compressed() -> WhereClauseOption {
2030         WhereClauseOption {
2031             suppress_comma: true,
2032             snuggle: false,
2033             compress_where: true,
2034         }
2035     }
2036
2037     pub fn snuggled(current: &str) -> WhereClauseOption {
2038         WhereClauseOption {
2039             suppress_comma: false,
2040             snuggle: trimmed_last_line_width(current) == 1,
2041             compress_where: false,
2042         }
2043     }
2044 }
2045
2046 fn rewrite_args(
2047     context: &RewriteContext,
2048     args: &[ast::Arg],
2049     explicit_self: Option<&ast::ExplicitSelf>,
2050     one_line_budget: usize,
2051     multi_line_budget: usize,
2052     indent: Indent,
2053     arg_indent: Indent,
2054     span: Span,
2055     variadic: bool,
2056     generics_str_contains_newline: bool,
2057 ) -> Option<String> {
2058     let mut arg_item_strs = args.iter()
2059         .map(|arg| arg.rewrite(context, Shape::legacy(multi_line_budget, arg_indent)))
2060         .collect::<Option<Vec<_>>>()?;
2061
2062     // Account for sugary self.
2063     // FIXME: the comment for the self argument is dropped. This is blocked
2064     // on rust issue #27522.
2065     let min_args = explicit_self
2066         .and_then(|explicit_self| {
2067             rewrite_explicit_self(explicit_self, args, context)
2068         })
2069         .map_or(1, |self_str| {
2070             arg_item_strs[0] = self_str;
2071             2
2072         });
2073
2074     // Comments between args.
2075     let mut arg_items = Vec::new();
2076     if min_args == 2 {
2077         arg_items.push(ListItem::from_str(""));
2078     }
2079
2080     // FIXME(#21): if there are no args, there might still be a comment, but
2081     // without spans for the comment or parens, there is no chance of
2082     // getting it right. You also don't get to put a comment on self, unless
2083     // it is explicit.
2084     if args.len() >= min_args || variadic {
2085         let comment_span_start = if min_args == 2 {
2086             let second_arg_start = if arg_has_pattern(&args[1]) {
2087                 args[1].pat.span.lo()
2088             } else {
2089                 args[1].ty.span.lo()
2090             };
2091             let reduced_span = mk_sp(span.lo(), second_arg_start);
2092
2093             context.codemap.span_after_last(reduced_span, ",")
2094         } else {
2095             span.lo()
2096         };
2097
2098         enum ArgumentKind<'a> {
2099             Regular(&'a ast::Arg),
2100             Variadic(BytePos),
2101         }
2102
2103         let variadic_arg = if variadic {
2104             let variadic_span = mk_sp(args.last().unwrap().ty.span.hi(), span.hi());
2105             let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
2106             Some(ArgumentKind::Variadic(variadic_start))
2107         } else {
2108             None
2109         };
2110
2111         let more_items = itemize_list(
2112             context.codemap,
2113             args[min_args - 1..]
2114                 .iter()
2115                 .map(ArgumentKind::Regular)
2116                 .chain(variadic_arg),
2117             ")",
2118             |arg| match *arg {
2119                 ArgumentKind::Regular(arg) => span_lo_for_arg(arg),
2120                 ArgumentKind::Variadic(start) => start,
2121             },
2122             |arg| match *arg {
2123                 ArgumentKind::Regular(arg) => arg.ty.span.hi(),
2124                 ArgumentKind::Variadic(start) => start + BytePos(3),
2125             },
2126             |arg| match *arg {
2127                 ArgumentKind::Regular(..) => None,
2128                 ArgumentKind::Variadic(..) => Some("...".to_owned()),
2129             },
2130             comment_span_start,
2131             span.hi(),
2132             false,
2133         );
2134
2135         arg_items.extend(more_items);
2136     }
2137
2138     let fits_in_one_line = !generics_str_contains_newline
2139         && (arg_items.is_empty()
2140             || arg_items.len() == 1 && arg_item_strs[0].len() <= one_line_budget);
2141
2142     for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
2143         item.item = Some(arg);
2144     }
2145
2146     let last_line_ends_with_comment = arg_items
2147         .iter()
2148         .last()
2149         .and_then(|item| item.post_comment.as_ref())
2150         .map_or(false, |s| s.trim().starts_with("//"));
2151
2152     let (indent, trailing_comma) = match context.config.fn_args_layout() {
2153         IndentStyle::Block if fits_in_one_line => {
2154             (indent.block_indent(context.config), SeparatorTactic::Never)
2155         }
2156         IndentStyle::Block => (
2157             indent.block_indent(context.config),
2158             context.config.trailing_comma(),
2159         ),
2160         IndentStyle::Visual if last_line_ends_with_comment => {
2161             (arg_indent, context.config.trailing_comma())
2162         }
2163         IndentStyle::Visual => (arg_indent, SeparatorTactic::Never),
2164     };
2165
2166     let tactic = definitive_tactic(
2167         &arg_items,
2168         context.config.fn_args_density().to_list_tactic(),
2169         Separator::Comma,
2170         one_line_budget,
2171     );
2172     let budget = match tactic {
2173         DefinitiveListTactic::Horizontal => one_line_budget,
2174         _ => multi_line_budget,
2175     };
2176
2177     debug!("rewrite_args: budget: {}, tactic: {:?}", budget, tactic);
2178
2179     let fmt = ListFormatting {
2180         tactic: tactic,
2181         separator: ",",
2182         trailing_separator: if variadic {
2183             SeparatorTactic::Never
2184         } else {
2185             trailing_comma
2186         },
2187         separator_place: SeparatorPlace::Back,
2188         shape: Shape::legacy(budget, indent),
2189         ends_with_newline: tactic.ends_with_newline(context.config.fn_args_layout()),
2190         preserve_newline: true,
2191         config: context.config,
2192     };
2193
2194     write_list(&arg_items, &fmt)
2195 }
2196
2197 fn arg_has_pattern(arg: &ast::Arg) -> bool {
2198     if let ast::PatKind::Ident(_, ident, _) = arg.pat.node {
2199         ident.node != symbol::keywords::Invalid.ident()
2200     } else {
2201         true
2202     }
2203 }
2204
2205 fn compute_budgets_for_args(
2206     context: &RewriteContext,
2207     result: &str,
2208     indent: Indent,
2209     ret_str_len: usize,
2210     newline_brace: bool,
2211     has_braces: bool,
2212     force_vertical_layout: bool,
2213 ) -> Option<((usize, usize, Indent))> {
2214     debug!(
2215         "compute_budgets_for_args {} {:?}, {}, {}",
2216         result.len(),
2217         indent,
2218         ret_str_len,
2219         newline_brace
2220     );
2221     // Try keeping everything on the same line.
2222     if !result.contains('\n') && !force_vertical_layout {
2223         // 2 = `()`, 3 = `() `, space is before ret_string.
2224         let overhead = if ret_str_len == 0 { 2 } else { 3 };
2225         let mut used_space = indent.width() + result.len() + ret_str_len + overhead;
2226         if has_braces {
2227             if !newline_brace {
2228                 // 2 = `{}`
2229                 used_space += 2;
2230             }
2231         } else {
2232             // 1 = `;`
2233             used_space += 1;
2234         }
2235         let one_line_budget = context.budget(used_space);
2236
2237         if one_line_budget > 0 {
2238             // 4 = "() {".len()
2239             let (indent, multi_line_budget) = match context.config.fn_args_layout() {
2240                 IndentStyle::Block => {
2241                     let indent = indent.block_indent(context.config);
2242                     (indent, context.budget(indent.width() + 1))
2243                 }
2244                 IndentStyle::Visual => {
2245                     let indent = indent + result.len() + 1;
2246                     let multi_line_overhead = indent.width() + if newline_brace { 2 } else { 4 };
2247                     (indent, context.budget(multi_line_overhead))
2248                 }
2249             };
2250
2251             return Some((one_line_budget, multi_line_budget, indent));
2252         }
2253     }
2254
2255     // Didn't work. we must force vertical layout and put args on a newline.
2256     let new_indent = indent.block_indent(context.config);
2257     let used_space = match context.config.fn_args_layout() {
2258         // 1 = `,`
2259         IndentStyle::Block => new_indent.width() + 1,
2260         // Account for `)` and possibly ` {`.
2261         IndentStyle::Visual => new_indent.width() + if ret_str_len == 0 { 1 } else { 3 },
2262     };
2263     Some((0, context.budget(used_space), new_indent))
2264 }
2265
2266 fn newline_for_brace(config: &Config, where_clause: &ast::WhereClause, has_body: bool) -> bool {
2267     match (config.fn_brace_style(), config.where_density()) {
2268         (BraceStyle::AlwaysNextLine, _) => true,
2269         (_, Density::Compressed) if where_clause.predicates.len() == 1 => false,
2270         (_, Density::CompressedIfEmpty) if where_clause.predicates.len() == 1 && !has_body => false,
2271         (BraceStyle::SameLineWhere, _) if !where_clause.predicates.is_empty() => true,
2272         _ => false,
2273     }
2274 }
2275
2276 fn rewrite_generics(
2277     context: &RewriteContext,
2278     generics: &ast::Generics,
2279     shape: Shape,
2280     span: Span,
2281 ) -> Option<String> {
2282     let g_shape = generics_shape_from_config(context.config, shape, 0)?;
2283     let one_line_width = shape.width.checked_sub(2).unwrap_or(0);
2284     rewrite_generics_inner(context, generics, g_shape, one_line_width, span).or_else(|| {
2285         rewrite_generics_inner(context, generics, g_shape, 0, span)
2286     })
2287 }
2288
2289 fn rewrite_generics_inner(
2290     context: &RewriteContext,
2291     generics: &ast::Generics,
2292     shape: Shape,
2293     one_line_width: usize,
2294     span: Span,
2295 ) -> Option<String> {
2296     // FIXME: convert bounds to where clauses where they get too big or if
2297     // there is a where clause at all.
2298
2299     // Wrapper type
2300     enum GenericsArg<'a> {
2301         Lifetime(&'a ast::LifetimeDef),
2302         TyParam(&'a ast::TyParam),
2303     }
2304     impl<'a> Rewrite for GenericsArg<'a> {
2305         fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2306             match *self {
2307                 GenericsArg::Lifetime(ref lifetime) => lifetime.rewrite(context, shape),
2308                 GenericsArg::TyParam(ref ty) => ty.rewrite(context, shape),
2309             }
2310         }
2311     }
2312     impl<'a> Spanned for GenericsArg<'a> {
2313         fn span(&self) -> Span {
2314             match *self {
2315                 GenericsArg::Lifetime(ref lifetime) => lifetime.span(),
2316                 GenericsArg::TyParam(ref ty) => ty.span(),
2317             }
2318         }
2319     }
2320
2321     if generics.lifetimes.is_empty() && generics.ty_params.is_empty() {
2322         return Some(String::new());
2323     }
2324
2325     let generics_args = generics
2326         .lifetimes
2327         .iter()
2328         .map(|lt| GenericsArg::Lifetime(lt))
2329         .chain(generics.ty_params.iter().map(|ty| GenericsArg::TyParam(ty)));
2330     let items = itemize_list(
2331         context.codemap,
2332         generics_args,
2333         ">",
2334         |arg| arg.span().lo(),
2335         |arg| arg.span().hi(),
2336         |arg| arg.rewrite(context, shape),
2337         context.codemap.span_after(span, "<"),
2338         span.hi(),
2339         false,
2340     );
2341     format_generics_item_list(context, items, shape, one_line_width)
2342 }
2343
2344 pub fn generics_shape_from_config(config: &Config, shape: Shape, offset: usize) -> Option<Shape> {
2345     match config.generics_indent() {
2346         IndentStyle::Visual => shape.visual_indent(1 + offset).sub_width(offset + 2),
2347         IndentStyle::Block => {
2348             // 1 = ","
2349             shape
2350                 .block()
2351                 .block_indent(config.tab_spaces())
2352                 .with_max_width(config)
2353                 .sub_width(1)
2354         }
2355     }
2356 }
2357
2358 pub fn format_generics_item_list<I>(
2359     context: &RewriteContext,
2360     items: I,
2361     shape: Shape,
2362     one_line_budget: usize,
2363 ) -> Option<String>
2364 where
2365     I: Iterator<Item = ListItem>,
2366 {
2367     let item_vec = items.collect::<Vec<_>>();
2368
2369     let tactic = definitive_tactic(
2370         &item_vec,
2371         ListTactic::HorizontalVertical,
2372         Separator::Comma,
2373         one_line_budget,
2374     );
2375     let fmt = ListFormatting {
2376         tactic: tactic,
2377         separator: ",",
2378         trailing_separator: if context.config.generics_indent() == IndentStyle::Visual {
2379             SeparatorTactic::Never
2380         } else {
2381             context.config.trailing_comma()
2382         },
2383         separator_place: SeparatorPlace::Back,
2384         shape: shape,
2385         ends_with_newline: tactic.ends_with_newline(context.config.generics_indent()),
2386         preserve_newline: true,
2387         config: context.config,
2388     };
2389
2390     let list_str = write_list(&item_vec, &fmt)?;
2391
2392     Some(wrap_generics_with_angle_brackets(
2393         context,
2394         &list_str,
2395         shape.indent,
2396     ))
2397 }
2398
2399 pub fn wrap_generics_with_angle_brackets(
2400     context: &RewriteContext,
2401     list_str: &str,
2402     list_offset: Indent,
2403 ) -> String {
2404     if context.config.generics_indent() == IndentStyle::Block
2405         && (list_str.contains('\n') || list_str.ends_with(','))
2406     {
2407         format!(
2408             "<\n{}{}\n{}>",
2409             list_offset.to_string(context.config),
2410             list_str,
2411             list_offset
2412                 .block_unindent(context.config)
2413                 .to_string(context.config)
2414         )
2415     } else if context.config.spaces_within_angle_brackets() {
2416         format!("< {} >", list_str)
2417     } else {
2418         format!("<{}>", list_str)
2419     }
2420 }
2421
2422 fn rewrite_trait_bounds(
2423     context: &RewriteContext,
2424     type_param_bounds: &ast::TyParamBounds,
2425     shape: Shape,
2426 ) -> Option<String> {
2427     let bounds: &[_] = type_param_bounds;
2428
2429     if bounds.is_empty() {
2430         return Some(String::new());
2431     }
2432     let bound_str = bounds
2433         .iter()
2434         .map(|ty_bound| ty_bound.rewrite(context, shape))
2435         .collect::<Option<Vec<_>>>()?;
2436     Some(format!(": {}", join_bounds(context, shape, &bound_str)))
2437 }
2438
2439 fn rewrite_where_clause_rfc_style(
2440     context: &RewriteContext,
2441     where_clause: &ast::WhereClause,
2442     shape: Shape,
2443     terminator: &str,
2444     span_end: Option<BytePos>,
2445     span_end_before_where: BytePos,
2446     where_clause_option: WhereClauseOption,
2447 ) -> Option<String> {
2448     let block_shape = shape.block().with_max_width(context.config);
2449
2450     let (span_before, span_after) =
2451         missing_span_before_after_where(span_end_before_where, where_clause);
2452     let (comment_before, comment_after) =
2453         rewrite_comments_before_after_where(context, span_before, span_after, shape)?;
2454
2455     let starting_newline = if where_clause_option.snuggle && comment_before.is_empty() {
2456         " ".to_owned()
2457     } else {
2458         "\n".to_owned() + &block_shape.indent.to_string(context.config)
2459     };
2460
2461     let clause_shape = block_shape.block_left(context.config.tab_spaces())?;
2462     // 1 = `,`
2463     let clause_shape = clause_shape.sub_width(1)?;
2464     // each clause on one line, trailing comma (except if suppress_comma)
2465     let span_start = where_clause.predicates[0].span().lo();
2466     // If we don't have the start of the next span, then use the end of the
2467     // predicates, but that means we miss comments.
2468     let len = where_clause.predicates.len();
2469     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2470     let span_end = span_end.unwrap_or(end_of_preds);
2471     let items = itemize_list(
2472         context.codemap,
2473         where_clause.predicates.iter(),
2474         terminator,
2475         |pred| pred.span().lo(),
2476         |pred| pred.span().hi(),
2477         |pred| pred.rewrite(context, clause_shape),
2478         span_start,
2479         span_end,
2480         false,
2481     );
2482     let comma_tactic = if where_clause_option.suppress_comma {
2483         SeparatorTactic::Never
2484     } else {
2485         context.config.trailing_comma()
2486     };
2487
2488     let fmt = ListFormatting {
2489         tactic: DefinitiveListTactic::Vertical,
2490         separator: ",",
2491         trailing_separator: comma_tactic,
2492         separator_place: SeparatorPlace::Back,
2493         shape: clause_shape,
2494         ends_with_newline: true,
2495         preserve_newline: true,
2496         config: context.config,
2497     };
2498     let preds_str = write_list(&items.collect::<Vec<_>>(), &fmt)?;
2499
2500     let comment_separator = |comment: &str, shape: Shape| if comment.is_empty() {
2501         String::new()
2502     } else {
2503         format!("\n{}", shape.indent.to_string(context.config))
2504     };
2505     let newline_before_where = comment_separator(&comment_before, shape);
2506     let newline_after_where = comment_separator(&comment_after, clause_shape);
2507
2508     // 6 = `where `
2509     let clause_sep = if where_clause_option.compress_where && comment_before.is_empty()
2510         && comment_after.is_empty() && !preds_str.contains('\n')
2511         && 6 + preds_str.len() <= shape.width
2512     {
2513         String::from(" ")
2514     } else {
2515         format!("\n{}", clause_shape.indent.to_string(context.config))
2516     };
2517     Some(format!(
2518         "{}{}{}where{}{}{}{}",
2519         starting_newline,
2520         comment_before,
2521         newline_before_where,
2522         newline_after_where,
2523         comment_after,
2524         clause_sep,
2525         preds_str
2526     ))
2527 }
2528
2529 fn rewrite_where_clause(
2530     context: &RewriteContext,
2531     where_clause: &ast::WhereClause,
2532     brace_style: BraceStyle,
2533     shape: Shape,
2534     density: Density,
2535     terminator: &str,
2536     span_end: Option<BytePos>,
2537     span_end_before_where: BytePos,
2538     where_clause_option: WhereClauseOption,
2539 ) -> Option<String> {
2540     if where_clause.predicates.is_empty() {
2541         return Some(String::new());
2542     }
2543
2544     if context.config.where_style() == Style::Rfc {
2545         return rewrite_where_clause_rfc_style(
2546             context,
2547             where_clause,
2548             shape,
2549             terminator,
2550             span_end,
2551             span_end_before_where,
2552             where_clause_option,
2553         );
2554     }
2555
2556     let extra_indent = Indent::new(context.config.tab_spaces(), 0);
2557
2558     let offset = match context.config.where_pred_indent() {
2559         IndentStyle::Block => shape.indent + extra_indent.block_indent(context.config),
2560         // 6 = "where ".len()
2561         IndentStyle::Visual => shape.indent + extra_indent + 6,
2562     };
2563     // FIXME: if where_pred_indent != Visual, then the budgets below might
2564     // be out by a char or two.
2565
2566     let budget = context.config.max_width() - offset.width();
2567     let span_start = where_clause.predicates[0].span().lo();
2568     // If we don't have the start of the next span, then use the end of the
2569     // predicates, but that means we miss comments.
2570     let len = where_clause.predicates.len();
2571     let end_of_preds = where_clause.predicates[len - 1].span().hi();
2572     let span_end = span_end.unwrap_or(end_of_preds);
2573     let items = itemize_list(
2574         context.codemap,
2575         where_clause.predicates.iter(),
2576         terminator,
2577         |pred| pred.span().lo(),
2578         |pred| pred.span().hi(),
2579         |pred| pred.rewrite(context, Shape::legacy(budget, offset)),
2580         span_start,
2581         span_end,
2582         false,
2583     );
2584     let item_vec = items.collect::<Vec<_>>();
2585     // FIXME: we don't need to collect here if the where_layout isn't
2586     // HorizontalVertical.
2587     let tactic = definitive_tactic(
2588         &item_vec,
2589         context.config.where_layout(),
2590         Separator::Comma,
2591         budget,
2592     );
2593
2594     let mut comma_tactic = context.config.trailing_comma();
2595     // Kind of a hack because we don't usually have trailing commas in where clauses.
2596     if comma_tactic == SeparatorTactic::Vertical || where_clause_option.suppress_comma {
2597         comma_tactic = SeparatorTactic::Never;
2598     }
2599
2600     let fmt = ListFormatting {
2601         tactic: tactic,
2602         separator: ",",
2603         trailing_separator: comma_tactic,
2604         separator_place: SeparatorPlace::Back,
2605         shape: Shape::legacy(budget, offset),
2606         ends_with_newline: tactic.ends_with_newline(context.config.where_pred_indent()),
2607         preserve_newline: true,
2608         config: context.config,
2609     };
2610     let preds_str = write_list(&item_vec, &fmt)?;
2611
2612     let end_length = if terminator == "{" {
2613         // If the brace is on the next line we don't need to count it otherwise it needs two
2614         // characters " {"
2615         match brace_style {
2616             BraceStyle::AlwaysNextLine | BraceStyle::SameLineWhere => 0,
2617             BraceStyle::PreferSameLine => 2,
2618         }
2619     } else if terminator == "=" {
2620         2
2621     } else {
2622         terminator.len()
2623     };
2624     if density == Density::Tall || preds_str.contains('\n')
2625         || shape.indent.width() + " where ".len() + preds_str.len() + end_length > shape.width
2626     {
2627         Some(format!(
2628             "\n{}where {}",
2629             (shape.indent + extra_indent).to_string(context.config),
2630             preds_str
2631         ))
2632     } else {
2633         Some(format!(" where {}", preds_str))
2634     }
2635 }
2636
2637 fn missing_span_before_after_where(
2638     before_item_span_end: BytePos,
2639     where_clause: &ast::WhereClause,
2640 ) -> (Span, Span) {
2641     let missing_span_before = mk_sp(before_item_span_end, where_clause.span.lo());
2642     // 5 = `where`
2643     let pos_after_where = where_clause.span.lo() + BytePos(5);
2644     let missing_span_after = mk_sp(pos_after_where, where_clause.predicates[0].span().lo());
2645     (missing_span_before, missing_span_after)
2646 }
2647
2648 fn rewrite_comments_before_after_where(
2649     context: &RewriteContext,
2650     span_before_where: Span,
2651     span_after_where: Span,
2652     shape: Shape,
2653 ) -> Option<(String, String)> {
2654     let before_comment = rewrite_missing_comment(span_before_where, shape, context)?;
2655     let after_comment = rewrite_missing_comment(
2656         span_after_where,
2657         shape.block_indent(context.config.tab_spaces()),
2658         context,
2659     )?;
2660     Some((before_comment, after_comment))
2661 }
2662
2663 fn format_header(item_name: &str, ident: ast::Ident, vis: &ast::Visibility) -> String {
2664     format!("{}{}{}", format_visibility(vis), item_name, ident)
2665 }
2666
2667 fn format_generics(
2668     context: &RewriteContext,
2669     generics: &ast::Generics,
2670     opener: &str,
2671     terminator: &str,
2672     brace_style: BraceStyle,
2673     force_same_line_brace: bool,
2674     offset: Indent,
2675     span: Span,
2676     used_width: usize,
2677 ) -> Option<String> {
2678     let shape = Shape::legacy(context.budget(used_width + offset.width()), offset);
2679     let mut result = rewrite_generics(context, generics, shape, span)?;
2680
2681     let same_line_brace = if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
2682         let budget = context.budget(last_line_used_width(&result, offset.width()));
2683         let option = WhereClauseOption::snuggled(&result);
2684         // If the generics are not parameterized then generics.span.hi() == 0,
2685         // so we use span.lo(), which is the position after `struct Foo`.
2686         let span_end_before_where = if generics.is_parameterized() {
2687             generics.span.hi()
2688         } else {
2689             span.lo()
2690         };
2691         let where_clause_str = rewrite_where_clause(
2692             context,
2693             &generics.where_clause,
2694             brace_style,
2695             Shape::legacy(budget, offset.block_only()),
2696             Density::Tall,
2697             terminator,
2698             Some(span.hi()),
2699             span_end_before_where,
2700             option,
2701         )?;
2702         result.push_str(&where_clause_str);
2703         force_same_line_brace || brace_style == BraceStyle::PreferSameLine
2704             || (generics.where_clause.predicates.is_empty()
2705                 && trimmed_last_line_width(&result) == 1)
2706     } else {
2707         force_same_line_brace || trimmed_last_line_width(&result) == 1
2708             || brace_style != BraceStyle::AlwaysNextLine
2709     };
2710     let total_used_width = last_line_used_width(&result, used_width);
2711     let remaining_budget = context.budget(total_used_width);
2712     // If the same line brace if forced, it indicates that we are rewriting an item with empty body,
2713     // and hence we take the closer into account as well for one line budget.
2714     // We assume that the closer has the same length as the opener.
2715     let overhead = if force_same_line_brace {
2716         1 + opener.len() + opener.len()
2717     } else {
2718         1 + opener.len()
2719     };
2720     let forbid_same_line_brace = overhead > remaining_budget;
2721     if !forbid_same_line_brace && same_line_brace {
2722         result.push(' ');
2723     } else {
2724         result.push('\n');
2725         result.push_str(&offset.block_only().to_string(context.config));
2726     }
2727     result.push_str(opener);
2728
2729     Some(result)
2730 }
2731
2732 impl Rewrite for ast::ForeignItem {
2733     fn rewrite(&self, context: &RewriteContext, shape: Shape) -> Option<String> {
2734         let attrs_str = self.attrs.rewrite(context, shape)?;
2735         // Drop semicolon or it will be interpreted as comment.
2736         // FIXME: this may be a faulty span from libsyntax.
2737         let span = mk_sp(self.span.lo(), self.span.hi() - BytePos(1));
2738
2739         let item_str = match self.node {
2740             ast::ForeignItemKind::Fn(ref fn_decl, ref generics) => rewrite_fn_base(
2741                 context,
2742                 shape.indent,
2743                 self.ident,
2744                 &FnSig::new(fn_decl, generics, self.vis.clone()),
2745                 span,
2746                 false,
2747                 false,
2748             ).map(|(s, _)| format!("{};", s)),
2749             ast::ForeignItemKind::Static(ref ty, is_mutable) => {
2750                 // FIXME(#21): we're dropping potential comments in between the
2751                 // function keywords here.
2752                 let vis = format_visibility(&self.vis);
2753                 let mut_str = if is_mutable { "mut " } else { "" };
2754                 let prefix = format!("{}static {}{}:", vis, mut_str, self.ident);
2755                 // 1 = ;
2756                 let shape = shape.sub_width(1)?;
2757                 ty.rewrite(context, shape).map(|ty_str| {
2758                     // 1 = space between prefix and type.
2759                     let sep = if prefix.len() + ty_str.len() + 1 <= shape.width {
2760                         String::from(" ")
2761                     } else {
2762                         let nested_indent = shape.indent.block_indent(context.config);
2763                         format!("\n{}", nested_indent.to_string(context.config))
2764                     };
2765                     format!("{}{}{};", prefix, sep, ty_str)
2766                 })
2767             }
2768             ast::ForeignItemKind::Ty => {
2769                 let vis = format_visibility(&self.vis);
2770                 Some(format!("{}type {};", vis, self.ident))
2771             }
2772         }?;
2773
2774         let missing_span = if self.attrs.is_empty() {
2775             mk_sp(self.span.lo(), self.span.lo())
2776         } else {
2777             mk_sp(self.attrs[self.attrs.len() - 1].span.hi(), self.span.lo())
2778         };
2779         combine_strs_with_missing_comments(
2780             context,
2781             &attrs_str,
2782             &item_str,
2783             missing_span,
2784             shape,
2785             false,
2786         )
2787     }
2788 }