Skip to content

[red-knot] Enhancing Diagnostics for Compare Expression Inference #13787

@cake-monotone

Description

@cake-monotone

This issue was suggested by @carljm and is related to the following threads: #13712 (comment), #13781 (comment), #13712 (comment)

Current Problems

Currently, the infer_binary_type_comparison, infer_lexicographic_type_comparison, and perform_rich_comparison functions in infer.rs return an Option<Type>, where None indicates that the comparison is not defined.

However, with the addition of comparison logic for Tuple and Union types, we’ve found that using Option may not provide sufficient diagnostic information.

For example, consider the following code:

(1, 2) < (1, "hello")

The Python runtime provides an appropriate diagnostic message:

Traceback (most recent call last):
  File "/home/cake/works/playground/test.py", line 9, in <module>
    (1, 2) < (1, "hello")
TypeError: '<' not supported between instances of 'int' and 'str'

In contrast, our current Option implementation would result in:

Operator `<` is not supported for types `tuple[Literal[1], Literal[2]]` and `tuple[Literal[1], Literal["hello"]]`

(This is just my expected result; comparison between int and str isn’t implemented yet.)

Implementation

I’m considering a straightforward change to the following structure. Any suggestions are welcome!

struct OperatorUnsupportedError<'db> {
    op: ast::CmpOp,
    lhs: Type<'db>,
    rhs: Type<'db>,
}

// ...

fn infer_binary_type_comparison(
    &mut self,
    left: Type<'db>,
    op: ast::CmpOp,
    right: Type<'db>,
) -> Result<Type<'db>, OperatorUnsupportedError<'db>>

Metadata

Metadata

Assignees

No one assigned

    Labels

    diagnosticsRelated to reporting of diagnostics.tyMulti-file analysis & type inference

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions