diff --git a/src/black/__init__.py b/src/black/__init__.py index f9f1b51c6fa..eb5d6e40892 100644 --- a/src/black/__init__.py +++ b/src/black/__init__.py @@ -66,6 +66,7 @@ from black.parsing import ( # noqa F401 ASTSafetyError, InvalidInput, + SourceASTParseError, lib2to3_parse, parse_ast, stringify_ast, @@ -1086,6 +1087,8 @@ def check_stability_and_equivalence( """ try: assert_equivalent(src_contents, dst_contents) + except SourceASTParseError: + raise except ASTSafetyError: if _target_versions_exceed_runtime(mode.target_versions): raise ASTSafetyError( @@ -1632,7 +1635,7 @@ def assert_equivalent(src: str, dst: str) -> None: try: src_ast = parse_ast(src) except Exception as exc: - raise ASTSafetyError( + raise SourceASTParseError( "cannot use --safe with this file; failed to parse source file AST: " f"{exc}\n" "This could be caused by running Black with an older Python version " diff --git a/src/black/parsing.py b/src/black/parsing.py index cb4f715dcb3..5dc234c911a 100644 --- a/src/black/parsing.py +++ b/src/black/parsing.py @@ -106,6 +106,15 @@ class ASTSafetyError(Exception): """Raised when Black's generated code is not equivalent to the old AST.""" +class SourceASTParseError(Exception): + """Raised when the source file cannot be parsed by ast.parse(). + + This is not a bug in Black — Black's lib2to3-based parser is more lenient + than Python's ast.parse(), so it may accept code that ast.parse() rejects. + In blackd, this should be reported as a 400 Bad Request. + """ + + def _parse_single_version( src: str, version: tuple[int, int], *, type_comments: bool ) -> ast.AST: diff --git a/src/blackd/__init__.py b/src/blackd/__init__.py index 4646e919735..5df160b6b7b 100644 --- a/src/blackd/__init__.py +++ b/src/blackd/__init__.py @@ -206,6 +206,8 @@ async def handle( return web.Response(status=204, headers=headers) except black.InvalidInput as e: return web.Response(status=400, headers=headers, text=str(e)) + except black.SourceASTParseError as e: + return web.Response(status=400, headers=headers, text=str(e)) except web.HTTPException: raise except Exception as e: