@@ -259,6 +259,26 @@ impl Formatter {
259259 /// with lambdas in data structures like arrays or function arguments.
260260 #[ inline( always) ]
261261 fn fix_dangling_commas ( & mut self ) -> & mut Self {
262+ // This is for cases where a team uses commas at the start of lines to
263+ // separate arguments or elements in arrays and use inline comments to
264+ // describe the elements
265+ // This is done in the Godot Nakama repository for example.
266+ let comment_re = RegexBuilder :: new ( r"(?m)(?P<before>[^\n\r]*?)(?P<comment>#[^\n\r]*)\n\s+," )
267+ . build ( )
268+ . expect ( "dangling comma with comment regex should compile" ) ;
269+
270+ self . regex_replace_all_outside_strings ( comment_re, |caps : & regex:: Captures | {
271+ let before = caps. name ( "before" ) . unwrap ( ) . as_str ( ) ;
272+ let comment = caps. name ( "comment" ) . unwrap ( ) . as_str ( ) ;
273+
274+ let before_trimmed = before. trim_end ( ) ;
275+ if before_trimmed. trim ( ) . is_empty ( ) || before_trimmed. ends_with ( ',' ) {
276+ return caps. get ( 0 ) . unwrap ( ) . as_str ( ) . to_string ( ) ;
277+ }
278+
279+ format ! ( "{}, {}" , before_trimmed, comment. trim_start( ) )
280+ } ) ;
281+
262282 // This targets cases where a comma is on its own line with only
263283 // whitespace before it instead of being at the end of the previous
264284 // line
@@ -268,7 +288,13 @@ impl Formatter {
268288 . build ( )
269289 . expect ( "dangling comma regex should compile" ) ;
270290
271- self . regex_replace_all_outside_strings ( re, "$1," ) ;
291+ self . regex_replace_all_outside_strings ( re, |caps : & regex:: Captures | {
292+ let first_part = caps. get ( 1 ) . unwrap ( ) . as_str ( ) ;
293+ let mut replacement = String :: with_capacity ( first_part. len ( ) + 1 ) ;
294+ replacement. push_str ( first_part) ;
295+ replacement. push ( ',' ) ;
296+ replacement
297+ } ) ;
272298 self
273299 }
274300
0 commit comments