## Summary This PR updates the formatter to preserve trailing semicolon for Jupyter Notebooks. The motivation behind the change is that semicolons in notebooks are typically used to hide the output, for example when plotting. This is highlighted in the linked issue. The conditions required as to when the trailing semicolon should be preserved are: 1. It should be a top-level statement which is last in the module. 2. For statement, it can be either assignment, annotated assignment, or augmented assignment. Here, the target should only be a single identifier i.e., multiple assignments or tuple unpacking isn't considered. 3. For expression, it can be any. ## Test Plan Add a new integration test in `ruff_cli`. The test notebook basically acts as a document as to which trailing semicolons are to be preserved. fixes: #8254
57 lines
1.5 KiB
Rust
57 lines
1.5 KiB
Rust
use ruff_python_ast as ast;
|
|
use ruff_python_ast::{Expr, Operator, StmtExpr};
|
|
|
|
use crate::comments::{SourceComment, SuppressionKind};
|
|
|
|
use crate::expression::maybe_parenthesize_expression;
|
|
use crate::expression::parentheses::Parenthesize;
|
|
use crate::prelude::*;
|
|
use crate::statement::trailing_semicolon;
|
|
|
|
#[derive(Default)]
|
|
pub struct FormatStmtExpr;
|
|
|
|
impl FormatNodeRule<StmtExpr> for FormatStmtExpr {
|
|
fn fmt_fields(&self, item: &StmtExpr, f: &mut PyFormatter) -> FormatResult<()> {
|
|
let StmtExpr { value, .. } = item;
|
|
|
|
if is_arithmetic_like(value) {
|
|
maybe_parenthesize_expression(value, item, Parenthesize::Optional).fmt(f)?;
|
|
} else {
|
|
value.format().fmt(f)?;
|
|
}
|
|
|
|
if f.options().source_type().is_ipynb()
|
|
&& f.context().node_level().is_last_top_level_statement()
|
|
&& trailing_semicolon(item.into(), f.context().source()).is_some()
|
|
{
|
|
token(";").fmt(f)?;
|
|
}
|
|
|
|
Ok(())
|
|
}
|
|
|
|
fn is_suppressed(
|
|
&self,
|
|
trailing_comments: &[SourceComment],
|
|
context: &PyFormatContext,
|
|
) -> bool {
|
|
SuppressionKind::has_skip_comment(trailing_comments, context.source())
|
|
}
|
|
}
|
|
|
|
const fn is_arithmetic_like(expression: &Expr) -> bool {
|
|
matches!(
|
|
expression,
|
|
Expr::BinOp(ast::ExprBinOp {
|
|
op: Operator::BitOr
|
|
| Operator::BitXor
|
|
| Operator::LShift
|
|
| Operator::RShift
|
|
| Operator::Add
|
|
| Operator::Sub,
|
|
..
|
|
})
|
|
)
|
|
}
|