1 use std::cell::RefCell;
3 use syntax::parse::ParseSess;
4 use syntax::source_map::{self, BytePos, Pos, SourceMap, Span};
5 use syntax::{ast, visit};
8 use crate::comment::{rewrite_comment, CodeCharKind, CommentCodeSlices};
9 use crate::config::{BraceStyle, Config};
10 use crate::coverage::transform_missing_snippet;
12 format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item,
13 rewrite_associated_impl_type, rewrite_associated_type, rewrite_existential_impl_type,
14 rewrite_existential_type, rewrite_extern_crate, rewrite_type_alias, FnBraceStyle, FnSig,
15 StaticParts, StructParts,
17 use crate::macros::{rewrite_macro, rewrite_macro_def, MacroPosition};
18 use crate::rewrite::{Rewrite, RewriteContext};
19 use crate::shape::{Indent, Shape};
20 use crate::skip::{is_skip_attr, SkipContext};
21 use crate::source_map::{LineRangeUtils, SpanUtils};
22 use crate::spanned::Spanned;
23 use crate::stmt::Stmt;
25 self, contains_skip, count_newlines, depr_skip_annotation, inner_attributes, last_line_width,
26 mk_sp, ptr_vec_to_ref_vec, rewrite_ident, stmt_expr,
28 use crate::{ErrorKind, FormatReport, FormattingError};
30 /// Creates a string slice corresponding to the specified span.
31 pub(crate) struct SnippetProvider<'a> {
32 /// A pointer to the content of the file we are formatting.
34 /// A position of the start of `big_snippet`, used as an offset.
38 impl<'a> SnippetProvider<'a> {
39 pub(crate) fn span_to_snippet(&self, span: Span) -> Option<&str> {
40 let start_index = span.lo().to_usize().checked_sub(self.start_pos)?;
41 let end_index = span.hi().to_usize().checked_sub(self.start_pos)?;
42 Some(&self.big_snippet[start_index..end_index])
45 pub(crate) fn new(start_pos: BytePos, big_snippet: &'a str) -> Self {
46 let start_pos = start_pos.to_usize();
54 pub(crate) struct FmtVisitor<'a> {
55 parent_context: Option<&'a RewriteContext<'a>>,
56 pub(crate) parse_session: &'a ParseSess,
57 pub(crate) source_map: &'a SourceMap,
58 pub(crate) buffer: String,
59 pub(crate) last_pos: BytePos,
60 // FIXME: use an RAII util or closure for indenting
61 pub(crate) block_indent: Indent,
62 pub(crate) config: &'a Config,
63 pub(crate) is_if_else_block: bool,
64 pub(crate) snippet_provider: &'a SnippetProvider<'a>,
65 pub(crate) line_number: usize,
66 /// List of 1-based line ranges which were annotated with skip
67 /// Both bounds are inclusifs.
68 pub(crate) skipped_range: Vec<(usize, usize)>,
69 pub(crate) macro_rewrite_failure: bool,
70 pub(crate) report: FormatReport,
71 pub(crate) skip_context: SkipContext,
74 impl<'a> Drop for FmtVisitor<'a> {
76 if let Some(ctx) = self.parent_context {
77 if self.macro_rewrite_failure {
78 ctx.macro_rewrite_failure.replace(true);
84 impl<'b, 'a: 'b> FmtVisitor<'a> {
85 fn set_parent_context(&mut self, context: &'a RewriteContext<'_>) {
86 self.parent_context = Some(context);
89 pub(crate) fn shape(&self) -> Shape {
90 Shape::indented(self.block_indent, self.config)
93 fn next_span(&self, hi: BytePos) -> Span {
94 mk_sp(self.last_pos, hi)
97 fn visit_stmt(&mut self, stmt: &Stmt<'_>) {
99 "visit_stmt: {:?} {:?}",
100 self.source_map.lookup_char_pos(stmt.span().lo()),
101 self.source_map.lookup_char_pos(stmt.span().hi())
104 match stmt.as_ast_node().node {
105 ast::StmtKind::Item(ref item) => {
106 self.visit_item(item);
107 // Handle potential `;` after the item.
108 self.format_missing(stmt.span().hi());
110 ast::StmtKind::Local(..) | ast::StmtKind::Expr(..) | ast::StmtKind::Semi(..) => {
111 let attrs = get_attrs_from_stmt(stmt.as_ast_node());
112 if contains_skip(attrs) {
113 self.push_skipped_with_span(
116 get_span_without_attrs(stmt.as_ast_node()),
119 let shape = self.shape();
120 let rewrite = self.with_context(|ctx| stmt.rewrite(&ctx, shape));
121 self.push_rewrite(stmt.span(), rewrite)
124 ast::StmtKind::Mac(ref mac) => {
125 let (ref mac, _macro_style, ref attrs) = **mac;
126 if self.visit_attrs(attrs, ast::AttrStyle::Outer) {
127 self.push_skipped_with_span(
130 get_span_without_attrs(stmt.as_ast_node()),
133 self.visit_mac(mac, None, MacroPosition::Statement);
135 self.format_missing(stmt.span().hi());
140 /// Remove spaces between the opening brace and the first statement or the inner attribute
142 fn trim_spaces_after_opening_brace(
145 inner_attrs: Option<&[ast::Attribute]>,
147 if let Some(first_stmt) = b.stmts.first() {
149 .and_then(|attrs| inner_attributes(attrs).first().map(|attr| attr.span.lo()))
150 .unwrap_or_else(|| first_stmt.span().lo());
151 let missing_span = self.next_span(hi);
152 let snippet = self.snippet(missing_span);
153 let len = CommentCodeSlices::new(snippet)
155 .and_then(|(kind, _, s)| {
156 if kind == CodeCharKind::Normal {
162 if let Some(len) = len {
163 self.last_pos = self.last_pos + BytePos::from_usize(len);
168 pub(crate) fn visit_block(
171 inner_attrs: Option<&[ast::Attribute]>,
175 "visit_block: {:?} {:?}",
176 self.source_map.lookup_char_pos(b.span.lo()),
177 self.source_map.lookup_char_pos(b.span.hi())
180 // Check if this block has braces.
181 let brace_compensation = BytePos(if has_braces { 1 } else { 0 });
183 self.last_pos = self.last_pos + brace_compensation;
184 self.block_indent = self.block_indent.block_indent(self.config);
186 self.trim_spaces_after_opening_brace(b, inner_attrs);
188 // Format inner attributes if available.
189 if let Some(attrs) = inner_attrs {
190 self.visit_attrs(attrs, ast::AttrStyle::Inner);
193 self.walk_block_stmts(b);
195 if !b.stmts.is_empty() {
196 if let Some(expr) = stmt_expr(&b.stmts[b.stmts.len() - 1]) {
197 if utils::semicolon_for_expr(&self.get_context(), expr) {
203 let rest_span = self.next_span(b.span.hi());
204 if out_of_file_lines_range!(self, rest_span) {
205 self.push_str(self.snippet(rest_span));
206 self.block_indent = self.block_indent.block_unindent(self.config);
208 // Ignore the closing brace.
209 let missing_span = self.next_span(b.span.hi() - brace_compensation);
210 self.close_block(missing_span, self.unindent_comment_on_closing_brace(b));
212 self.last_pos = source!(self, b.span).hi();
215 fn close_block(&mut self, span: Span, unindent_comment: bool) {
216 let config = self.config;
218 let mut last_hi = span.lo();
219 let mut unindented = false;
220 let mut prev_ends_with_newline = false;
221 let mut extra_newline = false;
223 let skip_normal = |s: &str| {
224 let trimmed = s.trim();
225 trimmed.is_empty() || trimmed.chars().all(|c| c == ';')
228 for (kind, offset, sub_slice) in CommentCodeSlices::new(self.snippet(span)) {
229 let sub_slice = transform_missing_snippet(config, sub_slice);
231 debug!("close_block: {:?} {:?} {:?}", kind, offset, sub_slice);
234 CodeCharKind::Comment => {
235 if !unindented && unindent_comment {
237 self.block_indent = self.block_indent.block_unindent(config);
239 let span_in_between = mk_sp(last_hi, span.lo() + BytePos::from_usize(offset));
240 let snippet_in_between = self.snippet(span_in_between);
241 let mut comment_on_same_line = !snippet_in_between.contains("\n");
243 let mut comment_shape =
244 Shape::indented(self.block_indent, config).comment(config);
245 if comment_on_same_line {
246 // 1 = a space before `//`
247 let offset_len = 1 + last_line_width(&self.buffer)
248 .saturating_sub(self.block_indent.width());
250 .visual_indent(offset_len)
251 .sub_width(offset_len)
253 Some(shp) => comment_shape = shp,
254 None => comment_on_same_line = false,
258 if comment_on_same_line {
261 if count_newlines(snippet_in_between) >= 2 || extra_newline {
264 self.push_str(&self.block_indent.to_string_with_newline(config));
267 let comment_str = rewrite_comment(&sub_slice, false, comment_shape, config);
269 Some(ref s) => self.push_str(s),
270 None => self.push_str(&sub_slice),
273 CodeCharKind::Normal if skip_normal(&sub_slice) => {
274 extra_newline = prev_ends_with_newline && sub_slice.contains('\n');
277 CodeCharKind::Normal => {
278 self.push_str(&self.block_indent.to_string_with_newline(config));
279 self.push_str(sub_slice.trim());
282 prev_ends_with_newline = sub_slice.ends_with('\n');
283 extra_newline = false;
284 last_hi = span.lo() + BytePos::from_usize(offset + sub_slice.len());
287 self.block_indent = self.block_indent.block_indent(self.config);
289 self.block_indent = self.block_indent.block_unindent(self.config);
290 self.push_str(&self.block_indent.to_string_with_newline(config));
294 fn unindent_comment_on_closing_brace(&self, b: &ast::Block) -> bool {
295 self.is_if_else_block && !b.stmts.is_empty()
298 // Note that this only gets called for function definitions. Required methods
299 // on traits do not get handled here.
302 fk: visit::FnKind<'_>,
303 generics: &ast::Generics,
306 defaultness: ast::Defaultness,
307 inner_attrs: Option<&[ast::Attribute]>,
309 let indent = self.block_indent;
311 let rewrite = match fk {
312 visit::FnKind::ItemFn(ident, _, _, b) | visit::FnKind::Method(ident, _, _, b) => {
314 self.rewrite_fn_before_block(
317 &FnSig::from_fn_kind(&fk, generics, fd, defaultness),
318 mk_sp(s.lo(), b.span.lo()),
321 visit::FnKind::Closure(_) => unreachable!(),
324 if let Some((fn_str, fn_brace_style)) = rewrite {
325 self.format_missing_with_indent(source!(self, s).lo());
327 if let Some(rw) = self.single_line_fn(&fn_str, block, inner_attrs) {
329 self.last_pos = s.hi();
333 self.push_str(&fn_str);
334 match fn_brace_style {
335 FnBraceStyle::SameLine => self.push_str(" "),
336 FnBraceStyle::NextLine => {
337 self.push_str(&self.block_indent.to_string_with_newline(self.config))
341 self.last_pos = source!(self, block.span).lo();
343 self.format_missing(source!(self, block.span).lo());
346 self.visit_block(block, inner_attrs, true)
349 pub(crate) fn visit_item(&mut self, item: &ast::Item) {
350 skip_out_of_file_lines_range_visitor!(self, item.span);
352 // This is where we bail out if there is a skip attribute. This is only
353 // complex in the module case. It is complex because the module could be
354 // in a separate file and there might be attributes in both files, but
355 // the AST lumps them all together.
357 let mut attrs = &item.attrs;
358 let skip_context_saved = self.skip_context.clone();
359 self.skip_context.update_with_attrs(&attrs);
361 let should_visit_node_again = match item.node {
362 // For use/extern crate items, skip rewriting attributes but check for a skip attribute.
363 ast::ItemKind::Use(..) | ast::ItemKind::ExternCrate(_) => {
364 if contains_skip(attrs) {
365 self.push_skipped_with_span(attrs.as_slice(), item.span(), item.span());
371 // Module is inline, in this case we treat it like any other item.
372 _ if !is_mod_decl(item) => {
373 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
374 self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());
380 // Module is not inline, but should be skipped.
381 ast::ItemKind::Mod(..) if contains_skip(&item.attrs) => false,
382 // Module is not inline and should not be skipped. We want
383 // to process only the attributes in the current file.
384 ast::ItemKind::Mod(..) => {
385 filtered_attrs = filter_inline_attrs(&item.attrs, item.span());
386 // Assert because if we should skip it should be caught by
388 assert!(!self.visit_attrs(&filtered_attrs, ast::AttrStyle::Outer));
389 attrs = &filtered_attrs;
393 if self.visit_attrs(&item.attrs, ast::AttrStyle::Outer) {
394 self.push_skipped_with_span(item.attrs.as_slice(), item.span(), item.span());
402 if should_visit_node_again {
404 ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
405 ast::ItemKind::Impl(..) => {
406 let block_indent = self.block_indent;
407 let rw = self.with_context(|ctx| format_impl(&ctx, item, block_indent));
408 self.push_rewrite(item.span, rw);
410 ast::ItemKind::Trait(..) => {
411 let block_indent = self.block_indent;
412 let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent));
413 self.push_rewrite(item.span, rw);
415 ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
416 let shape = Shape::indented(self.block_indent, self.config);
417 let rw = format_trait_alias(
425 self.push_rewrite(item.span, rw);
427 ast::ItemKind::ExternCrate(_) => {
428 let rw = rewrite_extern_crate(&self.get_context(), item, self.shape());
429 let span = if attrs.is_empty() {
432 mk_sp(attrs[0].span.lo(), item.span.hi())
434 self.push_rewrite(span, rw);
436 ast::ItemKind::Struct(..) | ast::ItemKind::Union(..) => {
437 self.visit_struct(&StructParts::from_item(item));
439 ast::ItemKind::Enum(ref def, ref generics) => {
440 self.format_missing_with_indent(source!(self, item.span).lo());
441 self.visit_enum(item.ident, &item.vis, def, generics, item.span);
442 self.last_pos = source!(self, item.span).hi();
444 ast::ItemKind::Mod(ref module) => {
445 let is_inline = !is_mod_decl(item);
446 self.format_missing_with_indent(source!(self, item.span).lo());
447 self.format_mod(module, &item.vis, item.span, item.ident, attrs, is_inline);
449 ast::ItemKind::Mac(ref mac) => {
450 self.visit_mac(mac, Some(item.ident), MacroPosition::Item);
452 ast::ItemKind::ForeignMod(ref foreign_mod) => {
453 self.format_missing_with_indent(source!(self, item.span).lo());
454 self.format_foreign_mod(foreign_mod, item.span);
456 ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => {
457 self.visit_static(&StaticParts::from_item(item));
459 ast::ItemKind::Fn(ref decl, ref fn_header, ref generics, ref body) => {
460 let inner_attrs = inner_attributes(&item.attrs);
462 visit::FnKind::ItemFn(item.ident, fn_header, &item.vis, body),
466 ast::Defaultness::Final,
470 ast::ItemKind::Ty(ref ty, ref generics) => {
471 let rewrite = rewrite_type_alias(
479 self.push_rewrite(item.span, rewrite);
481 ast::ItemKind::Existential(ref generic_bounds, ref generics) => {
482 let rewrite = rewrite_existential_type(
490 self.push_rewrite(item.span, rewrite);
492 ast::ItemKind::GlobalAsm(..) => {
493 let snippet = Some(self.snippet(item.span).to_owned());
494 self.push_rewrite(item.span, snippet);
496 ast::ItemKind::MacroDef(ref def) => {
497 let rewrite = rewrite_macro_def(
506 self.push_rewrite(item.span, rewrite);
510 self.skip_context = skip_context_saved;
513 pub(crate) fn visit_trait_item(&mut self, ti: &ast::TraitItem) {
514 skip_out_of_file_lines_range_visitor!(self, ti.span);
516 if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
517 self.push_skipped_with_span(ti.attrs.as_slice(), ti.span(), ti.span());
522 ast::TraitItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
523 ast::TraitItemKind::Method(ref sig, None) => {
524 let indent = self.block_indent;
526 self.rewrite_required_fn(indent, ti.ident, sig, &ti.generics, ti.span);
527 self.push_rewrite(ti.span, rewrite);
529 ast::TraitItemKind::Method(ref sig, Some(ref body)) => {
530 let inner_attrs = inner_attributes(&ti.attrs);
532 visit::FnKind::Method(ti.ident, sig, None, body),
536 ast::Defaultness::Final,
540 ast::TraitItemKind::Type(ref generic_bounds, ref type_default) => {
541 let rewrite = rewrite_associated_type(
543 type_default.as_ref(),
545 Some(generic_bounds),
549 self.push_rewrite(ti.span, rewrite);
551 ast::TraitItemKind::Macro(ref mac) => {
552 self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
557 pub(crate) fn visit_impl_item(&mut self, ii: &ast::ImplItem) {
558 skip_out_of_file_lines_range_visitor!(self, ii.span);
560 if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
561 self.push_skipped_with_span(ii.attrs.as_slice(), ii.span(), ii.span());
566 ast::ImplItemKind::Method(ref sig, ref body) => {
567 let inner_attrs = inner_attributes(&ii.attrs);
569 visit::FnKind::Method(ii.ident, sig, Some(&ii.vis), body),
577 ast::ImplItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
578 ast::ImplItemKind::Type(ref ty) => {
579 let rewrite = rewrite_associated_impl_type(
587 self.push_rewrite(ii.span, rewrite);
589 ast::ImplItemKind::Existential(ref generic_bounds) => {
590 let rewrite = rewrite_existential_impl_type(
597 self.push_rewrite(ii.span, rewrite);
599 ast::ImplItemKind::Macro(ref mac) => {
600 self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
605 fn visit_mac(&mut self, mac: &ast::Mac, ident: Option<ast::Ident>, pos: MacroPosition) {
606 skip_out_of_file_lines_range_visitor!(self, mac.span);
609 let shape = self.shape().saturating_sub_width(1);
610 let rewrite = self.with_context(|ctx| rewrite_macro(mac, ident, ctx, shape, pos));
611 self.push_rewrite(mac.span, rewrite);
614 pub(crate) fn push_str(&mut self, s: &str) {
615 self.line_number += count_newlines(s);
616 self.buffer.push_str(s);
619 #[allow(clippy::needless_pass_by_value)]
620 fn push_rewrite_inner(&mut self, span: Span, rewrite: Option<String>) {
621 if let Some(ref s) = rewrite {
624 let snippet = self.snippet(span);
625 self.push_str(snippet);
627 self.last_pos = source!(self, span).hi();
630 pub(crate) fn push_rewrite(&mut self, span: Span, rewrite: Option<String>) {
631 self.format_missing_with_indent(source!(self, span).lo());
632 self.push_rewrite_inner(span, rewrite);
635 pub(crate) fn push_skipped_with_span(
637 attrs: &[ast::Attribute],
641 self.format_missing_with_indent(source!(self, item_span).lo());
642 // do not take into account the lines with attributes as part of the skipped range
643 let attrs_end = attrs
645 .map(|attr| self.source_map.lookup_char_pos(attr.span.hi()).line)
648 let first_line = self.source_map.lookup_char_pos(main_span.lo()).line;
649 // Statement can start after some newlines and/or spaces
650 // or it can be on the same line as the last attribute.
651 // So here we need to take a minimum between the two.
652 let lo = std::cmp::min(attrs_end + 1, first_line);
653 self.push_rewrite_inner(item_span, None);
654 let hi = self.line_number + 1;
655 self.skipped_range.push((lo, hi));
658 pub(crate) fn from_context(ctx: &'a RewriteContext<'_>) -> FmtVisitor<'a> {
659 let mut visitor = FmtVisitor::from_source_map(
662 ctx.snippet_provider,
665 visitor.skip_context.update(ctx.skip_context.clone());
666 visitor.set_parent_context(ctx);
670 pub(crate) fn from_source_map(
671 parse_session: &'a ParseSess,
673 snippet_provider: &'a SnippetProvider<'_>,
674 report: FormatReport,
675 ) -> FmtVisitor<'a> {
677 parent_context: None,
679 source_map: parse_session.source_map(),
680 buffer: String::with_capacity(snippet_provider.big_snippet.len() * 2),
681 last_pos: BytePos(0),
682 block_indent: Indent::empty(),
684 is_if_else_block: false,
687 skipped_range: vec![],
688 macro_rewrite_failure: false,
690 skip_context: Default::default(),
694 pub(crate) fn opt_snippet(&'b self, span: Span) -> Option<&'a str> {
695 self.snippet_provider.span_to_snippet(span)
698 pub(crate) fn snippet(&'b self, span: Span) -> &'a str {
699 self.opt_snippet(span).unwrap()
702 // Returns true if we should skip the following item.
703 pub(crate) fn visit_attrs(&mut self, attrs: &[ast::Attribute], style: ast::AttrStyle) -> bool {
705 if attr.check_name(depr_skip_annotation()) {
706 let file_name = self.source_map.span_to_filename(attr.span).into();
709 vec![FormattingError::from_span(
712 ErrorKind::DeprecatedAttr,
715 } else if self.is_unknown_rustfmt_attr(&attr.path.segments) {
716 let file_name = self.source_map.span_to_filename(attr.span).into();
719 vec![FormattingError::from_span(
727 if contains_skip(attrs) {
731 let attrs: Vec<_> = attrs.iter().filter(|a| a.style == style).cloned().collect();
732 if attrs.is_empty() {
736 let rewrite = attrs.rewrite(&self.get_context(), self.shape());
737 let span = mk_sp(attrs[0].span.lo(), attrs[attrs.len() - 1].span.hi());
738 self.push_rewrite(span, rewrite);
743 fn is_unknown_rustfmt_attr(&self, segments: &[ast::PathSegment]) -> bool {
744 if segments[0].ident.to_string() != "rustfmt" {
747 !is_skip_attr(segments)
750 fn walk_mod_items(&mut self, m: &ast::Mod) {
751 self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&m.items));
754 fn walk_stmts(&mut self, stmts: &[Stmt<'_>]) {
755 if stmts.is_empty() {
759 // Extract leading `use ...;`.
760 let items: Vec<_> = stmts
762 .take_while(|stmt| stmt.to_item().map_or(false, is_use_item))
763 .filter_map(|stmt| stmt.to_item())
766 if items.is_empty() {
767 self.visit_stmt(&stmts[0]);
768 self.walk_stmts(&stmts[1..]);
770 self.visit_items_with_reordering(&items);
771 self.walk_stmts(&stmts[items.len()..]);
775 fn walk_block_stmts(&mut self, b: &ast::Block) {
776 self.walk_stmts(&Stmt::from_ast_nodes(b.stmts.iter()))
782 vis: &ast::Visibility,
785 attrs: &[ast::Attribute],
788 let vis_str = utils::format_visibility(&self.get_context(), vis);
789 self.push_str(&*vis_str);
790 self.push_str("mod ");
791 // Calling `to_owned()` to work around borrow checker.
792 let ident_str = rewrite_ident(&self.get_context(), ident).to_owned();
793 self.push_str(&ident_str);
796 match self.config.brace_style() {
797 BraceStyle::AlwaysNextLine => {
798 let indent_str = self.block_indent.to_string_with_newline(self.config);
799 self.push_str(&indent_str);
802 _ => self.push_str(" {"),
804 // Hackery to account for the closing }.
805 let mod_lo = self.snippet_provider.span_after(source!(self, s), "{");
807 self.snippet(mk_sp(mod_lo, source!(self, m.inner).hi() - BytePos(1)));
808 let body_snippet = body_snippet.trim();
809 if body_snippet.is_empty() {
812 self.last_pos = mod_lo;
813 self.block_indent = self.block_indent.block_indent(self.config);
814 self.visit_attrs(attrs, ast::AttrStyle::Inner);
815 self.walk_mod_items(m);
816 let missing_span = self.next_span(m.inner.hi() - BytePos(1));
817 self.close_block(missing_span, false);
819 self.last_pos = source!(self, m.inner).hi();
822 self.last_pos = source!(self, s).hi();
826 pub(crate) fn format_separate_mod(
829 source_file: &source_map::SourceFile,
831 self.block_indent = Indent::empty();
832 self.walk_mod_items(m);
833 self.format_missing_with_indent(source_file.end_pos);
836 pub(crate) fn skip_empty_lines(&mut self, end_pos: BytePos) {
837 while let Some(pos) = self
839 .opt_span_after(self.next_span(end_pos), "\n")
841 if let Some(snippet) = self.opt_snippet(self.next_span(pos)) {
842 if snippet.trim().is_empty() {
851 pub(crate) fn with_context<F>(&mut self, f: F) -> Option<String>
853 F: Fn(&RewriteContext<'_>) -> Option<String>,
855 // FIXME borrow checker fighting - can be simplified a lot with NLL.
856 let (result, mrf) = {
857 let context = self.get_context();
858 let result = f(&context);
859 let mrf = &context.macro_rewrite_failure.borrow();
860 (result, *std::ops::Deref::deref(mrf))
863 self.macro_rewrite_failure |= mrf;
867 pub(crate) fn get_context(&self) -> RewriteContext<'_> {
869 parse_session: self.parse_session,
870 source_map: self.source_map,
872 inside_macro: RefCell::new(false),
873 use_block: RefCell::new(false),
874 is_if_else_block: RefCell::new(false),
875 force_one_line_chain: RefCell::new(false),
876 snippet_provider: self.snippet_provider,
877 macro_rewrite_failure: RefCell::new(false),
878 report: self.report.clone(),
879 skip_context: self.skip_context.clone(),