4 use crate::comment::recover_comment_removed;
5 use crate::config::Version;
6 use crate::expr::{format_expr, ExprType};
7 use crate::rewrite::{Rewrite, RewriteContext};
8 use crate::shape::Shape;
9 use crate::source_map::LineRangeUtils;
10 use crate::spanned::Spanned;
11 use crate::utils::semicolon_for_stmt;
13 pub(crate) struct Stmt<'a> {
18 impl<'a> Spanned for Stmt<'a> {
19 fn span(&self) -> Span {
25 pub(crate) fn as_ast_node(&self) -> &ast::Stmt {
29 pub(crate) fn to_item(&self) -> Option<&ast::Item> {
30 match self.inner.kind {
31 ast::StmtKind::Item(ref item) => Some(&**item),
36 pub(crate) fn from_ast_node(inner: &'a ast::Stmt, is_last: bool) -> Self {
37 Stmt { inner, is_last }
40 pub(crate) fn from_ast_nodes<I>(iter: I) -> Vec<Self>
42 I: Iterator<Item = &'a ast::Stmt>,
44 let mut result = vec![];
45 let mut iter = iter.peekable();
46 while iter.peek().is_some() {
48 inner: iter.next().unwrap(),
49 is_last: iter.peek().is_none(),
55 fn is_last_expr(&self) -> bool {
60 match self.as_ast_node().kind {
61 ast::StmtKind::Expr(ref expr) => match expr.kind {
62 ast::ExprKind::Ret(..) | ast::ExprKind::Continue(..) | ast::ExprKind::Break(..) => {
72 impl<'a> Rewrite for Stmt<'a> {
73 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
74 let expr_type = if context.config.version() == Version::Two && self.is_last_expr() {
75 ExprType::SubExpression
79 format_stmt(context, shape, self.as_ast_node(), expr_type)
83 impl Rewrite for ast::Stmt {
84 fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
85 format_stmt(context, shape, self, ExprType::Statement)
90 context: &RewriteContext<'_>,
95 skip_out_of_file_lines_range!(context, stmt.span());
97 let result = match stmt.kind {
98 ast::StmtKind::Local(ref local) => local.rewrite(context, shape),
99 ast::StmtKind::Expr(ref ex) | ast::StmtKind::Semi(ref ex) => {
100 let suffix = if semicolon_for_stmt(context, stmt) {
106 let shape = shape.sub_width(suffix.len())?;
107 format_expr(ex, expr_type, context, shape).map(|s| s + suffix)
109 ast::StmtKind::Mac(..) | ast::StmtKind::Item(..) => None,
111 result.and_then(|res| recover_comment_removed(res, stmt.span(), context))