Skip to content

Implement rewrite_result for AST nodes #6201

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

Closed
wants to merge 2 commits into from
Closed
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
58 changes: 57 additions & 1 deletion src/chains.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ use crate::config::{IndentStyle, Version};
use crate::expr::rewrite_call;
use crate::lists::extract_pre_comment;
use crate::macros::convert_try_mac;
use crate::rewrite::{Rewrite, RewriteContext};
use crate::rewrite::{Rewrite, RewriteContext, RewriteError};
use crate::shape::Shape;
use crate::source_map::SpanUtils;
use crate::utils::{
Expand Down Expand Up @@ -543,6 +543,62 @@ impl Rewrite for Chain {
let result = formatter.join_rewrites(context, child_shape)?;
wrap_str(result, context.config.max_width(), shape)
}

fn rewrite_result(
&self,
context: &RewriteContext<'_>,
shape: Shape,
) -> Result<String, crate::rewrite::RewriteError> {
debug!("rewrite chain {:?} {:?}", self, shape);

let mut formatter = match context.config.indent_style() {
IndentStyle::Block => {
Box::new(ChainFormatterBlock::new(self)) as Box<dyn ChainFormatter>
}
IndentStyle::Visual => {
Box::new(ChainFormatterVisual::new(self)) as Box<dyn ChainFormatter>
}
};

formatter
.format_root(&self.parent, context, shape)
.ok_or_else(|| RewriteError::Unknown)?;
if let Some(result) = formatter.pure_root() {
return wrap_str(result, context.config.max_width(), shape).ok_or_else(|| {
// pure_root() returns Some when there's no child
RewriteError::ExceedsMaxWidth {
configured_width: context.config.max_width(),
span: self.parent.span,
}
});
}

// Decide how to layout the rest of the chain.
let child_shape = formatter
.child_shape(context, shape)
.ok_or_else(|| RewriteError::Unknown)?;

formatter
.format_children(context, child_shape)
.ok_or_else(|| RewriteError::Unknown)?;
formatter
.format_last_child(context, shape, child_shape)
.ok_or_else(|| RewriteError::Unknown)?;

let result = formatter
.join_rewrites(context, child_shape)
.ok_or_else(|| RewriteError::Unknown)?;
// Q. what should be the value of span?
wrap_str(result, context.config.max_width(), shape).ok_or_else(|| {
RewriteError::ExceedsMaxWidth {
configured_width: context.config.max_width(),
span: mk_sp(
self.parent.span.lo(),
self.children.last().unwrap().span.hi(),
),
}
})
}
}

// There are a few types for formatting chains. This is because there is a lot
Expand Down
172 changes: 171 additions & 1 deletion src/items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::expr::{
use crate::lists::{definitive_tactic, itemize_list, write_list, ListFormatting, Separator};
use crate::macros::{rewrite_macro, MacroPosition};
use crate::overflow;
use crate::rewrite::{Rewrite, RewriteContext};
use crate::rewrite::{Rewrite, RewriteContext, RewriteError};
use crate::shape::{Indent, Shape};
use crate::source_map::{LineRangeUtils, SpanUtils};
use crate::spanned::Spanned;
Expand Down Expand Up @@ -185,6 +185,176 @@ impl Rewrite for ast::Local {
result.push(';');
Some(result)
}

fn rewrite_result(
&self,
context: &RewriteContext<'_>,
shape: Shape,
) -> Result<String, RewriteError> {
debug!(
"Local::rewrite {:?} {} {:?}",
self, shape.width, shape.indent
);

skip_out_of_file_lines_range_err!(context, self.span);

if contains_skip(&self.attrs) {
return Err(RewriteError::SkipFormatting);
}

let attrs_str = self.attrs.rewrite_result(context, shape)?;
let mut result = if attrs_str.is_empty() {
"let ".to_owned()
} else {
combine_strs_with_missing_comments(
context,
&attrs_str,
"let ",
mk_sp(
self.attrs.last().map(|a| a.span.hi()).unwrap(),
self.span.lo(),
),
shape,
false,
)
.ok_or_else(|| RewriteError::Unknown)?
};
let let_kw_offset = result.len() - "let ".len();

// 4 = "let ".len()
let pat_shape = shape
.offset_left(4)
.ok_or_else(|| RewriteError::ExceedsMaxWidth {
configured_width: shape.width,
span: self.span(),
})?;
// 1 = ;
let pat_shape = pat_shape
.sub_width(1)
.ok_or_else(|| RewriteError::ExceedsMaxWidth {
configured_width: shape.width,
span: self.span(),
})?;
let pat_str = self.pat.rewrite_result(context, pat_shape)?;
result.push_str(&pat_str);

// String that is placed within the assignment pattern and expression.
let infix = {
let mut infix = String::with_capacity(32);

if let Some(ref ty) = self.ty {
let separator = type_annotation_separator(context.config);
let ty_shape = if pat_str.contains('\n') {
shape.with_max_width(context.config)
} else {
shape
}
.offset_left(last_line_width(&result) + separator.len())
.ok_or_else(|| RewriteError::ExceedsMaxWidth {
configured_width: shape.width,
span: self.span(),
})?
// 2 = ` =`
.sub_width(2)
.ok_or_else(|| RewriteError::ExceedsMaxWidth {
configured_width: shape.width,
span: self.span(),
})?;

let rewrite = ty.rewrite_result(context, ty_shape)?;

infix.push_str(separator);
infix.push_str(&rewrite);
}

if self.kind.init().is_some() {
infix.push_str(" =");
}

infix
};

result.push_str(&infix);

if let Some((init, else_block)) = self.kind.init_else_opt() {
// 1 = trailing semicolon;
let nested_shape = shape
.sub_width(1)
.ok_or_else(|| RewriteError::ExceedsMaxWidth {
configured_width: shape.width,
span: self.span(),
})?;

result = rewrite_assign_rhs(
context,
result,
init,
&RhsAssignKind::Expr(&init.kind, init.span),
nested_shape,
)
.ok_or_else(|| RewriteError::Unknown)?;

if let Some(block) = else_block {
let else_kw_span = init.span.between(block.span);
// Strip attributes and comments to check if newline is needed before the else
// keyword from the initializer part. (#5901)
let init_str = if context.config.version() == Version::Two {
&result[let_kw_offset..]
} else {
result.as_str()
};
let force_newline_else = pat_str.contains('\n')
|| !same_line_else_kw_and_brace(init_str, context, else_kw_span, nested_shape);
let else_kw = rewrite_else_kw_with_comments(
force_newline_else,
true,
context,
else_kw_span,
shape,
);
result.push_str(&else_kw);

// At this point we've written `let {pat} = {expr} else' into the buffer, and we
// want to calculate up front if there's room to write the divergent block on the
// same line. The available space varies based on indentation so we clamp the width
// on the smaller of `shape.width` and `single_line_let_else_max_width`.
let max_width =
std::cmp::min(shape.width, context.config.single_line_let_else_max_width());

// If available_space hits zero we know for sure this will be a multi-lined block
let assign_str_with_else_kw = if context.config.version() == Version::Two {
&result[let_kw_offset..]
} else {
result.as_str()
};
let available_space = max_width.saturating_sub(assign_str_with_else_kw.len());

let allow_single_line = !force_newline_else
&& available_space > 0
&& allow_single_line_let_else_block(assign_str_with_else_kw, block);

let mut rw_else_block =
rewrite_let_else_block(block, allow_single_line, context, shape)
.ok_or_else(|| RewriteError::Unknown)?;

let single_line_else = !rw_else_block.contains('\n');
// +1 for the trailing `;`
let else_block_exceeds_width = rw_else_block.len() + 1 > available_space;

if allow_single_line && single_line_else && else_block_exceeds_width {
// writing this on one line would exceed the available width
// so rewrite the else block over multiple lines.
rw_else_block = rewrite_let_else_block(block, false, context, shape)
.ok_or_else(|| RewriteError::Unknown)?;
}

result.push_str(&rw_else_block);
};
}

result.push(';');
Ok(result)
}
}

/// When the initializer expression is multi-lined, then the else keyword and opening brace of the
Expand Down
25 changes: 24 additions & 1 deletion src/rewrite.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use std::rc::Rc;

use rustc_ast::ptr;
use rustc_span::Span;
use thiserror::Error;

use crate::config::{Config, IndentStyle};
use crate::parse::session::ParseSess;
Expand All @@ -16,6 +17,15 @@ use crate::FormatReport;
pub(crate) trait Rewrite {
/// Rewrite self into shape.
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String>;
/// Rewrite self into shape, return RewriteError on formatting failure.
/// rewrite() calls will be eventually replaced with rewrite_result()
fn rewrite_result(
&self,
context: &RewriteContext<'_>,
shape: Shape,
) -> Result<String, RewriteError> {
self.rewrite(context, shape).ok_or(RewriteError::Unknown)
}
}

impl<T: Rewrite> Rewrite for ptr::P<T> {
Expand All @@ -24,6 +34,20 @@ impl<T: Rewrite> Rewrite for ptr::P<T> {
}
}

#[derive(Error, Debug)]
pub(crate) enum RewriteError {
#[error("Formatting was skipped due to skip attribute or out of file range.")]
SkipFormatting,

// Question. (1) may miss span ex) wrap_str (2) width? offset? max_width?
#[error("It exceeds the required width of {configured_width} for the span: {span:?}")]
ExceedsMaxWidth { configured_width: usize, span: Span },

/// Format failure that does not fit to above categories.
#[error("An unknown error occurred during formatting.")]
Unknown,
}

#[derive(Clone)]
pub(crate) struct RewriteContext<'a> {
pub(crate) parse_sess: &'a ParseSess,
Expand All @@ -44,7 +68,6 @@ pub(crate) struct RewriteContext<'a> {
pub(crate) skip_context: SkipContext,
pub(crate) skipped_range: Rc<RefCell<Vec<(usize, usize)>>>,
}

pub(crate) struct InsideMacroGuard {
is_nested_macro_context: bool,
inside_macro_ref: Rc<Cell<bool>>,
Expand Down
8 changes: 8 additions & 0 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,14 @@ macro_rules! skip_out_of_file_lines_range {
};
}

macro_rules! skip_out_of_file_lines_range_err {
($self:ident, $span:expr) => {
if out_of_file_lines_range!($self, $span) {
return Err(RewriteError::SkipFormatting);
}
};
}

macro_rules! skip_out_of_file_lines_range_visitor {
($self:ident, $span:expr) => {
if out_of_file_lines_range!($self, $span) {
Expand Down
Loading