@@ -252,12 +252,13 @@ fn extract_tokens_to_reorder(
252252 // We need to check if the comments are contiguous with the declaration they are
253253 // attached to.
254254 let mut class_docstring_comments = Vec :: new ( ) ;
255- let mut found_non_comment_non_class = false ;
255+ let mut class_docstring_comments_rows = Vec :: new ( ) ;
256256 for ( node, text) in & all_nodes {
257257 match node. kind ( ) {
258258 "comment" => {
259- if text. trim_start ( ) . starts_with ( "##" ) && !found_non_comment_non_class {
259+ if text. trim_start ( ) . starts_with ( "##" ) {
260260 class_docstring_comments. push ( text. clone ( ) ) ;
261+ class_docstring_comments_rows. push ( node. start_position ( ) . row ) ;
261262 }
262263 }
263264 "class_name_statement" | "extends_statement" | "annotation" => {
@@ -266,7 +267,24 @@ fn extract_tokens_to_reorder(
266267 // Any other element means we're past the top of the file, so we stop
267268 // collecting the class docstring
268269 _ => {
269- found_non_comment_non_class = true ;
270+ // if the last node of the docstring is immediately followed by the current node
271+ if class_docstring_comments_rows
272+ . last ( )
273+ . is_some_and ( |row| row + 1 == node. start_position ( ) . row )
274+ {
275+ // count how many rows are belong to the statement docstring
276+ let statement_docstring_rows = class_docstring_comments_rows
277+ . iter ( )
278+ . rev ( )
279+ . zip ( ( 0 ..) . map ( |i| class_docstring_comments_rows. last ( ) . unwrap ( ) - i) )
280+ . take_while ( |( actual, expected) | * * actual == * expected)
281+ . count ( ) ;
282+ class_docstring_comments
283+ . truncate ( class_docstring_comments. len ( ) - statement_docstring_rows) ;
284+ class_docstring_comments_rows
285+ . truncate ( class_docstring_comments_rows. len ( ) - statement_docstring_rows) ;
286+ }
287+ break ;
270288 }
271289 }
272290 }
@@ -304,7 +322,7 @@ fn extract_tokens_to_reorder(
304322 "comment" => {
305323 // We already processed class docstring comments, so we skip them here
306324 // This may look inefficient but in practice it should not have much impact
307- if text . trim_start ( ) . starts_with ( "##" ) && class_docstring_comments . contains ( & text ) {
325+ if class_docstring_comments_rows . contains ( & node . start_position ( ) . row ) {
308326 continue ;
309327 } else {
310328 pending_comments. push ( text) ;
0 commit comments