Skip to content

[red-knot] consider fixing spans related to relative imports #15977

Open
@BurntSushi

Description

Description

This issue originally sprouted from here: #15976 (comment)

Consider this Python program:

from ...zqzqzqzq import hi

Running red-knot at present gives you this:

$ run-red-knot -q pr1 -- check
error: lint:unresolved-import
 --> /home/andrew/astral/ruff/play/diags/play/test.py:1:9
  |
1 | from ...zqzqzqzq import hi
  |         ^^^^^^^^ Cannot resolve import `...zqzqzqzq`
  |

The range here is a little inconsistent with the actual message. The range is only on the module name, but the message includes the preceding .... Indeed, if we futz with the Python program a bit more, we can somewhat observe what's going wrong:

from . . . zqzqzqzq import hi

Gives this:

$ run-red-knot -q pr1 -- check
error: lint:unresolved-import
 --> /home/andrew/astral/ruff/play/diags/play/test.py:1:12
  |
1 | from . . . zqzqzqzq import hi
  |            ^^^^^^^^ Cannot resolve import `...zqzqzqzq`
  |

Here, the diagnostic message is showing something that does not match the actual source code.

I believe the underlying problem is the AST definition of a from import:

/// See also [ImportFrom](https://docs.python.org/3/library/ast.html#ast.ImportFrom)
#[derive(Clone, Debug, PartialEq)]
pub struct StmtImportFrom {
pub range: TextRange,
pub module: Option<Identifier>,
pub names: Vec<Alias>,
pub level: u32,
}

Namely, it normalizes the level based on the preceding dots. But in doing so, this drops the range associated with the dots.

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't workingdiagnosticsRelated to reporting of diagnostics.red-knotMulti-file analysis & type inference

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions