Skip to content

semantic: Optional match on a method of a class declared later in the module: SPY0202 'Unknown type Some' #2249

Open

Description

@antonsynd

A match on the T? result of a method fails when the method's class is declared later in the same module than the code doing the match.

class User:
    later: Later

    def __init__(self):
        self.later = Later()

    def run(self) -> int:
        match self.later.get():
            case Some(v):
                return 1 if v else 2
            case None():
                return 0


class Later:
    def get(self) -> bool?:
        return Some(True)


def main():
    print(User().run())

sharpyc run (0.22.0):

error[SPY0202]: Unknown type 'Some' in positional pattern
error[SPY0200]: Undefined identifier 'v'
error[SPY0227]: Cannot infer type for 'None()' without a type annotation. ...

Moving class Later above class User compiles and prints 1. Calls and field accesses on the later class already work; only the typing of the Optional patterns breaks. Classes are visible module-wide, so declaration order should not matter here.

Found in the HGSS demo (antonsynd/vibe-pokemon-sharpy, findings C42). Workaround there: declare the class before its users.

Activity

  1. antonsynd commented on Oct 6, 2026

    @antonsynd
    OwnerAuthor

    Batching 2026-10-05 @ 1e5d54c — charter .claude/plans/remediation-round-2026-09-20-batching.md §3.50, P52 — declaration-order independence (order N39, after P13b; Semantic binder; generator FIRST).

    A member of a module-level type declared LATER in the module types identically to one declared earlier, in every position — declaration order never produces an Unknown. Lane / reach: ice · program. Measured @ 1e5d54c (probes/m2249/): your cell reproduces through a field receiver, a direct Later().get() call, a match EXPRESSION, and after binding to an UNTYPED local; t: str = Later().get_int() (later class, -> int) is SPY0908 CS0029 — untyped, not mistyped, so the member call types Unknown and the Optional pattern head has no home; x: bool? = Later().get() then match x runs; a later FREE FUNCTION get() runs; case 1: and is not None on the same scrutinee run because they never read its type; the earlier-declared control runs. So this is not a match defect: the binder resolves a later class's member signatures after the bodies that use them. Matrix: declaring kind {class, struct, union, dataclass, interface, enum} × member {method, property, field, static method, constructor} × position {annotated store, match scrutinee, argument, condition, return, chained access} × order {declared before, declared after, in a later-listed project file}. Generator FIRST: each cell emitted twice (type before / after its user), identical diagnostics and output asserted, allowlist ratchet. Class tracker: this issue. No seam hypothesis — the plan measures the seam.

  2. added
    lane:iceInternal compiler error: SPY0908/SPY0909, a CSxxxx leak, a crash
    reach:programAn ordinary program a Python programmer would write hits it
    class-trackerThe one issue per class: carries the contract and the cell table
    on Oct 6, 2026
  3. antonsynd commented on Nov 4, 2026

    @antonsynd
    OwnerAuthor

    Batching 2026-11-03 @ 89fba5e — charter .claude/plans/remediation-round-2026-09-20-batching.md §3.11, P52 — declaration-order independence — moved from row 11 to row 6c⁶⁸, directly after P80 (the name-resolution block) and still before P51; its generator row becomes "EXISTS — P77a's harness gains declaring-type order × member × position" (Ruling R-KH, owner 2026-11-03, (a)).

    Why: this contract — "a member of a type declared LATER types identically in every position; declaration order never produces an Unknown" — is rule N1 of docs/design/name-resolution.md ("declaration order never changes what a name means") applied at the binder's type-member pass, so it lands directly behind the block that writes N1's spec text, with its matrix generated by the block's harness instead of a second generator. Rejected: stay at row 11 (N1's spec sentence written with its type-member half still open). Lane / reach: ice · program. Tier full (c) — (b) lapsed because the generator exists. P51 still follows.

  4. antonsynd commented on Nov 5, 2026

    @antonsynd
    OwnerAuthor

    P52, later-declared type member: 5 allowlist row(s) drain with this issue.

    Measured by the name-resolution differential harness (P77a, #2421) @ 5f8a4c4e2. Each row is a generated cell in src/Sharpy.Compiler.Tests/Conformance/name-resolution-differential-allowlist.txt. The rows pin the verdict class: a fix turns them green, the ratchet then reports them STALE, and they are deleted with the fix.

    family class rule code rows
    TypeMember FalseRefusal P52 SPY0203, SPY0202, SPY0200 2
    TypeMember FalseRefusal P52 SPY0224, SPY0367, SPY0200 2
    TypeMember FalseRefusal P52 SPY0202, SPY0200 1

    This includes the union × constructor × match × after cell (typemember/union/constructor/bare/match/after, SPY0224 + SPY0367 + SPY0200), a sibling of this class. The typed capture shape case v: Later the plan listed is not a pattern row: it is SPY0102, because the parser never sets BindingPattern.Type.

    All 5 rows
    typemember/class/optional-method/bare/match/after FalseRefusal
    typemember/union/constructor/alias/match/after FalseRefusal
    typemember/union/constructor/alias/match/before FalseRefusal
    typemember/union/constructor/bare/match/after FalseRefusal
    typemember/union/constructor/bare/store-then-match/after FalseRefusal
    

    5f8a4c4e2 and the allowlist file are on local dev until the next push.

  5. antonsynd commented on Nov 5, 2026

    @antonsynd
    OwnerAuthor

    Drain set update @ fd925ddca (measured): 3 rows cite this issue, down from 5. Two alias rows moved to #1925, because the route now reads the spelling.

    These shas are on local dev, not pushed yet.

  6. antonsynd commented on Nov 5, 2026

    @antonsynd
    OwnerAuthor

    Batching 2026-11-05 @ ee9a007 — charter .claude/plans/remediation-round-2026-09-20-batching.md §3.11, P52 — declaration-order independence (order 6c⁶⁸). Cell: T !E with E declared LATER — a !E suffix naming an error type declared below its use → observed SPY0908 CS0029 when E is below, SPY0260 when E is above @ fd925dd (the harness's declaring-type-order axis; found by P77a's verify round); expected one verdict in both orders (the same as the above-order one). Lane ice, reach program. The matrix's member axis gains the error-type position of a T !E annotation (declared before / after); the 3 name-resolution allowlist rows citing this issue drain here. Placement unchanged.

  7. antonsynd commented on Nov 6, 2026

    @antonsynd
    OwnerAuthor

    Drain set after P77b (name-resolution differential, branch remote/p77b-implement-plan @ 0c0bdcf)

    9 rows of src/Sharpy.Compiler.Tests/Conformance/name-resolution-differential-allowlist.txt cite this issue (3 at the plan base 2279c0d). New rows:

    • +5 from 34408d2 (TYPEMEMBER shape map);
    • +1 from 09330b5 (axis 11, the result wrap: CS0029 at Bare).

    When the cure lands, every one of these rows must drain: a stale row fails the sweep.

    read/type-position/result-error/Later/value=Bare Ice # #2249 ice
    typemember/class/optional-method/bare/match/after FalseRefusal # #2249 false-refusal
    typemember/union/constructor/bare/match/after FalseRefusal # #2249 false-refusal
    typemember/union/constructor/bare/store-then-match/after FalseRefusal # #2249 false-refusal
    typemember/union/method/bare/argument/after FalseRefusal # #2249 false-refusal
    typemember/union/method/bare/condition/after FalseRefusal # #2249 false-refusal
    typemember/union/method/bare/match/after FalseRefusal # #2249 false-refusal
    typemember/union/method/bare/return/after FalseRefusal # #2249 false-refusal
    typemember/union/method/bare/store/after FalseRefusal # #2249 false-refusal
    

    Generated by Claude Code

  8. 5 remaining items

  9. antonsynd commented on Nov 7, 2026

    @antonsynd
    OwnerAuthor

    Drain set @ 87ac3853e (P77b, PR #2453 merged into dev): 9 allowlist row(s) cite this issue.

    Measured from src/Sharpy.Compiler.Tests/Conformance/name-resolution-differential-allowlist.txt @ 87ac3853e (origin/dev; the name-resolution differential harness, pool 8889, allowlist 2595 rows, 19 cited issues). Each row is a generated cell that pins its verdict class: the fix for this issue turns the cell green, the ratchet then reports the row STALE, and the row is deleted with the fix. This comment supersedes the P77a drain-set comment of 2026-11-05 on this issue (where one exists) and any drain-set comment from the reverted first P77b attempt; the counts here are the merged ones. Family is the first segment of the cell id; the lane is the row's own.

    family class lane rows
    typemember FalseRefusal false-refusal 8
    read Ice ice 1
    All 9 row(s)
    read/result-form/BareValue/Later Ice
    typemember/class/optional-method/bare/match/after FalseRefusal
    typemember/union/constructor/bare/match/after FalseRefusal
    typemember/union/constructor/bare/store-then-match/after FalseRefusal
    typemember/union/method/bare/argument/after FalseRefusal
    typemember/union/method/bare/condition/after FalseRefusal
    typemember/union/method/bare/match/after FalseRefusal
    typemember/union/method/bare/return/after FalseRefusal
    typemember/union/method/bare/store/after FalseRefusal
    

    Generated by Claude Code

  10. antonsynd commented on Nov 13, 2026

    @antonsynd
    OwnerAuthor

    Cells: argument checks are skipped against the members of a class declared later in the module. Found by plan-4e2867's fifth verify pass and again by the independent review of PR #2671; outside that plan's contract. Measured with the built sharpyc run @ cbb7816 (product code identical to dev @ 7279914).

    class IBag has __init__(self, a: int, b: int), __contains__(self, item: int) -> bool and has(self, item: int) -> bool. The same def use() is placed above or below it:

    Cell Program in use() Class above Class below
    membership needle "x" in IBag(1, 2) SPY0222 SPY0908 (CS1503)
    literal None needle None in IBag(1, 2) SPY0222 SPY0908 (CS1503)
    method argument IBag(1, 2).has("x") SPY0220 SPY0908 (CS1503)
    constructor argument IBag("a", 2).a SPY0220 SPY0908 (CS1503)
    control, well-typed 1 in IBag(1, 2), IBag(1, 2).has(1) runs, True True runs, True True

    So a call on the later class resolves and runs (as this issue's body says), but its parameter types are not there when the argument is checked, and Roslyn does the refusing. This is the same later-declared-class gap as the Optional-pattern cell above, at the argument-check seam.

    Reported by the verifier, not re-measured here: with a class-typed element (None in Bag(a, c) over a plain class), the below form runs and prints False where the above form is refused SPY0222.

    OptionalMembershipDifferentialTests places its __contains__ classes above the code that tests them, so it never exercises the below form.

    Lane / reach: ice · program. Probes: session scratchpad ord/u1…u5.


    Generated by Claude Code

  11. antonsynd commented on Nov 13, 2026

    @antonsynd
    OwnerAuthor

    Cell (plan-4e2867 for #2635, /verify-implementation sibling-cell prober @ 3643549; the same at the base 32e6488, so not introduced by #2635). CPython 3.15.2.

    The generator of #2635 already excludes one declaration-order program here (IBag, a __contains__ class declared below its use). The reach is wider than a __contains__ class: any container read from a member of a later-declared class.

    Cell Program Observed Expected Lane Reach Found by
    T | None needle into a container that is a field or a method result of a class declared BELOW the use def probe(x: int | None) -> None:
    h = Holder()
    print(x in h.items, x in h.get())
    def main():
    probe(1)
    probe(5)
    probe(None)
    class Holder:
    items: list[int]
    def __init__(self):
    self.items = [1, 2]
    def get(self) -> set[int]:
    return {1, 2}
    SPY0908 (CS1503: int? to int), by run True True / False False / False False ice program plan-4e2867 / prober

    Controls, same commit: with x: int the program runs; with Holder declared above probe the int | None program runs and matches CPython. So the member's type is absent when the membership site is checked, and no lowering kind is recorded for the needle.


    Generated by Claude Code

  12. antonsynd commented on Nov 16, 2026

    @antonsynd
    OwnerAuthor

    Cells from /verify-implementation on plan-67a01f (P93, PR #2699): the same declaration-order axis on membership and iteration. Found by the sibling-cell prober @ 98daf12; probe sharpyc run, oracle CPython 3.15.2.

    A class declared after the function that uses it has unresolved member signatures while that function's body is checked. A wrong-annotation probe is silent, so the reads are Unknown, not mistyped:

    def main() -> None:
        s: str = Late2().m()          # no SPY0220; SPY0908 (CS0029 int -> string)
        for x in Late([1]):
            t: str = x                # no SPY0220; SPY0908 (CS0029)
    
    class Late2:
        def m(self) -> int:
            return 1
    
    class Late:
        _xs: list[int]
        def __init__(self, xs: list[int]):
            self._xs = xs
        def __iter__(self) -> Iterator[int]:
            return iter(self._xs)

    Membership on a user iterable (P93 D1) reads those signatures, so every cell below is refused although for x in Late(..) over the same class runs and the class moved above main answers:

    cell (Late* declared after main) CPython cd40715 98daf12
    x in Late([1, 2]), x not in Late([1, 2]) (producer __iter__) True / False SPY0320 SPY0320
    generic host Late[int] value SPY0320 SPY0320
    generator __iter__ value SPY0320 SPY0320
    __iter__ + __next__ pair value SPY0320 SPY0908 (CS1503, Enumerable.Contains<object>) at 98daf12; SPY0320 again after the verify round's fix on PR #2699
    chain link 0 < x in Late(..) value SPY0519 SPY0320
    use inside a method of an earlier class value SPY0320 SPY0320
    parameter typed b: Late value SPY0320 SPY0320
    subclass needle into a later ZooBag value SPY0320 SPY0320

    Lane false-refusal (the for element and the method call are ICE behind SPY0908), reach program. The LSP route reports the same codes at the same spans, beside its SPY1001 note that Late implements IEnumerable<int32>.


    Generated by Claude Code

  13. antonsynd commented on Nov 16, 2026

    @antonsynd
    OwnerAuthor

    One more declared-after-use cell from the P93 verify round (PR #2699): an iterating override declared after its use.

    class Base:
        def __iter__(self) -> Iterator[int]:
            return iter([1, 2])
    
    def main() -> None:
        print(1 in Late(), 4 in Late())
    
    class Late(Base):
        def __iter__(self) -> Iterator[int]:
            return iter([4, 5])
    observed
    sharpyc run @ cd40715 (P93 base) SPY0320
    sharpyc run @ 5e73463 SPY0320
    CPython 3.15.2 False True
    the same classes with Late declared before main @ 5e73463 False True

    Lane: false-refusal. The cause is this class's: Late.__iter__'s return type is unresolved when main's body is checked, so the in rule cannot tell an iterating override from one that returns a list. Between 98daf12 and 88e5d74 on the PR branch this program happened to answer, because the rule walked past the unresolved override to Base.__iter__; that same walk answered 1 in Early() with the base's elements when the override was -> list[int] (a silent wrong answer, CPython raises TypeError), so 5e73463 stops the walk at the nearest __iter__. Once later declarations are resolved before bodies are checked, this cell answers without a change at the in site.


    Generated by Claude Code

  14. antonsynd commented on Nov 18, 2026

    @antonsynd
    OwnerAuthor

    Cells for this class from P77 (plan-775c50). The class is "a type declared later is not fully typed where an earlier declaration uses it". These cells are member types: a type's field types are resolved only when its body is checked (TypeChecker.Definitions.cs, CheckClass / CheckStruct). Module functions and consts get a signature pre-pass; type members get none. So a function declared above the type checks the member against Unknown, and Roslyn catches the type error instead of the checker.

    cell program observed @ 726e449 expected
    @static read, function above the class def f() -> str: return H.t; class H: @static t: int = 7; def main(): print(f()) SPY0908 (CS0029) SPY0260 "Cannot return type 'int32' from function expecting 'str'", which the function below the class gets
    instance field read, function above the class def g(o: O) -> str: return o.x; class O: x: int = 3 SPY0908 (CS0029) SPY0260
    store, function above the class def s(): H.t = "s" above class H: @static t: int = 7 SPY0908 (CS0029) a checker type error

    P77 fixed the identity half of this position dependence, in 726e449. That half had been silently wrong: the field was replaced by a copy when its class body was checked, so a use above the class bound a symbol without the class's recorded facts. Now every use binds the one symbol, whatever its position. The type half above is not fixed, because it needs a member-signature pre-pass.

    Lane: ice · reach: program.


    Generated by Claude Code

  15. antonsynd commented on Nov 19, 2026

    @antonsynd
    OwnerAuthor

    Sibling sites from plan-775c50's /verify-implementation (report only; no failing program found).

    726e449 (in #2742) stopped CheckClass / CheckStruct replacing each FIELD with a with copy on entering the body, because a use above the type had bound the earlier, fact-less symbol. The same copy shape is still there for the other member kinds, at a2876b2e2:

    • TypeChecker.Definitions.cs:2751: typeSymbol.Properties[i] = propSymbol with { Type = resolvedType }
    • TypeChecker.Definitions.cs:2189 and :2195: the same for events

    Property facts are found by a declaration lookup today (FindProperty, MemberOf(owner, name)), which is why no cell fails: H.hp read from a function above its class prints 4 3 at both 6d6c5c9b2 and a2876b2e2. A consumer that keeps the symbol it bound, as the field's did, would see the stale copy.


    Generated by Claude Code

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    class-trackerThe one issue per class: carries the contract and the cell tablelane:iceInternal compiler error: SPY0908/SPY0909, a CSxxxx leak, a crashreach:programAn ordinary program a Python programmer would write hits it

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions