Skip to content

bpo-45811: Improve error message when source code contains invisible control characters #29654

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

Merged
merged 1 commit into from
Nov 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Lib/test/test_syntax.py
Original file line number Diff line number Diff line change
Expand Up @@ -1528,6 +1528,9 @@ def test_error_parenthesis(self):
for paren in ")]}":
self._check_error(paren + "1 + 2", f"unmatched '\\{paren}'")

def test_invisible_characters(self):
self._check_error('print\x17("Hello")', "invalid non-printable character")

def test_match_call_does_not_raise_syntax_error(self):
code = """
def match(x):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Improve the tokenizer errors when encountering invisible control characters
in the parser. Patch by Pablo Galindo
6 changes: 6 additions & 0 deletions Parser/tokenizer.c
Original file line number Diff line number Diff line change
Expand Up @@ -2045,6 +2045,12 @@ tok_get(struct tok_state *tok, const char **p_start, const char **p_end)
break;
}

if (!Py_UNICODE_ISPRINTABLE(c)) {
char hex[9];
(void)PyOS_snprintf(hex, sizeof(hex), "%04X", c);
return syntaxerror(tok, "invalid non-printable character U+%s", hex);
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am keeping the error simple to keep it consistent with invalid non-printable characters in names

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense.

}

/* Punctuation character */
*p_start = tok->start;
*p_end = tok->cur;
Expand Down