-
Notifications
You must be signed in to change notification settings - Fork 899
/
suite.rs
960 lines (858 loc) · 34.3 KB
/
suite.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
use ruff_formatter::{
write, FormatContext, FormatOwnedWithRule, FormatRefWithRule, FormatRuleWithOptions,
};
use ruff_python_ast::helpers::is_compound_statement;
use ruff_python_ast::AnyNodeRef;
use ruff_python_ast::{self as ast, Expr, PySourceType, Stmt, Suite};
use ruff_python_trivia::{lines_after, lines_after_ignoring_end_of_line_trivia, lines_before};
use ruff_text_size::{Ranged, TextRange};
use crate::comments::{
leading_comments, trailing_comments, Comments, LeadingDanglingTrailingComments,
};
use crate::context::{NodeLevel, TopLevelStatementPosition, WithIndentLevel, WithNodeLevel};
use crate::expression::expr_string_literal::ExprStringLiteralKind;
use crate::prelude::*;
use crate::preview::{
is_blank_line_after_nested_stub_class_enabled, is_dummy_implementations_enabled,
is_module_docstring_newlines_enabled, is_no_blank_line_before_class_docstring_enabled,
};
use crate::statement::stmt_expr::FormatStmtExpr;
use crate::verbatim::{
suppressed_node, write_suppressed_statements_starting_with_leading_comment,
write_suppressed_statements_starting_with_trailing_comment,
};
/// Level at which the [`Suite`] appears in the source code.
#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
pub enum SuiteKind {
/// Statements at the module level / top level
TopLevel,
/// Statements in a function body.
Function,
/// Statements in a class body.
Class,
/// Statements in any other body (e.g., `if` or `while`).
#[default]
Other,
}
#[derive(Debug)]
pub struct FormatSuite {
kind: SuiteKind,
}
impl Default for FormatSuite {
fn default() -> Self {
FormatSuite {
kind: SuiteKind::Other,
}
}
}
impl FormatRule<Suite, PyFormatContext<'_>> for FormatSuite {
fn fmt(&self, statements: &Suite, f: &mut PyFormatter) -> FormatResult<()> {
let mut iter = statements.iter();
let Some(first) = iter.next() else {
return Ok(());
};
let node_level = match self.kind {
SuiteKind::TopLevel => NodeLevel::TopLevel(
iter.clone()
.next()
.map_or(TopLevelStatementPosition::Last, |_| {
TopLevelStatementPosition::Other
}),
),
SuiteKind::Function | SuiteKind::Class | SuiteKind::Other => {
NodeLevel::CompoundStatement
}
};
let comments = f.context().comments().clone();
let source = f.context().source();
let source_type = f.options().source_type();
let f = WithNodeLevel::new(node_level, f);
let f = &mut WithIndentLevel::new(f.context().indent_level().increment(), f);
// Format the first statement in the body, which often has special formatting rules.
let first = match self.kind {
SuiteKind::Other => {
if is_class_or_function_definition(first)
&& !comments.has_leading(first)
&& !source_type.is_stub()
{
// Add an empty line for any nested functions or classes defined within
// non-function or class compound statements, e.g., this is stable formatting:
// ```python
// if True:
//
// def test():
// ...
// ```
empty_line().fmt(f)?;
}
SuiteChildStatement::Other(first)
}
SuiteKind::Function => {
if let Some(docstring) = DocstringStmt::try_from_statement(first, self.kind) {
SuiteChildStatement::Docstring(docstring)
} else {
SuiteChildStatement::Other(first)
}
}
SuiteKind::Class => {
if let Some(docstring) = DocstringStmt::try_from_statement(first, self.kind) {
if !comments.has_leading(first)
&& lines_before(first.start(), source) > 1
&& !source_type.is_stub()
&& !is_no_blank_line_before_class_docstring_enabled(f.context())
{
// Allow up to one empty line before a class docstring, e.g., this is
// stable formatting:
//
// ```python
// class Test:
//
// """Docstring"""
// ```
//
// But, in preview mode, we don't want to allow any empty lines before a
// class docstring, e.g., this is preview formatting:
//
// ```python
// class Test:
// """Docstring"""
// ```
empty_line().fmt(f)?;
}
SuiteChildStatement::Docstring(docstring)
} else {
SuiteChildStatement::Other(first)
}
}
SuiteKind::TopLevel => {
if let Some(docstring) = DocstringStmt::try_from_statement(first, self.kind) {
SuiteChildStatement::Docstring(docstring)
} else {
SuiteChildStatement::Other(first)
}
}
};
let first_comments = comments.leading_dangling_trailing(first);
let (mut preceding, mut empty_line_after_docstring) = if first_comments
.leading
.iter()
.any(|comment| comment.is_suppression_off_comment(source))
{
(
write_suppressed_statements_starting_with_leading_comment(first, &mut iter, f)?,
false,
)
} else if first_comments
.trailing
.iter()
.any(|comment| comment.is_suppression_off_comment(source))
{
(
write_suppressed_statements_starting_with_trailing_comment(first, &mut iter, f)?,
false,
)
} else {
first.fmt(f)?;
#[allow(clippy::if_same_then_else)]
let empty_line_after_docstring = if matches!(first, SuiteChildStatement::Docstring(_))
&& self.kind == SuiteKind::Class
{
true
} else if is_module_docstring_newlines_enabled(f.context())
&& self.kind == SuiteKind::TopLevel
&& matches!(first, SuiteChildStatement::Docstring(_))
{
// Only in preview mode, insert a newline after a module level docstring, but treat
// it as a docstring otherwise. See: https://github.com/psf/black/pull/3932.
true
} else {
false
};
(first.statement(), empty_line_after_docstring)
};
let mut preceding_comments = comments.leading_dangling_trailing(preceding);
while let Some(following) = iter.next() {
if self.kind == SuiteKind::TopLevel && iter.clone().next().is_none() {
f.context_mut()
.set_node_level(NodeLevel::TopLevel(TopLevelStatementPosition::Last));
}
let following_comments = comments.leading_dangling_trailing(following);
let needs_empty_lines = if is_class_or_function_definition(following) {
// Here we insert empty lines even if the preceding has a trailing own line comment
true
} else {
// Find nested class or function definitions that need an empty line after them.
//
// ```python
// def f():
// if True:
//
// def double(s):
// return s + s
//
// print("below function")
// ```
std::iter::successors(
Some(AnyNodeRef::from(preceding)),
AnyNodeRef::last_child_in_body,
)
.take_while(|last_child|
// If there is a comment between preceding and following the empty lines were
// inserted before the comment by preceding and there are no extra empty lines
// after the comment.
// ```python
// class Test:
// def a(self):
// pass
// # trailing comment
//
//
// # two lines before, one line after
//
// c = 30
// ````
// This also includes nested class/function definitions, so we stop recursing
// once we see a node with a trailing own line comment:
// ```python
// def f():
// if True:
//
// def double(s):
// return s + s
//
// # nested trailing own line comment
// print("below function with trailing own line comment")
// ```
!comments.has_trailing_own_line(*last_child))
.any(|last_child| {
matches!(
last_child,
AnyNodeRef::StmtFunctionDef(_) | AnyNodeRef::StmtClassDef(_)
)
})
};
// Add empty lines before and after a function or class definition. If the preceding
// node is a function or class, and contains trailing comments, then the statement
// itself will add the requisite empty lines when formatting its comments.
if needs_empty_lines {
if source_type.is_stub() {
stub_file_empty_lines(
self.kind,
preceding,
following,
&preceding_comments,
&following_comments,
f,
)?;
} else {
// Preserve empty lines after a stub implementation but don't insert a new one if there isn't any present in the source.
// This is useful when having multiple function overloads that should be grouped to getter by omitting new lines between them.
let is_preceding_stub_function_without_empty_line =
is_dummy_implementations_enabled(f.context())
&& following.is_function_def_stmt()
&& preceding
.as_function_def_stmt()
.is_some_and(|preceding_stub| {
contains_only_an_ellipsis(
&preceding_stub.body,
f.context().comments(),
) && lines_after_ignoring_end_of_line_trivia(
preceding_stub.end(),
f.context().source(),
) < 2
});
if !is_preceding_stub_function_without_empty_line {
match self.kind {
SuiteKind::TopLevel => {
write!(f, [empty_line(), empty_line()])?;
}
SuiteKind::Function | SuiteKind::Class | SuiteKind::Other => {
empty_line().fmt(f)?;
}
}
}
}
} else if is_import_definition(preceding)
&& (!is_import_definition(following) || following_comments.has_leading())
{
// Enforce _at least_ one empty line after an import statement (but allow up to
// two at the top-level). In this context, "after an import statement" means that
// that the previous node is an import, and the following node is an import _or_ has
// a leading comment.
match self.kind {
SuiteKind::TopLevel => {
let end = if let Some(last_trailing) = preceding_comments.trailing.last() {
last_trailing.end()
} else {
preceding.end()
};
match lines_after(end, source) {
0..=2 => empty_line().fmt(f)?,
_ => match source_type {
PySourceType::Stub => {
empty_line().fmt(f)?;
}
PySourceType::Python | PySourceType::Ipynb => {
write!(f, [empty_line(), empty_line()])?;
}
},
}
}
SuiteKind::Function | SuiteKind::Class | SuiteKind::Other => {
empty_line().fmt(f)?;
}
}
} else if is_compound_statement(preceding) {
// Handles the case where a body has trailing comments. The issue is that RustPython does not include
// the comments in the range of the suite. This means, the body ends right after the last statement in the body.
// ```python
// def test():
// ...
// # The body of `test` ends right after `...` and before this comment
//
// # leading comment
//
//
// a = 10
// ```
// Using `lines_after` for the node doesn't work because it would count the lines after the `...`
// which is 0 instead of 1, the number of lines between the trailing comment and
// the leading comment. This is why the suite handling counts the lines before the
// start of the next statement or before the first leading comments for compound statements.
let start = if let Some(first_leading) = following_comments.leading.first() {
first_leading.start()
} else {
following.start()
};
match lines_before(start, source) {
0 | 1 => hard_line_break().fmt(f)?,
2 => empty_line().fmt(f)?,
_ => match self.kind {
SuiteKind::TopLevel => match source_type {
PySourceType::Stub => {
empty_line().fmt(f)?;
}
PySourceType::Python | PySourceType::Ipynb => {
write!(f, [empty_line(), empty_line()])?;
}
},
SuiteKind::Function | SuiteKind::Class | SuiteKind::Other => {
empty_line().fmt(f)?;
}
},
}
} else if empty_line_after_docstring {
// Enforce an empty line after a class docstring, e.g., these are both stable
// formatting:
// ```python
// class Test:
// """Docstring"""
//
// ...
//
//
// class Test:
//
// """Docstring"""
//
// ...
// ```
empty_line().fmt(f)?;
} else {
// Insert the appropriate number of empty lines based on the node level, e.g.:
// * [`NodeLevel::Module`]: Up to two empty lines
// * [`NodeLevel::CompoundStatement`]: Up to one empty line
// * [`NodeLevel::Expression`]: No empty lines
// It's necessary to skip any trailing line comment because our parser doesn't
// include trailing comments in the node's range:
// ```python
// a # The range of `a` ends right before this comment
//
// b
// ```
let end = preceding_comments
.trailing
.last()
.map_or(preceding.end(), |comment| comment.slice().end());
match node_level {
NodeLevel::TopLevel(_) => match lines_after(end, source) {
0 | 1 => hard_line_break().fmt(f)?,
2 => empty_line().fmt(f)?,
_ => match source_type {
PySourceType::Stub => {
empty_line().fmt(f)?;
}
PySourceType::Python | PySourceType::Ipynb => {
write!(f, [empty_line(), empty_line()])?;
}
},
},
NodeLevel::CompoundStatement => match lines_after(end, source) {
0 | 1 => hard_line_break().fmt(f)?,
_ => empty_line().fmt(f)?,
},
NodeLevel::Expression(_) | NodeLevel::ParenthesizedExpression => {
hard_line_break().fmt(f)?;
}
}
}
if following_comments
.leading
.iter()
.any(|comment| comment.is_suppression_off_comment(source))
{
preceding = write_suppressed_statements_starting_with_leading_comment(
SuiteChildStatement::Other(following),
&mut iter,
f,
)?;
preceding_comments = comments.leading_dangling_trailing(preceding);
} else if following_comments
.trailing
.iter()
.any(|comment| comment.is_suppression_off_comment(source))
{
preceding = write_suppressed_statements_starting_with_trailing_comment(
SuiteChildStatement::Other(following),
&mut iter,
f,
)?;
preceding_comments = comments.leading_dangling_trailing(preceding);
} else {
following.format().fmt(f)?;
preceding = following;
preceding_comments = following_comments;
}
empty_line_after_docstring = false;
}
Ok(())
}
}
/// Stub files have bespoke rules for empty lines.
///
/// These rules are ported from black (preview mode at time of writing) using the stubs test case:
/// <https://github.com/psf/black/blob/c160e4b7ce30c661ac4f2dfa5038becf1b8c5c33/src/black/lines.py#L576-L744>
fn stub_file_empty_lines(
kind: SuiteKind,
preceding: &Stmt,
following: &Stmt,
preceding_comments: &LeadingDanglingTrailingComments,
following_comments: &LeadingDanglingTrailingComments,
f: &mut PyFormatter,
) -> FormatResult<()> {
let source = f.context().source();
// Preserve the empty line if the definitions are separated by a comment
let empty_line_condition = preceding_comments.has_trailing()
|| following_comments.has_leading()
|| !stub_suite_can_omit_empty_line(preceding, following, f);
let require_empty_line = should_insert_blank_line_after_class_in_stub_file(
preceding.into(),
Some(following.into()),
f.context(),
);
match kind {
SuiteKind::TopLevel => {
if empty_line_condition || require_empty_line {
empty_line().fmt(f)
} else {
hard_line_break().fmt(f)
}
}
SuiteKind::Class | SuiteKind::Other | SuiteKind::Function => {
if (empty_line_condition
&& lines_after_ignoring_end_of_line_trivia(preceding.end(), source) > 1)
|| require_empty_line
{
empty_line().fmt(f)
} else {
hard_line_break().fmt(f)
}
}
}
}
/// Checks if an empty line should be inserted after a class definition.
///
/// This is only valid if the [`blank_line_after_nested_stub_class`](https://github.com/astral-sh/ruff/issues/8891)
/// preview rule is enabled and the source to be formatted is a stub file.
///
/// If `following` is `None`, then the preceding node is the last one in a suite. The
/// caller needs to make sure that the suite which the preceding node is part of is
/// followed by an alternate branch and shouldn't be a top-level suite.
pub(crate) fn should_insert_blank_line_after_class_in_stub_file(
preceding: AnyNodeRef<'_>,
following: Option<AnyNodeRef<'_>>,
context: &PyFormatContext,
) -> bool {
if !(is_blank_line_after_nested_stub_class_enabled(context)
&& context.options().source_type().is_stub())
{
return false;
}
let comments = context.comments();
match preceding.as_stmt_class_def() {
Some(class) if contains_only_an_ellipsis(&class.body, comments) => {
let Some(following) = following else {
// The formatter is at the start of an alternate branch such as
// an `else` block.
//
// ```python
// if foo:
// class Nested:
// pass
// else:
// pass
// ```
//
// In the above code, the preceding node is the `Nested` class
// which has no following node.
return true;
};
// If the preceding class has decorators, then we need to add an empty
// line even if it only contains ellipsis.
//
// ```python
// class Top:
// @decorator
// class Nested1: ...
// foo = 1
// ```
let preceding_has_decorators = !class.decorator_list.is_empty();
// If the following statement is a class definition, then an empty line
// should be inserted if it (1) doesn't just contain ellipsis, or (2) has decorators.
//
// ```python
// class Top:
// class Nested1: ...
// class Nested2:
// pass
//
// class Top:
// class Nested1: ...
// @decorator
// class Nested2: ...
// ```
//
// Both of the above examples should add a blank line in between.
let following_is_class_without_only_ellipsis_or_has_decorators =
following.as_stmt_class_def().is_some_and(|following| {
!contains_only_an_ellipsis(&following.body, comments)
|| !following.decorator_list.is_empty()
});
preceding_has_decorators
|| following_is_class_without_only_ellipsis_or_has_decorators
|| following.is_stmt_function_def()
}
Some(_) => {
// Preceding statement is a class definition whose body isn't only an ellipsis.
// Here, we should only add a blank line if the class doesn't have a trailing
// own line comment as that's handled by the class formatting itself.
!comments.has_trailing_own_line(preceding)
}
None => {
// If preceding isn't a class definition, let's check if the last statement
// in the body, going all the way down, is a class definition.
//
// ```python
// if foo:
// if bar:
// class Nested:
// pass
// if other:
// pass
// ```
//
// But, if it contained a trailing own line comment, then it's handled
// by the class formatting itself.
//
// ```python
// if foo:
// if bar:
// class Nested:
// pass
// # comment
// if other:
// pass
// ```
std::iter::successors(
preceding.last_child_in_body(),
AnyNodeRef::last_child_in_body,
)
.take_while(|last_child| !comments.has_trailing_own_line(*last_child))
.any(|last_child| last_child.is_stmt_class_def())
}
}
}
/// Only a function to compute it lazily
fn stub_suite_can_omit_empty_line(preceding: &Stmt, following: &Stmt, f: &PyFormatter) -> bool {
// Two subsequent class definitions that both have an ellipsis only body
// ```python
// class A: ...
// class B: ...
//
// @decorator
// class C: ...
// ```
let class_sequences_with_ellipsis_only = preceding
.as_class_def_stmt()
.is_some_and(|class| contains_only_an_ellipsis(&class.body, f.context().comments()))
&& following.as_class_def_stmt().is_some_and(|class| {
contains_only_an_ellipsis(&class.body, f.context().comments())
&& class.decorator_list.is_empty()
});
// Black for some reasons accepts decorators in place of empty lines
// ```python
// def _count1(): ...
// @final
// class LockType1: ...
//
// def _count2(): ...
//
// class LockType2: ...
// ```
let class_decorator_instead_of_empty_line = preceding.is_function_def_stmt()
&& following
.as_class_def_stmt()
.is_some_and(|class| !class.decorator_list.is_empty());
// A function definition following a stub function definition
// ```python
// def test(): ...
// def b(): a
// ```
let function_with_ellipsis = preceding
.as_function_def_stmt()
.is_some_and(|function| contains_only_an_ellipsis(&function.body, f.context().comments()))
&& following.is_function_def_stmt();
class_sequences_with_ellipsis_only
|| class_decorator_instead_of_empty_line
|| function_with_ellipsis
}
/// Returns `true` if a function or class body contains only an ellipsis with no comments.
pub(crate) fn contains_only_an_ellipsis(body: &[Stmt], comments: &Comments) -> bool {
match body {
[Stmt::Expr(ast::StmtExpr { value, .. })] => {
let [node] = body else {
return false;
};
value.is_ellipsis_literal_expr()
&& !comments.has_leading(node)
&& !comments.has_trailing_own_line(node)
}
_ => false,
}
}
/// Returns `true` if a [`Stmt`] is a class or function definition.
const fn is_class_or_function_definition(stmt: &Stmt) -> bool {
matches!(stmt, Stmt::FunctionDef(_) | Stmt::ClassDef(_))
}
/// Returns `true` if a [`Stmt`] is an import.
const fn is_import_definition(stmt: &Stmt) -> bool {
matches!(stmt, Stmt::Import(_) | Stmt::ImportFrom(_))
}
impl FormatRuleWithOptions<Suite, PyFormatContext<'_>> for FormatSuite {
type Options = SuiteKind;
fn with_options(mut self, options: Self::Options) -> Self {
self.kind = options;
self
}
}
impl<'ast> AsFormat<PyFormatContext<'ast>> for Suite {
type Format<'a> = FormatRefWithRule<'a, Suite, FormatSuite, PyFormatContext<'ast>>;
fn format(&self) -> Self::Format<'_> {
FormatRefWithRule::new(self, FormatSuite::default())
}
}
impl<'ast> IntoFormat<PyFormatContext<'ast>> for Suite {
type Format = FormatOwnedWithRule<Suite, FormatSuite, PyFormatContext<'ast>>;
fn into_format(self) -> Self::Format {
FormatOwnedWithRule::new(self, FormatSuite::default())
}
}
/// A statement representing a docstring.
#[derive(Copy, Clone, Debug)]
pub(crate) struct DocstringStmt<'a> {
/// The [`Stmt::Expr`]
docstring: &'a Stmt,
/// The parent suite kind
suite_kind: SuiteKind,
}
impl<'a> DocstringStmt<'a> {
/// Checks if the statement is a simple string that can be formatted as a docstring
fn try_from_statement(stmt: &'a Stmt, suite_kind: SuiteKind) -> Option<DocstringStmt<'a>> {
let Stmt::Expr(ast::StmtExpr { value, .. }) = stmt else {
return None;
};
match value.as_ref() {
Expr::StringLiteral(ast::ExprStringLiteral { value, .. })
if !value.is_implicit_concatenated() =>
{
Some(DocstringStmt {
docstring: stmt,
suite_kind,
})
}
_ => None,
}
}
}
impl Format<PyFormatContext<'_>> for DocstringStmt<'_> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
let comments = f.context().comments().clone();
let node_comments = comments.leading_dangling_trailing(self.docstring);
if FormatStmtExpr.is_suppressed(node_comments.trailing, f.context()) {
suppressed_node(self.docstring).fmt(f)
} else {
// SAFETY: Safe because `DocStringStmt` guarantees that it only ever wraps a `ExprStmt` containing a `ExprStringLiteral`.
let string_literal = self
.docstring
.as_expr_stmt()
.unwrap()
.value
.as_string_literal_expr()
.unwrap();
// We format the expression, but the statement carries the comments
write!(
f,
[
leading_comments(node_comments.leading),
string_literal
.format()
.with_options(ExprStringLiteralKind::Docstring),
]
)?;
if self.suite_kind == SuiteKind::Class {
// Comments after class docstrings need a newline between the docstring and the
// comment (https://github.com/astral-sh/ruff/issues/7948).
// ```python
// class ModuleBrowser:
// """Browse module classes and functions in IDLE."""
// # ^ Insert a newline above here
//
// def __init__(self, master, path, *, _htest=False, _utest=False):
// pass
// ```
if let Some(own_line) = node_comments
.trailing
.iter()
.find(|comment| comment.line_position().is_own_line())
{
if lines_before(own_line.start(), f.context().source()) < 2 {
empty_line().fmt(f)?;
}
}
}
trailing_comments(node_comments.trailing).fmt(f)
}
}
}
/// A Child of a suite.
#[derive(Copy, Clone, Debug)]
pub(crate) enum SuiteChildStatement<'a> {
/// A docstring documenting a class or function definition.
Docstring(DocstringStmt<'a>),
/// Any other statement.
Other(&'a Stmt),
}
impl<'a> SuiteChildStatement<'a> {
pub(crate) const fn statement(self) -> &'a Stmt {
match self {
SuiteChildStatement::Docstring(docstring) => docstring.docstring,
SuiteChildStatement::Other(statement) => statement,
}
}
}
impl Ranged for SuiteChildStatement<'_> {
fn range(&self) -> TextRange {
self.statement().range()
}
}
impl<'a> From<SuiteChildStatement<'a>> for AnyNodeRef<'a> {
fn from(value: SuiteChildStatement<'a>) -> Self {
value.statement().into()
}
}
impl Format<PyFormatContext<'_>> for SuiteChildStatement<'_> {
fn fmt(&self, f: &mut Formatter<PyFormatContext<'_>>) -> FormatResult<()> {
match self {
SuiteChildStatement::Docstring(docstring) => docstring.fmt(f),
SuiteChildStatement::Other(statement) => statement.format().fmt(f),
}
}
}
#[cfg(test)]
mod tests {
use ruff_formatter::format;
use ruff_python_parser::parse_suite;
use ruff_python_trivia::CommentRanges;
use crate::comments::Comments;
use crate::prelude::*;
use crate::statement::suite::SuiteKind;
use crate::PyFormatOptions;
fn format_suite(level: SuiteKind) -> String {
let source = r"
a = 10
three_leading_newlines = 80
two_leading_newlines = 20
one_leading_newline = 10
no_leading_newline = 30
class InTheMiddle:
pass
trailing_statement = 1
def func():
pass
def trailing_func():
pass
";
let statements = parse_suite(source).unwrap();
let comment_ranges = CommentRanges::default();
let context = PyFormatContext::new(
PyFormatOptions::default(),
source,
Comments::from_ranges(&comment_ranges),
);
let test_formatter =
format_with(|f: &mut PyFormatter| statements.format().with_options(level).fmt(f));
let formatted = format!(context, [test_formatter]).unwrap();
let printed = formatted.print().unwrap();
printed.as_code().to_string()
}
#[test]
fn top_level() {
let formatted = format_suite(SuiteKind::TopLevel);
assert_eq!(
formatted,
r"a = 10
three_leading_newlines = 80
two_leading_newlines = 20
one_leading_newline = 10
no_leading_newline = 30
class InTheMiddle:
pass
trailing_statement = 1
def func():
pass
def trailing_func():
pass
"
);
}
#[test]
fn nested_level() {
let formatted = format_suite(SuiteKind::Other);
assert_eq!(
formatted,
r"a = 10
three_leading_newlines = 80
two_leading_newlines = 20
one_leading_newline = 10
no_leading_newline = 30
class InTheMiddle:
pass
trailing_statement = 1
def func():
pass
def trailing_func():
pass
"
);
}
}