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.
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.
11 // Formatting top-level items - functions, structs, enums, traits, impls.
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;
22 impl<'a> FmtVisitor<'a> {
23 pub fn rewrite_fn(&mut self,
27 explicit_self: Option<&ast::ExplicitSelf>,
28 generics: &ast::Generics,
29 unsafety: &ast::Unsafety,
35 let newline_brace = self.newline_for_brace(&generics.where_clause);
37 let mut result = self.rewrite_fn_base(indent,
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.
53 result.push_str(&make_indent(indent));
61 pub fn rewrite_required_fn(&mut self,
68 // Drop semicolon or it will be interpreted as comment
69 let span_end = span.hi - BytePos(1);
71 let mut result = self.rewrite_fn_base(indent,
74 Some(&sig.explicit_self),
78 ast::Visibility::Inherited,
82 // Re-attach semicolon
88 fn rewrite_fn_base(&mut self,
92 explicit_self: Option<&ast::ExplicitSelf>,
93 generics: &ast::Generics,
94 unsafety: &ast::Unsafety,
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.
104 let where_clause = &generics.where_clause;
106 let mut result = String::with_capacity(1024);
108 if vis == ast::Visibility::Public {
109 result.push_str("pub ");
111 if let &ast::Unsafety::Unsafe = unsafety {
112 result.push_str("unsafe ");
114 if *abi != abi::Rust {
115 result.push_str("extern ");
116 result.push_str(&abi.to_string());
121 result.push_str("fn ");
122 result.push_str(&token::get_ident(ident));
125 let generics_indent = indent + result.len();
126 result.push_str(&self.rewrite_generics(generics,
128 span_for_return(&fd.output).lo));
130 let ret_str = self.rewrite_return(&fd.output);
133 let (one_line_budget, multi_line_budget, arg_indent) =
134 self.compute_budgets_for_args(&mut result, indent, ret_str.len(), newline_brace);
136 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {}",
137 one_line_budget, multi_line_budget, arg_indent);
140 result.push_str(&self.rewrite_args(&fd.inputs,
145 span_for_return(&fd.output)));
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
163 result.push_str(&make_indent(indent));
167 result.push_str(&ret_str);
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 {
177 result.push_str(snippet);
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
187 result.push_str(&self.rewrite_where_clause(where_clause, indent, span_end));
192 fn rewrite_args(&self,
194 explicit_self: Option<&ast::ExplicitSelf>,
195 one_line_budget: usize,
196 multi_line_budget: usize,
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(),
211 let mut_str = match m {
212 &ast::Mutability::MutMutable => "mut ".to_owned(),
213 &ast::Mutability::MutImmutable => String::new(),
215 arg_item_strs[0] = format!("&{}{}self", lt_str, mut_str);
218 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
219 arg_item_strs[0] = format!("self: {}", pprust::ty_to_string(ty));
221 ast::ExplicitSelf_::SelfValue(_) => {
222 assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
224 // this hacky solution caused by absence of `Mutability` in `SelfValue`.
226 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _)
229 ast::Mutability::MutMutable => "mut ",
230 ast::Mutability::MutImmutable => "",
233 panic!("there is a bug or change in structure of AST, aborting.");
237 arg_item_strs[0] = format!("{}self", mut_str);
244 // Comments between args
245 let mut arg_comments = Vec::new();
247 arg_comments.push("".to_owned());
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(),
257 |arg| arg.pat.span.lo,
258 |arg| arg.ty.span.hi,
262 debug!("comments: {:?}", arg_comments);
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;
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();
273 let fmt = ListFormatting {
276 trailing_separator: SeparatorTactic::Never,
278 h_width: one_line_budget,
279 v_width: multi_line_budget,
282 write_list(&arg_strs, &fmt)
285 // Gets comments in between items of a list.
286 fn make_comments_for_list<T, I, F1, F2>(&self,
293 next_span_start: BytePos)
295 where I: Iterator<Item=T>,
296 F1: Fn(&T) -> BytePos,
297 F2: Fn(&T) -> BytePos
299 let mut result = prefix;
301 let mut prev_end = get_hi(&it.next().unwrap());
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);
312 result.push(snippet.to_owned());
313 prev_end = get_hi(&item);
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());
332 fn compute_budgets_for_args(&self,
337 -> (usize, usize, usize)
339 let mut budgets = None;
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;
348 let one_line_budget = if used_space > config!(max_width) {
351 config!(max_width) - used_space
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));
366 // Didn't work. we must force vertical layout and put args on a newline.
367 if let None = budgets {
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 {
375 // TODO take evasive action, perhaps kill the indent or something.
377 // 5 = new indent + `(`
378 budgets = Some((0, max_space - used_space, indent + 5));
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,
393 pub fn visit_struct(&mut self,
395 vis: ast::Visibility,
396 struct_def: &ast::StructDef,
397 generics: &ast::Generics,
400 let header_str = self.struct_header(ident, vis);
401 self.changes.push_str_span(span, &header_str);
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?");
409 self.changes.push_str_span(span, ";");
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);
417 if generics.where_clause.predicates.len() > 0 {
418 generics_buf.push_str(&self.rewrite_where_clause(&generics.where_clause,
420 struct_def.fields[0].span.lo));
421 generics_buf.push_str(&make_indent(self.block_indent));
422 generics_buf.push_str("\n{");
425 generics_buf.push_str(" {");
427 self.changes.push_str_span(span, &generics_buf);
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);
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);
437 self.block_indent -= config!(tab_spaces);
439 self.format_missing_with_indent(span.lo + BytePos(struct_snippet.rfind('}').unwrap() as u32));
440 self.changes.push_str_span(span, "}");
443 fn struct_header(&self,
445 vis: ast::Visibility)
448 let vis = if vis == ast::Visibility::Public {
454 format!("{}struct {}", vis, &token::get_ident(ident))
458 fn visit_field(&mut self,
459 field: &ast::StructField,
461 // These two args are for missing spans hacks.
462 struct_start: BytePos,
463 struct_snippet: &str)
465 if self.visit_attrs(&field.node.attrs) {
468 self.format_missing_with_indent(field.span.lo);
470 let name = match field.node.kind {
471 ast::StructFieldKind::NamedField(ident, _) => Some(token::get_ident(ident)),
472 ast::StructFieldKind::UnnamedField(_) => None,
474 let vis = match field.node.kind {
475 ast::StructFieldKind::NamedField(_, vis) |
476 ast::StructFieldKind::UnnamedField(vis) => if vis == ast::Visibility::Public {
482 let typ = pprust::ty_to_string(&field.node.ty);
484 let mut field_str = match 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{}{}",
492 &make_indent(self.block_indent + config!(tab_spaces)),
495 format!("{}{}: {}", vis, name, typ)
498 None => format!("{}{}", vis, typ),
500 if !last_field || config!(struct_trailing_comma) {
503 self.changes.push_str_span(field.span, &field_str);
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(',') {
513 self.last_pos = hi + BytePos(comma_pos as u32 + 1);
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 {
526 let budget = config!(max_width) - indent - 2;
527 // TODO might need to insert a newline if the generics are really long
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));
534 // Extract comments between generics.
535 let lt_spans = lifetimes.iter().map(|l| {
536 let hi = if l.bounds.len() == 0 {
539 l.bounds[l.bounds.len() - 1].span.hi
541 codemap::mk_sp(l.lifetime.span.lo, hi)
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),
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;
558 let generics_strs: Vec<_> = lt_strs.chain(ty_strs).zip(comments.into_iter()).collect();
559 let fmt = ListFormatting {
562 trailing_separator: SeparatorTactic::Never,
567 result.push_str(&write_list(&generics_strs, &fmt));
574 fn rewrite_where_clause(&self,
575 where_clause: &ast::WhereClause,
580 let mut result = String::new();
581 if where_clause.predicates.len() == 0 {
586 result.push_str(&make_indent(indent + 4));
587 result.push_str("where ");
589 let comments = self.make_comments_for_list(Vec::new(),
590 where_clause.predicates.iter(),
593 |pred| span_for_where_pred(pred).lo,
594 |pred| span_for_where_pred(pred).hi,
597 let where_strs: Vec<_> = where_clause.predicates.iter()
598 .map(|p| (self.rewrite_pred(p)))
599 .zip(comments.into_iter())
602 let budget = config!(ideal_width) + config!(leeway) - indent - 10;
603 let fmt = ListFormatting {
604 tactic: ListTactic::Vertical,
606 trailing_separator: SeparatorTactic::Never,
611 result.push_str(&write_list(&where_strs, &fmt));
616 fn rewrite_return(&self, ret: &ast::FunctionRetTy) -> String {
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),
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 {
627 pprust::pat_to_string(&arg.pat),
628 pprust::ty_to_string(&arg.ty))
632 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
634 ast::FunctionRetTy::NoReturn(ref span) |
635 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
636 ast::FunctionRetTy::Return(ref ty) => ty.span,
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.
643 if let Some(ref def) = ty.default {
644 return codemap::mk_sp(lo, def.span.hi);
646 if ty.bounds.len() == 0 {
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,
653 codemap::mk_sp(lo, hi)
656 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
658 ast::WherePredicate::BoundPredicate(ref p) => p.span,
659 ast::WherePredicate::RegionPredicate(ref p) => p.span,
660 ast::WherePredicate::EqPredicate(ref p) => p.span,