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, StructLitStyle};
14 use utils::{format_mutability, format_visibility, make_indent, contains_skip, span_after,
15 end_typaram, wrap_str};
16 use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, ListTactic};
17 use expr::rewrite_assign_rhs;
18 use comment::FindUncommented;
19 use visitor::FmtVisitor;
20 use rewrite::{Rewrite, RewriteContext};
21 use config::{Config, BlockIndentStyle, Density};
23 use syntax::{ast, abi};
24 use syntax::codemap::{self, Span, BytePos};
25 use syntax::print::pprust;
26 use syntax::parse::token;
28 impl<'a> FmtVisitor<'a> {
29 pub fn visit_let(&mut self, local: &ast::Local, span: Span) {
30 self.format_missing_with_indent(span.lo);
32 // String that is placed within the assignment pattern and expression.
34 let mut infix = String::new();
36 if let Some(ref ty) = local.ty {
38 // FIXME silly width, indent
39 infix.push_str(&ty.rewrite(&self.get_context(), 1000, 0).unwrap());
42 if local.init.is_some() {
49 // New scope so we drop the borrow of self (context) in time to mutably
50 // borrow self to mutate its buffer.
52 let context = self.get_context();
53 let mut result = "let ".to_owned();
54 let pattern_offset = self.block_indent + result.len() + infix.len();
56 let pattern_width = match self.config.max_width.checked_sub(pattern_offset + 1) {
61 match local.pat.rewrite(&context, pattern_offset, pattern_width) {
62 Some(ref pat_string) => result.push_str(pat_string),
66 result.push_str(&infix);
68 if let Some(ref ex) = local.init {
69 let max_width = match self.config.max_width.checked_sub(context.block_indent + 1) {
74 // 1 = trailing semicolon;
75 let rhs = rewrite_assign_rhs(&context, result, ex, max_width, context.block_indent);
78 Some(result) => result,
86 self.buffer.push_str(&result);
87 self.buffer.push_str(";");
88 self.last_pos = span.hi;
91 pub fn rewrite_fn(&mut self,
95 explicit_self: Option<&ast::ExplicitSelf>,
96 generics: &ast::Generics,
97 unsafety: &ast::Unsafety,
98 constness: &ast::Constness,
100 vis: ast::Visibility,
103 let mut newline_brace = self.newline_for_brace(&generics.where_clause);
105 let mut result = try_opt!(self.rewrite_fn_base(indent,
117 if self.config.fn_brace_style != BraceStyle::AlwaysNextLine && !result.contains('\n') {
118 newline_brace = false;
121 // Prepare for the function body by possibly adding a newline and
123 // FIXME we'll miss anything between the end of the signature and the
124 // start of the body, but we need more spans from the compiler to solve
128 result.push_str(&make_indent(indent));
136 pub fn rewrite_required_fn(&mut self,
139 sig: &ast::MethodSig,
142 // Drop semicolon or it will be interpreted as comment
143 let span = codemap::mk_sp(span.lo, span.hi - BytePos(1));
145 let mut result = try_opt!(self.rewrite_fn_base(indent,
148 Some(&sig.explicit_self),
153 ast::Visibility::Inherited,
157 // Re-attach semicolon
163 fn rewrite_fn_base(&mut self,
167 explicit_self: Option<&ast::ExplicitSelf>,
168 generics: &ast::Generics,
169 unsafety: &ast::Unsafety,
170 constness: &ast::Constness,
172 vis: ast::Visibility,
176 // FIXME we'll lose any comments in between parts of the function decl, but anyone
177 // who comments there probably deserves what they get.
179 let where_clause = &generics.where_clause;
181 let mut result = String::with_capacity(1024);
183 result.push_str(format_visibility(vis));
185 if let &ast::Unsafety::Unsafe = unsafety {
186 result.push_str("unsafe ");
188 if let &ast::Constness::Const = constness {
189 result.push_str("const ");
191 if *abi != abi::Rust {
192 result.push_str("extern ");
193 result.push_str(&abi.to_string());
198 result.push_str("fn ");
199 result.push_str(&ident.to_string());
202 let generics_indent = indent + result.len();
203 let generics_span = codemap::mk_sp(span.lo, span_for_return(&fd.output).lo);
204 let generics_str = try_opt!(self.rewrite_generics(generics,
208 result.push_str(&generics_str);
210 let context = self.get_context();
211 let ret_str = fd.output.rewrite(&context, self.config.max_width - indent, indent).unwrap();
214 let (one_line_budget, multi_line_budget, mut arg_indent) =
215 self.compute_budgets_for_args(&result, indent, ret_str.len(), newline_brace);
217 debug!("rewrite_fn: one_line_budget: {}, multi_line_budget: {}, arg_indent: {}",
218 one_line_budget, multi_line_budget, arg_indent);
220 // Check if vertical layout was forced by compute_budget_for_args.
221 if one_line_budget <= 0 {
222 if self.config.fn_args_paren_newline {
224 result.push_str(&make_indent(arg_indent));
225 arg_indent = arg_indent + 1; // extra space for `(`
228 result.push_str("(\n");
229 result.push_str(&make_indent(arg_indent));
231 } else if self.config.fn_args_layout == StructLitStyle::Block {
232 arg_indent = indent + self.config.tab_spaces;
233 result.push_str("(\n");
234 result.push_str(&make_indent(arg_indent));
239 // A conservative estimation, to goal is to be over all parens in generics
240 let args_start = generics.ty_params
242 .map(|tp| end_typaram(tp))
244 let args_span = codemap::mk_sp(span_after(codemap::mk_sp(args_start, span.hi),
247 span_for_return(&fd.output).lo);
248 let arg_str = try_opt!(self.rewrite_args(&fd.inputs,
255 result.push_str(&arg_str);
256 if self.config.fn_args_layout == StructLitStyle::Block {
262 if !ret_str.is_empty() {
263 // If we've already gone multi-line, or the return type would push
264 // over the max width, then put the return type on a new line.
265 // Unless we are formatting args like a block, in which case there
266 // should always be room for the return type.
267 if (result.contains("\n") ||
268 result.len() + indent + ret_str.len() > self.config.max_width) &&
269 self.config.fn_args_layout != StructLitStyle::Block {
270 let indent = match self.config.fn_return_indent {
271 ReturnIndent::WithWhereClause => indent + 4,
272 // TODO we might want to check that using the arg indent doesn't
273 // blow our budget, and if it does, then fallback to the where
279 result.push_str(&make_indent(indent));
283 result.push_str(&ret_str);
285 // Comment between return type and the end of the decl.
286 let snippet_lo = fd.output.span().hi;
287 if where_clause.predicates.is_empty() {
288 let snippet_hi = span.hi;
289 let snippet = self.snippet(codemap::mk_sp(snippet_lo, snippet_hi));
290 let snippet = snippet.trim();
291 if !snippet.is_empty() {
293 result.push_str(snippet);
296 // FIXME it would be nice to catch comments between the return type
297 // and the where clause, but we don't have a span for the where
302 let where_density = if (self.config.where_density == Density::Compressed &&
303 (!result.contains('\n') ||
304 self.config.fn_args_layout == StructLitStyle::Block)) ||
305 (self.config.fn_args_layout == StructLitStyle::Block &&
306 ret_str.is_empty()) {
313 let where_clause_str = try_opt!(self.rewrite_where_clause(where_clause,
318 result.push_str(&where_clause_str);
323 fn rewrite_args(&self,
325 explicit_self: Option<&ast::ExplicitSelf>,
326 one_line_budget: usize,
327 multi_line_budget: usize,
332 let context = self.get_context();
333 let mut arg_item_strs = try_opt!(args.iter()
335 arg.rewrite(&context, multi_line_budget, indent)
337 .collect::<Option<Vec<_>>>());
339 // Account for sugary self.
340 // FIXME: the comment for the self argument is dropped. This is blocked
341 // on rust issue #27522.
342 let min_args = explicit_self.and_then(|explicit_self| {
343 rewrite_explicit_self(explicit_self, args)
346 arg_item_strs[0] = self_str;
351 // Comments between args.
352 let mut arg_items = Vec::new();
354 arg_items.push(ListItem::from_str(""));
357 // TODO if there are no args, there might still be a comment, but without
358 // spans for the comment or parens, there is no chance of getting it right.
359 // You also don't get to put a comment on self, unless it is explicit.
360 if args.len() >= min_args {
361 let comment_span_start = if min_args == 2 {
362 span_after(span, ",", self.codemap)
367 let more_items = itemize_list(self.codemap,
368 args[min_args-1..].iter(),
370 |arg| span_lo_for_arg(arg),
371 |arg| arg.ty.span.hi,
376 arg_items.extend(more_items);
379 assert_eq!(arg_item_strs.len(), arg_items.len());
381 for (item, arg) in arg_items.iter_mut().zip(arg_item_strs) {
385 let indent = match self.config.fn_arg_indent {
386 BlockIndentStyle::Inherit => indent,
387 BlockIndentStyle::Tabbed => indent + self.config.tab_spaces,
388 BlockIndentStyle::Visual => arg_indent,
391 let fmt = ListFormatting {
392 tactic: self.config.fn_args_density.to_list_tactic(),
394 trailing_separator: SeparatorTactic::Never,
396 h_width: one_line_budget,
397 v_width: multi_line_budget,
398 ends_with_newline: false,
401 write_list(&arg_items, &fmt)
404 fn compute_budgets_for_args(&self,
409 -> (usize, usize, usize) {
410 let mut budgets = None;
412 // Try keeping everything on the same line
413 if !result.contains("\n") {
414 // 3 = `() `, space is before ret_string
415 let mut used_space = indent + result.len() + ret_str_len + 3;
419 let one_line_budget = if used_space > self.config.max_width {
422 self.config.max_width - used_space
426 let used_space = indent + result.len() + 2;
427 let max_space = self.config.ideal_width + self.config.leeway;
428 debug!("compute_budgets_for_args: used_space: {}, max_space: {}",
429 used_space, max_space);
430 if used_space < max_space {
431 budgets = Some((one_line_budget,
432 max_space - used_space,
433 indent + result.len() + 1));
437 // Didn't work. we must force vertical layout and put args on a newline.
438 if let None = budgets {
439 let new_indent = indent + self.config.tab_spaces;
440 let used_space = new_indent + 2; // account for `(` and `)`
441 let max_space = self.config.ideal_width + self.config.leeway;
442 if used_space > max_space {
444 // TODO take evasive action, perhaps kill the indent or something.
446 budgets = Some((0, max_space - used_space, new_indent));
453 fn newline_for_brace(&self, where_clause: &ast::WhereClause) -> bool {
454 match self.config.fn_brace_style {
455 BraceStyle::AlwaysNextLine => true,
456 BraceStyle::SameLineWhere if !where_clause.predicates.is_empty() => true,
461 pub fn visit_enum(&mut self,
463 vis: ast::Visibility,
464 enum_def: &ast::EnumDef,
465 generics: &ast::Generics,
467 let header_str = self.format_header("enum ", ident, vis);
468 self.buffer.push_str(&header_str);
470 let enum_snippet = self.snippet(span);
471 let body_start = span.lo + BytePos(enum_snippet.find_uncommented("{").unwrap() as u32 + 1);
472 let generics_str = self.format_generics(generics,
475 self.block_indent + self.config.tab_spaces,
476 codemap::mk_sp(span.lo, body_start))
478 self.buffer.push_str(&generics_str);
480 self.last_pos = body_start;
481 self.block_indent += self.config.tab_spaces;
482 for (i, f) in enum_def.variants.iter().enumerate() {
483 let next_span_start: BytePos = if i == enum_def.variants.len() - 1 {
486 enum_def.variants[i + 1].span.lo
489 self.visit_variant(f, i == enum_def.variants.len() - 1, next_span_start);
491 self.block_indent -= self.config.tab_spaces;
493 self.format_missing_with_indent(span.lo + BytePos(enum_snippet.rfind('}').unwrap() as u32));
494 self.buffer.push_str("}");
497 // Variant of an enum
498 fn visit_variant(&mut self, field: &ast::Variant, last_field: bool, next_span_start: BytePos) {
499 if self.visit_attrs(&field.node.attrs) {
503 self.format_missing_with_indent(field.span.lo);
505 let result = match field.node.kind {
506 ast::VariantKind::TupleVariantKind(ref types) => {
507 let vis = format_visibility(field.node.vis);
508 self.buffer.push_str(vis);
509 let name = field.node.name.to_string();
510 self.buffer.push_str(&name);
512 let mut result = String::new();
514 if !types.is_empty() {
515 let items = itemize_list(self.codemap,
518 |arg| arg.ty.span.lo,
519 |arg| arg.ty.span.hi,
521 // FIXME silly width, indent
523 .rewrite(&self.get_context(), 1000, 0)
526 span_after(field.span, "(", self.codemap),
531 let indent = self.block_indent + vis.len() + field.node.name.to_string().len() +
534 let comma_cost = if self.config.enum_trailing_comma {
539 let budget = self.config.ideal_width - indent - comma_cost - 1; // 1 = )
541 let fmt = ListFormatting {
542 tactic: ListTactic::HorizontalVertical,
544 trailing_separator: SeparatorTactic::Never,
548 ends_with_newline: true,
550 let list_str = match write_list(&items.collect::<Vec<_>>(), &fmt) {
551 Some(list_str) => list_str,
555 result.push_str(&list_str);
559 if let Some(ref expr) = field.node.disr_expr {
560 result.push_str(" = ");
561 let expr_snippet = self.snippet(expr.span);
562 result.push_str(&expr_snippet);
564 // Make sure we do not exceed column limit
567 self.config.max_width >= vis.len() + name.len() + expr_snippet.len() + 4,
568 "Enum variant exceeded column limit");
573 ast::VariantKind::StructVariantKind(ref struct_def) => {
574 // TODO Should limit the width, as we have a trailing comma
575 let struct_rewrite = self.format_struct("",
583 match struct_rewrite {
584 Some(struct_str) => struct_str,
589 self.buffer.push_str(&result);
591 if !last_field || self.config.enum_trailing_comma {
592 self.buffer.push_str(",");
595 self.last_pos = field.span.hi + BytePos(1);
598 fn format_struct(&self,
601 vis: ast::Visibility,
602 struct_def: &ast::StructDef,
603 generics: Option<&ast::Generics>,
607 let mut result = String::with_capacity(1024);
609 let header_str = self.format_header(item_name, ident, vis);
610 result.push_str(&header_str);
612 if struct_def.fields.is_empty() {
617 let is_tuple = match struct_def.fields[0].node.kind {
618 ast::StructFieldKind::NamedField(..) => false,
619 ast::StructFieldKind::UnnamedField(..) => true,
622 let (opener, terminator) = if is_tuple {
628 let generics_str = match generics {
630 try_opt!(self.format_generics(g,
633 offset + header_str.len(),
634 codemap::mk_sp(span.lo,
635 struct_def.fields[0].span.lo)))
637 None => opener.to_owned(),
639 result.push_str(&generics_str);
641 let items = itemize_list(self.codemap,
642 struct_def.fields.iter(),
645 // Include attributes and doc comments, if present
646 if !field.node.attrs.is_empty() {
647 field.node.attrs[0].span.lo
652 |field| field.node.ty.span.hi,
653 |field| self.format_field(field),
654 span_after(span, opener.trim(), self.codemap),
657 // 2 terminators and a semicolon
658 let used_budget = offset + header_str.len() + generics_str.len() + 3;
660 // Conservative approximation
661 let single_line_cost = (span.hi - struct_def.fields[0].span.lo).0;
662 let break_line = !is_tuple || generics_str.contains('\n') ||
663 single_line_cost as usize + used_budget > self.config.max_width;
665 let tactic = if break_line {
666 let indentation = make_indent(offset + self.config.tab_spaces);
668 result.push_str(&indentation);
672 ListTactic::Horizontal
676 let budget = self.config.ideal_width - offset + self.config.tab_spaces - 1;
677 let fmt = ListFormatting {
680 trailing_separator: self.config.struct_trailing_comma,
681 indent: offset + self.config.tab_spaces,
682 h_width: self.config.max_width,
684 ends_with_newline: true,
686 let list_str = write_list(&items.collect::<Vec<_>>(), &fmt).unwrap();
688 result.push_str(&list_str);
692 result.push_str(&make_indent(offset));
695 result.push_str(terminator);
704 pub fn visit_struct(&mut self,
706 vis: ast::Visibility,
707 struct_def: &ast::StructDef,
708 generics: &ast::Generics,
710 let indent = self.block_indent;
711 let result = self.format_struct("struct ",
720 self.buffer.push_str(&result);
721 self.last_pos = span.hi;
724 fn format_header(&self, item_name: &str, ident: ast::Ident, vis: ast::Visibility) -> String {
725 format!("{}{}{}", format_visibility(vis), item_name, ident)
728 fn format_generics(&self,
729 generics: &ast::Generics,
732 generics_offset: usize,
735 let mut result = try_opt!(self.rewrite_generics(generics, offset, generics_offset, span));
737 if !generics.where_clause.predicates.is_empty() || result.contains('\n') {
738 let where_clause_str = try_opt!(self.rewrite_where_clause(&generics.where_clause,
743 result.push_str(&where_clause_str);
744 result.push_str(&make_indent(self.block_indent));
746 result.push_str(opener.trim());
748 result.push_str(opener);
755 fn format_field(&self, field: &ast::StructField) -> String {
756 if contains_skip(&field.node.attrs) {
757 return self.snippet(codemap::mk_sp(field.node.attrs[0].span.lo, field.span.hi));
760 let name = match field.node.kind {
761 ast::StructFieldKind::NamedField(ident, _) => Some(ident.to_string()),
762 ast::StructFieldKind::UnnamedField(_) => None,
764 let vis = match field.node.kind {
765 ast::StructFieldKind::NamedField(_, vis) |
766 ast::StructFieldKind::UnnamedField(vis) => format_visibility(vis),
768 // FIXME silly width, indent
769 let typ = field.node.ty.rewrite(&self.get_context(), 1000, 0).unwrap();
771 let indent = self.block_indent + self.config.tab_spaces;
772 let mut attr_str = field.node
774 .rewrite(&self.get_context(),
775 self.config.max_width - indent,
778 if !attr_str.is_empty() {
780 attr_str.push_str(&make_indent(indent));
784 Some(name) => format!("{}{}{}: {}", attr_str, vis, name, typ),
785 None => format!("{}{}{}", attr_str, vis, typ),
789 fn rewrite_generics(&self,
790 generics: &ast::Generics,
792 generics_offset: usize,
795 // FIXME convert bounds to where clauses where they get too big or if
796 // there is a where clause at all.
797 let lifetimes: &[_] = &generics.lifetimes;
798 let tys: &[_] = &generics.ty_params;
799 if lifetimes.is_empty() && tys.is_empty() {
800 return Some(String::new());
803 let offset = match self.config.generics_indent {
804 BlockIndentStyle::Inherit => offset,
805 BlockIndentStyle::Tabbed => offset + self.config.tab_spaces,
807 BlockIndentStyle::Visual => generics_offset + 1,
810 let h_budget = self.config.max_width - generics_offset - 2;
811 // TODO might need to insert a newline if the generics are really long
813 // Strings for the generics.
814 let context = self.get_context();
815 // FIXME: don't unwrap
816 let lt_strs = lifetimes.iter().map(|lt| lt.rewrite(&context, h_budget, offset).unwrap());
817 let ty_strs = tys.iter()
818 .map(|ty_param| ty_param.rewrite(&context, h_budget, offset).unwrap());
820 // Extract comments between generics.
821 let lt_spans = lifetimes.iter().map(|l| {
822 let hi = if l.bounds.is_empty() {
825 l.bounds[l.bounds.len() - 1].span.hi
827 codemap::mk_sp(l.lifetime.span.lo, hi)
829 let ty_spans = tys.iter().map(span_for_ty_param);
831 let items = itemize_list(self.codemap,
832 lt_spans.chain(ty_spans),
837 span_after(span, "<", self.codemap),
839 let mut items = items.collect::<Vec<_>>();
841 for (item, ty) in items.iter_mut().zip(lt_strs.chain(ty_strs)) {
845 let fmt = ListFormatting::for_fn(h_budget, offset);
846 let list_str = try_opt!(write_list(&items, &fmt));
848 Some(format!("<{}>", list_str))
851 fn rewrite_where_clause(&self,
852 where_clause: &ast::WhereClause,
858 if where_clause.predicates.is_empty() {
859 return Some(String::new());
862 let extra_indent = match self.config.where_indent {
863 BlockIndentStyle::Inherit => 0,
864 BlockIndentStyle::Tabbed | BlockIndentStyle::Visual => config.tab_spaces,
867 let context = self.get_context();
869 let offset = match self.config.where_pred_indent {
870 BlockIndentStyle::Inherit => indent + extra_indent,
871 BlockIndentStyle::Tabbed => indent + extra_indent + config.tab_spaces,
872 // 6 = "where ".len()
873 BlockIndentStyle::Visual => indent + extra_indent + 6,
875 // FIXME: if where_pred_indent != Visual, then the budgets below might
876 // be out by a char or two.
878 let budget = self.config.ideal_width + self.config.leeway - offset;
879 let span_start = span_for_where_pred(&where_clause.predicates[0]).lo;
880 let items = itemize_list(self.codemap,
881 where_clause.predicates.iter(),
883 |pred| span_for_where_pred(pred).lo,
884 |pred| span_for_where_pred(pred).hi,
885 // FIXME: we should handle failure better
886 // this will be taken care of when write_list
887 // takes Rewrite object: see issue #133
888 |pred| pred.rewrite(&context, budget, offset).unwrap(),
892 let fmt = ListFormatting {
893 tactic: self.config.where_layout,
895 trailing_separator: SeparatorTactic::Never,
899 ends_with_newline: true,
901 let preds_str = try_opt!(write_list(&items.collect::<Vec<_>>(), &fmt));
903 // 9 = " where ".len() + " {".len()
904 if density == Density::Tall || preds_str.contains('\n') ||
905 indent + 9 + preds_str.len() > self.config.max_width {
906 Some(format!("\n{}where {}",
907 make_indent(indent + extra_indent),
910 Some(format!(" where {}", preds_str))
915 impl Rewrite for ast::FunctionRetTy {
916 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
918 ast::FunctionRetTy::DefaultReturn(_) => Some(String::new()),
919 ast::FunctionRetTy::NoReturn(_) => {
921 Some("-> !".to_owned())
926 ast::FunctionRetTy::Return(ref ty) => {
927 let inner_width = try_opt!(width.checked_sub(3));
928 ty.rewrite(context, inner_width, offset + 3).map(|r| format!("-> {}", r))
934 impl Rewrite for ast::Arg {
935 fn rewrite(&self, context: &RewriteContext, width: usize, offset: usize) -> Option<String> {
936 if is_named_arg(self) {
937 if let ast::Ty_::TyInfer = self.ty.node {
938 wrap_str(pprust::pat_to_string(&self.pat), context.config.max_width, width, offset)
940 let mut result = pprust::pat_to_string(&self.pat);
941 result.push_str(": ");
942 let max_width = try_opt!(width.checked_sub(result.len()));
943 let ty_str = try_opt!(self.ty.rewrite(context, max_width, offset + result.len()));
944 result.push_str(&ty_str);
948 self.ty.rewrite(context, width, offset)
953 fn rewrite_explicit_self(explicit_self: &ast::ExplicitSelf, args: &[ast::Arg]) -> Option<String> {
954 match explicit_self.node {
955 ast::ExplicitSelf_::SelfRegion(lt, m, _) => {
956 let mut_str = format_mutability(m);
958 Some(ref l) => Some(format!("&{} {}self", pprust::lifetime_to_string(l), mut_str)),
959 None => Some(format!("&{}self", mut_str)),
962 ast::ExplicitSelf_::SelfExplicit(ref ty, _) => {
963 Some(format!("self: {}", pprust::ty_to_string(ty)))
965 ast::ExplicitSelf_::SelfValue(_) => {
966 assert!(args.len() >= 1, "&[ast::Arg] shouldn't be empty.");
968 // this hacky solution caused by absence of `Mutability` in `SelfValue`.
970 if let ast::Pat_::PatIdent(ast::BindingMode::BindByValue(mutability), _, _) =
972 format_mutability(mutability)
974 panic!("there is a bug or change in structure of AST, aborting.");
978 Some(format!("{}self", mut_str))
984 pub fn span_lo_for_arg(arg: &ast::Arg) -> BytePos {
985 if is_named_arg(arg) {
992 pub fn span_hi_for_arg(arg: &ast::Arg) -> BytePos {
994 ast::Ty_::TyInfer if is_named_arg(arg) => arg.pat.span.hi,
999 fn is_named_arg(arg: &ast::Arg) -> bool {
1000 if let ast::Pat_::PatIdent(_, ident, _) = arg.pat.node {
1001 ident.node != token::special_idents::invalid
1007 fn span_for_return(ret: &ast::FunctionRetTy) -> Span {
1009 ast::FunctionRetTy::NoReturn(ref span) |
1010 ast::FunctionRetTy::DefaultReturn(ref span) => span.clone(),
1011 ast::FunctionRetTy::Return(ref ty) => ty.span,
1015 fn span_for_ty_param(ty: &ast::TyParam) -> Span {
1016 // Note that ty.span is the span for ty.ident, not the whole item.
1017 let lo = ty.span.lo;
1018 if let Some(ref def) = ty.default {
1019 return codemap::mk_sp(lo, def.span.hi);
1021 if ty.bounds.is_empty() {
1024 let hi = match ty.bounds[ty.bounds.len() - 1] {
1025 ast::TyParamBound::TraitTyParamBound(ref ptr, _) => ptr.span.hi,
1026 ast::TyParamBound::RegionTyParamBound(ref l) => l.span.hi,
1028 codemap::mk_sp(lo, hi)
1031 fn span_for_where_pred(pred: &ast::WherePredicate) -> Span {
1033 ast::WherePredicate::BoundPredicate(ref p) => p.span,
1034 ast::WherePredicate::RegionPredicate(ref p) => p.span,
1035 ast::WherePredicate::EqPredicate(ref p) => p.span,