Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swallow warnings when performing AST checks #4189

Merged
merged 4 commits into from
Jan 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@

<!-- Changes to Black's terminal output and error messages -->

- Black will swallow any `SyntaxWarning`s or `DeprecationWarning`s produced by the `ast`
module when performing equivalence checks (#4189)

### _Blackd_

<!-- Changes to blackd -->
Expand Down
16 changes: 10 additions & 6 deletions src/black/parsing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import ast
import sys
import warnings
from typing import Iterable, Iterator, List, Set, Tuple

from black.mode import VERSION_TO_FEATURES, Feature, TargetVersion, supports_feature
Expand Down Expand Up @@ -109,13 +110,16 @@ def lib2to3_unparse(node: Node) -> str:
return code


def parse_single_version(
def _parse_single_version(
src: str, version: Tuple[int, int], *, type_comments: bool
) -> ast.AST:
filename = "<unknown>"
return ast.parse(
src, filename, feature_version=version, type_comments=type_comments
)
with warnings.catch_warnings():
warnings.simplefilter("ignore", SyntaxWarning)
warnings.simplefilter("ignore", DeprecationWarning)
return ast.parse(
src, filename, feature_version=version, type_comments=type_comments
)


def parse_ast(src: str) -> ast.AST:
Expand All @@ -125,15 +129,15 @@ def parse_ast(src: str) -> ast.AST:
first_error = ""
for version in sorted(versions, reverse=True):
try:
return parse_single_version(src, version, type_comments=True)
return _parse_single_version(src, version, type_comments=True)
except SyntaxError as e:
if not first_error:
first_error = str(e)

# Try to parse without type comments
for version in sorted(versions, reverse=True):
try:
return parse_single_version(src, version, type_comments=False)
return _parse_single_version(src, version, type_comments=False)
except SyntaxError:
pass

Expand Down
Loading