Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Changes to how match statements interact with enums #728

Merged
merged 3 commits into from
Feb 5, 2025
Merged

Conversation

Akuli
Copy link
Owner

@Akuli Akuli commented Feb 5, 2025

Two things.

Compiler must know what enum values are matched

This is no longer valid:

enum Thingy:
    Foo
    Bar
    Baz

def get_bar() -> Thingy:
    return Thingy.Bar

def do_stuff(t: Thingy) -> None:
    match t:
        case get_bar():  # error on this line
            ...

When matching over enums, cases must be simple EnumName.MemberName, nothing more complicated is allowed.

New UB

After this PR, the following function will invoke UB if you do thingy_to_string(7 as Thingy):

enum Thingy:
    Foo
    Bar
    Baz

def thingy_to_string(t: Thingy) -> byte*:
    match t:
        case Thingy.Foo:
            return "It's a foo"
        case Thingy.Bar:
            return "Barbar"
        case Thingy.Baz:
            return "Bazzz"
    # We never get here, because we return in all cases

Currently the match statement does nothing, which means that the compiler should complain about how the function might not return a value. It doesn't because undefined value checks are currently missing. After this PR, the match statement invokes UB.

UB happens only in a very specific scenario:

  • Matching over an enum
  • All enum members are handled one by one (otherwise, there is a compiler error)
  • No case _
  • Value passed to match statement is not one of the enum members

I will document this (and other match statement things) in next PR.

@Akuli Akuli changed the title Add Undefined Behavior to match statements in a corner case Change how match statements interact with enums Feb 5, 2025
@Akuli Akuli changed the title Change how match statements interact with enums Changes to how match statements interact with enums Feb 5, 2025
@Akuli Akuli merged commit 446da9b into main Feb 5, 2025
39 checks passed
@Akuli Akuli deleted the match-ub-impl branch February 5, 2025 01:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant