Skip to content

Commit

Permalink
Merge pull request #7462 from tk0miya/7461_empty_tuple
Browse files Browse the repository at this point in the history
Fix #7461: py domain: fails with IndexError for empty tuple in type annotation
  • Loading branch information
tk0miya committed Apr 13, 2020
2 parents 503a7c1 + c835523 commit a4edbc1
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 6 deletions.
3 changes: 3 additions & 0 deletions CHANGES
Expand Up @@ -47,6 +47,9 @@ Features added
Bugs fixed
----------

* #7461: py domain: fails with IndexError for empty tuple in type annotation
* #7461: autodoc: empty tuple in type annotation is not shown correctly

Testing
--------

Expand Down
15 changes: 10 additions & 5 deletions sphinx/domains/python.py
Expand Up @@ -114,11 +114,16 @@ def unparse(node: ast.AST) -> List[Node]:
result.append(addnodes.desc_sig_punctuation('', ']'))
return result
elif isinstance(node, ast.Tuple):
result = []
for elem in node.elts:
result.extend(unparse(elem))
result.append(addnodes.desc_sig_punctuation('', ', '))
result.pop()
if node.elts:
result = []
for elem in node.elts:
result.extend(unparse(elem))
result.append(addnodes.desc_sig_punctuation('', ', '))
result.pop()
else:
result = [addnodes.desc_sig_punctuation('', '('),
addnodes.desc_sig_punctuation('', ')')]

return result
else:
raise SyntaxError # unsupported syntax
Expand Down
5 changes: 4 additions & 1 deletion sphinx/pycode/ast.py
Expand Up @@ -114,7 +114,10 @@ def unparse(node: ast.AST) -> str:
elif isinstance(node, ast.UnaryOp):
return "%s %s" % (unparse(node.op), unparse(node.operand))
elif isinstance(node, ast.Tuple):
return ", ".join(unparse(e) for e in node.elts)
if node.elts:
return ", ".join(unparse(e) for e in node.elts)
else:
return "()"
elif sys.version_info > (3, 6) and isinstance(node, ast.Constant):
# this branch should be placed at last
return repr(node.value)
Expand Down
7 changes: 7 additions & 0 deletions tests/test_domain_py.py
Expand Up @@ -255,6 +255,13 @@ def test_parse_annotation():
[pending_xref, "int"],
[desc_sig_punctuation, "]"]))

doctree = _parse_annotation("Tuple[()]")
assert_node(doctree, ([pending_xref, "Tuple"],
[desc_sig_punctuation, "["],
[desc_sig_punctuation, "("],
[desc_sig_punctuation, ")"],
[desc_sig_punctuation, "]"]))

doctree = _parse_annotation("Callable[[int, int], int]")
assert_node(doctree, ([pending_xref, "Callable"],
[desc_sig_punctuation, "["],
Expand Down
1 change: 1 addition & 0 deletions tests/test_pycode_ast.py
Expand Up @@ -54,6 +54,7 @@
("- 1", "- 1"), # UnaryOp
("- a", "- a"), # USub
("(1, 2, 3)", "1, 2, 3"), # Tuple
("()", "()"), # Tuple (empty)
])
def test_unparse(source, expected):
module = ast.parse(source)
Expand Down

0 comments on commit a4edbc1

Please sign in to comment.