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

bpo-38870: fixing unhandled hexescape in docstrings at ast.unparse #20166

Merged
merged 3 commits into from May 18, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 11 additions & 3 deletions Lib/ast.py
Expand Up @@ -1088,18 +1088,26 @@ def visit_Name(self, node):
self.write(node.id)

def _write_docstring(self, node):
def esc_char(c):
if c in ("\n", "\t"):
# In the AST form, we don't know the author's intentation
# about how this should be displayed. We'll only escape
# \n and \t, because they are more likely to be unescaped
# in the source
return c
return c.encode('unicode_escape').decode('ascii')

self.fill()
if node.kind == "u":
self.write("u")

value = node.value
if value:
# Preserve quotes in the docstring by escaping them
value = value.replace("\\", "\\\\")
value = value.replace('"""', '""\"')
value = value.replace("\r", "\\r")
value = "".join(map(esc_char, value))
if value[-1] == '"':
value = value.replace('"', '\\"', -1)
value = value.replace('"""', '""\\"')

self.write(f'"""{value}"""')

Expand Down
6 changes: 5 additions & 1 deletion Lib/test/test_unparse.py
Expand Up @@ -324,7 +324,11 @@ def test_docstrings(self):
'\\t',
'\n',
'\\n',
'\r\\r\t\\t\n\\n'
'\r\\r\t\\t\n\\n',
'""">>> content = \"\"\"blabla\"\"\" <<<"""',
r'foo\n\x00'
'🐍⛎𩸽üéş^\X\BB\N{LONG RIGHTWARDS SQUIGGLE ARROW}'
i64 marked this conversation as resolved.
Show resolved Hide resolved

)
for docstring in docstrings:
# check as Module docstrings for easy testing
Expand Down