Skip to content

Support complete enum literal union equivalence - #11597

Merged
Rich Chiodo (rchiodo) merged 7 commits into
mainfrom
rchiodo-correct-enum-equivalence
Aug 10, 2026
Merged

Rich Chiodo (rchiodo) merged 7 commits into
mainfrom
rchiodo-correct-enum-equivalence

Conversation

@rchiodo

Copy link
Copy Markdown
Collaborator

Summary

  • Treat non-Flag enum classes and complete unions of their literal members as contextually equivalent for assignment and assert_type
  • Support the equivalence in both directions, including invariant list/dict and enum-containing union positions
  • Exclude Flag, IntFlag, and indirect Flag subclasses using full-MRO checks
  • Conservatively disable expansion when the statically known enum member set may be incomplete

Design

Enum identity remains nominal by default. The evaluator expands a bare enum only after the destination shape establishes that an enum-literal comparison is needed. A cached union bit makes this destination guard O(1), so unrelated assignments do not enumerate enum symbol tables.

Invariant comparisons normalize both sides locally, which supports reverse substitution such as list[Literal[Color.RED, Color.GREEN]] to list[Color] without globally rewriting enum types. Free TypeVar solving runs before expansion, preserving broad enum inference; bound source TypeVars are concretized only within the known literal-union assignment context.

assert_type uses the same expansion primitive and recursively normalizes nested generic, tuple, and union shapes only after ordinary type identity fails.

Enum expansion is disabled for full-MRO Flag ancestry, custom or unknown enum metaclasses, and class bodies with assignment targets that cannot be represented in the static class symbol table. This avoids treating a known subset as complete for detectable dynamic member creation while keeping aliases, auto(), and statically named members with unknown values supported.

Relation to #11584

This implementation was developed independently from current main and does not modify or supersede #11584. It corrects edge cases identified during independent review of that approach:

  • full-MRO Flag/IntFlag exclusion rather than direct-base-only checks
  • reverse invariant equivalence
  • destination guarding before member enumeration
  • conservative handling of detectable incomplete member sets and custom metaclasses
  • preservation of TypeVar inference and enum identity
  • recursive assert_type equivalence for required nested shapes

Conformance

The exact current upstream python/typing conformance/tests/enums_expansion.py was run with a rebuilt CLI. Before this change, Pyright reported the intentional Flag diagnostic at line 56 plus failures at lines 85-86. After this change, output contains exactly the intentional line 56 diagnostic: 1 error, 0 warnings, 0 informations.

Tests

  • cd packages/pyright-internal && npm run build
  • cd packages/pyright-internal && npx jest typeEvaluator3.test -t Enum --forceExit --runInBand
  • all typeEvaluator1.test through typeEvaluator8.test: 1183 tests passed
  • type-server test bundle and src/tests/typeServer: 24 tests passed
  • npm run typecheck
  • npm run check:eslint
  • npm run check:prettier
  • git diff --check
  • rebuilt CLI against the exact upstream enum expansion conformance file

@StellaHuang95

Stella Huang (StellaHuang95) commented Aug 6, 2026 •

Copy link
Copy Markdown
Collaborator

🔒 Automated review in progress — Stella Huang (@StellaHuang95) is auto-reviewing this PR.

@github-actions

This comment has been minimized.

@StellaHuang95

Copy link
Copy Markdown
Collaborator

Separately, the downstream Pylance async evaluator still has the direct-base-only Flag exclusion and lacks this expansion/completeness behavior. Track the parity port when this Pyright change is imported so indirect Flag subclasses remain excluded.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved via Review Center.

@StellaHuang95 Stella Huang (StellaHuang95) added the review-auto:approved Automated review: no blocking findings (approval posted). label Aug 7, 2026
Only concretize top-level TypeVars to probe for a matching enum subtype and
fall back to the original type when no enum expansion occurs, so unrelated
invariant comparisons like list[T] vs list[ColorLiterals] are unaffected. Adds
regression coverage for TypeVar sources in both invariant directions.

Co-authored-by: Copilot <[email protected]>
@github-actions

This comment has been minimized.

@StellaHuang95

Copy link
Copy Markdown
Collaborator

Please mirror the enum expansion and full-MRO Flag/unknown-member exclusion in Pylance's async evaluator before merging; the current change leaves the shipped async path without this behavior.

@StellaHuang95 Stella Huang (StellaHuang95) added review-auto:changes-requested Automated review: posted blocking findings to address. and removed review-auto:approved Automated review: no blocking findings (approval posted). labels Aug 7, 2026
@rchiodo

Copy link
Copy Markdown
Collaborator Author

Thanks — agreed the Pylance async evaluator needs the same enum-literal expansion plus the full-MRO Flag/unknown-member exclusion. That change belongs in the downstream pyrx monorepo (packages/pylance-internal), which is a separate repository and not part of this microsoft/pyright checkout, so it can't be made in this PR.

This Pyright PR is complete on its own: the expansion + full-MRO/unknown-member exclusion live in typeEvaluator.ts and are covered by enum15.py (including the Flag, DynamicBody, and CustomMetaEnum cases). The Pylance async-evaluator parity port will be handled downstream when this change is imported into pyrx; I'll track it there so indirect Flag subclasses stay excluded and the async path gets the expansion/completeness behavior. It is a downstream follow-up rather than a blocker on the Pyright side.

@github-actions

This comment has been minimized.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved via Review Center.

@StellaHuang95 Stella Huang (StellaHuang95) added review-auto:approved Automated review: no blocking findings (approval posted). and removed review-auto:changes-requested Automated review: posted blocking findings to address. labels Aug 8, 2026
@github-actions

This comment has been minimized.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved via Review Center.

Add parity and Flag match coverage, document union cache construction, and conservatively handle runtime-extensible enum member sets.

Co-authored-by: Copilot <[email protected]>
@github-actions

This comment has been minimized.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved via Review Center.

Add @unique regression coverage for the conservative enum member-completeness policy.

Co-authored-by: Copilot <[email protected]>
@github-actions

This comment has been minimized.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved via Review Center.

@github-actions

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

sympy (https://github.com/sympy/sympy)
+   .../projects/sympy/sympy/solvers/diophantine/tests/test_diophantine.py:314:30 - error: Cannot access attribute "as_independent" for class "Basic"
+     Attribute "as_independent" is unknown (reportAttributeAccessIssue)
+   .../projects/sympy/sympy/solvers/diophantine/tests/test_diophantine.py:380:15 - error: Operator "*" not supported for "None" (reportOptionalOperand)
+   .../projects/sympy/sympy/solvers/diophantine/tests/test_diophantine.py:383:13 - error: No overloads for "__init__" match the provided arguments (reportCallIssue)
+   .../projects/sympy/sympy/solvers/diophantine/tests/test_diophantine.py:383:18 - error: Argument of type "list[Iterator[Unknown]]" cannot be assigned to parameter "iterable" of type "Iterable[list[bytes]]" in function "__init__" (reportArgumentType)
+   .../projects/sympy/sympy/solvers/diophantine/tests/test_diophantine.py:383:30 - error: Cannot access attribute "as_independent" for class "Basic"
+     Attribute "as_independent" is unknown (reportAttributeAccessIssue)
+   .../projects/sympy/sympy/solvers/diophantine/tests/test_diophantine.py:383:78 - error: "args" is not a known attribute of "None" (reportOptionalMemberAccess)
- 38290 errors, 82 warnings, 0 informations
+ 38296 errors, 82 warnings, 0 informations

@rchiodo
Rich Chiodo (rchiodo) merged commit fd9ddad into main Aug 10, 2026
20 checks passed
collectLiteralEnumClasses(implementation, literalEnumClasses, recursively, recursionCount);
}
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Warning · Non-blocking recommendation

collectLiteralEnumClasses and normalizeEnumTypes must remain aligned with assignType's recursive shape handling. Add a parity regression using a deeper mixed shape (for example, dict[Color, list[Callable[[Color], Color]]]) through both assignment and assert_type so future walker drift is detected.


// Concretize top-level TypeVars only to probe for a matching enum subtype.
// If no enum expansion actually occurs (for example, an unrelated source
// TypeVar whose bound is not one of the comparison's enum classes), preserve

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Warning · Non-blocking recommendation

For a source such as T | Color, concretizing the whole source also concretizes the unrelated T; once Color expands, the returned union retains that concretized sibling. Preserve unrelated union members' TypeVars, or add a focused regression test that locks down the intended inference behavior.

if (
ClassType.isEnumClass(classType) &&
(node.d.decorators.length > 0 ||
enumMemberSetMayBeDynamicallyModified ||

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Warning · Non-blocking recommendation

This _missing_ check depends on the current typeshed layout: if a future stub declares _missing_ on IntEnum or StrEnum, complete-union equivalence will silently become unavailable for those enums. Please scope the check to user-defined overrides, or document and test the typeshed assumption explicitly.

const isInvariant = (flags & AssignTypeFlags.Invariant) !== 0;
srcType = expandEnumTypeForLiteralComparison(srcType, destType, /* concretizeTypeVars */ !isInvariant);
if (isInvariant) {
destType = expandEnumTypeForLiteralComparison(destType, srcType, /* concretizeTypeVars */ false);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Warning · Non-blocking recommendation

This normalization applies to every assignType caller, including overload overlap and redundancy analysis. Add a regression test that documents the intended diagnostics for overloads distinguishing a nominal enum from its complete literal union, so this broad semantic change does not cause an accidental future regression.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approved via Review Center.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review-auto:approved Automated review: no blocking findings (approval posted).

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants