Skip to content

utils: Add CodeMapExt extension trait for span_* methods #857

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 14, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 16 additions & 17 deletions src/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use rewrite::{Rewrite, RewriteContext};
use lists::{write_list, itemize_list, ListFormatting, SeparatorTactic, ListTactic,
DefinitiveListTactic, definitive_tactic, ListItem, format_fn_args};
use string::{StringFormat, rewrite_string};
use utils::{span_after, span_before, extra_offset, last_line_width, wrap_str, binary_search,
use utils::{CodeMapSpanUtils, extra_offset, last_line_width, wrap_str, binary_search,
first_line_width, semicolon_for_stmt};
use visitor::FmtVisitor;
use config::{Config, StructLitStyle, MultilineStyle};
Expand All @@ -39,7 +39,7 @@ impl Rewrite for ast::Expr {
let result = match self.node {
ast::Expr_::ExprVec(ref expr_vec) => {
rewrite_array(expr_vec.iter().map(|e| &**e),
mk_sp(span_after(self.span, "[", context.codemap), self.span.hi),
mk_sp(context.codemap.span_after(self.span, "["), self.span.hi),
context,
width,
offset)
Expand Down Expand Up @@ -332,7 +332,7 @@ fn rewrite_closure(capture: ast::CaptureClause,
|arg| span_lo_for_arg(arg),
|arg| span_hi_for_arg(arg),
|arg| arg.rewrite(context, budget, argument_offset),
span_after(span, "|", context.codemap),
context.codemap.span_after(span, "|"),
body.span.lo);
let item_vec = arg_items.collect::<Vec<_>>();
let tactic = definitive_tactic(&item_vec, ListTactic::HorizontalVertical, horizontal_budget);
Expand Down Expand Up @@ -660,9 +660,9 @@ fn rewrite_if_else(context: &RewriteContext,

let if_block_string = try_opt!(if_block.rewrite(context, width, offset));

let between_if_cond = mk_sp(span_after(span, "if", context.codemap),
let between_if_cond = mk_sp(context.codemap.span_after(span, "if"),
pat.map_or(cond.span.lo,
|_| span_before(span, "let", context.codemap)));
|_| context.codemap.span_before(span, "let")));

let between_if_cond_comment = extract_comment(between_if_cond, &context, offset, width);

Expand Down Expand Up @@ -707,17 +707,17 @@ fn rewrite_if_else(context: &RewriteContext,
};

let between_if_else_block = mk_sp(if_block.span.hi,
span_before(mk_sp(if_block.span.hi, else_block.span.lo),
"else",
context.codemap));
context.codemap.span_before(mk_sp(if_block.span.hi,
else_block.span.lo),
"else"));
let between_if_else_block_comment = extract_comment(between_if_else_block,
&context,
offset,
width);

let after_else = mk_sp(span_after(mk_sp(if_block.span.hi, else_block.span.lo),
"else",
context.codemap),
let after_else = mk_sp(context.codemap
.span_after(mk_sp(if_block.span.hi, else_block.span.lo),
"else"),
else_block.span.lo);
let after_else_comment = extract_comment(after_else, &context, offset, width);

Expand Down Expand Up @@ -863,9 +863,8 @@ fn rewrite_match(context: &RewriteContext,
let arm_indent = nested_context.block_indent;
let arm_indent_str = arm_indent.to_string(context.config);

let open_brace_pos = span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])),
"{",
context.codemap);
let open_brace_pos = context.codemap
.span_after(mk_sp(cond.span.hi, arm_start_pos(&arms[0])), "{");

for (i, arm) in arms.iter().enumerate() {
// Make sure we get the stuff between arms.
Expand Down Expand Up @@ -1275,7 +1274,7 @@ fn rewrite_call_inner<R>(context: &RewriteContext,
None => return Err(Ordering::Greater),
};

let span_lo = span_after(span, "(", context.codemap);
let span_lo = context.codemap.span_after(span, "(");
let span = mk_sp(span_lo, span.hi);

let extra_offset = extra_offset(&callee_str, offset);
Expand Down Expand Up @@ -1461,7 +1460,7 @@ fn rewrite_struct_lit<'a>(context: &RewriteContext,
}
}
},
span_after(span, "{", context.codemap),
context.codemap.span_after(span, "{"),
span.hi);
let item_vec = items.collect::<Vec<_>>();

Expand Down Expand Up @@ -1569,7 +1568,7 @@ pub fn rewrite_tuple<'a, I>(context: &RewriteContext,
return items.next().unwrap().rewrite(context, budget, indent).map(|s| format!("({},)", s));
}

let list_lo = span_after(span, "(", context.codemap);
let list_lo = context.codemap.span_after(span, "(");
let items = itemize_list(context.codemap,
items,
")",
Expand Down
4 changes: 2 additions & 2 deletions src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
use Indent;
use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic, definitive_tactic};
use types::rewrite_path;
use utils::span_after;
use utils::CodeMapSpanUtils;
use rewrite::{Rewrite, RewriteContext};

use syntax::ast;
Expand Down Expand Up @@ -130,7 +130,7 @@ pub fn rewrite_use_list(width: usize,
|vpi| vpi.span.lo,
|vpi| vpi.span.hi,
rewrite_path_item,
span_after(span, "{", context.codemap),
context.codemap.span_after(span, "{"),
span.hi);
items.extend(iter);
items
Expand Down
23 changes: 11 additions & 12 deletions src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@
// Formatting top-level items - functions, structs, enums, traits, impls.

use Indent;
use utils::{format_mutability, format_visibility, contains_skip, span_after, end_typaram,
wrap_str, last_line_width, semicolon_for_expr, format_unsafety, trim_newlines,
span_after_last};
use utils::{CodeMapSpanUtils, format_mutability, format_visibility, contains_skip, end_typaram,
wrap_str, last_line_width, semicolon_for_expr, format_unsafety, trim_newlines};
use lists::{write_list, itemize_list, ListItem, ListFormatting, SeparatorTactic,
DefinitiveListTactic, definitive_tactic, format_item_list};
use expr::{is_empty_block, is_simple_block_stmt, rewrite_assign_rhs};
Expand Down Expand Up @@ -452,7 +451,7 @@ pub fn format_impl(context: &RewriteContext, item: &ast::Item, offset: Indent) -
result.push_str(format_unsafety(unsafety));
result.push_str("impl");

let lo = span_after(item.span, "impl", context.codemap);
let lo = context.codemap.span_after(item.span, "impl");
let hi = match *trait_ref {
Some(ref tr) => tr.path.span.lo,
None => self_ty.span.lo,
Expand Down Expand Up @@ -633,7 +632,7 @@ fn format_struct_struct(context: &RewriteContext,
let header_str = format_header(item_name, ident, vis);
result.push_str(&header_str);

let body_lo = span_after(span, "{", context.codemap);
let body_lo = context.codemap.span_after(span, "{");

let generics_str = match generics {
Some(g) => {
Expand Down Expand Up @@ -680,7 +679,7 @@ fn format_struct_struct(context: &RewriteContext,
},
|field| field.node.ty.span.hi,
|field| field.rewrite(context, item_budget, item_indent),
span_after(span, "{", context.codemap),
context.codemap.span_after(span, "{"),
span.hi);
// 1 = ,
let budget = context.config.max_width - offset.width() + context.config.tab_spaces - 1;
Expand Down Expand Up @@ -762,7 +761,7 @@ fn format_tuple_struct(context: &RewriteContext,
},
|field| field.node.ty.span.hi,
|field| field.rewrite(context, item_budget, item_indent),
span_after(span, "(", context.codemap),
context.codemap.span_after(span, "("),
span.hi);
let body = try_opt!(format_item_list(items, item_budget, item_indent, context.config));
result.push_str(&body);
Expand Down Expand Up @@ -798,7 +797,7 @@ pub fn rewrite_type_alias(context: &RewriteContext,
result.push_str(&ident.to_string());

let generics_indent = indent + result.len();
let generics_span = mk_sp(span_after(span, "type", context.codemap), ty.span.lo);
let generics_span = mk_sp(context.codemap.span_after(span, "type"), ty.span.lo);
let generics_width = context.config.max_width - " =".len();
let generics_str = try_opt!(rewrite_generics(context,
generics,
Expand Down Expand Up @@ -1152,7 +1151,7 @@ fn rewrite_fn_base(context: &RewriteContext,
let args_start = generics.ty_params
.last()
.map_or(span.lo, |tp| end_typaram(tp));
let args_span = mk_sp(span_after(mk_sp(args_start, span.hi), "(", context.codemap),
let args_span = mk_sp(context.codemap.span_after(mk_sp(args_start, span.hi), "("),
span_for_return(&fd.output).lo);
let arg_str = try_opt!(rewrite_args(context,
&fd.inputs,
Expand Down Expand Up @@ -1304,7 +1303,7 @@ fn rewrite_args(context: &RewriteContext,
if args.len() >= min_args || variadic {
let comment_span_start = if min_args == 2 {
let reduced_span = mk_sp(span.lo, args[1].ty.span.lo);
span_after_last(reduced_span, ",", context.codemap)
context.codemap.span_after_last(reduced_span, ",")
} else {
span.lo
};
Expand All @@ -1316,7 +1315,7 @@ fn rewrite_args(context: &RewriteContext,

let variadic_arg = if variadic {
let variadic_span = mk_sp(args.last().unwrap().ty.span.hi, span.hi);
let variadic_start = span_after(variadic_span, "...", context.codemap) - BytePos(3);
let variadic_start = context.codemap.span_after(variadic_span, "...") - BytePos(3);
Some(ArgumentKind::Variadic(variadic_start))
} else {
None
Expand Down Expand Up @@ -1476,7 +1475,7 @@ fn rewrite_generics(context: &RewriteContext,
|&(sp, _)| sp.hi,
// FIXME: don't clone
|&(_, ref str)| str.clone(),
span_after(span, "<", context.codemap),
context.codemap.span_after(span, "<"),
span.hi);
let list_str = try_opt!(format_item_list(items, h_budget, offset, context.config));

Expand Down
7 changes: 3 additions & 4 deletions src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ use Indent;
use rewrite::RewriteContext;
use expr::{rewrite_call, rewrite_array};
use comment::FindUncommented;
use utils::{wrap_str, span_after};
use utils::{CodeMapSpanUtils, wrap_str};

const FORCED_BRACKET_MACROS: &'static [&'static str] = &["vec!"];

Expand Down Expand Up @@ -104,9 +104,8 @@ pub fn rewrite_macro(mac: &ast::Mac,
// Format macro invocation as array literal.
let extra_offset = macro_name.len();
let rewrite = try_opt!(rewrite_array(expr_vec.iter().map(|x| &**x),
mk_sp(span_after(mac.span,
original_style.opener(),
context.codemap),
mk_sp(context.codemap.span_after(mac.span,
original_style.opener()),
mac.span.hi - BytePos(1)),
context,
try_opt!(width.checked_sub(extra_offset)),
Expand Down
6 changes: 3 additions & 3 deletions src/patterns.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

use Indent;
use rewrite::{Rewrite, RewriteContext};
use utils::{wrap_str, format_mutability, span_after};
use utils::{CodeMapSpanUtils, wrap_str, format_mutability};
use lists::{format_item_list, itemize_list};
use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
use types::rewrite_path;
Expand Down Expand Up @@ -84,7 +84,7 @@ impl Rewrite for Pat {
|item| item.span.lo,
|item| item.span.hi,
|item| item.rewrite(context, width, offset),
span_after(self.span, "(", context.codemap),
context.codemap.span_after(self.span, "("),
self.span.hi);
Some(format!("{}({})",
path_str,
Expand Down Expand Up @@ -141,7 +141,7 @@ impl Rewrite for Pat {
|f| f.span.lo,
|f| f.span.hi,
|f| f.node.rewrite(context, budget, offset),
span_after(self.span, "{", context.codemap),
context.codemap.span_after(self.span, "{"),
self.span.hi);
let mut field_string = try_opt!(format_item_list(items,
budget,
Expand Down
6 changes: 3 additions & 3 deletions src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use syntax::abi;
use {Indent, Spanned};
use lists::{format_item_list, itemize_list, format_fn_args};
use rewrite::{Rewrite, RewriteContext};
use utils::{extra_offset, span_after, format_mutability, wrap_str};
use utils::{CodeMapSpanUtils, extra_offset, format_mutability, wrap_str};
use expr::{rewrite_unary_prefix, rewrite_pair, rewrite_tuple};
use config::TypeDensity;

Expand Down Expand Up @@ -183,7 +183,7 @@ fn rewrite_segment(expr_context: bool,
.collect::<Vec<_>>();

let next_span_lo = param_list.last().unwrap().get_span().hi + BytePos(1);
let list_lo = span_after(codemap::mk_sp(*span_lo, span_hi), "<", context.codemap);
let list_lo = context.codemap.span_after(codemap::mk_sp(*span_lo, span_hi), "<");
let separator = if expr_context {
"::"
} else {
Expand Down Expand Up @@ -246,7 +246,7 @@ fn format_function_type<'a, I>(inputs: I,
let budget = try_opt!(width.checked_sub(2));
// 1 for (
let offset = offset + 1;
let list_lo = span_after(span, "(", context.codemap);
let list_lo = context.codemap.span_after(span, "(");
let items = itemize_list(context.codemap,
inputs,
")",
Expand Down
62 changes: 35 additions & 27 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,42 +20,50 @@ use rewrite::{Rewrite, RewriteContext};

use SKIP_ANNOTATION;

// Computes the length of a string's last line, minus offset.
#[inline]
pub fn extra_offset(text: &str, offset: Indent) -> usize {
match text.rfind('\n') {
// 1 for newline character
Some(idx) => text.len() - idx - 1 - offset.width(),
None => text.len(),
}
pub trait CodeMapSpanUtils {
fn span_after(&self, original: Span, needle: &str) -> BytePos;
fn span_after_last(&self, original: Span, needle: &str) -> BytePos;
fn span_before(&self, original: Span, needle: &str) -> BytePos;
}

#[inline]
pub fn span_after(original: Span, needle: &str, codemap: &CodeMap) -> BytePos {
let snippet = codemap.span_to_snippet(original).unwrap();
let offset = snippet.find_uncommented(needle).unwrap() + needle.len();
impl CodeMapSpanUtils for CodeMap {
#[inline]
fn span_after(&self, original: Span, needle: &str) -> BytePos {
let snippet = self.span_to_snippet(original).unwrap();
let offset = snippet.find_uncommented(needle).unwrap() + needle.len();

original.lo + BytePos(offset as u32)
}
original.lo + BytePos(offset as u32)
}

#[inline]
pub fn span_before(original: Span, needle: &str, codemap: &CodeMap) -> BytePos {
let snippet = codemap.span_to_snippet(original).unwrap();
let offset = snippet.find_uncommented(needle).unwrap();
#[inline]
fn span_after_last(&self, original: Span, needle: &str) -> BytePos {
let snippet = self.span_to_snippet(original).unwrap();
let mut offset = 0;

original.lo + BytePos(offset as u32)
}
while let Some(additional_offset) = snippet[offset..].find_uncommented(needle) {
offset += additional_offset + needle.len();
}

#[inline]
pub fn span_after_last(original: Span, needle: &str, codemap: &CodeMap) -> BytePos {
let snippet = codemap.span_to_snippet(original).unwrap();
let mut offset = 0;
original.lo + BytePos(offset as u32)
}

#[inline]
fn span_before(&self, original: Span, needle: &str) -> BytePos {
let snippet = self.span_to_snippet(original).unwrap();
let offset = snippet.find_uncommented(needle).unwrap();

while let Some(additional_offset) = snippet[offset..].find_uncommented(needle) {
offset += additional_offset + needle.len();
original.lo + BytePos(offset as u32)
}
}

original.lo + BytePos(offset as u32)
// Computes the length of a string's last line, minus offset.
#[inline]
pub fn extra_offset(text: &str, offset: Indent) -> usize {
match text.rfind('\n') {
// 1 for newline character
Some(idx) => text.len() - idx - 1 - offset.width(),
None => text.len(),
}
}

#[inline]
Expand Down
4 changes: 2 additions & 2 deletions src/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use syntax::visit;
use strings::string_buffer::StringBuffer;

use Indent;
use utils;
use utils::{self, CodeMapSpanUtils};
use config::Config;
use rewrite::{Rewrite, RewriteContext};
use comment::rewrite_comment;
Expand Down Expand Up @@ -450,7 +450,7 @@ impl<'a> FmtVisitor<'a> {
if is_internal {
self.buffer.push_str(" {");
// Hackery to account for the closing }.
let mod_lo = ::utils::span_after(s, "{", self.codemap);
let mod_lo = self.codemap.span_after(s, "{");
let body_snippet = self.snippet(codemap::mk_sp(mod_lo, m.inner.hi - BytePos(1)));
let body_snippet = body_snippet.trim();
if body_snippet.is_empty() {
Expand Down