]> git.lizzy.rs Git - rust.git/blob - src/items.rs
Merge pull request #75 from nrc/structs
[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 {ReturnIndent, BraceStyle};
14 use utils::make_indent;
15 use lists::{write_list, ListFormatting, SeparatorTactic, ListTactic};
16 use visitor::FmtVisitor;
17 use syntax::{ast, abi};
18 use syntax::codemap::{self, Span, BytePos};
19 use syntax::print::pprust;
20 use syntax::parse::token;
21
22 impl<'a> FmtVisitor<'a> {
23     pub fn rewrite_fn(&mut self,
24                       indent: usize,
25                       ident: ast::Ident,
26                       fd: &ast::FnDecl,
27                       explicit_self: Option<&ast::ExplicitSelf>,
28                       generics: &ast::Generics,
29                       unsafety: &ast::Unsafety,
30                       abi: &abi::Abi,
31                       vis: ast::Visibility,
32                       span_end: BytePos)
33         -> String
34     {
35         let newline_brace = self.newline_for_brace(&generics.where_clause);
36
37         let mut result = self.rewrite_fn_base(indent,
38                                               ident,
39                                               fd,
40                                               explicit_self,
41                                               generics,
42                                               unsafety,
43                                               abi,
44                                               vis,
45                                               span_end,
46                                               newline_brace);
47
48         // Prepare for the function body by possibly adding a newline and indent.
49         // FIXME we'll miss anything between the end of the signature and the start
50         // of the body, but we need more spans from the compiler to solve this.
51         if newline_brace {
52             result.push('\n');
53             result.push_str(&make_indent(indent));
54         } else {
55             result.push(' ');
56         }
57
58         result
59     }
60
61     pub fn rewrite_required_fn(&mut self,
62                                indent: usize,
63                                ident: ast::Ident,
64                                sig: &ast::MethodSig,
65                                span: Span)
66         -> String
67     {
68         // Drop semicolon or it will be interpreted as comment
69         let span_end = span.hi - BytePos(1);
70
71         let mut result = self.rewrite_fn_base(indent,
72                                               ident,
73                                               &sig.decl,
74                                               Some(&sig.explicit_self),
75                                               &sig.generics,
76                                               &sig.unsafety,
77                                               &sig.abi,
78                                               ast::Visibility::Inherited,
79                                               span_end,
80                                               false);
81
82         // Re-attach semicolon
83         result.push(';');
84
85         result
86     }
87
88     fn rewrite_fn_base(&mut self,
89                        indent: usize,
90                        ident: ast::Ident,
91                        fd: &ast::FnDecl,
92                        explicit_self: Option<&ast::ExplicitSelf>,
93                        generics: &ast::Generics,
94                        unsafety: &ast::Unsafety,
95                        abi: &abi::Abi,
96                        vis: ast::Visibility,
97                        span_end: BytePos,
98                        newline_brace: bool)
99         -> String
100     {
101         // FIXME we'll lose any comments in between parts of the function decl, but anyone
102         // who comments there probably deserves what they get.
103
104         let where_clause = &generics.where_clause;
105
106         let mut result = String::with_capacity(1024);
107         // Vis unsafety abi.
108         if vis == ast::Visibility::Public {
109             result.push_str("pub ");
110         }
111         if let &ast::Unsafety::Unsafe = unsafety {
112             result.push_str("unsafe ");
113         }
114         if *abi != abi::Rust {
115             result.push_str("extern ");
116             result.push_str(&abi.to_string());
117             result.push(' ');
118         }
119
120         // fn foo
121         result.push_str("fn ");
122         result.push_str(&token::get_ident(ident));
123
124         // Generics.
125         let generics_indent = indent + result.len();
126         result.push_str(&self.rewrite_generics(generics,
127                                                generics_indent,
128                                                span_for_return(&fd.output).lo));
129
130         let ret_str = self.rewrite_return(&fd.output);
131
132         // Args.
133         let (one_line_budget, multi_line_budget, arg_indent) =
134             self.compute_budgets_for_args(&mut result, indent, ret_str.len(), newline_brace);
135
136         debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {}",
137                one_line_budget, multi_line_budget, arg_indent);
138
139         result.push('(');
140         result.push_str(&self.rewrite_args(&fd.inputs,
141                                            explicit_self,
142                                            one_line_budget,
143                                            multi_line_budget,
144                                            arg_indent,
145                                            span_for_return(&fd.output)));
146         result.push(')');
147
148         // Return type.
149         if ret_str.len() > 0 {
150             // If we've already gone multi-line, or the return type would push
151             // over the max width, then put the return type on a new line.
152             if result.contains("\n") ||
153                result.len() + indent + ret_str.len() > config!(max_width) {
154                 let indent = match config!(fn_return_indent) {
155                     ReturnIndent::WithWhereClause => indent + 4,
156                     // TODO we might want to check that using the arg indent doesn't
157                     // blow our budget, and if it does, then fallback to the where
158                     // clause indent.
159                     _ => arg_indent,
160                 };
161
162                 result.push('\n');
163                 result.push_str(&make_indent(indent));
164             } else {
165                 result.push(' ');
166             }
167             result.push_str(&ret_str);
168
169             // Comment between return type and the end of the decl.
170             let snippet_lo = fd.output.span().hi;
171             if where_clause.predicates.len() == 0 {
172                 let snippet_hi = span_end;
173                 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
174                 let snippet = snippet.trim();
175                 if snippet.len() > 0 {
176                     result.push(' ');
177                     result.push_str(snippet);
178                 }
179             } else {
180                 // FIXME it would be nice to catch comments between the return type
181                 // and the where clause, but we don't have a span for the where
182                 // clause.
183             }
184         }
185
186         // Where clause.
187         result.push_str(&self.rewrite_where_clause(where_clause, indent, span_end));
188
189         result
190     }
191
192     fn rewrite_args(&self,
193                     args: &[ast::Arg],
194                     explicit_self: Option<&ast::ExplicitSelf>,
195                     one_line_budget: usize,
196                     multi_line_budget: usize,
197                     arg_indent: usize,
198                     ret_span: Span)
199         -> String
200     {
201         let mut arg_item_strs: Vec<_> = args.iter().map(|a| self.rewrite_fn_input(a)).collect();
202         // Account for sugary self.
203         let mut min_args = 1;
204         if let Some(explicit_self) = explicit_self {
205             match explicit_self.node {
206                 ast::ExplicitSelf_::SelfRegion(ref lt, ref m, _) => {
207                     let lt_str = match lt {
208                         &Some(ref l) => format!("{} ", pprust::lifetime_to_string(l)),
209                         &None => String::new(),
210                     };
211                     let mut_str = match m {
212                         &ast::Mutability::MutMutable => "mut ".to_owned(),
213                         &ast::Mutability::MutImmutable => String::new(),
214                     };
215                     arg_item_strs[0] = format!("&{}{}self", lt_str, mut_str);
216                     min_args = 2;
217                 }
218                 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
219                     arg_item_strs[0] = format!("self: {}", pprust::ty_to_string(ty));
220                 }
221                 ast::ExplicitSelf_::SelfValue(_) => {
222                     assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
223
224                     // this hacky solution caused by absence of `Mutability` in `SelfValue`.
225                     let mut_str = {
226                         if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _)
227                                 = args[0].pat.node {
228                             match mutability {
229                                 ast::Mutability::MutMutable => "mut ",
230                                 ast::Mutability::MutImmutable => "",
231                             }
232                         } else {
233                             panic!("there is a bug or change in structure of AST, aborting.");
234                         }
235                     };
236
237                     arg_item_strs[0] = format!("{}self", mut_str);
238                     min_args = 2;
239                 }
240                 _ => {}
241             }
242         }
243
244         // Comments between args
245         let mut arg_comments = Vec::new();
246         if min_args == 2 {
247             arg_comments.push("".to_owned());
248         }
249         // TODO if there are no args, there might still be a comment, but without
250         // spans for the comment or parens, there is no chance of getting it right.
251         // You also don't get to put a comment on self, unless it is explicit.
252         if args.len() >= min_args {
253             arg_comments = self.make_comments_for_list(arg_comments,
254                                                        args[min_args-1..].iter(),
255                                                        ",",
256                                                        ")",
257                                                        |arg| arg.pat.span.lo,
258                                                        |arg| arg.ty.span.hi,
259                                                        ret_span.lo);
260         }
261
262         debug!("comments: {:?}", arg_comments);
263
264         // If there are // comments, keep them multi-line.
265         let mut list_tactic = ListTactic::HorizontalVertical;
266         if arg_comments.iter().any(|c| c.contains("//")) {
267             list_tactic = ListTactic::Vertical;
268         }
269
270         assert_eq!(arg_item_strs.len(), arg_comments.len());
271         let arg_strs: Vec<_> = arg_item_strs.into_iter().zip(arg_comments.into_iter()).collect();
272
273         let fmt = ListFormatting {
274             tactic: list_tactic,
275             separator: ",",
276             trailing_separator: SeparatorTactic::Never,
277             indent: arg_indent,
278             h_width: one_line_budget,
279             v_width: multi_line_budget,
280         };
281
282         write_list(&arg_strs, &fmt)
283     }
284
285     // Gets comments in between items of a list.
286     fn make_comments_for_list<T, I, F1, F2>(&self,
287                                             prefix: Vec<String>,
288                                             mut it: I,
289                                             separator: &str,
290                                             terminator: &str,
291                                             get_lo: F1,
292                                             get_hi: F2,
293                                             next_span_start: BytePos)
294         -> Vec<String>
295         where I: Iterator<Item=T>,
296               F1: Fn(&T) -> BytePos,
297               F2: Fn(&T) -> BytePos
298     {
299         let mut result = prefix;
300
301         let mut prev_end = get_hi(&it.next().unwrap());
302         for item in it {
303             let cur_start = get_lo(&item);
304             let snippet = self.snippet(codemap::mk_sp(prev_end, cur_start));
305             let mut snippet = snippet.trim();
306             let white_space: &[_] = &[' ', '\t'];
307             if snippet.starts_with(separator) {
308                 snippet = snippet[separator.len()..].trim_matches(white_space);
309             } else if snippet.ends_with(separator) {
310                 snippet = snippet[..snippet.len()-separator.len()].trim_matches(white_space);
311             }
312             result.push(snippet.to_owned());
313             prev_end = get_hi(&item);
314         }
315         // Get the last commment.
316         // FIXME If you thought the crap with the commas was ugly, just wait.
317         // This is awful. We're going to look from the last item span to the
318         // start of the return type span, then we drop everything after the
319         // first closing paren. Obviously, this will break if there is a
320         // closing paren in the comment.
321         // The fix is comments in the AST or a span for the closing paren.
322         let snippet = self.snippet(codemap::mk_sp(prev_end, next_span_start));
323         let snippet = snippet.trim();
324         let snippet = &snippet[..snippet.find(terminator)
325                                     .unwrap_or(snippet.find(separator).unwrap_or(snippet.len()))];
326         let snippet = snippet.trim();
327         result.push(snippet.to_owned());
328
329         result
330     }
331
332     fn compute_budgets_for_args(&self,
333                                 result: &mut String,
334                                 indent: usize,
335                                 ret_str_len: usize,
336                                 newline_brace: bool)
337         -> (usize, usize, usize)
338     {
339         let mut budgets = None;
340
341         // Try keeping everything on the same line
342         if !result.contains("\n") {
343             // 3 = `() `, space is before ret_string
344             let mut used_space = indent + result.len() + ret_str_len + 3;
345             if !newline_brace {
346                 used_space += 2;
347             }
348             let one_line_budget = if used_space > config!(max_width) {
349                 0
350             } else {
351                 config!(max_width) - used_space
352             };
353
354             // 2 = `()`
355             let used_space = indent + result.len() + 2;
356             let max_space = config!(ideal_width) + config!(leeway);
357             debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
358                    used_space, max_space);
359             if used_space < max_space {
360                 budgets = Some((one_line_budget,
361                                 max_space - used_space,
362                                 indent + result.len() + 1));
363             }
364         }
365
366         // Didn't work. we must force vertical layout and put args on a newline.
367         if let None = budgets {
368             result.push('\n');
369             result.push_str(&make_indent(indent + 4));
370             // 6 = new indent + `()`
371             let used_space = indent + 6;
372             let max_space = config!(ideal_width) + config!(leeway);
373             if used_space > max_space {
374                 // Whoops! bankrupt.
375                 // TODO take evasive action, perhaps kill the indent or something.
376             } else {
377                 // 5 = new indent + `(`
378                 budgets = Some((0, max_space - used_space, indent + 5));
379             }
380         }
381
382         budgets.unwrap()
383     }
384
385     fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
386         match config!(fn_brace_style) {
387             BraceStyle::AlwaysNextLine => true,
388             BraceStyle::SameLineWhere if where_clause.predicates.len() > 0 => true,
389             _ => false,
390         }
391     }
392
393     pub fn visit_struct(&mut self,
394                         ident: ast::Ident,
395                         vis: ast::Visibility,
396                         struct_def: &ast::StructDef,
397                         generics: &ast::Generics,
398                         span: Span)
399     {
400         let header_str = self.struct_header(ident, vis);
401         self.changes.push_str_span(span, &header_str);
402
403         if struct_def.fields.len() == 0 {
404             assert!(generics.where_clause.predicates.len() == 0,
405                     "No-field struct with where clause?");
406             assert!(generics.lifetimes.len() == 0, "No-field struct with generics?");
407             assert!(generics.ty_params.len() == 0, "No-field struct with generics?");
408
409             self.changes.push_str_span(span, ";");
410             return;
411         }
412
413         let mut generics_buf = String::new();
414         let generics_str = self.rewrite_generics(generics, self.block_indent, struct_def.fields[0].span.lo);
415         generics_buf.push_str(&generics_str);
416
417         if generics.where_clause.predicates.len() > 0 {
418             generics_buf.push_str(&self.rewrite_where_clause(&generics.where_clause,
419                                                              self.block_indent,
420                                                              struct_def.fields[0].span.lo));
421             generics_buf.push_str(&make_indent(self.block_indent));
422             generics_buf.push_str("\n{");
423
424         } else {
425             generics_buf.push_str(" {");
426         }
427         self.changes.push_str_span(span, &generics_buf);
428
429         let struct_snippet = self.snippet(span);
430         // FIXME this will give incorrect results if there is a { in a commet.
431         self.last_pos = span.lo + BytePos(struct_snippet.find('{').unwrap() as u32 + 1);
432
433         self.block_indent += config!(tab_spaces);
434         for (i, f) in struct_def.fields.iter().enumerate() {
435             self.visit_field(f, i == struct_def.fields.len() - 1, span.lo, &struct_snippet);
436         }
437         self.block_indent -= config!(tab_spaces);
438
439         self.format_missing_with_indent(span.lo + BytePos(struct_snippet.rfind('}').unwrap() as u32));
440         self.changes.push_str_span(span, "}");
441     }
442
443     fn struct_header(&self,
444                      ident: ast::Ident,
445                      vis: ast::Visibility)
446         -> String
447     {
448         let vis = if vis == ast::Visibility::Public {
449             "pub "
450         } else {
451             ""
452         };
453
454         format!("{}struct {}", vis, &token::get_ident(ident))
455     }
456
457     // Field of a struct
458     fn visit_field(&mut self,
459                    field: &ast::StructField,
460                    last_field: bool,
461                    // These two args are for missing spans hacks.
462                    struct_start: BytePos,
463                    struct_snippet: &str)
464     {
465         if self.visit_attrs(&field.node.attrs) {
466             return;
467         }
468         self.format_missing_with_indent(field.span.lo);
469
470         let name = match field.node.kind {
471             ast::StructFieldKind::NamedField(ident, _) => Some(token::get_ident(ident)),
472             ast::StructFieldKind::UnnamedField(_) => None,
473         };
474         let vis = match field.node.kind {
475             ast::StructFieldKind::NamedField(_, vis) |
476             ast::StructFieldKind::UnnamedField(vis) => if vis == ast::Visibility::Public {
477                 "pub "
478             } else {
479                 ""
480             }
481         };
482         let typ = pprust::ty_to_string(&field.node.ty);
483
484         let mut field_str = match name {
485             Some(name) => {
486                 let budget = config!(ideal_width) - self.block_indent;
487                 // 3 is being conservative and assuming that there will be a trailing comma.
488                 if self.block_indent + vis.len() + name.len() + typ.len() + 3 > budget {
489                     format!("{}{}:\n{}{}",
490                             vis,
491                             name,
492                             &make_indent(self.block_indent + config!(tab_spaces)),
493                             typ)
494                 } else {
495                     format!("{}{}: {}", vis, name, typ)
496                 }
497             }
498             None => format!("{}{}", vis, typ),
499         };
500         if !last_field || config!(struct_trailing_comma) {
501             field_str.push(',');
502         }
503         self.changes.push_str_span(field.span, &field_str);
504
505         // This hack makes sure we only add comments etc. after the comma, and
506         // makes sure we don't repeat any commas.
507         let hi = field.span.hi;
508         // FIXME a comma in a comment will break this hack.
509         let comma_pos = match struct_snippet[(hi.0 - struct_start.0) as usize..].find(',') {
510             Some(i) => i,
511             None => 0,
512         };
513         self.last_pos = hi + BytePos(comma_pos as u32 + 1);
514     }
515
516     fn rewrite_generics(&self, generics: &ast::Generics, indent: usize, span_end: BytePos) -> String {
517         // FIXME convert bounds to where clauses where they get too big or if
518         // there is a where clause at all.
519         let mut result = String::new();
520         let lifetimes: &[_] = &generics.lifetimes;
521         let tys: &[_] = &generics.ty_params;
522         if lifetimes.len() + tys.len() == 0 {
523             return result;
524         }
525
526         let budget = config!(max_width) - indent - 2;
527         // TODO might need to insert a newline if the generics are really long
528         result.push('<');
529
530         // Strings for the generics.
531         let lt_strs = lifetimes.iter().map(|l| self.rewrite_lifetime_def(l));
532         let ty_strs = tys.iter().map(|ty| self.rewrite_ty_param(ty));
533
534         // Extract comments between generics.
535         let lt_spans = lifetimes.iter().map(|l| {
536             let hi = if l.bounds.len() == 0 {
537                 l.lifetime.span.hi
538             } else {
539                 l.bounds[l.bounds.len() - 1].span.hi
540             };
541             codemap::mk_sp(l.lifetime.span.lo, hi)
542         });
543         let ty_spans = tys.iter().map(span_for_ty_param);
544         let comments = self.make_comments_for_list(Vec::new(),
545                                                    lt_spans.chain(ty_spans),
546                                                    ",",
547                                                    ">",
548                                                    |sp| sp.lo,
549                                                    |sp| sp.hi,
550                                                    span_end);
551
552         // If there are // comments, keep them multi-line.
553         let mut list_tactic = ListTactic::HorizontalVertical;
554         if comments.iter().any(|c| c.contains("//")) {
555             list_tactic = ListTactic::Vertical;
556         }
557
558         let generics_strs: Vec<_> = lt_strs.chain(ty_strs).zip(comments.into_iter()).collect();
559         let fmt = ListFormatting {
560             tactic: list_tactic,
561             separator: ",",
562             trailing_separator: SeparatorTactic::Never,
563             indent: indent + 1,
564             h_width: budget,
565             v_width: budget,
566         };
567         result.push_str(&write_list(&generics_strs, &fmt));
568
569         result.push('>');
570
571         result
572     }
573
574     fn rewrite_where_clause(&self,
575                             where_clause: &ast::WhereClause,
576                             indent: usize,
577                             span_end: BytePos)
578         -> String
579     {
580         let mut result = String::new();
581         if where_clause.predicates.len() == 0 {
582             return result;
583         }
584
585         result.push('\n');
586         result.push_str(&make_indent(indent + 4));
587         result.push_str("where ");
588
589         let comments = self.make_comments_for_list(Vec::new(),
590                                                    where_clause.predicates.iter(),
591                                                    ",",
592                                                    "{",
593                                                    |pred| span_for_where_pred(pred).lo,
594                                                    |pred| span_for_where_pred(pred).hi,
595                                                    span_end);
596
597         let where_strs: Vec<_> = where_clause.predicates.iter()
598                                                         .map(|p| (self.rewrite_pred(p)))
599                                                         .zip(comments.into_iter())
600                                                         .collect();
601
602         let budget = config!(ideal_width) + config!(leeway) - indent - 10;
603         let fmt = ListFormatting {
604             tactic: ListTactic::Vertical,
605             separator: ",",
606             trailing_separator: SeparatorTactic::Never,
607             indent: indent + 10,
608             h_width: budget,
609             v_width: budget,
610         };
611         result.push_str(&write_list(&where_strs, &fmt));
612
613         result
614     }
615
616     fn rewrite_return(&self, ret: &ast::FunctionRetTy) -> String {
617         match *ret {
618             ast::FunctionRetTy::DefaultReturn(_) => String::new(),
619             ast::FunctionRetTy::NoReturn(_) => "-> !".to_owned(),
620             ast::FunctionRetTy::Return(ref ty) => "-> ".to_owned() + &pprust::ty_to_string(ty),
621         }
622     }
623
624     // TODO we farm this out, but this could spill over the column limit, so we ought to handle it properly
625     fn rewrite_fn_input(&self, arg: &ast::Arg) -> String {
626         format!("{}: {}",
627                 pprust::pat_to_string(&arg.pat),
628                 pprust::ty_to_string(&arg.ty))
629     }
630 }
631
632 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
633     match *ret {
634         ast::FunctionRetTy::NoReturn(ref span) |
635         ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
636         ast::FunctionRetTy::Return(ref ty) => ty.span,
637     }
638 }
639
640 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
641     // Note that ty.span is the span for ty.ident, not the whole item.
642     let lo = ty.span.lo;
643     if let Some(ref def) = ty.default {
644         return codemap::mk_sp(lo, def.span.hi);
645     }
646     if ty.bounds.len() == 0 {
647         return ty.span;
648     }
649     let hi = match ty.bounds[ty.bounds.len() - 1] {
650         ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
651         ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
652     };
653     codemap::mk_sp(lo, hi)
654 }
655
656 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
657     match *pred {
658         ast::WherePredicate::BoundPredicate(ref p) => p.span,
659         ast::WherePredicate::RegionPredicate(ref p) => p.span,
660         ast::WherePredicate::EqPredicate(ref p) => p.span,
661     }
662 }