diff --git a/pylsp/plugins/pyflakes_lint.py b/pylsp/plugins/pyflakes_lint.py index 8a04276c..1a8ca92c 100644 --- a/pylsp/plugins/pyflakes_lint.py +++ b/pylsp/plugins/pyflakes_lint.py @@ -1,6 +1,9 @@ # Copyright 2017-2020 Palantir Technologies, Inc. # Copyright 2021- Python Language Server Contributors. +from io import StringIO +from tokenize import detect_encoding + from pyflakes import api as pyflakes_api from pyflakes import messages @@ -24,19 +27,41 @@ @hookimpl def pylsp_lint(workspace, document): with workspace.report_progress("lint: pyflakes"): - reporter = PyflakesDiagnosticReport(document.lines) - pyflakes_api.check( - document.source.encode("utf-8"), document.path, reporter=reporter - ) + source = document.source + # Python only treats CR, LF and CRLF as physical line breaks. + lines = StringIO(source, newline=None).readlines() + reporter = PyflakesDiagnosticReport(lines) + try: + source = _source_for_pyflakes(source, lines) + except UnicodeEncodeError as error: + reporter.unexpectedError(document.path, str(error)) + else: + pyflakes_api.check(source, document.path, reporter) return reporter.diagnostics +def _source_for_pyflakes(source, lines): + header = (line.encode("utf-8") for line in lines[:2]) + try: + encoding, _ = detect_encoding(header.__next__) + if b"#\n".decode(encoding) == "#\n": + # Validate the declaration, but lint the editor's original text. + # Some encodings change characters on a round trip. + if encoding not in ("utf-8", "utf-8-sig"): + source.encode(encoding) + return source.removeprefix("\ufeff") + except (SyntaxError, LookupError, UnicodeDecodeError): + pass + # Let Python report invalid or conflicting encoding declarations. + return source.encode("utf-8") + + class PyflakesDiagnosticReport: def __init__(self, lines) -> None: self.lines = lines self.diagnostics = [] - def unexpectedError(self, _filename, msg) -> None: # pragma: no cover + def unexpectedError(self, _filename, msg) -> None: err_range = { "start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 0}, @@ -73,12 +98,21 @@ def syntaxError(self, _filename, msg, lineno, offset, text) -> None: def flake(self, message) -> None: """Get message like :: """ + line_number = message.lineno - 1 + line = self.lines[line_number].rstrip("\r\n") + # Pyflakes uses AST UTF-8 byte offsets. LSP positions count UTF-16 code units. + if line.isascii(): + start, end = message.col, len(line) + else: + byte_column = message.col + if line_number == 0 and line.startswith("\ufeff"): + byte_column += 3 + prefix = line.encode("utf-8")[:byte_column].decode("utf-8") + start = len(prefix.encode("utf-16-le")) // 2 + end = len(line.encode("utf-16-le")) // 2 err_range = { - "start": {"line": message.lineno - 1, "character": message.col}, - "end": { - "line": message.lineno - 1, - "character": len(self.lines[message.lineno - 1]), - }, + "start": {"line": line_number, "character": start}, + "end": {"line": line_number, "character": end}, } severity = lsp.DiagnosticSeverity.Warning diff --git a/test/plugins/test_pyflakes_lint.py b/test/plugins/test_pyflakes_lint.py index 8ab36320..aa8dc761 100644 --- a/test/plugins/test_pyflakes_lint.py +++ b/test/plugins/test_pyflakes_lint.py @@ -3,6 +3,8 @@ import sys +import pytest + from pylsp import lsp, uris from pylsp.plugins import pyflakes_lint from pylsp.workspace import Document @@ -67,3 +69,70 @@ def test_unicode_encoding(workspace) -> None: assert len(diags) == 1 assert diags[0]["message"] == "'sys' imported but unused" + + +@pytest.mark.parametrize( + ("text", "start", "end"), + [ + ('"x"; missing', 5, 12), + ('"é"; missing', 5, 12), + ('"中"; missing', 5, 12), + ('"😀"; missing', 6, 13), + ('"e\u0301"; missing', 6, 13), + ('missing; "😀"', 0, 13), + ], +) +@pytest.mark.parametrize("ending", ["", "\n", "\r\n"]) +def test_undefined_name_range_uses_utf16(workspace, text, start, end, ending) -> None: + doc = Document(DOC_URI, workspace, "pass\n" + text + ending) + diag = pyflakes_lint.pylsp_lint(workspace, doc)[0] + assert diag["message"] == "undefined name 'missing'" + assert diag["range"] == { + "start": {"line": 1, "character": start}, + "end": {"line": 1, "character": end}, + } + + +@pytest.mark.parametrize( + ("source", "line", "start", "end"), + [ + ('"start\u2028😀"\n1; missing\n', 1, 3, 10), + ("\fmissing\n", 0, 1, 8), + ("\ufeffé = 1; missing\n", 0, 8, 15), + ("# coding: latin-1\ré = 1\rprint(é); missing\r", 2, 10, 17), + ('# coding: cp932\n"¢"; missing\n', 1, 5, 12), + ], +) +def test_undefined_name_in_editor_source(workspace, source, line, start, end) -> None: + doc = Document(DOC_URI, workspace, source) + (diag,) = pyflakes_lint.pylsp_lint(workspace, doc) + assert diag["message"] == "undefined name 'missing'" + assert diag["range"] == { + "start": {"line": line, "character": start}, + "end": {"line": line, "character": end}, + } + + +@pytest.mark.parametrize( + "source", + [ + "#!/usr/bin/env python\r# coding: Native2Ascii\rx = 1\r", + "# coding: rot13\nx = 1\n", + "\ufeff# coding: latin-1\nx = 1\n", + ], +) +def test_invalid_encoding_declaration(workspace, source) -> None: + with pytest.raises(SyntaxError) as error: + compile(source.encode("utf-8"), "", "exec") + doc = Document(DOC_URI, workspace, source) + (diag,) = pyflakes_lint.pylsp_lint(workspace, doc) + assert diag["message"] == error.value.msg + assert diag["severity"] == lsp.DiagnosticSeverity.Error + + +def test_editor_text_outside_declared_encoding(workspace) -> None: + source = '# coding: ascii\n"é"; missing\n' + doc = Document(DOC_URI, workspace, source) + (diag,) = pyflakes_lint.pylsp_lint(workspace, doc) + assert "ascii" in diag["message"] + assert diag["severity"] == lsp.DiagnosticSeverity.Error diff --git a/test/test_notebook_document.py b/test/test_notebook_document.py index 215258e1..93cbcadc 100644 --- a/test/test_notebook_document.py +++ b/test/test_notebook_document.py @@ -117,7 +117,7 @@ def test_notebook_document__did_open( "source": "pyflakes", "range": { "start": {"line": 1, "character": 0}, - "end": {"line": 1, "character": 11}, + "end": {"line": 1, "character": 10}, }, "message": "'sys' imported but unused", "severity": 2, @@ -126,7 +126,7 @@ def test_notebook_document__did_open( "source": "pyflakes", "range": { "start": {"line": 3, "character": 0}, - "end": {"line": 3, "character": 4}, + "end": {"line": 3, "character": 3}, }, "message": "undefined name 'abc'", "severity": 1, @@ -153,7 +153,7 @@ def test_notebook_document__did_open( "source": "pyflakes", "range": { "start": {"line": 0, "character": 0}, - "end": {"line": 0, "character": 2}, + "end": {"line": 0, "character": 1}, }, "message": "undefined name 'x'", "severity": 1, @@ -170,7 +170,7 @@ def test_notebook_document__did_open( "source": "pyflakes", "range": { "start": {"line": 0, "character": 0}, - "end": {"line": 0, "character": 2}, + "end": {"line": 0, "character": 1}, }, "message": "undefined name 'y'", "severity": 1, @@ -207,7 +207,7 @@ def test_notebook_document__did_change( "source": "pyflakes", "range": { "start": {"line": 0, "character": 0}, - "end": {"line": 0, "character": 11}, + "end": {"line": 0, "character": 10}, }, "message": "'sys' imported but unused", "severity": 2, @@ -329,7 +329,7 @@ def test_notebook_document__did_change( "source": "pyflakes", "range": { "start": {"line": 0, "character": 0}, - "end": {"line": 0, "character": 11}, + "end": {"line": 0, "character": 10}, }, "message": "'sys' imported but unused", "severity": 2,