Skip to content

Commit

Permalink
pythongh-106359: Fix corner case bugs in Argument Clinic converter pa…
Browse files Browse the repository at this point in the history
…rser

DSLParser.parse_converter() could return unusable kwdicts in some rare cases
  • Loading branch information
erlend-aasland committed Jul 3, 2023
1 parent 60e41a0 commit 851f63c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 21 deletions.
23 changes: 10 additions & 13 deletions Lib/test/test_clinic.py
Original file line number Diff line number Diff line change
Expand Up @@ -797,21 +797,18 @@ def test_other_bizarre_things_in_annotations_fail(self):
Error on line 0:
Annotations must be either a name, a function call, or a string.
"""

s = self.parse_function_should_fail(
'module os\nos.access\n path: {"some": "dictionary"}'
)
self.assertEqual(s, expected_failure_message)

s = self.parse_function_should_fail(
'module os\nos.access\n path: ["list", "of", "strings"]'
dataset = (
'module os\nos.access\n path: {"some": "dictionary"}',
'module os\nos.access\n path: ["list", "of", "strings"]',
'module os\nos.access\n path: (x for x in range(42))',
'module fo\nfo.barbaz\n o: bool(**{None: "bang!"})',
'module fo\nfo.barbaz -> bool(**{None: "bang!"})',
)
self.assertEqual(s, expected_failure_message)

s = self.parse_function_should_fail(
'module os\nos.access\n path: (x for x in range(42))'
)
self.assertEqual(s, expected_failure_message)
for fn in dataset:
with self.subTest(fn=fn):
actual = self.parse_function_should_fail(fn)
self.assertEqual(actual, expected_failure_message)

def test_unused_param(self):
block = self.parse("""
Expand Down
17 changes: 9 additions & 8 deletions Tools/clinic/clinic.py
Original file line number Diff line number Diff line change
Expand Up @@ -5033,26 +5033,27 @@ def bad_node(self, node):
key = f"{parameter_name}_as_{c_name}" if c_name else parameter_name
self.function.parameters[key] = p

KwargDict = dict[str | None, Any]
KwargDict = dict[str, Any]

@staticmethod
def parse_converter(annotation: ast.expr | None) -> tuple[str, bool, KwargDict]:
msg = "Annotations must be either a name, a function call, or a string."
match annotation:
case ast.Constant(value=str() as value):
return value, True, {}
case ast.Name(name):
return name, False, {}
case ast.Call(func=ast.Name(name)):
symbols = globals()
kwargs = {
node.arg: eval_ast_expr(node.value, symbols)
for node in annotation.keywords
}
kwargs: dict[str, Any] = {}
for node in annotation.keywords:
if not isinstance(node.arg, str):
fail(msg)
kwargs[node.arg] = eval_ast_expr(node.value, symbols)
print(kwargs)
return name, False, kwargs
case _:
fail(
"Annotations must be either a name, a function call, or a string."
)
fail(msg)

def parse_special_symbol(self, symbol):
if symbol == '*':
Expand Down

0 comments on commit 851f63c

Please sign in to comment.