Skip to content

Commit

Permalink
Swallow warnings when performing AST checks (#4189)
Browse files Browse the repository at this point in the history
Fixes #4188
  • Loading branch information
hauntsaninja committed Jan 28, 2024
1 parent 0b4364b commit d919746
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
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

0 comments on commit d919746

Please sign in to comment.