Skip to content

Commit

Permalink
Fix formatter panic with comment after parenthesized dict value (#5293)
Browse files Browse the repository at this point in the history
## Summary

This snippet used to panic because it expected to see a comma or
something similar after the `2` but met the closing parentheses that is
not part of the range and panicked
```python
a = {
    1: (2),
    # comment
    3: True,
}
```

Originally found in
https://github.com/bolucat/Firefox/blob/636a717ef025c16434997dc89e42351ef740ee6b/testing/marionette/client/marionette_driver/geckoinstance.py#L109

This snippet is also the test plan.
  • Loading branch information
konstin committed Jun 22, 2023
1 parent f7e1cf4 commit d407165
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 8 deletions.
Expand Up @@ -48,3 +48,11 @@
C: 0.1 * (10.0 / 12),
D: 0.1 * (10.0 / 12),
}

# Regression test for formatter panic with comment after parenthesized dict value
# Originally found in https://github.com/bolucat/Firefox/blob/636a717ef025c16434997dc89e42351ef740ee6b/testing/marionette/client/marionette_driver/geckoinstance.py#L109
a = {
1: (2),
# comment
3: True,
}
24 changes: 16 additions & 8 deletions crates/ruff_python_formatter/src/comments/placement.rs
Expand Up @@ -991,14 +991,22 @@ fn handle_dict_unpacking_comment<'a>(
.skip_trivia();

// we start from the preceding node but we skip its token
if let Some(first) = tokens.next() {
debug_assert!(matches!(
first,
Token {
kind: TokenKind::LBrace | TokenKind::Comma | TokenKind::Colon,
..
}
));
for token in tokens.by_ref() {
// Skip closing parentheses that are not part of the node range
if token.kind == TokenKind::RParen {
continue;
}
debug_assert!(
matches!(
token,
Token {
kind: TokenKind::LBrace | TokenKind::Comma | TokenKind::Colon,
..
}
),
"{token:?}",
);
break;
}

// if the remaining tokens from the previous node is exactly `**`,
Expand Down
Expand Up @@ -54,6 +54,14 @@ mapping = {
C: 0.1 * (10.0 / 12),
D: 0.1 * (10.0 / 12),
}
# Regression test for formatter panic with comment after parenthesized dict value
# Originally found in https://github.com/bolucat/Firefox/blob/636a717ef025c16434997dc89e42351ef740ee6b/testing/marionette/client/marionette_driver/geckoinstance.py#L109
a = {
1: (2),
# comment
3: True,
}
```


Expand Down Expand Up @@ -112,6 +120,14 @@ mapping = {
C: 0.1 * (10.0 / 12),
D: 0.1 * (10.0 / 12),
}
# Regression test for formatter panic with comment after parenthesized dict value
# Originally found in https://github.com/bolucat/Firefox/blob/636a717ef025c16434997dc89e42351ef740ee6b/testing/marionette/client/marionette_driver/geckoinstance.py#L109
a = {
1: (2),
# comment
3: True,
}
```


0 comments on commit d407165

Please sign in to comment.